1 //===-- AArch64ISelLowering.cpp - AArch64 DAG Lowering Implementation ----===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the AArch64TargetLowering class.
12 //===----------------------------------------------------------------------===//
14 #include "AArch64ISelLowering.h"
15 #include "AArch64CallingConvention.h"
16 #include "AArch64MachineFunctionInfo.h"
17 #include "AArch64PerfectShuffle.h"
18 #include "AArch64Subtarget.h"
19 #include "AArch64TargetMachine.h"
20 #include "AArch64TargetObjectFile.h"
21 #include "MCTargetDesc/AArch64AddressingModes.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/CodeGen/CallingConvLower.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineInstrBuilder.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/GetElementPtrTypeIterator.h"
29 #include "llvm/IR/Intrinsics.h"
30 #include "llvm/IR/Type.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetOptions.h"
38 #define DEBUG_TYPE "aarch64-lower"
40 STATISTIC(NumTailCalls, "Number of tail calls");
41 STATISTIC(NumShiftInserts, "Number of vector shift inserts");
43 // Place holder until extr generation is tested fully.
45 EnableAArch64ExtrGeneration("aarch64-extr-generation", cl::Hidden,
46 cl::desc("Allow AArch64 (or (shift)(shift))->extract"),
50 EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden,
51 cl::desc("Allow AArch64 SLI/SRI formation"),
54 // FIXME: The necessary dtprel relocations don't seem to be supported
55 // well in the GNU bfd and gold linkers at the moment. Therefore, by
56 // default, for now, fall back to GeneralDynamic code generation.
57 cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration(
58 "aarch64-elf-ldtls-generation", cl::Hidden,
59 cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
62 /// Value type used for condition codes.
63 static const MVT MVT_CC = MVT::i32;
65 AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
66 const AArch64Subtarget &STI)
67 : TargetLowering(TM), Subtarget(&STI) {
69 // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
70 // we have to make something up. Arbitrarily, choose ZeroOrOne.
71 setBooleanContents(ZeroOrOneBooleanContent);
72 // When comparing vectors the result sets the different elements in the
73 // vector to all-one or all-zero.
74 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
76 // Set up the register classes.
77 addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
78 addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
80 if (Subtarget->hasFPARMv8()) {
81 addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
82 addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
83 addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
84 addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
87 if (Subtarget->hasNEON()) {
88 addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
89 addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
90 // Someone set us up the NEON.
91 addDRTypeForNEON(MVT::v2f32);
92 addDRTypeForNEON(MVT::v8i8);
93 addDRTypeForNEON(MVT::v4i16);
94 addDRTypeForNEON(MVT::v2i32);
95 addDRTypeForNEON(MVT::v1i64);
96 addDRTypeForNEON(MVT::v1f64);
97 addDRTypeForNEON(MVT::v4f16);
99 addQRTypeForNEON(MVT::v4f32);
100 addQRTypeForNEON(MVT::v2f64);
101 addQRTypeForNEON(MVT::v16i8);
102 addQRTypeForNEON(MVT::v8i16);
103 addQRTypeForNEON(MVT::v4i32);
104 addQRTypeForNEON(MVT::v2i64);
105 addQRTypeForNEON(MVT::v8f16);
108 // Compute derived properties from the register classes
109 computeRegisterProperties(Subtarget->getRegisterInfo());
111 // Provide all sorts of operation actions
112 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
113 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
114 setOperationAction(ISD::SETCC, MVT::i32, Custom);
115 setOperationAction(ISD::SETCC, MVT::i64, Custom);
116 setOperationAction(ISD::SETCC, MVT::f32, Custom);
117 setOperationAction(ISD::SETCC, MVT::f64, Custom);
118 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
119 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
120 setOperationAction(ISD::BR_CC, MVT::i64, Custom);
121 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
122 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
123 setOperationAction(ISD::SELECT, MVT::i32, Custom);
124 setOperationAction(ISD::SELECT, MVT::i64, Custom);
125 setOperationAction(ISD::SELECT, MVT::f32, Custom);
126 setOperationAction(ISD::SELECT, MVT::f64, Custom);
127 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
128 setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
129 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
130 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
131 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
132 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
134 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
135 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
136 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
138 setOperationAction(ISD::FREM, MVT::f32, Expand);
139 setOperationAction(ISD::FREM, MVT::f64, Expand);
140 setOperationAction(ISD::FREM, MVT::f80, Expand);
142 // Custom lowering hooks are needed for XOR
143 // to fold it into CSINC/CSINV.
144 setOperationAction(ISD::XOR, MVT::i32, Custom);
145 setOperationAction(ISD::XOR, MVT::i64, Custom);
147 // Virtually no operation on f128 is legal, but LLVM can't expand them when
148 // there's a valid register class, so we need custom operations in most cases.
149 setOperationAction(ISD::FABS, MVT::f128, Expand);
150 setOperationAction(ISD::FADD, MVT::f128, Custom);
151 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
152 setOperationAction(ISD::FCOS, MVT::f128, Expand);
153 setOperationAction(ISD::FDIV, MVT::f128, Custom);
154 setOperationAction(ISD::FMA, MVT::f128, Expand);
155 setOperationAction(ISD::FMUL, MVT::f128, Custom);
156 setOperationAction(ISD::FNEG, MVT::f128, Expand);
157 setOperationAction(ISD::FPOW, MVT::f128, Expand);
158 setOperationAction(ISD::FREM, MVT::f128, Expand);
159 setOperationAction(ISD::FRINT, MVT::f128, Expand);
160 setOperationAction(ISD::FSIN, MVT::f128, Expand);
161 setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
162 setOperationAction(ISD::FSQRT, MVT::f128, Expand);
163 setOperationAction(ISD::FSUB, MVT::f128, Custom);
164 setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
165 setOperationAction(ISD::SETCC, MVT::f128, Custom);
166 setOperationAction(ISD::BR_CC, MVT::f128, Custom);
167 setOperationAction(ISD::SELECT, MVT::f128, Custom);
168 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
169 setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
171 // Lowering for many of the conversions is actually specified by the non-f128
172 // type. The LowerXXX function will be trivial when f128 isn't involved.
173 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
174 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
175 setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
176 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
177 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
178 setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
179 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
180 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
181 setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
182 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
183 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
184 setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
185 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
186 setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
188 // Variable arguments.
189 setOperationAction(ISD::VASTART, MVT::Other, Custom);
190 setOperationAction(ISD::VAARG, MVT::Other, Custom);
191 setOperationAction(ISD::VACOPY, MVT::Other, Custom);
192 setOperationAction(ISD::VAEND, MVT::Other, Expand);
194 // Variable-sized objects.
195 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
196 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
197 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
199 // Exception handling.
200 // FIXME: These are guesses. Has this been defined yet?
201 setExceptionPointerRegister(AArch64::X0);
202 setExceptionSelectorRegister(AArch64::X1);
204 // Constant pool entries
205 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
208 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
210 // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
211 setOperationAction(ISD::ADDC, MVT::i32, Custom);
212 setOperationAction(ISD::ADDE, MVT::i32, Custom);
213 setOperationAction(ISD::SUBC, MVT::i32, Custom);
214 setOperationAction(ISD::SUBE, MVT::i32, Custom);
215 setOperationAction(ISD::ADDC, MVT::i64, Custom);
216 setOperationAction(ISD::ADDE, MVT::i64, Custom);
217 setOperationAction(ISD::SUBC, MVT::i64, Custom);
218 setOperationAction(ISD::SUBE, MVT::i64, Custom);
220 // AArch64 lacks both left-rotate and popcount instructions.
221 setOperationAction(ISD::ROTL, MVT::i32, Expand);
222 setOperationAction(ISD::ROTL, MVT::i64, Expand);
224 // AArch64 doesn't have {U|S}MUL_LOHI.
225 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
226 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
229 // Expand the undefined-at-zero variants to cttz/ctlz to their defined-at-zero
230 // counterparts, which AArch64 supports directly.
231 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
232 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
233 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
234 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
236 setOperationAction(ISD::CTPOP, MVT::i32, Custom);
237 setOperationAction(ISD::CTPOP, MVT::i64, Custom);
239 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
240 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
241 setOperationAction(ISD::SREM, MVT::i32, Expand);
242 setOperationAction(ISD::SREM, MVT::i64, Expand);
243 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
244 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
245 setOperationAction(ISD::UREM, MVT::i32, Expand);
246 setOperationAction(ISD::UREM, MVT::i64, Expand);
248 // Custom lower Add/Sub/Mul with overflow.
249 setOperationAction(ISD::SADDO, MVT::i32, Custom);
250 setOperationAction(ISD::SADDO, MVT::i64, Custom);
251 setOperationAction(ISD::UADDO, MVT::i32, Custom);
252 setOperationAction(ISD::UADDO, MVT::i64, Custom);
253 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
254 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
255 setOperationAction(ISD::USUBO, MVT::i32, Custom);
256 setOperationAction(ISD::USUBO, MVT::i64, Custom);
257 setOperationAction(ISD::SMULO, MVT::i32, Custom);
258 setOperationAction(ISD::SMULO, MVT::i64, Custom);
259 setOperationAction(ISD::UMULO, MVT::i32, Custom);
260 setOperationAction(ISD::UMULO, MVT::i64, Custom);
262 setOperationAction(ISD::FSIN, MVT::f32, Expand);
263 setOperationAction(ISD::FSIN, MVT::f64, Expand);
264 setOperationAction(ISD::FCOS, MVT::f32, Expand);
265 setOperationAction(ISD::FCOS, MVT::f64, Expand);
266 setOperationAction(ISD::FPOW, MVT::f32, Expand);
267 setOperationAction(ISD::FPOW, MVT::f64, Expand);
268 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
269 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
271 // f16 is a storage-only type, always promote it to f32.
272 setOperationAction(ISD::SETCC, MVT::f16, Promote);
273 setOperationAction(ISD::BR_CC, MVT::f16, Promote);
274 setOperationAction(ISD::SELECT_CC, MVT::f16, Promote);
275 setOperationAction(ISD::SELECT, MVT::f16, Promote);
276 setOperationAction(ISD::FADD, MVT::f16, Promote);
277 setOperationAction(ISD::FSUB, MVT::f16, Promote);
278 setOperationAction(ISD::FMUL, MVT::f16, Promote);
279 setOperationAction(ISD::FDIV, MVT::f16, Promote);
280 setOperationAction(ISD::FREM, MVT::f16, Promote);
281 setOperationAction(ISD::FMA, MVT::f16, Promote);
282 setOperationAction(ISD::FNEG, MVT::f16, Promote);
283 setOperationAction(ISD::FABS, MVT::f16, Promote);
284 setOperationAction(ISD::FCEIL, MVT::f16, Promote);
285 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote);
286 setOperationAction(ISD::FCOS, MVT::f16, Promote);
287 setOperationAction(ISD::FFLOOR, MVT::f16, Promote);
288 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote);
289 setOperationAction(ISD::FPOW, MVT::f16, Promote);
290 setOperationAction(ISD::FPOWI, MVT::f16, Promote);
291 setOperationAction(ISD::FRINT, MVT::f16, Promote);
292 setOperationAction(ISD::FSIN, MVT::f16, Promote);
293 setOperationAction(ISD::FSINCOS, MVT::f16, Promote);
294 setOperationAction(ISD::FSQRT, MVT::f16, Promote);
295 setOperationAction(ISD::FEXP, MVT::f16, Promote);
296 setOperationAction(ISD::FEXP2, MVT::f16, Promote);
297 setOperationAction(ISD::FLOG, MVT::f16, Promote);
298 setOperationAction(ISD::FLOG2, MVT::f16, Promote);
299 setOperationAction(ISD::FLOG10, MVT::f16, Promote);
300 setOperationAction(ISD::FROUND, MVT::f16, Promote);
301 setOperationAction(ISD::FTRUNC, MVT::f16, Promote);
302 setOperationAction(ISD::FMINNUM, MVT::f16, Promote);
303 setOperationAction(ISD::FMAXNUM, MVT::f16, Promote);
304 setOperationAction(ISD::FMINNAN, MVT::f16, Promote);
305 setOperationAction(ISD::FMAXNAN, MVT::f16, Promote);
307 // v4f16 is also a storage-only type, so promote it to v4f32 when that is
309 setOperationAction(ISD::FADD, MVT::v4f16, Promote);
310 setOperationAction(ISD::FSUB, MVT::v4f16, Promote);
311 setOperationAction(ISD::FMUL, MVT::v4f16, Promote);
312 setOperationAction(ISD::FDIV, MVT::v4f16, Promote);
313 setOperationAction(ISD::FP_EXTEND, MVT::v4f16, Promote);
314 setOperationAction(ISD::FP_ROUND, MVT::v4f16, Promote);
315 AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32);
316 AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32);
317 AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32);
318 AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32);
319 AddPromotedToType(ISD::FP_EXTEND, MVT::v4f16, MVT::v4f32);
320 AddPromotedToType(ISD::FP_ROUND, MVT::v4f16, MVT::v4f32);
322 // Expand all other v4f16 operations.
323 // FIXME: We could generate better code by promoting some operations to
325 setOperationAction(ISD::FABS, MVT::v4f16, Expand);
326 setOperationAction(ISD::FCEIL, MVT::v4f16, Expand);
327 setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand);
328 setOperationAction(ISD::FCOS, MVT::v4f16, Expand);
329 setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand);
330 setOperationAction(ISD::FMA, MVT::v4f16, Expand);
331 setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand);
332 setOperationAction(ISD::FNEG, MVT::v4f16, Expand);
333 setOperationAction(ISD::FPOW, MVT::v4f16, Expand);
334 setOperationAction(ISD::FPOWI, MVT::v4f16, Expand);
335 setOperationAction(ISD::FREM, MVT::v4f16, Expand);
336 setOperationAction(ISD::FROUND, MVT::v4f16, Expand);
337 setOperationAction(ISD::FRINT, MVT::v4f16, Expand);
338 setOperationAction(ISD::FSIN, MVT::v4f16, Expand);
339 setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand);
340 setOperationAction(ISD::FSQRT, MVT::v4f16, Expand);
341 setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand);
342 setOperationAction(ISD::SETCC, MVT::v4f16, Expand);
343 setOperationAction(ISD::BR_CC, MVT::v4f16, Expand);
344 setOperationAction(ISD::SELECT, MVT::v4f16, Expand);
345 setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand);
346 setOperationAction(ISD::FEXP, MVT::v4f16, Expand);
347 setOperationAction(ISD::FEXP2, MVT::v4f16, Expand);
348 setOperationAction(ISD::FLOG, MVT::v4f16, Expand);
349 setOperationAction(ISD::FLOG2, MVT::v4f16, Expand);
350 setOperationAction(ISD::FLOG10, MVT::v4f16, Expand);
353 // v8f16 is also a storage-only type, so expand it.
354 setOperationAction(ISD::FABS, MVT::v8f16, Expand);
355 setOperationAction(ISD::FADD, MVT::v8f16, Expand);
356 setOperationAction(ISD::FCEIL, MVT::v8f16, Expand);
357 setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand);
358 setOperationAction(ISD::FCOS, MVT::v8f16, Expand);
359 setOperationAction(ISD::FDIV, MVT::v8f16, Expand);
360 setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand);
361 setOperationAction(ISD::FMA, MVT::v8f16, Expand);
362 setOperationAction(ISD::FMUL, MVT::v8f16, Expand);
363 setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand);
364 setOperationAction(ISD::FNEG, MVT::v8f16, Expand);
365 setOperationAction(ISD::FPOW, MVT::v8f16, Expand);
366 setOperationAction(ISD::FPOWI, MVT::v8f16, Expand);
367 setOperationAction(ISD::FREM, MVT::v8f16, Expand);
368 setOperationAction(ISD::FROUND, MVT::v8f16, Expand);
369 setOperationAction(ISD::FRINT, MVT::v8f16, Expand);
370 setOperationAction(ISD::FSIN, MVT::v8f16, Expand);
371 setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
372 setOperationAction(ISD::FSQRT, MVT::v8f16, Expand);
373 setOperationAction(ISD::FSUB, MVT::v8f16, Expand);
374 setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand);
375 setOperationAction(ISD::SETCC, MVT::v8f16, Expand);
376 setOperationAction(ISD::BR_CC, MVT::v8f16, Expand);
377 setOperationAction(ISD::SELECT, MVT::v8f16, Expand);
378 setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand);
379 setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand);
380 setOperationAction(ISD::FEXP, MVT::v8f16, Expand);
381 setOperationAction(ISD::FEXP2, MVT::v8f16, Expand);
382 setOperationAction(ISD::FLOG, MVT::v8f16, Expand);
383 setOperationAction(ISD::FLOG2, MVT::v8f16, Expand);
384 setOperationAction(ISD::FLOG10, MVT::v8f16, Expand);
386 // AArch64 has implementations of a lot of rounding-like FP operations.
387 for (MVT Ty : {MVT::f32, MVT::f64}) {
388 setOperationAction(ISD::FFLOOR, Ty, Legal);
389 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
390 setOperationAction(ISD::FCEIL, Ty, Legal);
391 setOperationAction(ISD::FRINT, Ty, Legal);
392 setOperationAction(ISD::FTRUNC, Ty, Legal);
393 setOperationAction(ISD::FROUND, Ty, Legal);
394 setOperationAction(ISD::FMINNUM, Ty, Legal);
395 setOperationAction(ISD::FMAXNUM, Ty, Legal);
396 setOperationAction(ISD::FMINNAN, Ty, Legal);
397 setOperationAction(ISD::FMAXNAN, Ty, Legal);
400 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
402 if (Subtarget->isTargetMachO()) {
403 // For iOS, we don't want to the normal expansion of a libcall to
404 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
406 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
407 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
409 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
410 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
413 // Make floating-point constants legal for the large code model, so they don't
414 // become loads from the constant pool.
415 if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
416 setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
417 setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
420 // AArch64 does not have floating-point extending loads, i1 sign-extending
421 // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
422 for (MVT VT : MVT::fp_valuetypes()) {
423 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
424 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
425 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
426 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
428 for (MVT VT : MVT::integer_valuetypes())
429 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
431 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
432 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
433 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
434 setTruncStoreAction(MVT::f128, MVT::f80, Expand);
435 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
436 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
437 setTruncStoreAction(MVT::f128, MVT::f16, Expand);
439 setOperationAction(ISD::BITCAST, MVT::i16, Custom);
440 setOperationAction(ISD::BITCAST, MVT::f16, Custom);
442 // Indexed loads and stores are supported.
443 for (unsigned im = (unsigned)ISD::PRE_INC;
444 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
445 setIndexedLoadAction(im, MVT::i8, Legal);
446 setIndexedLoadAction(im, MVT::i16, Legal);
447 setIndexedLoadAction(im, MVT::i32, Legal);
448 setIndexedLoadAction(im, MVT::i64, Legal);
449 setIndexedLoadAction(im, MVT::f64, Legal);
450 setIndexedLoadAction(im, MVT::f32, Legal);
451 setIndexedLoadAction(im, MVT::f16, Legal);
452 setIndexedStoreAction(im, MVT::i8, Legal);
453 setIndexedStoreAction(im, MVT::i16, Legal);
454 setIndexedStoreAction(im, MVT::i32, Legal);
455 setIndexedStoreAction(im, MVT::i64, Legal);
456 setIndexedStoreAction(im, MVT::f64, Legal);
457 setIndexedStoreAction(im, MVT::f32, Legal);
458 setIndexedStoreAction(im, MVT::f16, Legal);
462 setOperationAction(ISD::TRAP, MVT::Other, Legal);
464 // We combine OR nodes for bitfield operations.
465 setTargetDAGCombine(ISD::OR);
467 // Vector add and sub nodes may conceal a high-half opportunity.
468 // Also, try to fold ADD into CSINC/CSINV..
469 setTargetDAGCombine(ISD::ADD);
470 setTargetDAGCombine(ISD::SUB);
472 setTargetDAGCombine(ISD::XOR);
473 setTargetDAGCombine(ISD::SINT_TO_FP);
474 setTargetDAGCombine(ISD::UINT_TO_FP);
476 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
478 setTargetDAGCombine(ISD::ANY_EXTEND);
479 setTargetDAGCombine(ISD::ZERO_EXTEND);
480 setTargetDAGCombine(ISD::SIGN_EXTEND);
481 setTargetDAGCombine(ISD::BITCAST);
482 setTargetDAGCombine(ISD::CONCAT_VECTORS);
483 setTargetDAGCombine(ISD::STORE);
485 setTargetDAGCombine(ISD::MUL);
487 setTargetDAGCombine(ISD::SELECT);
488 setTargetDAGCombine(ISD::VSELECT);
490 setTargetDAGCombine(ISD::INTRINSIC_VOID);
491 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
492 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
494 MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 8;
495 MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 4;
496 MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = 4;
498 setStackPointerRegisterToSaveRestore(AArch64::SP);
500 setSchedulingPreference(Sched::Hybrid);
503 MaskAndBranchFoldingIsLegal = true;
504 EnableExtLdPromotion = true;
506 setMinFunctionAlignment(2);
508 setHasExtractBitsInsn(true);
510 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
512 if (Subtarget->hasNEON()) {
513 // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
514 // silliness like this:
515 setOperationAction(ISD::FABS, MVT::v1f64, Expand);
516 setOperationAction(ISD::FADD, MVT::v1f64, Expand);
517 setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
518 setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
519 setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
520 setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
521 setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
522 setOperationAction(ISD::FMA, MVT::v1f64, Expand);
523 setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
524 setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
525 setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
526 setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
527 setOperationAction(ISD::FREM, MVT::v1f64, Expand);
528 setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
529 setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
530 setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
531 setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
532 setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
533 setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
534 setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
535 setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
536 setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
537 setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
538 setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
539 setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
541 setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
542 setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
543 setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
544 setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
545 setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
547 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
549 // AArch64 doesn't have a direct vector ->f32 conversion instructions for
550 // elements smaller than i32, so promote the input to i32 first.
551 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Promote);
552 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Promote);
553 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Promote);
554 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Promote);
555 // i8 and i16 vector elements also need promotion to i32 for v8i8 or v8i16
556 // -> v8f16 conversions.
557 setOperationAction(ISD::SINT_TO_FP, MVT::v8i8, Promote);
558 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Promote);
559 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
560 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Promote);
561 // Similarly, there is no direct i32 -> f64 vector conversion instruction.
562 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
563 setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
564 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
565 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
566 // Or, direct i32 -> f16 vector conversion. Set it so custom, so the
567 // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
568 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
569 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
571 // AArch64 doesn't have MUL.2d:
572 setOperationAction(ISD::MUL, MVT::v2i64, Expand);
573 // Custom handling for some quad-vector types to detect MULL.
574 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
575 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
576 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
578 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
579 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
580 // Likewise, narrowing and extending vector loads/stores aren't handled
582 for (MVT VT : MVT::vector_valuetypes()) {
583 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
585 setOperationAction(ISD::MULHS, VT, Expand);
586 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
587 setOperationAction(ISD::MULHU, VT, Expand);
588 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
590 setOperationAction(ISD::BSWAP, VT, Expand);
592 for (MVT InnerVT : MVT::vector_valuetypes()) {
593 setTruncStoreAction(VT, InnerVT, Expand);
594 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
595 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
596 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
600 // AArch64 has implementations of a lot of rounding-like FP operations.
601 for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
602 setOperationAction(ISD::FFLOOR, Ty, Legal);
603 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
604 setOperationAction(ISD::FCEIL, Ty, Legal);
605 setOperationAction(ISD::FRINT, Ty, Legal);
606 setOperationAction(ISD::FTRUNC, Ty, Legal);
607 setOperationAction(ISD::FROUND, Ty, Legal);
611 // Prefer likely predicted branches to selects on out-of-order cores.
612 if (Subtarget->isCortexA57())
613 PredictableSelectIsExpensive = true;
616 void AArch64TargetLowering::addTypeForNEON(EVT VT, EVT PromotedBitwiseVT) {
617 if (VT == MVT::v2f32 || VT == MVT::v4f16) {
618 setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
619 AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i32);
621 setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
622 AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i32);
623 } else if (VT == MVT::v2f64 || VT == MVT::v4f32 || VT == MVT::v8f16) {
624 setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
625 AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i64);
627 setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
628 AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i64);
631 // Mark vector float intrinsics as expand.
632 if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
633 setOperationAction(ISD::FSIN, VT.getSimpleVT(), Expand);
634 setOperationAction(ISD::FCOS, VT.getSimpleVT(), Expand);
635 setOperationAction(ISD::FPOWI, VT.getSimpleVT(), Expand);
636 setOperationAction(ISD::FPOW, VT.getSimpleVT(), Expand);
637 setOperationAction(ISD::FLOG, VT.getSimpleVT(), Expand);
638 setOperationAction(ISD::FLOG2, VT.getSimpleVT(), Expand);
639 setOperationAction(ISD::FLOG10, VT.getSimpleVT(), Expand);
640 setOperationAction(ISD::FEXP, VT.getSimpleVT(), Expand);
641 setOperationAction(ISD::FEXP2, VT.getSimpleVT(), Expand);
643 // But we do support custom-lowering for FCOPYSIGN.
644 setOperationAction(ISD::FCOPYSIGN, VT.getSimpleVT(), Custom);
647 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT.getSimpleVT(), Custom);
648 setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getSimpleVT(), Custom);
649 setOperationAction(ISD::BUILD_VECTOR, VT.getSimpleVT(), Custom);
650 setOperationAction(ISD::VECTOR_SHUFFLE, VT.getSimpleVT(), Custom);
651 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT.getSimpleVT(), Custom);
652 setOperationAction(ISD::SRA, VT.getSimpleVT(), Custom);
653 setOperationAction(ISD::SRL, VT.getSimpleVT(), Custom);
654 setOperationAction(ISD::SHL, VT.getSimpleVT(), Custom);
655 setOperationAction(ISD::AND, VT.getSimpleVT(), Custom);
656 setOperationAction(ISD::OR, VT.getSimpleVT(), Custom);
657 setOperationAction(ISD::SETCC, VT.getSimpleVT(), Custom);
658 setOperationAction(ISD::CONCAT_VECTORS, VT.getSimpleVT(), Legal);
660 setOperationAction(ISD::SELECT, VT.getSimpleVT(), Expand);
661 setOperationAction(ISD::SELECT_CC, VT.getSimpleVT(), Expand);
662 setOperationAction(ISD::VSELECT, VT.getSimpleVT(), Expand);
663 for (MVT InnerVT : MVT::all_valuetypes())
664 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT.getSimpleVT(), Expand);
666 // CNT supports only B element sizes.
667 if (VT != MVT::v8i8 && VT != MVT::v16i8)
668 setOperationAction(ISD::CTPOP, VT.getSimpleVT(), Expand);
670 setOperationAction(ISD::UDIV, VT.getSimpleVT(), Expand);
671 setOperationAction(ISD::SDIV, VT.getSimpleVT(), Expand);
672 setOperationAction(ISD::UREM, VT.getSimpleVT(), Expand);
673 setOperationAction(ISD::SREM, VT.getSimpleVT(), Expand);
674 setOperationAction(ISD::FREM, VT.getSimpleVT(), Expand);
676 setOperationAction(ISD::FP_TO_SINT, VT.getSimpleVT(), Custom);
677 setOperationAction(ISD::FP_TO_UINT, VT.getSimpleVT(), Custom);
679 // [SU][MIN|MAX] and [SU]ABSDIFF are available for all NEON types apart from
681 if (!VT.isFloatingPoint() &&
682 VT.getSimpleVT() != MVT::v2i64 && VT.getSimpleVT() != MVT::v1i64)
683 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX,
684 ISD::SABSDIFF, ISD::UABSDIFF})
685 setOperationAction(Opcode, VT.getSimpleVT(), Legal);
687 // F[MIN|MAX][NUM|NAN] are available for all FP NEON types (not f16 though!).
688 if (VT.isFloatingPoint() && VT.getVectorElementType() != MVT::f16)
689 for (unsigned Opcode : {ISD::FMINNAN, ISD::FMAXNAN,
690 ISD::FMINNUM, ISD::FMAXNUM})
691 setOperationAction(Opcode, VT.getSimpleVT(), Legal);
693 if (Subtarget->isLittleEndian()) {
694 for (unsigned im = (unsigned)ISD::PRE_INC;
695 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
696 setIndexedLoadAction(im, VT.getSimpleVT(), Legal);
697 setIndexedStoreAction(im, VT.getSimpleVT(), Legal);
702 void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
703 addRegisterClass(VT, &AArch64::FPR64RegClass);
704 addTypeForNEON(VT, MVT::v2i32);
707 void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
708 addRegisterClass(VT, &AArch64::FPR128RegClass);
709 addTypeForNEON(VT, MVT::v4i32);
712 EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
716 return VT.changeVectorElementTypeToInteger();
719 /// computeKnownBitsForTargetNode - Determine which of the bits specified in
720 /// Mask are known to be either zero or one and return them in the
721 /// KnownZero/KnownOne bitsets.
722 void AArch64TargetLowering::computeKnownBitsForTargetNode(
723 const SDValue Op, APInt &KnownZero, APInt &KnownOne,
724 const SelectionDAG &DAG, unsigned Depth) const {
725 switch (Op.getOpcode()) {
728 case AArch64ISD::CSEL: {
729 APInt KnownZero2, KnownOne2;
730 DAG.computeKnownBits(Op->getOperand(0), KnownZero, KnownOne, Depth + 1);
731 DAG.computeKnownBits(Op->getOperand(1), KnownZero2, KnownOne2, Depth + 1);
732 KnownZero &= KnownZero2;
733 KnownOne &= KnownOne2;
736 case ISD::INTRINSIC_W_CHAIN: {
737 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
738 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
741 case Intrinsic::aarch64_ldaxr:
742 case Intrinsic::aarch64_ldxr: {
743 unsigned BitWidth = KnownOne.getBitWidth();
744 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
745 unsigned MemBits = VT.getScalarType().getSizeInBits();
746 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
752 case ISD::INTRINSIC_WO_CHAIN:
753 case ISD::INTRINSIC_VOID: {
754 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
758 case Intrinsic::aarch64_neon_umaxv:
759 case Intrinsic::aarch64_neon_uminv: {
760 // Figure out the datatype of the vector operand. The UMINV instruction
761 // will zero extend the result, so we can mark as known zero all the
762 // bits larger than the element datatype. 32-bit or larget doesn't need
763 // this as those are legal types and will be handled by isel directly.
764 MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
765 unsigned BitWidth = KnownZero.getBitWidth();
766 if (VT == MVT::v8i8 || VT == MVT::v16i8) {
767 assert(BitWidth >= 8 && "Unexpected width!");
768 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
770 } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
771 assert(BitWidth >= 16 && "Unexpected width!");
772 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
782 MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
787 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
791 if (Subtarget->requiresStrictAlign())
793 // FIXME: True for Cyclone, but not necessary others.
800 AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
801 const TargetLibraryInfo *libInfo) const {
802 return AArch64::createFastISel(funcInfo, libInfo);
805 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
806 switch ((AArch64ISD::NodeType)Opcode) {
807 case AArch64ISD::FIRST_NUMBER: break;
808 case AArch64ISD::CALL: return "AArch64ISD::CALL";
809 case AArch64ISD::ADRP: return "AArch64ISD::ADRP";
810 case AArch64ISD::ADDlow: return "AArch64ISD::ADDlow";
811 case AArch64ISD::LOADgot: return "AArch64ISD::LOADgot";
812 case AArch64ISD::RET_FLAG: return "AArch64ISD::RET_FLAG";
813 case AArch64ISD::BRCOND: return "AArch64ISD::BRCOND";
814 case AArch64ISD::CSEL: return "AArch64ISD::CSEL";
815 case AArch64ISD::FCSEL: return "AArch64ISD::FCSEL";
816 case AArch64ISD::CSINV: return "AArch64ISD::CSINV";
817 case AArch64ISD::CSNEG: return "AArch64ISD::CSNEG";
818 case AArch64ISD::CSINC: return "AArch64ISD::CSINC";
819 case AArch64ISD::THREAD_POINTER: return "AArch64ISD::THREAD_POINTER";
820 case AArch64ISD::TLSDESC_CALLSEQ: return "AArch64ISD::TLSDESC_CALLSEQ";
821 case AArch64ISD::ADC: return "AArch64ISD::ADC";
822 case AArch64ISD::SBC: return "AArch64ISD::SBC";
823 case AArch64ISD::ADDS: return "AArch64ISD::ADDS";
824 case AArch64ISD::SUBS: return "AArch64ISD::SUBS";
825 case AArch64ISD::ADCS: return "AArch64ISD::ADCS";
826 case AArch64ISD::SBCS: return "AArch64ISD::SBCS";
827 case AArch64ISD::ANDS: return "AArch64ISD::ANDS";
828 case AArch64ISD::CCMP: return "AArch64ISD::CCMP";
829 case AArch64ISD::CCMN: return "AArch64ISD::CCMN";
830 case AArch64ISD::FCCMP: return "AArch64ISD::FCCMP";
831 case AArch64ISD::FCMP: return "AArch64ISD::FCMP";
832 case AArch64ISD::DUP: return "AArch64ISD::DUP";
833 case AArch64ISD::DUPLANE8: return "AArch64ISD::DUPLANE8";
834 case AArch64ISD::DUPLANE16: return "AArch64ISD::DUPLANE16";
835 case AArch64ISD::DUPLANE32: return "AArch64ISD::DUPLANE32";
836 case AArch64ISD::DUPLANE64: return "AArch64ISD::DUPLANE64";
837 case AArch64ISD::MOVI: return "AArch64ISD::MOVI";
838 case AArch64ISD::MOVIshift: return "AArch64ISD::MOVIshift";
839 case AArch64ISD::MOVIedit: return "AArch64ISD::MOVIedit";
840 case AArch64ISD::MOVImsl: return "AArch64ISD::MOVImsl";
841 case AArch64ISD::FMOV: return "AArch64ISD::FMOV";
842 case AArch64ISD::MVNIshift: return "AArch64ISD::MVNIshift";
843 case AArch64ISD::MVNImsl: return "AArch64ISD::MVNImsl";
844 case AArch64ISD::BICi: return "AArch64ISD::BICi";
845 case AArch64ISD::ORRi: return "AArch64ISD::ORRi";
846 case AArch64ISD::BSL: return "AArch64ISD::BSL";
847 case AArch64ISD::NEG: return "AArch64ISD::NEG";
848 case AArch64ISD::EXTR: return "AArch64ISD::EXTR";
849 case AArch64ISD::ZIP1: return "AArch64ISD::ZIP1";
850 case AArch64ISD::ZIP2: return "AArch64ISD::ZIP2";
851 case AArch64ISD::UZP1: return "AArch64ISD::UZP1";
852 case AArch64ISD::UZP2: return "AArch64ISD::UZP2";
853 case AArch64ISD::TRN1: return "AArch64ISD::TRN1";
854 case AArch64ISD::TRN2: return "AArch64ISD::TRN2";
855 case AArch64ISD::REV16: return "AArch64ISD::REV16";
856 case AArch64ISD::REV32: return "AArch64ISD::REV32";
857 case AArch64ISD::REV64: return "AArch64ISD::REV64";
858 case AArch64ISD::EXT: return "AArch64ISD::EXT";
859 case AArch64ISD::VSHL: return "AArch64ISD::VSHL";
860 case AArch64ISD::VLSHR: return "AArch64ISD::VLSHR";
861 case AArch64ISD::VASHR: return "AArch64ISD::VASHR";
862 case AArch64ISD::CMEQ: return "AArch64ISD::CMEQ";
863 case AArch64ISD::CMGE: return "AArch64ISD::CMGE";
864 case AArch64ISD::CMGT: return "AArch64ISD::CMGT";
865 case AArch64ISD::CMHI: return "AArch64ISD::CMHI";
866 case AArch64ISD::CMHS: return "AArch64ISD::CMHS";
867 case AArch64ISD::FCMEQ: return "AArch64ISD::FCMEQ";
868 case AArch64ISD::FCMGE: return "AArch64ISD::FCMGE";
869 case AArch64ISD::FCMGT: return "AArch64ISD::FCMGT";
870 case AArch64ISD::CMEQz: return "AArch64ISD::CMEQz";
871 case AArch64ISD::CMGEz: return "AArch64ISD::CMGEz";
872 case AArch64ISD::CMGTz: return "AArch64ISD::CMGTz";
873 case AArch64ISD::CMLEz: return "AArch64ISD::CMLEz";
874 case AArch64ISD::CMLTz: return "AArch64ISD::CMLTz";
875 case AArch64ISD::FCMEQz: return "AArch64ISD::FCMEQz";
876 case AArch64ISD::FCMGEz: return "AArch64ISD::FCMGEz";
877 case AArch64ISD::FCMGTz: return "AArch64ISD::FCMGTz";
878 case AArch64ISD::FCMLEz: return "AArch64ISD::FCMLEz";
879 case AArch64ISD::FCMLTz: return "AArch64ISD::FCMLTz";
880 case AArch64ISD::SADDV: return "AArch64ISD::SADDV";
881 case AArch64ISD::UADDV: return "AArch64ISD::UADDV";
882 case AArch64ISD::SMINV: return "AArch64ISD::SMINV";
883 case AArch64ISD::UMINV: return "AArch64ISD::UMINV";
884 case AArch64ISD::SMAXV: return "AArch64ISD::SMAXV";
885 case AArch64ISD::UMAXV: return "AArch64ISD::UMAXV";
886 case AArch64ISD::NOT: return "AArch64ISD::NOT";
887 case AArch64ISD::BIT: return "AArch64ISD::BIT";
888 case AArch64ISD::CBZ: return "AArch64ISD::CBZ";
889 case AArch64ISD::CBNZ: return "AArch64ISD::CBNZ";
890 case AArch64ISD::TBZ: return "AArch64ISD::TBZ";
891 case AArch64ISD::TBNZ: return "AArch64ISD::TBNZ";
892 case AArch64ISD::TC_RETURN: return "AArch64ISD::TC_RETURN";
893 case AArch64ISD::PREFETCH: return "AArch64ISD::PREFETCH";
894 case AArch64ISD::SITOF: return "AArch64ISD::SITOF";
895 case AArch64ISD::UITOF: return "AArch64ISD::UITOF";
896 case AArch64ISD::NVCAST: return "AArch64ISD::NVCAST";
897 case AArch64ISD::SQSHL_I: return "AArch64ISD::SQSHL_I";
898 case AArch64ISD::UQSHL_I: return "AArch64ISD::UQSHL_I";
899 case AArch64ISD::SRSHR_I: return "AArch64ISD::SRSHR_I";
900 case AArch64ISD::URSHR_I: return "AArch64ISD::URSHR_I";
901 case AArch64ISD::SQSHLU_I: return "AArch64ISD::SQSHLU_I";
902 case AArch64ISD::WrapperLarge: return "AArch64ISD::WrapperLarge";
903 case AArch64ISD::LD2post: return "AArch64ISD::LD2post";
904 case AArch64ISD::LD3post: return "AArch64ISD::LD3post";
905 case AArch64ISD::LD4post: return "AArch64ISD::LD4post";
906 case AArch64ISD::ST2post: return "AArch64ISD::ST2post";
907 case AArch64ISD::ST3post: return "AArch64ISD::ST3post";
908 case AArch64ISD::ST4post: return "AArch64ISD::ST4post";
909 case AArch64ISD::LD1x2post: return "AArch64ISD::LD1x2post";
910 case AArch64ISD::LD1x3post: return "AArch64ISD::LD1x3post";
911 case AArch64ISD::LD1x4post: return "AArch64ISD::LD1x4post";
912 case AArch64ISD::ST1x2post: return "AArch64ISD::ST1x2post";
913 case AArch64ISD::ST1x3post: return "AArch64ISD::ST1x3post";
914 case AArch64ISD::ST1x4post: return "AArch64ISD::ST1x4post";
915 case AArch64ISD::LD1DUPpost: return "AArch64ISD::LD1DUPpost";
916 case AArch64ISD::LD2DUPpost: return "AArch64ISD::LD2DUPpost";
917 case AArch64ISD::LD3DUPpost: return "AArch64ISD::LD3DUPpost";
918 case AArch64ISD::LD4DUPpost: return "AArch64ISD::LD4DUPpost";
919 case AArch64ISD::LD1LANEpost: return "AArch64ISD::LD1LANEpost";
920 case AArch64ISD::LD2LANEpost: return "AArch64ISD::LD2LANEpost";
921 case AArch64ISD::LD3LANEpost: return "AArch64ISD::LD3LANEpost";
922 case AArch64ISD::LD4LANEpost: return "AArch64ISD::LD4LANEpost";
923 case AArch64ISD::ST2LANEpost: return "AArch64ISD::ST2LANEpost";
924 case AArch64ISD::ST3LANEpost: return "AArch64ISD::ST3LANEpost";
925 case AArch64ISD::ST4LANEpost: return "AArch64ISD::ST4LANEpost";
926 case AArch64ISD::SMULL: return "AArch64ISD::SMULL";
927 case AArch64ISD::UMULL: return "AArch64ISD::UMULL";
933 AArch64TargetLowering::EmitF128CSEL(MachineInstr *MI,
934 MachineBasicBlock *MBB) const {
935 // We materialise the F128CSEL pseudo-instruction as some control flow and a
939 // [... previous instrs leading to comparison ...]
945 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
947 MachineFunction *MF = MBB->getParent();
948 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
949 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
950 DebugLoc DL = MI->getDebugLoc();
951 MachineFunction::iterator It = MBB;
954 unsigned DestReg = MI->getOperand(0).getReg();
955 unsigned IfTrueReg = MI->getOperand(1).getReg();
956 unsigned IfFalseReg = MI->getOperand(2).getReg();
957 unsigned CondCode = MI->getOperand(3).getImm();
958 bool NZCVKilled = MI->getOperand(4).isKill();
960 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
961 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
962 MF->insert(It, TrueBB);
963 MF->insert(It, EndBB);
965 // Transfer rest of current basic-block to EndBB
966 EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
968 EndBB->transferSuccessorsAndUpdatePHIs(MBB);
970 BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
971 BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
972 MBB->addSuccessor(TrueBB);
973 MBB->addSuccessor(EndBB);
975 // TrueBB falls through to the end.
976 TrueBB->addSuccessor(EndBB);
979 TrueBB->addLiveIn(AArch64::NZCV);
980 EndBB->addLiveIn(AArch64::NZCV);
983 BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
989 MI->eraseFromParent();
994 AArch64TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
995 MachineBasicBlock *BB) const {
996 switch (MI->getOpcode()) {
1001 llvm_unreachable("Unexpected instruction for custom inserter!");
1003 case AArch64::F128CSEL:
1004 return EmitF128CSEL(MI, BB);
1006 case TargetOpcode::STACKMAP:
1007 case TargetOpcode::PATCHPOINT:
1008 return emitPatchPoint(MI, BB);
1012 //===----------------------------------------------------------------------===//
1013 // AArch64 Lowering private implementation.
1014 //===----------------------------------------------------------------------===//
1016 //===----------------------------------------------------------------------===//
1018 //===----------------------------------------------------------------------===//
1020 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1022 static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1025 llvm_unreachable("Unknown condition code!");
1027 return AArch64CC::NE;
1029 return AArch64CC::EQ;
1031 return AArch64CC::GT;
1033 return AArch64CC::GE;
1035 return AArch64CC::LT;
1037 return AArch64CC::LE;
1039 return AArch64CC::HI;
1041 return AArch64CC::HS;
1043 return AArch64CC::LO;
1045 return AArch64CC::LS;
1049 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1050 static void changeFPCCToAArch64CC(ISD::CondCode CC,
1051 AArch64CC::CondCode &CondCode,
1052 AArch64CC::CondCode &CondCode2) {
1053 CondCode2 = AArch64CC::AL;
1056 llvm_unreachable("Unknown FP condition!");
1059 CondCode = AArch64CC::EQ;
1063 CondCode = AArch64CC::GT;
1067 CondCode = AArch64CC::GE;
1070 CondCode = AArch64CC::MI;
1073 CondCode = AArch64CC::LS;
1076 CondCode = AArch64CC::MI;
1077 CondCode2 = AArch64CC::GT;
1080 CondCode = AArch64CC::VC;
1083 CondCode = AArch64CC::VS;
1086 CondCode = AArch64CC::EQ;
1087 CondCode2 = AArch64CC::VS;
1090 CondCode = AArch64CC::HI;
1093 CondCode = AArch64CC::PL;
1097 CondCode = AArch64CC::LT;
1101 CondCode = AArch64CC::LE;
1105 CondCode = AArch64CC::NE;
1110 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1111 /// CC usable with the vector instructions. Fewer operations are available
1112 /// without a real NZCV register, so we have to use less efficient combinations
1113 /// to get the same effect.
1114 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1115 AArch64CC::CondCode &CondCode,
1116 AArch64CC::CondCode &CondCode2,
1121 // Mostly the scalar mappings work fine.
1122 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1125 Invert = true; // Fallthrough
1127 CondCode = AArch64CC::MI;
1128 CondCode2 = AArch64CC::GE;
1135 // All of the compare-mask comparisons are ordered, but we can switch
1136 // between the two by a double inversion. E.g. ULE == !OGT.
1138 changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1143 static bool isLegalArithImmed(uint64_t C) {
1144 // Matches AArch64DAGToDAGISel::SelectArithImmed().
1145 return (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1148 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1149 SDLoc dl, SelectionDAG &DAG) {
1150 EVT VT = LHS.getValueType();
1152 if (VT.isFloatingPoint())
1153 return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
1155 // The CMP instruction is just an alias for SUBS, and representing it as
1156 // SUBS means that it's possible to get CSE with subtract operations.
1157 // A later phase can perform the optimization of setting the destination
1158 // register to WZR/XZR if it ends up being unused.
1159 unsigned Opcode = AArch64ISD::SUBS;
1161 if (RHS.getOpcode() == ISD::SUB && isa<ConstantSDNode>(RHS.getOperand(0)) &&
1162 cast<ConstantSDNode>(RHS.getOperand(0))->getZExtValue() == 0 &&
1163 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1164 // We'd like to combine a (CMP op1, (sub 0, op2) into a CMN instruction on
1165 // the grounds that "op1 - (-op2) == op1 + op2". However, the C and V flags
1166 // can be set differently by this operation. It comes down to whether
1167 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1168 // everything is fine. If not then the optimization is wrong. Thus general
1169 // comparisons are only valid if op2 != 0.
1171 // So, finally, the only LLVM-native comparisons that don't mention C and V
1172 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1173 // the absence of information about op2.
1174 Opcode = AArch64ISD::ADDS;
1175 RHS = RHS.getOperand(1);
1176 } else if (LHS.getOpcode() == ISD::AND && isa<ConstantSDNode>(RHS) &&
1177 cast<ConstantSDNode>(RHS)->getZExtValue() == 0 &&
1178 !isUnsignedIntSetCC(CC)) {
1179 // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1180 // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1181 // of the signed comparisons.
1182 Opcode = AArch64ISD::ANDS;
1183 RHS = LHS.getOperand(1);
1184 LHS = LHS.getOperand(0);
1187 return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
1191 /// \defgroup AArch64CCMP CMP;CCMP matching
1193 /// These functions deal with the formation of CMP;CCMP;... sequences.
1194 /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1195 /// a comparison. They set the NZCV flags to a predefined value if their
1196 /// predicate is false. This allows to express arbitrary conjunctions, for
1197 /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B))))"
1200 /// ccmp B, inv(CB), CA
1201 /// check for CB flags
1203 /// In general we can create code for arbitrary "... (and (and A B) C)"
1204 /// sequences. We can also implement some "or" expressions, because "(or A B)"
1205 /// is equivalent to "not (and (not A) (not B))" and we can implement some
1206 /// negation operations:
1207 /// We can negate the results of a single comparison by inverting the flags
1208 /// used when the predicate fails and inverting the flags tested in the next
1209 /// instruction; We can also negate the results of the whole previous
1210 /// conditional compare sequence by inverting the flags tested in the next
1211 /// instruction. However there is no way to negate the result of a partial
1214 /// Therefore on encountering an "or" expression we can negate the subtree on
1215 /// one side and have to be able to push the negate to the leafs of the subtree
1216 /// on the other side (see also the comments in code). As complete example:
1217 /// "or (or (setCA (cmp A)) (setCB (cmp B)))
1218 /// (and (setCC (cmp C)) (setCD (cmp D)))"
1219 /// is transformed to
1220 /// "not (and (not (and (setCC (cmp C)) (setCC (cmp D))))
1221 /// (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1222 /// and implemented as:
1224 /// ccmp D, inv(CD), CC
1225 /// ccmp A, CA, inv(CD)
1226 /// ccmp B, CB, inv(CA)
1227 /// check for CB flags
1228 /// A counterexample is "or (and A B) (and C D)" which cannot be implemented
1229 /// by conditional compare sequences.
1232 /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
1233 static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1234 ISD::CondCode CC, SDValue CCOp,
1235 SDValue Condition, unsigned NZCV,
1236 SDLoc DL, SelectionDAG &DAG) {
1237 unsigned Opcode = 0;
1238 if (LHS.getValueType().isFloatingPoint())
1239 Opcode = AArch64ISD::FCCMP;
1240 else if (RHS.getOpcode() == ISD::SUB) {
1241 SDValue SubOp0 = RHS.getOperand(0);
1242 if (const ConstantSDNode *SubOp0C = dyn_cast<ConstantSDNode>(SubOp0))
1243 if (SubOp0C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1244 // See emitComparison() on why we can only do this for SETEQ and SETNE.
1245 Opcode = AArch64ISD::CCMN;
1246 RHS = RHS.getOperand(1);
1250 Opcode = AArch64ISD::CCMP;
1252 SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1253 return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1256 /// Returns true if @p Val is a tree of AND/OR/SETCC operations.
1257 /// CanPushNegate is set to true if we can push a negate operation through
1258 /// the tree in a was that we are left with AND operations and negate operations
1259 /// at the leafs only. i.e. "not (or (or x y) z)" can be changed to
1260 /// "and (and (not x) (not y)) (not z)"; "not (or (and x y) z)" cannot be
1261 /// brought into such a form.
1262 static bool isConjunctionDisjunctionTree(const SDValue Val, bool &CanPushNegate,
1263 unsigned Depth = 0) {
1264 if (!Val.hasOneUse())
1266 unsigned Opcode = Val->getOpcode();
1267 if (Opcode == ISD::SETCC) {
1268 CanPushNegate = true;
1271 // Protect against stack overflow.
1274 if (Opcode == ISD::AND || Opcode == ISD::OR) {
1275 SDValue O0 = Val->getOperand(0);
1276 SDValue O1 = Val->getOperand(1);
1277 bool CanPushNegateL;
1278 if (!isConjunctionDisjunctionTree(O0, CanPushNegateL, Depth+1))
1280 bool CanPushNegateR;
1281 if (!isConjunctionDisjunctionTree(O1, CanPushNegateR, Depth+1))
1283 // We cannot push a negate through an AND operation (it would become an OR),
1284 // we can however change a (not (or x y)) to (and (not x) (not y)) if we can
1285 // push the negate through the x/y subtrees.
1286 CanPushNegate = (Opcode == ISD::OR) && CanPushNegateL && CanPushNegateR;
1292 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1293 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1294 /// Tries to transform the given i1 producing node @p Val to a series compare
1295 /// and conditional compare operations. @returns an NZCV flags producing node
1296 /// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1297 /// transformation was not possible.
1298 /// On recursive invocations @p PushNegate may be set to true to have negation
1299 /// effects pushed to the tree leafs; @p Predicate is an NZCV flag predicate
1300 /// for the comparisons in the current subtree; @p Depth limits the search
1301 /// depth to avoid stack overflow.
1302 static SDValue emitConjunctionDisjunctionTree(SelectionDAG &DAG, SDValue Val,
1303 AArch64CC::CondCode &OutCC, bool PushNegate = false,
1304 SDValue CCOp = SDValue(), AArch64CC::CondCode Predicate = AArch64CC::AL,
1305 unsigned Depth = 0) {
1306 // We're at a tree leaf, produce a conditional comparison operation.
1307 unsigned Opcode = Val->getOpcode();
1308 if (Opcode == ISD::SETCC) {
1309 SDValue LHS = Val->getOperand(0);
1310 SDValue RHS = Val->getOperand(1);
1311 ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1312 bool isInteger = LHS.getValueType().isInteger();
1314 CC = getSetCCInverse(CC, isInteger);
1316 // Determine OutCC and handle FP special case.
1318 OutCC = changeIntCCToAArch64CC(CC);
1320 assert(LHS.getValueType().isFloatingPoint());
1321 AArch64CC::CondCode ExtraCC;
1322 changeFPCCToAArch64CC(CC, OutCC, ExtraCC);
1323 // Surpisingly some floating point conditions can't be tested with a
1324 // single condition code. Construct an additional comparison in this case.
1325 // See comment below on how we deal with OR conditions.
1326 if (ExtraCC != AArch64CC::AL) {
1328 if (!CCOp.getNode())
1329 ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
1331 SDValue ConditionOp = DAG.getConstant(Predicate, DL, MVT_CC);
1332 // Note that we want the inverse of ExtraCC, so NZCV is not inversed.
1333 unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(ExtraCC);
1334 ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, ConditionOp,
1338 Predicate = AArch64CC::getInvertedCondCode(ExtraCC);
1339 OutCC = AArch64CC::getInvertedCondCode(OutCC);
1343 // Produce a normal comparison if we are first in the chain
1344 if (!CCOp.getNode())
1345 return emitComparison(LHS, RHS, CC, DL, DAG);
1346 // Otherwise produce a ccmp.
1347 SDValue ConditionOp = DAG.getConstant(Predicate, DL, MVT_CC);
1348 AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1349 unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
1350 return emitConditionalComparison(LHS, RHS, CC, CCOp, ConditionOp, NZCV, DL,
1352 } else if ((Opcode != ISD::AND && Opcode != ISD::OR) || !Val->hasOneUse())
1355 assert((Opcode == ISD::OR || !PushNegate)
1356 && "Can only push negate through OR operation");
1358 // Check if both sides can be transformed.
1359 SDValue LHS = Val->getOperand(0);
1360 SDValue RHS = Val->getOperand(1);
1361 bool CanPushNegateL;
1362 if (!isConjunctionDisjunctionTree(LHS, CanPushNegateL, Depth+1))
1364 bool CanPushNegateR;
1365 if (!isConjunctionDisjunctionTree(RHS, CanPushNegateR, Depth+1))
1368 // Do we need to negate our operands?
1369 bool NegateOperands = Opcode == ISD::OR;
1370 // We can negate the results of all previous operations by inverting the
1371 // predicate flags giving us a free negation for one side. For the other side
1372 // we need to be able to push the negation to the leafs of the tree.
1373 if (NegateOperands) {
1374 if (!CanPushNegateL && !CanPushNegateR)
1376 // Order the side where we can push the negate through to LHS.
1377 if (!CanPushNegateL && CanPushNegateR) {
1378 std::swap(LHS, RHS);
1379 CanPushNegateL = true;
1383 // Emit RHS. If we want to negate the tree we only need to push a negate
1384 // through if we are already in a PushNegate case, otherwise we can negate
1385 // the "flags to test" afterwards.
1386 AArch64CC::CondCode RHSCC;
1387 SDValue CmpR = emitConjunctionDisjunctionTree(DAG, RHS, RHSCC, PushNegate,
1388 CCOp, Predicate, Depth+1);
1389 if (NegateOperands && !PushNegate)
1390 RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
1391 // Emit LHS. We must push the negate through if we need to negate it.
1392 SDValue CmpL = emitConjunctionDisjunctionTree(DAG, LHS, OutCC, NegateOperands,
1393 CmpR, RHSCC, Depth+1);
1394 // If we transformed an OR to and AND then we have to negate the result
1395 // (or absorb a PushNegate resulting in a double negation).
1396 if (Opcode == ISD::OR && !PushNegate)
1397 OutCC = AArch64CC::getInvertedCondCode(OutCC);
1403 static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1404 SDValue &AArch64cc, SelectionDAG &DAG, SDLoc dl) {
1405 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1406 EVT VT = RHS.getValueType();
1407 uint64_t C = RHSC->getZExtValue();
1408 if (!isLegalArithImmed(C)) {
1409 // Constant does not fit, try adjusting it by one?
1415 if ((VT == MVT::i32 && C != 0x80000000 &&
1416 isLegalArithImmed((uint32_t)(C - 1))) ||
1417 (VT == MVT::i64 && C != 0x80000000ULL &&
1418 isLegalArithImmed(C - 1ULL))) {
1419 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1420 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1421 RHS = DAG.getConstant(C, dl, VT);
1426 if ((VT == MVT::i32 && C != 0 &&
1427 isLegalArithImmed((uint32_t)(C - 1))) ||
1428 (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1429 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1430 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1431 RHS = DAG.getConstant(C, dl, VT);
1436 if ((VT == MVT::i32 && C != INT32_MAX &&
1437 isLegalArithImmed((uint32_t)(C + 1))) ||
1438 (VT == MVT::i64 && C != INT64_MAX &&
1439 isLegalArithImmed(C + 1ULL))) {
1440 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1441 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1442 RHS = DAG.getConstant(C, dl, VT);
1447 if ((VT == MVT::i32 && C != UINT32_MAX &&
1448 isLegalArithImmed((uint32_t)(C + 1))) ||
1449 (VT == MVT::i64 && C != UINT64_MAX &&
1450 isLegalArithImmed(C + 1ULL))) {
1451 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1452 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1453 RHS = DAG.getConstant(C, dl, VT);
1460 AArch64CC::CondCode AArch64CC;
1461 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
1462 const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
1464 // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
1465 // For the i8 operand, the largest immediate is 255, so this can be easily
1466 // encoded in the compare instruction. For the i16 operand, however, the
1467 // largest immediate cannot be encoded in the compare.
1468 // Therefore, use a sign extending load and cmn to avoid materializing the
1469 // -1 constant. For example,
1471 // ldrh w0, [x0, #0]
1474 // ldrsh w0, [x0, #0]
1476 // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
1477 // if and only if (sext LHS) == (sext RHS). The checks are in place to
1478 // ensure both the LHS and RHS are truly zero extended and to make sure the
1479 // transformation is profitable.
1480 if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
1481 cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
1482 cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
1483 LHS.getNode()->hasNUsesOfValue(1, 0)) {
1484 int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
1485 if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
1487 DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
1488 DAG.getValueType(MVT::i16));
1489 Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
1490 RHS.getValueType()),
1492 AArch64CC = changeIntCCToAArch64CC(CC);
1496 if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
1497 if ((Cmp = emitConjunctionDisjunctionTree(DAG, LHS, AArch64CC))) {
1498 if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
1499 AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
1505 Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
1506 AArch64CC = changeIntCCToAArch64CC(CC);
1508 AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
1512 static std::pair<SDValue, SDValue>
1513 getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
1514 assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
1515 "Unsupported value type");
1516 SDValue Value, Overflow;
1518 SDValue LHS = Op.getOperand(0);
1519 SDValue RHS = Op.getOperand(1);
1521 switch (Op.getOpcode()) {
1523 llvm_unreachable("Unknown overflow instruction!");
1525 Opc = AArch64ISD::ADDS;
1529 Opc = AArch64ISD::ADDS;
1533 Opc = AArch64ISD::SUBS;
1537 Opc = AArch64ISD::SUBS;
1540 // Multiply needs a little bit extra work.
1544 bool IsSigned = Op.getOpcode() == ISD::SMULO;
1545 if (Op.getValueType() == MVT::i32) {
1546 unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1547 // For a 32 bit multiply with overflow check we want the instruction
1548 // selector to generate a widening multiply (SMADDL/UMADDL). For that we
1549 // need to generate the following pattern:
1550 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
1551 LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
1552 RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
1553 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1554 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
1555 DAG.getConstant(0, DL, MVT::i64));
1556 // On AArch64 the upper 32 bits are always zero extended for a 32 bit
1557 // operation. We need to clear out the upper 32 bits, because we used a
1558 // widening multiply that wrote all 64 bits. In the end this should be a
1560 Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
1562 // The signed overflow check requires more than just a simple check for
1563 // any bit set in the upper 32 bits of the result. These bits could be
1564 // just the sign bits of a negative number. To perform the overflow
1565 // check we have to arithmetic shift right the 32nd bit of the result by
1566 // 31 bits. Then we compare the result to the upper 32 bits.
1567 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
1568 DAG.getConstant(32, DL, MVT::i64));
1569 UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
1570 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
1571 DAG.getConstant(31, DL, MVT::i64));
1572 // It is important that LowerBits is last, otherwise the arithmetic
1573 // shift will not be folded into the compare (SUBS).
1574 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
1575 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1578 // The overflow check for unsigned multiply is easy. We only need to
1579 // check if any of the upper 32 bits are set. This can be done with a
1580 // CMP (shifted register). For that we need to generate the following
1582 // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
1583 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
1584 DAG.getConstant(32, DL, MVT::i64));
1585 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1587 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1588 DAG.getConstant(0, DL, MVT::i64),
1589 UpperBits).getValue(1);
1593 assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
1594 // For the 64 bit multiply
1595 Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1597 SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
1598 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
1599 DAG.getConstant(63, DL, MVT::i64));
1600 // It is important that LowerBits is last, otherwise the arithmetic
1601 // shift will not be folded into the compare (SUBS).
1602 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1603 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1606 SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
1607 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1609 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1610 DAG.getConstant(0, DL, MVT::i64),
1611 UpperBits).getValue(1);
1618 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
1620 // Emit the AArch64 operation with overflow check.
1621 Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
1622 Overflow = Value.getValue(1);
1624 return std::make_pair(Value, Overflow);
1627 SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
1628 RTLIB::Libcall Call) const {
1629 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
1630 return makeLibCall(DAG, Call, MVT::f128, &Ops[0], Ops.size(), false,
1634 static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
1635 SDValue Sel = Op.getOperand(0);
1636 SDValue Other = Op.getOperand(1);
1638 // If neither operand is a SELECT_CC, give up.
1639 if (Sel.getOpcode() != ISD::SELECT_CC)
1640 std::swap(Sel, Other);
1641 if (Sel.getOpcode() != ISD::SELECT_CC)
1644 // The folding we want to perform is:
1645 // (xor x, (select_cc a, b, cc, 0, -1) )
1647 // (csel x, (xor x, -1), cc ...)
1649 // The latter will get matched to a CSINV instruction.
1651 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
1652 SDValue LHS = Sel.getOperand(0);
1653 SDValue RHS = Sel.getOperand(1);
1654 SDValue TVal = Sel.getOperand(2);
1655 SDValue FVal = Sel.getOperand(3);
1658 // FIXME: This could be generalized to non-integer comparisons.
1659 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
1662 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
1663 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
1665 // The values aren't constants, this isn't the pattern we're looking for.
1666 if (!CFVal || !CTVal)
1669 // We can commute the SELECT_CC by inverting the condition. This
1670 // might be needed to make this fit into a CSINV pattern.
1671 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
1672 std::swap(TVal, FVal);
1673 std::swap(CTVal, CFVal);
1674 CC = ISD::getSetCCInverse(CC, true);
1677 // If the constants line up, perform the transform!
1678 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
1680 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
1683 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
1684 DAG.getConstant(-1ULL, dl, Other.getValueType()));
1686 return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
1693 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
1694 EVT VT = Op.getValueType();
1696 // Let legalize expand this if it isn't a legal type yet.
1697 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
1700 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
1703 bool ExtraOp = false;
1704 switch (Op.getOpcode()) {
1706 llvm_unreachable("Invalid code");
1708 Opc = AArch64ISD::ADDS;
1711 Opc = AArch64ISD::SUBS;
1714 Opc = AArch64ISD::ADCS;
1718 Opc = AArch64ISD::SBCS;
1724 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
1725 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
1729 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
1730 // Let legalize expand this if it isn't a legal type yet.
1731 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
1735 AArch64CC::CondCode CC;
1736 // The actual operation that sets the overflow or carry flag.
1737 SDValue Value, Overflow;
1738 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
1740 // We use 0 and 1 as false and true values.
1741 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
1742 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
1744 // We use an inverted condition, because the conditional select is inverted
1745 // too. This will allow it to be selected to a single instruction:
1746 // CSINC Wd, WZR, WZR, invert(cond).
1747 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
1748 Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
1751 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
1752 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
1755 // Prefetch operands are:
1756 // 1: Address to prefetch
1758 // 3: int locality (0 = no locality ... 3 = extreme locality)
1759 // 4: bool isDataCache
1760 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
1762 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
1763 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
1764 unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
1766 bool IsStream = !Locality;
1767 // When the locality number is set
1769 // The front-end should have filtered out the out-of-range values
1770 assert(Locality <= 3 && "Prefetch locality out-of-range");
1771 // The locality degree is the opposite of the cache speed.
1772 // Put the number the other way around.
1773 // The encoding starts at 0 for level 1
1774 Locality = 3 - Locality;
1777 // built the mask value encoding the expected behavior.
1778 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit
1779 (!IsData << 3) | // IsDataCache bit
1780 (Locality << 1) | // Cache level bits
1781 (unsigned)IsStream; // Stream bit
1782 return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
1783 DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
1786 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
1787 SelectionDAG &DAG) const {
1788 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
1791 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
1793 return LowerF128Call(Op, DAG, LC);
1796 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
1797 SelectionDAG &DAG) const {
1798 if (Op.getOperand(0).getValueType() != MVT::f128) {
1799 // It's legal except when f128 is involved
1804 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
1806 // FP_ROUND node has a second operand indicating whether it is known to be
1807 // precise. That doesn't take part in the LibCall so we can't directly use
1809 SDValue SrcVal = Op.getOperand(0);
1810 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
1811 /*isSigned*/ false, SDLoc(Op)).first;
1814 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
1815 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1816 // Any additional optimization in this function should be recorded
1817 // in the cost tables.
1818 EVT InVT = Op.getOperand(0).getValueType();
1819 EVT VT = Op.getValueType();
1821 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
1824 DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
1826 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
1829 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
1832 MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
1833 VT.getVectorNumElements());
1834 SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
1835 return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
1838 // Type changing conversions are illegal.
1842 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
1843 SelectionDAG &DAG) const {
1844 if (Op.getOperand(0).getValueType().isVector())
1845 return LowerVectorFP_TO_INT(Op, DAG);
1847 // f16 conversions are promoted to f32.
1848 if (Op.getOperand(0).getValueType() == MVT::f16) {
1851 Op.getOpcode(), dl, Op.getValueType(),
1852 DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
1855 if (Op.getOperand(0).getValueType() != MVT::f128) {
1856 // It's legal except when f128 is involved
1861 if (Op.getOpcode() == ISD::FP_TO_SINT)
1862 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
1864 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
1866 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
1867 return makeLibCall(DAG, LC, Op.getValueType(), &Ops[0], Ops.size(), false,
1871 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
1872 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1873 // Any additional optimization in this function should be recorded
1874 // in the cost tables.
1875 EVT VT = Op.getValueType();
1877 SDValue In = Op.getOperand(0);
1878 EVT InVT = In.getValueType();
1880 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
1882 MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
1883 InVT.getVectorNumElements());
1884 In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
1885 return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
1888 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
1890 Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1891 EVT CastVT = VT.changeVectorElementTypeToInteger();
1892 In = DAG.getNode(CastOpc, dl, CastVT, In);
1893 return DAG.getNode(Op.getOpcode(), dl, VT, In);
1899 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
1900 SelectionDAG &DAG) const {
1901 if (Op.getValueType().isVector())
1902 return LowerVectorINT_TO_FP(Op, DAG);
1904 // f16 conversions are promoted to f32.
1905 if (Op.getValueType() == MVT::f16) {
1908 ISD::FP_ROUND, dl, MVT::f16,
1909 DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
1910 DAG.getIntPtrConstant(0, dl));
1913 // i128 conversions are libcalls.
1914 if (Op.getOperand(0).getValueType() == MVT::i128)
1917 // Other conversions are legal, unless it's to the completely software-based
1919 if (Op.getValueType() != MVT::f128)
1923 if (Op.getOpcode() == ISD::SINT_TO_FP)
1924 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
1926 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
1928 return LowerF128Call(Op, DAG, LC);
1931 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
1932 SelectionDAG &DAG) const {
1933 // For iOS, we want to call an alternative entry point: __sincos_stret,
1934 // which returns the values in two S / D registers.
1936 SDValue Arg = Op.getOperand(0);
1937 EVT ArgVT = Arg.getValueType();
1938 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
1945 Entry.isSExt = false;
1946 Entry.isZExt = false;
1947 Args.push_back(Entry);
1949 const char *LibcallName =
1950 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
1952 DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
1954 StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
1955 TargetLowering::CallLoweringInfo CLI(DAG);
1956 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
1957 .setCallee(CallingConv::Fast, RetTy, Callee, std::move(Args), 0);
1959 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1960 return CallResult.first;
1963 static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
1964 if (Op.getValueType() != MVT::f16)
1967 assert(Op.getOperand(0).getValueType() == MVT::i16);
1970 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
1971 Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
1973 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
1974 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
1978 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
1979 if (OrigVT.getSizeInBits() >= 64)
1982 assert(OrigVT.isSimple() && "Expecting a simple value type");
1984 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
1985 switch (OrigSimpleTy) {
1986 default: llvm_unreachable("Unexpected Vector Type");
1995 static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
1998 unsigned ExtOpcode) {
1999 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2000 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2001 // 64-bits we need to insert a new extension so that it will be 64-bits.
2002 assert(ExtTy.is128BitVector() && "Unexpected extension size");
2003 if (OrigTy.getSizeInBits() >= 64)
2006 // Must extend size to at least 64 bits to be used as an operand for VMULL.
2007 EVT NewVT = getExtensionTo64Bits(OrigTy);
2009 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2012 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2014 EVT VT = N->getValueType(0);
2016 if (N->getOpcode() != ISD::BUILD_VECTOR)
2019 for (const SDValue &Elt : N->op_values()) {
2020 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
2021 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
2022 unsigned HalfSize = EltSize / 2;
2024 if (!isIntN(HalfSize, C->getSExtValue()))
2027 if (!isUIntN(HalfSize, C->getZExtValue()))
2038 static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2039 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2040 return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2041 N->getOperand(0)->getValueType(0),
2045 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2046 EVT VT = N->getValueType(0);
2048 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
2049 unsigned NumElts = VT.getVectorNumElements();
2050 MVT TruncVT = MVT::getIntegerVT(EltSize);
2051 SmallVector<SDValue, 8> Ops;
2052 for (unsigned i = 0; i != NumElts; ++i) {
2053 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2054 const APInt &CInt = C->getAPIntValue();
2055 // Element types smaller than 32 bits are not legal, so use i32 elements.
2056 // The values are implicitly truncated so sext vs. zext doesn't matter.
2057 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
2059 return DAG.getNode(ISD::BUILD_VECTOR, dl,
2060 MVT::getVectorVT(TruncVT, NumElts), Ops);
2063 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
2064 if (N->getOpcode() == ISD::SIGN_EXTEND)
2066 if (isExtendedBUILD_VECTOR(N, DAG, true))
2071 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
2072 if (N->getOpcode() == ISD::ZERO_EXTEND)
2074 if (isExtendedBUILD_VECTOR(N, DAG, false))
2079 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2080 unsigned Opcode = N->getOpcode();
2081 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2082 SDNode *N0 = N->getOperand(0).getNode();
2083 SDNode *N1 = N->getOperand(1).getNode();
2084 return N0->hasOneUse() && N1->hasOneUse() &&
2085 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2090 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2091 unsigned Opcode = N->getOpcode();
2092 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2093 SDNode *N0 = N->getOperand(0).getNode();
2094 SDNode *N1 = N->getOperand(1).getNode();
2095 return N0->hasOneUse() && N1->hasOneUse() &&
2096 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2101 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2102 // Multiplications are only custom-lowered for 128-bit vectors so that
2103 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
2104 EVT VT = Op.getValueType();
2105 assert(VT.is128BitVector() && VT.isInteger() &&
2106 "unexpected type for custom-lowering ISD::MUL");
2107 SDNode *N0 = Op.getOperand(0).getNode();
2108 SDNode *N1 = Op.getOperand(1).getNode();
2109 unsigned NewOpc = 0;
2111 bool isN0SExt = isSignExtended(N0, DAG);
2112 bool isN1SExt = isSignExtended(N1, DAG);
2113 if (isN0SExt && isN1SExt)
2114 NewOpc = AArch64ISD::SMULL;
2116 bool isN0ZExt = isZeroExtended(N0, DAG);
2117 bool isN1ZExt = isZeroExtended(N1, DAG);
2118 if (isN0ZExt && isN1ZExt)
2119 NewOpc = AArch64ISD::UMULL;
2120 else if (isN1SExt || isN1ZExt) {
2121 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2122 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2123 if (isN1SExt && isAddSubSExt(N0, DAG)) {
2124 NewOpc = AArch64ISD::SMULL;
2126 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2127 NewOpc = AArch64ISD::UMULL;
2129 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2131 NewOpc = AArch64ISD::UMULL;
2137 if (VT == MVT::v2i64)
2138 // Fall through to expand this. It is not legal.
2141 // Other vector multiplications are legal.
2146 // Legalize to a S/UMULL instruction
2149 SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2151 Op0 = skipExtensionForVectorMULL(N0, DAG);
2152 assert(Op0.getValueType().is64BitVector() &&
2153 Op1.getValueType().is64BitVector() &&
2154 "unexpected types for extended operands to VMULL");
2155 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2157 // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2158 // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2159 // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2160 SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2161 SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2162 EVT Op1VT = Op1.getValueType();
2163 return DAG.getNode(N0->getOpcode(), DL, VT,
2164 DAG.getNode(NewOpc, DL, VT,
2165 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2166 DAG.getNode(NewOpc, DL, VT,
2167 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2170 SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2171 SelectionDAG &DAG) const {
2172 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2175 default: return SDValue(); // Don't custom lower most intrinsics.
2176 case Intrinsic::aarch64_thread_pointer: {
2177 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2178 return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
2183 SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
2184 SelectionDAG &DAG) const {
2185 switch (Op.getOpcode()) {
2187 llvm_unreachable("unimplemented operand");
2190 return LowerBITCAST(Op, DAG);
2191 case ISD::GlobalAddress:
2192 return LowerGlobalAddress(Op, DAG);
2193 case ISD::GlobalTLSAddress:
2194 return LowerGlobalTLSAddress(Op, DAG);
2196 return LowerSETCC(Op, DAG);
2198 return LowerBR_CC(Op, DAG);
2200 return LowerSELECT(Op, DAG);
2201 case ISD::SELECT_CC:
2202 return LowerSELECT_CC(Op, DAG);
2203 case ISD::JumpTable:
2204 return LowerJumpTable(Op, DAG);
2205 case ISD::ConstantPool:
2206 return LowerConstantPool(Op, DAG);
2207 case ISD::BlockAddress:
2208 return LowerBlockAddress(Op, DAG);
2210 return LowerVASTART(Op, DAG);
2212 return LowerVACOPY(Op, DAG);
2214 return LowerVAARG(Op, DAG);
2219 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
2226 return LowerXALUO(Op, DAG);
2228 return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
2230 return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
2232 return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
2234 return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
2236 return LowerFP_ROUND(Op, DAG);
2237 case ISD::FP_EXTEND:
2238 return LowerFP_EXTEND(Op, DAG);
2239 case ISD::FRAMEADDR:
2240 return LowerFRAMEADDR(Op, DAG);
2241 case ISD::RETURNADDR:
2242 return LowerRETURNADDR(Op, DAG);
2243 case ISD::INSERT_VECTOR_ELT:
2244 return LowerINSERT_VECTOR_ELT(Op, DAG);
2245 case ISD::EXTRACT_VECTOR_ELT:
2246 return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2247 case ISD::BUILD_VECTOR:
2248 return LowerBUILD_VECTOR(Op, DAG);
2249 case ISD::VECTOR_SHUFFLE:
2250 return LowerVECTOR_SHUFFLE(Op, DAG);
2251 case ISD::EXTRACT_SUBVECTOR:
2252 return LowerEXTRACT_SUBVECTOR(Op, DAG);
2256 return LowerVectorSRA_SRL_SHL(Op, DAG);
2257 case ISD::SHL_PARTS:
2258 return LowerShiftLeftParts(Op, DAG);
2259 case ISD::SRL_PARTS:
2260 case ISD::SRA_PARTS:
2261 return LowerShiftRightParts(Op, DAG);
2263 return LowerCTPOP(Op, DAG);
2264 case ISD::FCOPYSIGN:
2265 return LowerFCOPYSIGN(Op, DAG);
2267 return LowerVectorAND(Op, DAG);
2269 return LowerVectorOR(Op, DAG);
2271 return LowerXOR(Op, DAG);
2273 return LowerPREFETCH(Op, DAG);
2274 case ISD::SINT_TO_FP:
2275 case ISD::UINT_TO_FP:
2276 return LowerINT_TO_FP(Op, DAG);
2277 case ISD::FP_TO_SINT:
2278 case ISD::FP_TO_UINT:
2279 return LowerFP_TO_INT(Op, DAG);
2281 return LowerFSINCOS(Op, DAG);
2283 return LowerMUL(Op, DAG);
2284 case ISD::INTRINSIC_WO_CHAIN:
2285 return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2289 /// getFunctionAlignment - Return the Log2 alignment of this function.
2290 unsigned AArch64TargetLowering::getFunctionAlignment(const Function *F) const {
2294 //===----------------------------------------------------------------------===//
2295 // Calling Convention Implementation
2296 //===----------------------------------------------------------------------===//
2298 #include "AArch64GenCallingConv.inc"
2300 /// Selects the correct CCAssignFn for a given CallingConvention value.
2301 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2302 bool IsVarArg) const {
2305 llvm_unreachable("Unsupported calling convention.");
2306 case CallingConv::WebKit_JS:
2307 return CC_AArch64_WebKit_JS;
2308 case CallingConv::GHC:
2309 return CC_AArch64_GHC;
2310 case CallingConv::C:
2311 case CallingConv::Fast:
2312 if (!Subtarget->isTargetDarwin())
2313 return CC_AArch64_AAPCS;
2314 return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
2318 SDValue AArch64TargetLowering::LowerFormalArguments(
2319 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2320 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2321 SmallVectorImpl<SDValue> &InVals) const {
2322 MachineFunction &MF = DAG.getMachineFunction();
2323 MachineFrameInfo *MFI = MF.getFrameInfo();
2325 // Assign locations to all of the incoming arguments.
2326 SmallVector<CCValAssign, 16> ArgLocs;
2327 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2330 // At this point, Ins[].VT may already be promoted to i32. To correctly
2331 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2332 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2333 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
2334 // we use a special version of AnalyzeFormalArguments to pass in ValVT and
2336 unsigned NumArgs = Ins.size();
2337 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2338 unsigned CurArgIdx = 0;
2339 for (unsigned i = 0; i != NumArgs; ++i) {
2340 MVT ValVT = Ins[i].VT;
2341 if (Ins[i].isOrigArg()) {
2342 std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
2343 CurArgIdx = Ins[i].getOrigArgIndex();
2345 // Get type of the original argument.
2346 EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
2347 /*AllowUnknown*/ true);
2348 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
2349 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2350 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2352 else if (ActualMVT == MVT::i16)
2355 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2357 AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
2358 assert(!Res && "Call operand has unhandled type");
2361 assert(ArgLocs.size() == Ins.size());
2362 SmallVector<SDValue, 16> ArgValues;
2363 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2364 CCValAssign &VA = ArgLocs[i];
2366 if (Ins[i].Flags.isByVal()) {
2367 // Byval is used for HFAs in the PCS, but the system should work in a
2368 // non-compliant manner for larger structs.
2369 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2370 int Size = Ins[i].Flags.getByValSize();
2371 unsigned NumRegs = (Size + 7) / 8;
2373 // FIXME: This works on big-endian for composite byvals, which are the common
2374 // case. It should also work for fundamental types too.
2376 MFI->CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
2377 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
2378 InVals.push_back(FrameIdxN);
2383 if (VA.isRegLoc()) {
2384 // Arguments stored in registers.
2385 EVT RegVT = VA.getLocVT();
2388 const TargetRegisterClass *RC;
2390 if (RegVT == MVT::i32)
2391 RC = &AArch64::GPR32RegClass;
2392 else if (RegVT == MVT::i64)
2393 RC = &AArch64::GPR64RegClass;
2394 else if (RegVT == MVT::f16)
2395 RC = &AArch64::FPR16RegClass;
2396 else if (RegVT == MVT::f32)
2397 RC = &AArch64::FPR32RegClass;
2398 else if (RegVT == MVT::f64 || RegVT.is64BitVector())
2399 RC = &AArch64::FPR64RegClass;
2400 else if (RegVT == MVT::f128 || RegVT.is128BitVector())
2401 RC = &AArch64::FPR128RegClass;
2403 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2405 // Transform the arguments in physical registers into virtual ones.
2406 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2407 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2409 // If this is an 8, 16 or 32-bit value, it is really passed promoted
2410 // to 64 bits. Insert an assert[sz]ext to capture this, then
2411 // truncate to the right size.
2412 switch (VA.getLocInfo()) {
2414 llvm_unreachable("Unknown loc info!");
2415 case CCValAssign::Full:
2417 case CCValAssign::BCvt:
2418 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
2420 case CCValAssign::AExt:
2421 case CCValAssign::SExt:
2422 case CCValAssign::ZExt:
2423 // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
2424 // nodes after our lowering.
2425 assert(RegVT == Ins[i].VT && "incorrect register location selected");
2429 InVals.push_back(ArgValue);
2431 } else { // VA.isRegLoc()
2432 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
2433 unsigned ArgOffset = VA.getLocMemOffset();
2434 unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
2436 uint32_t BEAlign = 0;
2437 if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
2438 !Ins[i].Flags.isInConsecutiveRegs())
2439 BEAlign = 8 - ArgSize;
2441 int FI = MFI->CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
2443 // Create load nodes to retrieve arguments from the stack.
2444 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2447 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
2448 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
2449 MVT MemVT = VA.getValVT();
2451 switch (VA.getLocInfo()) {
2454 case CCValAssign::BCvt:
2455 MemVT = VA.getLocVT();
2457 case CCValAssign::SExt:
2458 ExtType = ISD::SEXTLOAD;
2460 case CCValAssign::ZExt:
2461 ExtType = ISD::ZEXTLOAD;
2463 case CCValAssign::AExt:
2464 ExtType = ISD::EXTLOAD;
2468 ArgValue = DAG.getExtLoad(
2469 ExtType, DL, VA.getLocVT(), Chain, FIN,
2470 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
2471 MemVT, false, false, false, 0);
2473 InVals.push_back(ArgValue);
2479 if (!Subtarget->isTargetDarwin()) {
2480 // The AAPCS variadic function ABI is identical to the non-variadic
2481 // one. As a result there may be more arguments in registers and we should
2482 // save them for future reference.
2483 saveVarArgRegisters(CCInfo, DAG, DL, Chain);
2486 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
2487 // This will point to the next argument passed via stack.
2488 unsigned StackOffset = CCInfo.getNextStackOffset();
2489 // We currently pass all varargs at 8-byte alignment.
2490 StackOffset = ((StackOffset + 7) & ~7);
2491 AFI->setVarArgsStackIndex(MFI->CreateFixedObject(4, StackOffset, true));
2494 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2495 unsigned StackArgSize = CCInfo.getNextStackOffset();
2496 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2497 if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
2498 // This is a non-standard ABI so by fiat I say we're allowed to make full
2499 // use of the stack area to be popped, which must be aligned to 16 bytes in
2501 StackArgSize = RoundUpToAlignment(StackArgSize, 16);
2503 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
2504 // a multiple of 16.
2505 FuncInfo->setArgumentStackToRestore(StackArgSize);
2507 // This realignment carries over to the available bytes below. Our own
2508 // callers will guarantee the space is free by giving an aligned value to
2511 // Even if we're not expected to free up the space, it's useful to know how
2512 // much is there while considering tail calls (because we can reuse it).
2513 FuncInfo->setBytesInStackArgArea(StackArgSize);
2518 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
2519 SelectionDAG &DAG, SDLoc DL,
2520 SDValue &Chain) const {
2521 MachineFunction &MF = DAG.getMachineFunction();
2522 MachineFrameInfo *MFI = MF.getFrameInfo();
2523 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2524 auto PtrVT = getPointerTy(DAG.getDataLayout());
2526 SmallVector<SDValue, 8> MemOps;
2528 static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
2529 AArch64::X3, AArch64::X4, AArch64::X5,
2530 AArch64::X6, AArch64::X7 };
2531 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
2532 unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
2534 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
2536 if (GPRSaveSize != 0) {
2537 GPRIdx = MFI->CreateStackObject(GPRSaveSize, 8, false);
2539 SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
2541 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
2542 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
2543 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
2544 SDValue Store = DAG.getStore(
2545 Val.getValue(1), DL, Val, FIN,
2546 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8), false,
2548 MemOps.push_back(Store);
2550 DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
2553 FuncInfo->setVarArgsGPRIndex(GPRIdx);
2554 FuncInfo->setVarArgsGPRSize(GPRSaveSize);
2556 if (Subtarget->hasFPARMv8()) {
2557 static const MCPhysReg FPRArgRegs[] = {
2558 AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
2559 AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
2560 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
2561 unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
2563 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
2565 if (FPRSaveSize != 0) {
2566 FPRIdx = MFI->CreateStackObject(FPRSaveSize, 16, false);
2568 SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
2570 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
2571 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
2572 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
2574 SDValue Store = DAG.getStore(
2575 Val.getValue(1), DL, Val, FIN,
2576 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16),
2578 MemOps.push_back(Store);
2579 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
2580 DAG.getConstant(16, DL, PtrVT));
2583 FuncInfo->setVarArgsFPRIndex(FPRIdx);
2584 FuncInfo->setVarArgsFPRSize(FPRSaveSize);
2587 if (!MemOps.empty()) {
2588 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
2592 /// LowerCallResult - Lower the result values of a call into the
2593 /// appropriate copies out of appropriate physical registers.
2594 SDValue AArch64TargetLowering::LowerCallResult(
2595 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
2596 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2597 SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
2598 SDValue ThisVal) const {
2599 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
2600 ? RetCC_AArch64_WebKit_JS
2601 : RetCC_AArch64_AAPCS;
2602 // Assign locations to each value returned by this call.
2603 SmallVector<CCValAssign, 16> RVLocs;
2604 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2606 CCInfo.AnalyzeCallResult(Ins, RetCC);
2608 // Copy all of the result registers out of their specified physreg.
2609 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2610 CCValAssign VA = RVLocs[i];
2612 // Pass 'this' value directly from the argument to return value, to avoid
2613 // reg unit interference
2614 if (i == 0 && isThisReturn) {
2615 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
2616 "unexpected return calling convention register assignment");
2617 InVals.push_back(ThisVal);
2622 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2623 Chain = Val.getValue(1);
2624 InFlag = Val.getValue(2);
2626 switch (VA.getLocInfo()) {
2628 llvm_unreachable("Unknown loc info!");
2629 case CCValAssign::Full:
2631 case CCValAssign::BCvt:
2632 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2636 InVals.push_back(Val);
2642 bool AArch64TargetLowering::isEligibleForTailCallOptimization(
2643 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
2644 bool isCalleeStructRet, bool isCallerStructRet,
2645 const SmallVectorImpl<ISD::OutputArg> &Outs,
2646 const SmallVectorImpl<SDValue> &OutVals,
2647 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2648 // For CallingConv::C this function knows whether the ABI needs
2649 // changing. That's not true for other conventions so they will have to opt in
2651 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
2654 const MachineFunction &MF = DAG.getMachineFunction();
2655 const Function *CallerF = MF.getFunction();
2656 CallingConv::ID CallerCC = CallerF->getCallingConv();
2657 bool CCMatch = CallerCC == CalleeCC;
2659 // Byval parameters hand the function a pointer directly into the stack area
2660 // we want to reuse during a tail call. Working around this *is* possible (see
2661 // X86) but less efficient and uglier in LowerCall.
2662 for (Function::const_arg_iterator i = CallerF->arg_begin(),
2663 e = CallerF->arg_end();
2665 if (i->hasByValAttr())
2668 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2669 if (IsTailCallConvention(CalleeCC) && CCMatch)
2674 // Externally-defined functions with weak linkage should not be
2675 // tail-called on AArch64 when the OS does not support dynamic
2676 // pre-emption of symbols, as the AAELF spec requires normal calls
2677 // to undefined weak functions to be replaced with a NOP or jump to the
2678 // next instruction. The behaviour of branch instructions in this
2679 // situation (as used for tail calls) is implementation-defined, so we
2680 // cannot rely on the linker replacing the tail call with a return.
2681 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2682 const GlobalValue *GV = G->getGlobal();
2683 const Triple &TT = getTargetMachine().getTargetTriple();
2684 if (GV->hasExternalWeakLinkage() &&
2685 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2689 // Now we search for cases where we can use a tail call without changing the
2690 // ABI. Sibcall is used in some places (particularly gcc) to refer to this
2693 // I want anyone implementing a new calling convention to think long and hard
2694 // about this assert.
2695 assert((!isVarArg || CalleeCC == CallingConv::C) &&
2696 "Unexpected variadic calling convention");
2698 if (isVarArg && !Outs.empty()) {
2699 // At least two cases here: if caller is fastcc then we can't have any
2700 // memory arguments (we'd be expected to clean up the stack afterwards). If
2701 // caller is C then we could potentially use its argument area.
2703 // FIXME: for now we take the most conservative of these in both cases:
2704 // disallow all variadic memory operands.
2705 SmallVector<CCValAssign, 16> ArgLocs;
2706 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2709 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
2710 for (const CCValAssign &ArgLoc : ArgLocs)
2711 if (!ArgLoc.isRegLoc())
2715 // If the calling conventions do not match, then we'd better make sure the
2716 // results are returned in the same way as what the caller expects.
2718 SmallVector<CCValAssign, 16> RVLocs1;
2719 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2721 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForCall(CalleeCC, isVarArg));
2723 SmallVector<CCValAssign, 16> RVLocs2;
2724 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2726 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForCall(CallerCC, isVarArg));
2728 if (RVLocs1.size() != RVLocs2.size())
2730 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2731 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2733 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2735 if (RVLocs1[i].isRegLoc()) {
2736 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2739 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2745 // Nothing more to check if the callee is taking no arguments
2749 SmallVector<CCValAssign, 16> ArgLocs;
2750 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2753 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2755 const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2757 // If the stack arguments for this call would fit into our own save area then
2758 // the call can be made tail.
2759 return CCInfo.getNextStackOffset() <= FuncInfo->getBytesInStackArgArea();
2762 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
2764 MachineFrameInfo *MFI,
2765 int ClobberedFI) const {
2766 SmallVector<SDValue, 8> ArgChains;
2767 int64_t FirstByte = MFI->getObjectOffset(ClobberedFI);
2768 int64_t LastByte = FirstByte + MFI->getObjectSize(ClobberedFI) - 1;
2770 // Include the original chain at the beginning of the list. When this is
2771 // used by target LowerCall hooks, this helps legalize find the
2772 // CALLSEQ_BEGIN node.
2773 ArgChains.push_back(Chain);
2775 // Add a chain value for each stack argument corresponding
2776 for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
2777 UE = DAG.getEntryNode().getNode()->use_end();
2779 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
2780 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
2781 if (FI->getIndex() < 0) {
2782 int64_t InFirstByte = MFI->getObjectOffset(FI->getIndex());
2783 int64_t InLastByte = InFirstByte;
2784 InLastByte += MFI->getObjectSize(FI->getIndex()) - 1;
2786 if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
2787 (FirstByte <= InFirstByte && InFirstByte <= LastByte))
2788 ArgChains.push_back(SDValue(L, 1));
2791 // Build a tokenfactor for all the chains.
2792 return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
2795 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
2796 bool TailCallOpt) const {
2797 return CallCC == CallingConv::Fast && TailCallOpt;
2800 bool AArch64TargetLowering::IsTailCallConvention(CallingConv::ID CallCC) const {
2801 return CallCC == CallingConv::Fast;
2804 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
2805 /// and add input and output parameter nodes.
2807 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
2808 SmallVectorImpl<SDValue> &InVals) const {
2809 SelectionDAG &DAG = CLI.DAG;
2811 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2812 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2813 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2814 SDValue Chain = CLI.Chain;
2815 SDValue Callee = CLI.Callee;
2816 bool &IsTailCall = CLI.IsTailCall;
2817 CallingConv::ID CallConv = CLI.CallConv;
2818 bool IsVarArg = CLI.IsVarArg;
2820 MachineFunction &MF = DAG.getMachineFunction();
2821 bool IsStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
2822 bool IsThisReturn = false;
2824 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2825 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2826 bool IsSibCall = false;
2829 // Check if it's really possible to do a tail call.
2830 IsTailCall = isEligibleForTailCallOptimization(
2831 Callee, CallConv, IsVarArg, IsStructRet,
2832 MF.getFunction()->hasStructRetAttr(), Outs, OutVals, Ins, DAG);
2833 if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
2834 report_fatal_error("failed to perform tail call elimination on a call "
2835 "site marked musttail");
2837 // A sibling call is one where we're under the usual C ABI and not planning
2838 // to change that but can still do a tail call:
2839 if (!TailCallOpt && IsTailCall)
2846 // Analyze operands of the call, assigning locations to each operand.
2847 SmallVector<CCValAssign, 16> ArgLocs;
2848 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
2852 // Handle fixed and variable vector arguments differently.
2853 // Variable vector arguments always go into memory.
2854 unsigned NumArgs = Outs.size();
2856 for (unsigned i = 0; i != NumArgs; ++i) {
2857 MVT ArgVT = Outs[i].VT;
2858 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2859 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
2860 /*IsVarArg=*/ !Outs[i].IsFixed);
2861 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
2862 assert(!Res && "Call operand has unhandled type");
2866 // At this point, Outs[].VT may already be promoted to i32. To correctly
2867 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2868 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2869 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
2870 // we use a special version of AnalyzeCallOperands to pass in ValVT and
2872 unsigned NumArgs = Outs.size();
2873 for (unsigned i = 0; i != NumArgs; ++i) {
2874 MVT ValVT = Outs[i].VT;
2875 // Get type of the original argument.
2876 EVT ActualVT = getValueType(DAG.getDataLayout(),
2877 CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
2878 /*AllowUnknown*/ true);
2879 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
2880 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2881 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2882 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2884 else if (ActualMVT == MVT::i16)
2887 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2888 bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
2889 assert(!Res && "Call operand has unhandled type");
2894 // Get a count of how many bytes are to be pushed on the stack.
2895 unsigned NumBytes = CCInfo.getNextStackOffset();
2898 // Since we're not changing the ABI to make this a tail call, the memory
2899 // operands are already available in the caller's incoming argument space.
2903 // FPDiff is the byte offset of the call's argument area from the callee's.
2904 // Stores to callee stack arguments will be placed in FixedStackSlots offset
2905 // by this amount for a tail call. In a sibling call it must be 0 because the
2906 // caller will deallocate the entire stack and the callee still expects its
2907 // arguments to begin at SP+0. Completely unused for non-tail calls.
2910 if (IsTailCall && !IsSibCall) {
2911 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
2913 // Since callee will pop argument stack as a tail call, we must keep the
2914 // popped size 16-byte aligned.
2915 NumBytes = RoundUpToAlignment(NumBytes, 16);
2917 // FPDiff will be negative if this tail call requires more space than we
2918 // would automatically have in our incoming argument space. Positive if we
2919 // can actually shrink the stack.
2920 FPDiff = NumReusableBytes - NumBytes;
2922 // The stack pointer must be 16-byte aligned at all times it's used for a
2923 // memory operation, which in practice means at *all* times and in
2924 // particular across call boundaries. Therefore our own arguments started at
2925 // a 16-byte aligned SP and the delta applied for the tail call should
2926 // satisfy the same constraint.
2927 assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
2930 // Adjust the stack pointer for the new arguments...
2931 // These operations are automatically eliminated by the prolog/epilog pass
2933 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, DL,
2937 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
2938 getPointerTy(DAG.getDataLayout()));
2940 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2941 SmallVector<SDValue, 8> MemOpChains;
2942 auto PtrVT = getPointerTy(DAG.getDataLayout());
2944 // Walk the register/memloc assignments, inserting copies/loads.
2945 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
2946 ++i, ++realArgIdx) {
2947 CCValAssign &VA = ArgLocs[i];
2948 SDValue Arg = OutVals[realArgIdx];
2949 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2951 // Promote the value if needed.
2952 switch (VA.getLocInfo()) {
2954 llvm_unreachable("Unknown loc info!");
2955 case CCValAssign::Full:
2957 case CCValAssign::SExt:
2958 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2960 case CCValAssign::ZExt:
2961 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2963 case CCValAssign::AExt:
2964 if (Outs[realArgIdx].ArgVT == MVT::i1) {
2965 // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
2966 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
2967 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
2969 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2971 case CCValAssign::BCvt:
2972 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2974 case CCValAssign::FPExt:
2975 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
2979 if (VA.isRegLoc()) {
2980 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i64) {
2981 assert(VA.getLocVT() == MVT::i64 &&
2982 "unexpected calling convention register assignment");
2983 assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
2984 "unexpected use of 'returned'");
2985 IsThisReturn = true;
2987 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2989 assert(VA.isMemLoc());
2992 MachinePointerInfo DstInfo;
2994 // FIXME: This works on big-endian for composite byvals, which are the
2995 // common case. It should also work for fundamental types too.
2996 uint32_t BEAlign = 0;
2997 unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
2998 : VA.getValVT().getSizeInBits();
2999 OpSize = (OpSize + 7) / 8;
3000 if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
3001 !Flags.isInConsecutiveRegs()) {
3003 BEAlign = 8 - OpSize;
3005 unsigned LocMemOffset = VA.getLocMemOffset();
3006 int32_t Offset = LocMemOffset + BEAlign;
3007 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3008 PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3011 Offset = Offset + FPDiff;
3012 int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3014 DstAddr = DAG.getFrameIndex(FI, PtrVT);
3016 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
3018 // Make sure any stack arguments overlapping with where we're storing
3019 // are loaded before this eventual operation. Otherwise they'll be
3021 Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
3023 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3025 DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3026 DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
3030 if (Outs[i].Flags.isByVal()) {
3032 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
3033 SDValue Cpy = DAG.getMemcpy(
3034 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
3035 /*isVol = */ false, /*AlwaysInline = */ false,
3036 /*isTailCall = */ false,
3037 DstInfo, MachinePointerInfo());
3039 MemOpChains.push_back(Cpy);
3041 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
3042 // promoted to a legal register type i32, we should truncate Arg back to
3044 if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
3045 VA.getValVT() == MVT::i16)
3046 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
3049 DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, false, false, 0);
3050 MemOpChains.push_back(Store);
3055 if (!MemOpChains.empty())
3056 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3058 // Build a sequence of copy-to-reg nodes chained together with token chain
3059 // and flag operands which copy the outgoing args into the appropriate regs.
3061 for (auto &RegToPass : RegsToPass) {
3062 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3063 RegToPass.second, InFlag);
3064 InFlag = Chain.getValue(1);
3067 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3068 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3069 // node so that legalize doesn't hack it.
3070 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3071 Subtarget->isTargetMachO()) {
3072 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3073 const GlobalValue *GV = G->getGlobal();
3074 bool InternalLinkage = GV->hasInternalLinkage();
3075 if (InternalLinkage)
3076 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3079 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT);
3080 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3082 } else if (ExternalSymbolSDNode *S =
3083 dyn_cast<ExternalSymbolSDNode>(Callee)) {
3084 const char *Sym = S->getSymbol();
3085 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
3086 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3088 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3089 const GlobalValue *GV = G->getGlobal();
3090 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3091 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3092 const char *Sym = S->getSymbol();
3093 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
3096 // We don't usually want to end the call-sequence here because we would tidy
3097 // the frame up *after* the call, however in the ABI-changing tail-call case
3098 // we've carefully laid out the parameters so that when sp is reset they'll be
3099 // in the correct location.
3100 if (IsTailCall && !IsSibCall) {
3101 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3102 DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
3103 InFlag = Chain.getValue(1);
3106 std::vector<SDValue> Ops;
3107 Ops.push_back(Chain);
3108 Ops.push_back(Callee);
3111 // Each tail call may have to adjust the stack by a different amount, so
3112 // this information must travel along with the operation for eventual
3113 // consumption by emitEpilogue.
3114 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3117 // Add argument registers to the end of the list so that they are known live
3119 for (auto &RegToPass : RegsToPass)
3120 Ops.push_back(DAG.getRegister(RegToPass.first,
3121 RegToPass.second.getValueType()));
3123 // Add a register mask operand representing the call-preserved registers.
3124 const uint32_t *Mask;
3125 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3127 // For 'this' returns, use the X0-preserving mask if applicable
3128 Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
3130 IsThisReturn = false;
3131 Mask = TRI->getCallPreservedMask(MF, CallConv);
3134 Mask = TRI->getCallPreservedMask(MF, CallConv);
3136 assert(Mask && "Missing call preserved mask for calling convention");
3137 Ops.push_back(DAG.getRegisterMask(Mask));
3139 if (InFlag.getNode())
3140 Ops.push_back(InFlag);
3142 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3144 // If we're doing a tall call, use a TC_RETURN here rather than an
3145 // actual call instruction.
3147 MF.getFrameInfo()->setHasTailCall();
3148 return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
3151 // Returns a chain and a flag for retval copy to use.
3152 Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
3153 InFlag = Chain.getValue(1);
3155 uint64_t CalleePopBytes = DoesCalleeRestoreStack(CallConv, TailCallOpt)
3156 ? RoundUpToAlignment(NumBytes, 16)
3159 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3160 DAG.getIntPtrConstant(CalleePopBytes, DL, true),
3163 InFlag = Chain.getValue(1);
3165 // Handle result values, copying them out of physregs into vregs that we
3167 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3168 InVals, IsThisReturn,
3169 IsThisReturn ? OutVals[0] : SDValue());
3172 bool AArch64TargetLowering::CanLowerReturn(
3173 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
3174 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
3175 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3176 ? RetCC_AArch64_WebKit_JS
3177 : RetCC_AArch64_AAPCS;
3178 SmallVector<CCValAssign, 16> RVLocs;
3179 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
3180 return CCInfo.CheckReturn(Outs, RetCC);
3184 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3186 const SmallVectorImpl<ISD::OutputArg> &Outs,
3187 const SmallVectorImpl<SDValue> &OutVals,
3188 SDLoc DL, SelectionDAG &DAG) const {
3189 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3190 ? RetCC_AArch64_WebKit_JS
3191 : RetCC_AArch64_AAPCS;
3192 SmallVector<CCValAssign, 16> RVLocs;
3193 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3195 CCInfo.AnalyzeReturn(Outs, RetCC);
3197 // Copy the result values into the output registers.
3199 SmallVector<SDValue, 4> RetOps(1, Chain);
3200 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
3201 ++i, ++realRVLocIdx) {
3202 CCValAssign &VA = RVLocs[i];
3203 assert(VA.isRegLoc() && "Can only return in registers!");
3204 SDValue Arg = OutVals[realRVLocIdx];
3206 switch (VA.getLocInfo()) {
3208 llvm_unreachable("Unknown loc info!");
3209 case CCValAssign::Full:
3210 if (Outs[i].ArgVT == MVT::i1) {
3211 // AAPCS requires i1 to be zero-extended to i8 by the producer of the
3212 // value. This is strictly redundant on Darwin (which uses "zeroext
3213 // i1"), but will be optimised out before ISel.
3214 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3215 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3218 case CCValAssign::BCvt:
3219 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3223 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
3224 Flag = Chain.getValue(1);
3225 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3228 RetOps[0] = Chain; // Update chain.
3230 // Add the flag if we have it.
3232 RetOps.push_back(Flag);
3234 return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
3237 //===----------------------------------------------------------------------===//
3238 // Other Lowering Code
3239 //===----------------------------------------------------------------------===//
3241 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
3242 SelectionDAG &DAG) const {
3243 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3245 const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
3246 const GlobalValue *GV = GN->getGlobal();
3247 unsigned char OpFlags =
3248 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
3250 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
3251 "unexpected offset in global node");
3253 // This also catched the large code model case for Darwin.
3254 if ((OpFlags & AArch64II::MO_GOT) != 0) {
3255 SDValue GotAddr = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
3256 // FIXME: Once remat is capable of dealing with instructions with register
3257 // operands, expand this into two nodes instead of using a wrapper node.
3258 return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
3261 if ((OpFlags & AArch64II::MO_CONSTPOOL) != 0) {
3262 assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
3263 "use of MO_CONSTPOOL only supported on small model");
3264 SDValue Hi = DAG.getTargetConstantPool(GV, PtrVT, 0, 0, AArch64II::MO_PAGE);
3265 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3266 unsigned char LoFlags = AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
3267 SDValue Lo = DAG.getTargetConstantPool(GV, PtrVT, 0, 0, LoFlags);
3268 SDValue PoolAddr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3269 SDValue GlobalAddr = DAG.getLoad(
3270 PtrVT, DL, DAG.getEntryNode(), PoolAddr,
3271 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
3272 /*isVolatile=*/false,
3273 /*isNonTemporal=*/true,
3274 /*isInvariant=*/true, 8);
3275 if (GN->getOffset() != 0)
3276 return DAG.getNode(ISD::ADD, DL, PtrVT, GlobalAddr,
3277 DAG.getConstant(GN->getOffset(), DL, PtrVT));
3281 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
3282 const unsigned char MO_NC = AArch64II::MO_NC;
3284 AArch64ISD::WrapperLarge, DL, PtrVT,
3285 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G3),
3286 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
3287 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
3288 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
3290 // Use ADRP/ADD or ADRP/LDR for everything else: the small model on ELF and
3291 // the only correct model on Darwin.
3292 SDValue Hi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
3293 OpFlags | AArch64II::MO_PAGE);
3294 unsigned char LoFlags = OpFlags | AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
3295 SDValue Lo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, LoFlags);
3297 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3298 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3302 /// \brief Convert a TLS address reference into the correct sequence of loads
3303 /// and calls to compute the variable's address (for Darwin, currently) and
3304 /// return an SDValue containing the final node.
3306 /// Darwin only has one TLS scheme which must be capable of dealing with the
3307 /// fully general situation, in the worst case. This means:
3308 /// + "extern __thread" declaration.
3309 /// + Defined in a possibly unknown dynamic library.
3311 /// The general system is that each __thread variable has a [3 x i64] descriptor
3312 /// which contains information used by the runtime to calculate the address. The
3313 /// only part of this the compiler needs to know about is the first xword, which
3314 /// contains a function pointer that must be called with the address of the
3315 /// entire descriptor in "x0".
3317 /// Since this descriptor may be in a different unit, in general even the
3318 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
3320 /// adrp x0, _var@TLVPPAGE
3321 /// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor
3322 /// ldr x1, [x0] ; x1 contains 1st entry of descriptor,
3323 /// ; the function pointer
3324 /// blr x1 ; Uses descriptor address in x0
3325 /// ; Address of _var is now in x0.
3327 /// If the address of _var's descriptor *is* known to the linker, then it can
3328 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
3329 /// a slight efficiency gain.
3331 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
3332 SelectionDAG &DAG) const {
3333 assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
3336 MVT PtrVT = getPointerTy(DAG.getDataLayout());
3337 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3340 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3341 SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
3343 // The first entry in the descriptor is a function pointer that we must call
3344 // to obtain the address of the variable.
3345 SDValue Chain = DAG.getEntryNode();
3346 SDValue FuncTLVGet =
3347 DAG.getLoad(MVT::i64, DL, Chain, DescAddr,
3348 MachinePointerInfo::getGOT(DAG.getMachineFunction()), false,
3350 Chain = FuncTLVGet.getValue(1);
3352 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3353 MFI->setAdjustsStack(true);
3355 // TLS calls preserve all registers except those that absolutely must be
3356 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
3358 const uint32_t *Mask =
3359 Subtarget->getRegisterInfo()->getTLSCallPreservedMask();
3361 // Finally, we can make the call. This is just a degenerate version of a
3362 // normal AArch64 call node: x0 takes the address of the descriptor, and
3363 // returns the address of the variable in this thread.
3364 Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
3366 DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3367 Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
3368 DAG.getRegisterMask(Mask), Chain.getValue(1));
3369 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
3372 /// When accessing thread-local variables under either the general-dynamic or
3373 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
3374 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
3375 /// is a function pointer to carry out the resolution.
3377 /// The sequence is:
3378 /// adrp x0, :tlsdesc:var
3379 /// ldr x1, [x0, #:tlsdesc_lo12:var]
3380 /// add x0, x0, #:tlsdesc_lo12:var
3381 /// .tlsdesccall var
3383 /// (TPIDR_EL0 offset now in x0)
3385 /// The above sequence must be produced unscheduled, to enable the linker to
3386 /// optimize/relax this sequence.
3387 /// Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
3388 /// above sequence, and expanded really late in the compilation flow, to ensure
3389 /// the sequence is produced as per above.
3390 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr, SDLoc DL,
3391 SelectionDAG &DAG) const {
3392 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3394 SDValue Chain = DAG.getEntryNode();
3395 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3397 SmallVector<SDValue, 2> Ops;
3398 Ops.push_back(Chain);
3399 Ops.push_back(SymAddr);
3401 Chain = DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, Ops);
3402 SDValue Glue = Chain.getValue(1);
3404 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
3408 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
3409 SelectionDAG &DAG) const {
3410 assert(Subtarget->isTargetELF() && "This function expects an ELF target");
3411 assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
3412 "ELF TLS only supported in small memory model");
3413 // Different choices can be made for the maximum size of the TLS area for a
3414 // module. For the small address model, the default TLS size is 16MiB and the
3415 // maximum TLS size is 4GiB.
3416 // FIXME: add -mtls-size command line option and make it control the 16MiB
3417 // vs. 4GiB code sequence generation.
3418 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3420 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
3422 if (DAG.getTarget().Options.EmulatedTLS)
3423 return LowerToTLSEmulatedModel(GA, DAG);
3425 if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
3426 if (Model == TLSModel::LocalDynamic)
3427 Model = TLSModel::GeneralDynamic;
3431 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3433 const GlobalValue *GV = GA->getGlobal();
3435 SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
3437 if (Model == TLSModel::LocalExec) {
3438 SDValue HiVar = DAG.getTargetGlobalAddress(
3439 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
3440 SDValue LoVar = DAG.getTargetGlobalAddress(
3442 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3444 SDValue TPWithOff_lo =
3445 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
3447 DAG.getTargetConstant(0, DL, MVT::i32)),
3450 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
3452 DAG.getTargetConstant(0, DL, MVT::i32)),
3455 } else if (Model == TLSModel::InitialExec) {
3456 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3457 TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
3458 } else if (Model == TLSModel::LocalDynamic) {
3459 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
3460 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
3461 // the beginning of the module's TLS region, followed by a DTPREL offset
3464 // These accesses will need deduplicating if there's more than one.
3465 AArch64FunctionInfo *MFI =
3466 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
3467 MFI->incNumLocalDynamicTLSAccesses();
3469 // The call needs a relocation too for linker relaxation. It doesn't make
3470 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3472 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
3475 // Now we can calculate the offset from TPIDR_EL0 to this module's
3476 // thread-local area.
3477 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
3479 // Now use :dtprel_whatever: operations to calculate this variable's offset
3480 // in its thread-storage area.
3481 SDValue HiVar = DAG.getTargetGlobalAddress(
3482 GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
3483 SDValue LoVar = DAG.getTargetGlobalAddress(
3484 GV, DL, MVT::i64, 0,
3485 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3487 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
3488 DAG.getTargetConstant(0, DL, MVT::i32)),
3490 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
3491 DAG.getTargetConstant(0, DL, MVT::i32)),
3493 } else if (Model == TLSModel::GeneralDynamic) {
3494 // The call needs a relocation too for linker relaxation. It doesn't make
3495 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3498 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3500 // Finally we can make a call to calculate the offset from tpidr_el0.
3501 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
3503 llvm_unreachable("Unsupported ELF TLS access model");
3505 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
3508 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
3509 SelectionDAG &DAG) const {
3510 if (Subtarget->isTargetDarwin())
3511 return LowerDarwinGlobalTLSAddress(Op, DAG);
3512 else if (Subtarget->isTargetELF())
3513 return LowerELFGlobalTLSAddress(Op, DAG);
3515 llvm_unreachable("Unexpected platform trying to use TLS");
3517 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3518 SDValue Chain = Op.getOperand(0);
3519 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3520 SDValue LHS = Op.getOperand(2);
3521 SDValue RHS = Op.getOperand(3);
3522 SDValue Dest = Op.getOperand(4);
3525 // Handle f128 first, since lowering it will result in comparing the return
3526 // value of a libcall against zero, which is just what the rest of LowerBR_CC
3527 // is expecting to deal with.
3528 if (LHS.getValueType() == MVT::f128) {
3529 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3531 // If softenSetCCOperands returned a scalar, we need to compare the result
3532 // against zero to select between true and false values.
3533 if (!RHS.getNode()) {
3534 RHS = DAG.getConstant(0, dl, LHS.getValueType());
3539 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
3541 unsigned Opc = LHS.getOpcode();
3542 if (LHS.getResNo() == 1 && isa<ConstantSDNode>(RHS) &&
3543 cast<ConstantSDNode>(RHS)->isOne() &&
3544 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3545 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
3546 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
3547 "Unexpected condition code.");
3548 // Only lower legal XALUO ops.
3549 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
3552 // The actual operation with overflow check.
3553 AArch64CC::CondCode OFCC;
3554 SDValue Value, Overflow;
3555 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
3557 if (CC == ISD::SETNE)
3558 OFCC = getInvertedCondCode(OFCC);
3559 SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
3561 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3565 if (LHS.getValueType().isInteger()) {
3566 assert((LHS.getValueType() == RHS.getValueType()) &&
3567 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3569 // If the RHS of the comparison is zero, we can potentially fold this
3570 // to a specialized branch.
3571 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
3572 if (RHSC && RHSC->getZExtValue() == 0) {
3573 if (CC == ISD::SETEQ) {
3574 // See if we can use a TBZ to fold in an AND as well.
3575 // TBZ has a smaller branch displacement than CBZ. If the offset is
3576 // out of bounds, a late MI-layer pass rewrites branches.
3577 // 403.gcc is an example that hits this case.
3578 if (LHS.getOpcode() == ISD::AND &&
3579 isa<ConstantSDNode>(LHS.getOperand(1)) &&
3580 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3581 SDValue Test = LHS.getOperand(0);
3582 uint64_t Mask = LHS.getConstantOperandVal(1);
3583 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
3584 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3588 return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
3589 } else if (CC == ISD::SETNE) {
3590 // See if we can use a TBZ to fold in an AND as well.
3591 // TBZ has a smaller branch displacement than CBZ. If the offset is
3592 // out of bounds, a late MI-layer pass rewrites branches.
3593 // 403.gcc is an example that hits this case.
3594 if (LHS.getOpcode() == ISD::AND &&
3595 isa<ConstantSDNode>(LHS.getOperand(1)) &&
3596 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3597 SDValue Test = LHS.getOperand(0);
3598 uint64_t Mask = LHS.getConstantOperandVal(1);
3599 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
3600 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3604 return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
3605 } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
3606 // Don't combine AND since emitComparison converts the AND to an ANDS
3607 // (a.k.a. TST) and the test in the test bit and branch instruction
3608 // becomes redundant. This would also increase register pressure.
3609 uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
3610 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
3611 DAG.getConstant(Mask, dl, MVT::i64), Dest);
3614 if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
3615 LHS.getOpcode() != ISD::AND) {
3616 // Don't combine AND since emitComparison converts the AND to an ANDS
3617 // (a.k.a. TST) and the test in the test bit and branch instruction
3618 // becomes redundant. This would also increase register pressure.
3619 uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
3620 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
3621 DAG.getConstant(Mask, dl, MVT::i64), Dest);
3625 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3626 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3630 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3632 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
3633 // clean. Some of them require two branches to implement.
3634 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3635 AArch64CC::CondCode CC1, CC2;
3636 changeFPCCToAArch64CC(CC, CC1, CC2);
3637 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3639 DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
3640 if (CC2 != AArch64CC::AL) {
3641 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
3642 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
3649 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
3650 SelectionDAG &DAG) const {
3651 EVT VT = Op.getValueType();
3654 SDValue In1 = Op.getOperand(0);
3655 SDValue In2 = Op.getOperand(1);
3656 EVT SrcVT = In2.getValueType();
3658 if (SrcVT.bitsLT(VT))
3659 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
3660 else if (SrcVT.bitsGT(VT))
3661 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
3666 SDValue VecVal1, VecVal2;
3667 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
3669 VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
3670 EltMask = 0x80000000ULL;
3672 if (!VT.isVector()) {
3673 VecVal1 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3674 DAG.getUNDEF(VecVT), In1);
3675 VecVal2 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3676 DAG.getUNDEF(VecVT), In2);
3678 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3679 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3681 } else if (VT == MVT::f64 || VT == MVT::v2f64) {
3685 // We want to materialize a mask with the high bit set, but the AdvSIMD
3686 // immediate moves cannot materialize that in a single instruction for
3687 // 64-bit elements. Instead, materialize zero and then negate it.
3690 if (!VT.isVector()) {
3691 VecVal1 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3692 DAG.getUNDEF(VecVT), In1);
3693 VecVal2 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3694 DAG.getUNDEF(VecVT), In2);
3696 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3697 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3700 llvm_unreachable("Invalid type for copysign!");
3703 SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
3705 // If we couldn't materialize the mask above, then the mask vector will be
3706 // the zero vector, and we need to negate it here.
3707 if (VT == MVT::f64 || VT == MVT::v2f64) {
3708 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
3709 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
3710 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
3714 DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
3717 return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
3718 else if (VT == MVT::f64)
3719 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
3721 return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
3724 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
3725 if (DAG.getMachineFunction().getFunction()->hasFnAttribute(
3726 Attribute::NoImplicitFloat))
3729 if (!Subtarget->hasNEON())
3732 // While there is no integer popcount instruction, it can
3733 // be more efficiently lowered to the following sequence that uses
3734 // AdvSIMD registers/instructions as long as the copies to/from
3735 // the AdvSIMD registers are cheap.
3736 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd
3737 // CNT V0.8B, V0.8B // 8xbyte pop-counts
3738 // ADDV B0, V0.8B // sum 8xbyte pop-counts
3739 // UMOV X0, V0.B[0] // copy byte result back to integer reg
3740 SDValue Val = Op.getOperand(0);
3742 EVT VT = Op.getValueType();
3745 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
3746 Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
3748 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
3749 SDValue UaddLV = DAG.getNode(
3750 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
3751 DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
3754 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
3758 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3760 if (Op.getValueType().isVector())
3761 return LowerVSETCC(Op, DAG);
3763 SDValue LHS = Op.getOperand(0);
3764 SDValue RHS = Op.getOperand(1);
3765 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3768 // We chose ZeroOrOneBooleanContents, so use zero and one.
3769 EVT VT = Op.getValueType();
3770 SDValue TVal = DAG.getConstant(1, dl, VT);
3771 SDValue FVal = DAG.getConstant(0, dl, VT);
3773 // Handle f128 first, since one possible outcome is a normal integer
3774 // comparison which gets picked up by the next if statement.
3775 if (LHS.getValueType() == MVT::f128) {
3776 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3778 // If softenSetCCOperands returned a scalar, use it.
3779 if (!RHS.getNode()) {
3780 assert(LHS.getValueType() == Op.getValueType() &&
3781 "Unexpected setcc expansion!");
3786 if (LHS.getValueType().isInteger()) {
3789 getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
3791 // Note that we inverted the condition above, so we reverse the order of
3792 // the true and false operands here. This will allow the setcc to be
3793 // matched to a single CSINC instruction.
3794 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
3797 // Now we know we're dealing with FP values.
3798 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3800 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
3801 // and do the comparison.
3802 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3804 AArch64CC::CondCode CC1, CC2;
3805 changeFPCCToAArch64CC(CC, CC1, CC2);
3806 if (CC2 == AArch64CC::AL) {
3807 changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
3808 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3810 // Note that we inverted the condition above, so we reverse the order of
3811 // the true and false operands here. This will allow the setcc to be
3812 // matched to a single CSINC instruction.
3813 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
3815 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
3816 // totally clean. Some of them require two CSELs to implement. As is in
3817 // this case, we emit the first CSEL and then emit a second using the output
3818 // of the first as the RHS. We're effectively OR'ing the two CC's together.
3820 // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
3821 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3823 DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3825 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
3826 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3830 SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
3831 SDValue RHS, SDValue TVal,
3832 SDValue FVal, SDLoc dl,
3833 SelectionDAG &DAG) const {
3834 // Handle f128 first, because it will result in a comparison of some RTLIB
3835 // call result against zero.
3836 if (LHS.getValueType() == MVT::f128) {
3837 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3839 // If softenSetCCOperands returned a scalar, we need to compare the result
3840 // against zero to select between true and false values.
3841 if (!RHS.getNode()) {
3842 RHS = DAG.getConstant(0, dl, LHS.getValueType());
3847 // Handle integers first.
3848 if (LHS.getValueType().isInteger()) {
3849 assert((LHS.getValueType() == RHS.getValueType()) &&
3850 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3852 unsigned Opcode = AArch64ISD::CSEL;
3854 // If both the TVal and the FVal are constants, see if we can swap them in
3855 // order to for a CSINV or CSINC out of them.
3856 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
3857 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
3859 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
3860 std::swap(TVal, FVal);
3861 std::swap(CTVal, CFVal);
3862 CC = ISD::getSetCCInverse(CC, true);
3863 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
3864 std::swap(TVal, FVal);
3865 std::swap(CTVal, CFVal);
3866 CC = ISD::getSetCCInverse(CC, true);
3867 } else if (TVal.getOpcode() == ISD::XOR) {
3868 // If TVal is a NOT we want to swap TVal and FVal so that we can match
3869 // with a CSINV rather than a CSEL.
3870 ConstantSDNode *CVal = dyn_cast<ConstantSDNode>(TVal.getOperand(1));
3872 if (CVal && CVal->isAllOnesValue()) {
3873 std::swap(TVal, FVal);
3874 std::swap(CTVal, CFVal);
3875 CC = ISD::getSetCCInverse(CC, true);
3877 } else if (TVal.getOpcode() == ISD::SUB) {
3878 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
3879 // that we can match with a CSNEG rather than a CSEL.
3880 ConstantSDNode *CVal = dyn_cast<ConstantSDNode>(TVal.getOperand(0));
3882 if (CVal && CVal->isNullValue()) {
3883 std::swap(TVal, FVal);
3884 std::swap(CTVal, CFVal);
3885 CC = ISD::getSetCCInverse(CC, true);
3887 } else if (CTVal && CFVal) {
3888 const int64_t TrueVal = CTVal->getSExtValue();
3889 const int64_t FalseVal = CFVal->getSExtValue();
3892 // If both TVal and FVal are constants, see if FVal is the
3893 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
3894 // instead of a CSEL in that case.
3895 if (TrueVal == ~FalseVal) {
3896 Opcode = AArch64ISD::CSINV;
3897 } else if (TrueVal == -FalseVal) {
3898 Opcode = AArch64ISD::CSNEG;
3899 } else if (TVal.getValueType() == MVT::i32) {
3900 // If our operands are only 32-bit wide, make sure we use 32-bit
3901 // arithmetic for the check whether we can use CSINC. This ensures that
3902 // the addition in the check will wrap around properly in case there is
3903 // an overflow (which would not be the case if we do the check with
3904 // 64-bit arithmetic).
3905 const uint32_t TrueVal32 = CTVal->getZExtValue();
3906 const uint32_t FalseVal32 = CFVal->getZExtValue();
3908 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
3909 Opcode = AArch64ISD::CSINC;
3911 if (TrueVal32 > FalseVal32) {
3915 // 64-bit check whether we can use CSINC.
3916 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
3917 Opcode = AArch64ISD::CSINC;
3919 if (TrueVal > FalseVal) {
3924 // Swap TVal and FVal if necessary.
3926 std::swap(TVal, FVal);
3927 std::swap(CTVal, CFVal);
3928 CC = ISD::getSetCCInverse(CC, true);
3931 if (Opcode != AArch64ISD::CSEL) {
3932 // Drop FVal since we can get its value by simply inverting/negating
3939 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3941 EVT VT = TVal.getValueType();
3942 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
3945 // Now we know we're dealing with FP values.
3946 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3947 assert(LHS.getValueType() == RHS.getValueType());
3948 EVT VT = TVal.getValueType();
3949 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3951 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
3952 // clean. Some of them require two CSELs to implement.
3953 AArch64CC::CondCode CC1, CC2;
3954 changeFPCCToAArch64CC(CC, CC1, CC2);
3955 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3956 SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3958 // If we need a second CSEL, emit it, using the output of the first as the
3959 // RHS. We're effectively OR'ing the two CC's together.
3960 if (CC2 != AArch64CC::AL) {
3961 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
3962 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3965 // Otherwise, return the output of the first CSEL.
3969 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
3970 SelectionDAG &DAG) const {
3971 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3972 SDValue LHS = Op.getOperand(0);
3973 SDValue RHS = Op.getOperand(1);
3974 SDValue TVal = Op.getOperand(2);
3975 SDValue FVal = Op.getOperand(3);
3977 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
3980 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
3981 SelectionDAG &DAG) const {
3982 SDValue CCVal = Op->getOperand(0);
3983 SDValue TVal = Op->getOperand(1);
3984 SDValue FVal = Op->getOperand(2);
3987 unsigned Opc = CCVal.getOpcode();
3988 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
3990 if (CCVal.getResNo() == 1 &&
3991 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3992 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
3993 // Only lower legal XALUO ops.
3994 if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
3997 AArch64CC::CondCode OFCC;
3998 SDValue Value, Overflow;
3999 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
4000 SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
4002 return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
4006 // Lower it the same way as we would lower a SELECT_CC node.
4009 if (CCVal.getOpcode() == ISD::SETCC) {
4010 LHS = CCVal.getOperand(0);
4011 RHS = CCVal.getOperand(1);
4012 CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
4015 RHS = DAG.getConstant(0, DL, CCVal.getValueType());
4018 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4021 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
4022 SelectionDAG &DAG) const {
4023 // Jump table entries as PC relative offsets. No additional tweaking
4024 // is necessary here. Just get the address of the jump table.
4025 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4026 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4029 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4030 !Subtarget->isTargetMachO()) {
4031 const unsigned char MO_NC = AArch64II::MO_NC;
4033 AArch64ISD::WrapperLarge, DL, PtrVT,
4034 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G3),
4035 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G2 | MO_NC),
4036 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G1 | MO_NC),
4037 DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4038 AArch64II::MO_G0 | MO_NC));
4042 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_PAGE);
4043 SDValue Lo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4044 AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4045 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4046 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4049 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
4050 SelectionDAG &DAG) const {
4051 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4052 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4055 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4056 // Use the GOT for the large code model on iOS.
4057 if (Subtarget->isTargetMachO()) {
4058 SDValue GotAddr = DAG.getTargetConstantPool(
4059 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4061 return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
4064 const unsigned char MO_NC = AArch64II::MO_NC;
4066 AArch64ISD::WrapperLarge, DL, PtrVT,
4067 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4068 CP->getOffset(), AArch64II::MO_G3),
4069 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4070 CP->getOffset(), AArch64II::MO_G2 | MO_NC),
4071 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4072 CP->getOffset(), AArch64II::MO_G1 | MO_NC),
4073 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4074 CP->getOffset(), AArch64II::MO_G0 | MO_NC));
4076 // Use ADRP/ADD or ADRP/LDR for everything else: the small memory model on
4077 // ELF, the only valid one on Darwin.
4079 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4080 CP->getOffset(), AArch64II::MO_PAGE);
4081 SDValue Lo = DAG.getTargetConstantPool(
4082 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4083 AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4085 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4086 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4090 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
4091 SelectionDAG &DAG) const {
4092 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
4093 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4095 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4096 !Subtarget->isTargetMachO()) {
4097 const unsigned char MO_NC = AArch64II::MO_NC;
4099 AArch64ISD::WrapperLarge, DL, PtrVT,
4100 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G3),
4101 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
4102 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
4103 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
4105 SDValue Hi = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGE);
4106 SDValue Lo = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGEOFF |
4108 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4109 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4113 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
4114 SelectionDAG &DAG) const {
4115 AArch64FunctionInfo *FuncInfo =
4116 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4119 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
4120 getPointerTy(DAG.getDataLayout()));
4121 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4122 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
4123 MachinePointerInfo(SV), false, false, 0);
4126 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
4127 SelectionDAG &DAG) const {
4128 // The layout of the va_list struct is specified in the AArch64 Procedure Call
4129 // Standard, section B.3.
4130 MachineFunction &MF = DAG.getMachineFunction();
4131 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4132 auto PtrVT = getPointerTy(DAG.getDataLayout());
4135 SDValue Chain = Op.getOperand(0);
4136 SDValue VAList = Op.getOperand(1);
4137 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4138 SmallVector<SDValue, 4> MemOps;
4140 // void *__stack at offset 0
4141 SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
4142 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
4143 MachinePointerInfo(SV), false, false, 8));
4145 // void *__gr_top at offset 8
4146 int GPRSize = FuncInfo->getVarArgsGPRSize();
4148 SDValue GRTop, GRTopAddr;
4151 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
4153 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
4154 GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
4155 DAG.getConstant(GPRSize, DL, PtrVT));
4157 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
4158 MachinePointerInfo(SV, 8), false, false, 8));
4161 // void *__vr_top at offset 16
4162 int FPRSize = FuncInfo->getVarArgsFPRSize();
4164 SDValue VRTop, VRTopAddr;
4165 VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4166 DAG.getConstant(16, DL, PtrVT));
4168 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
4169 VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
4170 DAG.getConstant(FPRSize, DL, PtrVT));
4172 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
4173 MachinePointerInfo(SV, 16), false, false, 8));
4176 // int __gr_offs at offset 24
4177 SDValue GROffsAddr =
4178 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
4179 MemOps.push_back(DAG.getStore(Chain, DL,
4180 DAG.getConstant(-GPRSize, DL, MVT::i32),
4181 GROffsAddr, MachinePointerInfo(SV, 24), false,
4184 // int __vr_offs at offset 28
4185 SDValue VROffsAddr =
4186 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
4187 MemOps.push_back(DAG.getStore(Chain, DL,
4188 DAG.getConstant(-FPRSize, DL, MVT::i32),
4189 VROffsAddr, MachinePointerInfo(SV, 28), false,
4192 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
4195 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
4196 SelectionDAG &DAG) const {
4197 return Subtarget->isTargetDarwin() ? LowerDarwin_VASTART(Op, DAG)
4198 : LowerAAPCS_VASTART(Op, DAG);
4201 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
4202 SelectionDAG &DAG) const {
4203 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
4206 unsigned VaListSize = Subtarget->isTargetDarwin() ? 8 : 32;
4207 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4208 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4210 return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1),
4212 DAG.getConstant(VaListSize, DL, MVT::i32),
4213 8, false, false, false, MachinePointerInfo(DestSV),
4214 MachinePointerInfo(SrcSV));
4217 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
4218 assert(Subtarget->isTargetDarwin() &&
4219 "automatic va_arg instruction only works on Darwin");
4221 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4222 EVT VT = Op.getValueType();
4224 SDValue Chain = Op.getOperand(0);
4225 SDValue Addr = Op.getOperand(1);
4226 unsigned Align = Op.getConstantOperandVal(3);
4227 auto PtrVT = getPointerTy(DAG.getDataLayout());
4229 SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V),
4230 false, false, false, 0);
4231 Chain = VAList.getValue(1);
4234 assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
4235 VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4236 DAG.getConstant(Align - 1, DL, PtrVT));
4237 VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
4238 DAG.getConstant(-(int64_t)Align, DL, PtrVT));
4241 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
4242 uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
4244 // Scalar integer and FP values smaller than 64 bits are implicitly extended
4245 // up to 64 bits. At the very least, we have to increase the striding of the
4246 // vaargs list to match this, and for FP values we need to introduce
4247 // FP_ROUND nodes as well.
4248 if (VT.isInteger() && !VT.isVector())
4250 bool NeedFPTrunc = false;
4251 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
4256 // Increment the pointer, VAList, to the next vaarg
4257 SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4258 DAG.getConstant(ArgSize, DL, PtrVT));
4259 // Store the incremented VAList to the legalized pointer
4260 SDValue APStore = DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V),
4263 // Load the actual argument out of the pointer VAList
4265 // Load the value as an f64.
4266 SDValue WideFP = DAG.getLoad(MVT::f64, DL, APStore, VAList,
4267 MachinePointerInfo(), false, false, false, 0);
4268 // Round the value down to an f32.
4269 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
4270 DAG.getIntPtrConstant(1, DL));
4271 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
4272 // Merge the rounded value with the chain output of the load.
4273 return DAG.getMergeValues(Ops, DL);
4276 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo(), false,
4280 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
4281 SelectionDAG &DAG) const {
4282 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4283 MFI->setFrameAddressIsTaken(true);
4285 EVT VT = Op.getValueType();
4287 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4289 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
4291 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
4292 MachinePointerInfo(), false, false, false, 0);
4296 // FIXME? Maybe this could be a TableGen attribute on some registers and
4297 // this table could be generated automatically from RegInfo.
4298 unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT,
4299 SelectionDAG &DAG) const {
4300 unsigned Reg = StringSwitch<unsigned>(RegName)
4301 .Case("sp", AArch64::SP)
4305 report_fatal_error(Twine("Invalid register name \""
4306 + StringRef(RegName) + "\"."));
4309 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
4310 SelectionDAG &DAG) const {
4311 MachineFunction &MF = DAG.getMachineFunction();
4312 MachineFrameInfo *MFI = MF.getFrameInfo();
4313 MFI->setReturnAddressIsTaken(true);
4315 EVT VT = Op.getValueType();
4317 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4319 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4320 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
4321 return DAG.getLoad(VT, DL, DAG.getEntryNode(),
4322 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
4323 MachinePointerInfo(), false, false, false, 0);
4326 // Return LR, which contains the return address. Mark it an implicit live-in.
4327 unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
4328 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4331 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4332 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
4333 SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
4334 SelectionDAG &DAG) const {
4335 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4336 EVT VT = Op.getValueType();
4337 unsigned VTBits = VT.getSizeInBits();
4339 SDValue ShOpLo = Op.getOperand(0);
4340 SDValue ShOpHi = Op.getOperand(1);
4341 SDValue ShAmt = Op.getOperand(2);
4343 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4345 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4347 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
4348 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
4349 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4350 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
4351 DAG.getConstant(VTBits, dl, MVT::i64));
4352 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4354 SDValue Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64),
4355 ISD::SETGE, dl, DAG);
4356 SDValue CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4358 SDValue FalseValLo = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4359 SDValue TrueValLo = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4361 DAG.getNode(AArch64ISD::CSEL, dl, VT, TrueValLo, FalseValLo, CCVal, Cmp);
4363 // AArch64 shifts larger than the register width are wrapped rather than
4364 // clamped, so we can't just emit "hi >> x".
4365 SDValue FalseValHi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4366 SDValue TrueValHi = Opc == ISD::SRA
4367 ? DAG.getNode(Opc, dl, VT, ShOpHi,
4368 DAG.getConstant(VTBits - 1, dl,
4370 : DAG.getConstant(0, dl, VT);
4372 DAG.getNode(AArch64ISD::CSEL, dl, VT, TrueValHi, FalseValHi, CCVal, Cmp);
4374 SDValue Ops[2] = { Lo, Hi };
4375 return DAG.getMergeValues(Ops, dl);
4378 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4379 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
4380 SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
4381 SelectionDAG &DAG) const {
4382 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4383 EVT VT = Op.getValueType();
4384 unsigned VTBits = VT.getSizeInBits();
4386 SDValue ShOpLo = Op.getOperand(0);
4387 SDValue ShOpHi = Op.getOperand(1);
4388 SDValue ShAmt = Op.getOperand(2);
4391 assert(Op.getOpcode() == ISD::SHL_PARTS);
4392 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
4393 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
4394 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4395 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
4396 DAG.getConstant(VTBits, dl, MVT::i64));
4397 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4398 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4400 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4402 SDValue Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64),
4403 ISD::SETGE, dl, DAG);
4404 SDValue CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4406 DAG.getNode(AArch64ISD::CSEL, dl, VT, Tmp3, FalseVal, CCVal, Cmp);
4408 // AArch64 shifts of larger than register sizes are wrapped rather than
4409 // clamped, so we can't just emit "lo << a" if a is too big.
4410 SDValue TrueValLo = DAG.getConstant(0, dl, VT);
4411 SDValue FalseValLo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4413 DAG.getNode(AArch64ISD::CSEL, dl, VT, TrueValLo, FalseValLo, CCVal, Cmp);
4415 SDValue Ops[2] = { Lo, Hi };
4416 return DAG.getMergeValues(Ops, dl);
4419 bool AArch64TargetLowering::isOffsetFoldingLegal(
4420 const GlobalAddressSDNode *GA) const {
4421 // The AArch64 target doesn't support folding offsets into global addresses.
4425 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4426 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
4427 // FIXME: We should be able to handle f128 as well with a clever lowering.
4428 if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32))
4432 return AArch64_AM::getFP64Imm(Imm) != -1;
4433 else if (VT == MVT::f32)
4434 return AArch64_AM::getFP32Imm(Imm) != -1;
4438 //===----------------------------------------------------------------------===//
4439 // AArch64 Optimization Hooks
4440 //===----------------------------------------------------------------------===//
4442 //===----------------------------------------------------------------------===//
4443 // AArch64 Inline Assembly Support
4444 //===----------------------------------------------------------------------===//
4446 // Table of Constraints
4447 // TODO: This is the current set of constraints supported by ARM for the
4448 // compiler, not all of them may make sense, e.g. S may be difficult to support.
4450 // r - A general register
4451 // w - An FP/SIMD register of some size in the range v0-v31
4452 // x - An FP/SIMD register of some size in the range v0-v15
4453 // I - Constant that can be used with an ADD instruction
4454 // J - Constant that can be used with a SUB instruction
4455 // K - Constant that can be used with a 32-bit logical instruction
4456 // L - Constant that can be used with a 64-bit logical instruction
4457 // M - Constant that can be used as a 32-bit MOV immediate
4458 // N - Constant that can be used as a 64-bit MOV immediate
4459 // Q - A memory reference with base register and no offset
4460 // S - A symbolic address
4461 // Y - Floating point constant zero
4462 // Z - Integer constant zero
4464 // Note that general register operands will be output using their 64-bit x
4465 // register name, whatever the size of the variable, unless the asm operand
4466 // is prefixed by the %w modifier. Floating-point and SIMD register operands
4467 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
4470 /// getConstraintType - Given a constraint letter, return the type of
4471 /// constraint it is for this target.
4472 AArch64TargetLowering::ConstraintType
4473 AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
4474 if (Constraint.size() == 1) {
4475 switch (Constraint[0]) {
4482 return C_RegisterClass;
4483 // An address with a single base register. Due to the way we
4484 // currently handle addresses it is the same as 'r'.
4489 return TargetLowering::getConstraintType(Constraint);
4492 /// Examine constraint type and operand type and determine a weight value.
4493 /// This object must already have been set up with the operand type
4494 /// and the current alternative constraint selected.
4495 TargetLowering::ConstraintWeight
4496 AArch64TargetLowering::getSingleConstraintMatchWeight(
4497 AsmOperandInfo &info, const char *constraint) const {
4498 ConstraintWeight weight = CW_Invalid;
4499 Value *CallOperandVal = info.CallOperandVal;
4500 // If we don't have a value, we can't do a match,
4501 // but allow it at the lowest weight.
4502 if (!CallOperandVal)
4504 Type *type = CallOperandVal->getType();
4505 // Look at the constraint type.
4506 switch (*constraint) {
4508 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
4512 if (type->isFloatingPointTy() || type->isVectorTy())
4513 weight = CW_Register;
4516 weight = CW_Constant;
4522 std::pair<unsigned, const TargetRegisterClass *>
4523 AArch64TargetLowering::getRegForInlineAsmConstraint(
4524 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
4525 if (Constraint.size() == 1) {
4526 switch (Constraint[0]) {
4528 if (VT.getSizeInBits() == 64)
4529 return std::make_pair(0U, &AArch64::GPR64commonRegClass);
4530 return std::make_pair(0U, &AArch64::GPR32commonRegClass);
4533 return std::make_pair(0U, &AArch64::FPR32RegClass);
4534 if (VT.getSizeInBits() == 64)
4535 return std::make_pair(0U, &AArch64::FPR64RegClass);
4536 if (VT.getSizeInBits() == 128)
4537 return std::make_pair(0U, &AArch64::FPR128RegClass);
4539 // The instructions that this constraint is designed for can
4540 // only take 128-bit registers so just use that regclass.
4542 if (VT.getSizeInBits() == 128)
4543 return std::make_pair(0U, &AArch64::FPR128_loRegClass);
4547 if (StringRef("{cc}").equals_lower(Constraint))
4548 return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
4550 // Use the default implementation in TargetLowering to convert the register
4551 // constraint into a member of a register class.
4552 std::pair<unsigned, const TargetRegisterClass *> Res;
4553 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
4555 // Not found as a standard register?
4557 unsigned Size = Constraint.size();
4558 if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
4559 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
4561 bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
4562 if (!Failed && RegNo >= 0 && RegNo <= 31) {
4563 // v0 - v31 are aliases of q0 - q31.
4564 // By default we'll emit v0-v31 for this unless there's a modifier where
4565 // we'll emit the correct register as well.
4566 Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
4567 Res.second = &AArch64::FPR128RegClass;
4575 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
4576 /// vector. If it is invalid, don't add anything to Ops.
4577 void AArch64TargetLowering::LowerAsmOperandForConstraint(
4578 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
4579 SelectionDAG &DAG) const {
4582 // Currently only support length 1 constraints.
4583 if (Constraint.length() != 1)
4586 char ConstraintLetter = Constraint[0];
4587 switch (ConstraintLetter) {
4591 // This set of constraints deal with valid constants for various instructions.
4592 // Validate and return a target constant for them if we can.
4594 // 'z' maps to xzr or wzr so it needs an input of 0.
4595 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4596 if (!C || C->getZExtValue() != 0)
4599 if (Op.getValueType() == MVT::i64)
4600 Result = DAG.getRegister(AArch64::XZR, MVT::i64);
4602 Result = DAG.getRegister(AArch64::WZR, MVT::i32);
4612 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4616 // Grab the value and do some validation.
4617 uint64_t CVal = C->getZExtValue();
4618 switch (ConstraintLetter) {
4619 // The I constraint applies only to simple ADD or SUB immediate operands:
4620 // i.e. 0 to 4095 with optional shift by 12
4621 // The J constraint applies only to ADD or SUB immediates that would be
4622 // valid when negated, i.e. if [an add pattern] were to be output as a SUB
4623 // instruction [or vice versa], in other words -1 to -4095 with optional
4624 // left shift by 12.
4626 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
4630 uint64_t NVal = -C->getSExtValue();
4631 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
4632 CVal = C->getSExtValue();
4637 // The K and L constraints apply *only* to logical immediates, including
4638 // what used to be the MOVI alias for ORR (though the MOVI alias has now
4639 // been removed and MOV should be used). So these constraints have to
4640 // distinguish between bit patterns that are valid 32-bit or 64-bit
4641 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
4642 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
4645 if (AArch64_AM::isLogicalImmediate(CVal, 32))
4649 if (AArch64_AM::isLogicalImmediate(CVal, 64))
4652 // The M and N constraints are a superset of K and L respectively, for use
4653 // with the MOV (immediate) alias. As well as the logical immediates they
4654 // also match 32 or 64-bit immediates that can be loaded either using a
4655 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
4656 // (M) or 64-bit 0x1234000000000000 (N) etc.
4657 // As a note some of this code is liberally stolen from the asm parser.
4659 if (!isUInt<32>(CVal))
4661 if (AArch64_AM::isLogicalImmediate(CVal, 32))
4663 if ((CVal & 0xFFFF) == CVal)
4665 if ((CVal & 0xFFFF0000ULL) == CVal)
4667 uint64_t NCVal = ~(uint32_t)CVal;
4668 if ((NCVal & 0xFFFFULL) == NCVal)
4670 if ((NCVal & 0xFFFF0000ULL) == NCVal)
4675 if (AArch64_AM::isLogicalImmediate(CVal, 64))
4677 if ((CVal & 0xFFFFULL) == CVal)
4679 if ((CVal & 0xFFFF0000ULL) == CVal)
4681 if ((CVal & 0xFFFF00000000ULL) == CVal)
4683 if ((CVal & 0xFFFF000000000000ULL) == CVal)
4685 uint64_t NCVal = ~CVal;
4686 if ((NCVal & 0xFFFFULL) == NCVal)
4688 if ((NCVal & 0xFFFF0000ULL) == NCVal)
4690 if ((NCVal & 0xFFFF00000000ULL) == NCVal)
4692 if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
4700 // All assembler immediates are 64-bit integers.
4701 Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
4705 if (Result.getNode()) {
4706 Ops.push_back(Result);
4710 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
4713 //===----------------------------------------------------------------------===//
4714 // AArch64 Advanced SIMD Support
4715 //===----------------------------------------------------------------------===//
4717 /// WidenVector - Given a value in the V64 register class, produce the
4718 /// equivalent value in the V128 register class.
4719 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
4720 EVT VT = V64Reg.getValueType();
4721 unsigned NarrowSize = VT.getVectorNumElements();
4722 MVT EltTy = VT.getVectorElementType().getSimpleVT();
4723 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
4726 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
4727 V64Reg, DAG.getConstant(0, DL, MVT::i32));
4730 /// getExtFactor - Determine the adjustment factor for the position when
4731 /// generating an "extract from vector registers" instruction.
4732 static unsigned getExtFactor(SDValue &V) {
4733 EVT EltType = V.getValueType().getVectorElementType();
4734 return EltType.getSizeInBits() / 8;
4737 /// NarrowVector - Given a value in the V128 register class, produce the
4738 /// equivalent value in the V64 register class.
4739 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
4740 EVT VT = V128Reg.getValueType();
4741 unsigned WideSize = VT.getVectorNumElements();
4742 MVT EltTy = VT.getVectorElementType().getSimpleVT();
4743 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
4746 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
4749 // Gather data to see if the operation can be modelled as a
4750 // shuffle in combination with VEXTs.
4751 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
4752 SelectionDAG &DAG) const {
4753 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
4755 EVT VT = Op.getValueType();
4756 unsigned NumElts = VT.getVectorNumElements();
4758 struct ShuffleSourceInfo {
4763 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
4764 // be compatible with the shuffle we intend to construct. As a result
4765 // ShuffleVec will be some sliding window into the original Vec.
4768 // Code should guarantee that element i in Vec starts at element "WindowBase
4769 // + i * WindowScale in ShuffleVec".
4773 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
4774 ShuffleSourceInfo(SDValue Vec)
4775 : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
4779 // First gather all vectors used as an immediate source for this BUILD_VECTOR
4781 SmallVector<ShuffleSourceInfo, 2> Sources;
4782 for (unsigned i = 0; i < NumElts; ++i) {
4783 SDValue V = Op.getOperand(i);
4784 if (V.getOpcode() == ISD::UNDEF)
4786 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4787 // A shuffle can only come from building a vector from various
4788 // elements of other vectors.
4792 // Add this element source to the list if it's not already there.
4793 SDValue SourceVec = V.getOperand(0);
4794 auto Source = std::find(Sources.begin(), Sources.end(), SourceVec);
4795 if (Source == Sources.end())
4796 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
4798 // Update the minimum and maximum lane number seen.
4799 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4800 Source->MinElt = std::min(Source->MinElt, EltNo);
4801 Source->MaxElt = std::max(Source->MaxElt, EltNo);
4804 // Currently only do something sane when at most two source vectors
4806 if (Sources.size() > 2)
4809 // Find out the smallest element size among result and two sources, and use
4810 // it as element size to build the shuffle_vector.
4811 EVT SmallestEltTy = VT.getVectorElementType();
4812 for (auto &Source : Sources) {
4813 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
4814 if (SrcEltTy.bitsLT(SmallestEltTy)) {
4815 SmallestEltTy = SrcEltTy;
4818 unsigned ResMultiplier =
4819 VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
4820 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
4821 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
4823 // If the source vector is too wide or too narrow, we may nevertheless be able
4824 // to construct a compatible shuffle either by concatenating it with UNDEF or
4825 // extracting a suitable range of elements.
4826 for (auto &Src : Sources) {
4827 EVT SrcVT = Src.ShuffleVec.getValueType();
4829 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
4832 // This stage of the search produces a source with the same element type as
4833 // the original, but with a total width matching the BUILD_VECTOR output.
4834 EVT EltVT = SrcVT.getVectorElementType();
4835 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
4836 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
4838 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
4839 assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
4840 // We can pad out the smaller vector for free, so if it's part of a
4843 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
4844 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
4848 assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
4850 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
4851 // Span too large for a VEXT to cope
4855 if (Src.MinElt >= NumSrcElts) {
4856 // The extraction can just take the second half
4858 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4859 DAG.getConstant(NumSrcElts, dl, MVT::i64));
4860 Src.WindowBase = -NumSrcElts;
4861 } else if (Src.MaxElt < NumSrcElts) {
4862 // The extraction can just take the first half
4864 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4865 DAG.getConstant(0, dl, MVT::i64));
4867 // An actual VEXT is needed
4869 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4870 DAG.getConstant(0, dl, MVT::i64));
4872 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4873 DAG.getConstant(NumSrcElts, dl, MVT::i64));
4874 unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
4876 Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
4878 DAG.getConstant(Imm, dl, MVT::i32));
4879 Src.WindowBase = -Src.MinElt;
4883 // Another possible incompatibility occurs from the vector element types. We
4884 // can fix this by bitcasting the source vectors to the same type we intend
4886 for (auto &Src : Sources) {
4887 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
4888 if (SrcEltTy == SmallestEltTy)
4890 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
4891 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
4892 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
4893 Src.WindowBase *= Src.WindowScale;
4896 // Final sanity check before we try to actually produce a shuffle.
4898 for (auto Src : Sources)
4899 assert(Src.ShuffleVec.getValueType() == ShuffleVT);
4902 // The stars all align, our next step is to produce the mask for the shuffle.
4903 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
4904 int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
4905 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
4906 SDValue Entry = Op.getOperand(i);
4907 if (Entry.getOpcode() == ISD::UNDEF)
4910 auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0));
4911 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
4913 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
4914 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
4916 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
4917 int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
4918 VT.getVectorElementType().getSizeInBits());
4919 int LanesDefined = BitsDefined / BitsPerShuffleLane;
4921 // This source is expected to fill ResMultiplier lanes of the final shuffle,
4922 // starting at the appropriate offset.
4923 int *LaneMask = &Mask[i * ResMultiplier];
4925 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
4926 ExtractBase += NumElts * (Src - Sources.begin());
4927 for (int j = 0; j < LanesDefined; ++j)
4928 LaneMask[j] = ExtractBase + j;
4931 // Final check before we try to produce nonsense...
4932 if (!isShuffleMaskLegal(Mask, ShuffleVT))
4935 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
4936 for (unsigned i = 0; i < Sources.size(); ++i)
4937 ShuffleOps[i] = Sources[i].ShuffleVec;
4939 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
4940 ShuffleOps[1], &Mask[0]);
4941 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
4944 // check if an EXT instruction can handle the shuffle mask when the
4945 // vector sources of the shuffle are the same.
4946 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4947 unsigned NumElts = VT.getVectorNumElements();
4949 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4955 // If this is a VEXT shuffle, the immediate value is the index of the first
4956 // element. The other shuffle indices must be the successive elements after
4958 unsigned ExpectedElt = Imm;
4959 for (unsigned i = 1; i < NumElts; ++i) {
4960 // Increment the expected index. If it wraps around, just follow it
4961 // back to index zero and keep going.
4963 if (ExpectedElt == NumElts)
4967 continue; // ignore UNDEF indices
4968 if (ExpectedElt != static_cast<unsigned>(M[i]))
4975 // check if an EXT instruction can handle the shuffle mask when the
4976 // vector sources of the shuffle are different.
4977 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
4979 // Look for the first non-undef element.
4980 const int *FirstRealElt = std::find_if(M.begin(), M.end(),
4981 [](int Elt) {return Elt >= 0;});
4983 // Benefit form APInt to handle overflow when calculating expected element.
4984 unsigned NumElts = VT.getVectorNumElements();
4985 unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
4986 APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
4987 // The following shuffle indices must be the successive elements after the
4988 // first real element.
4989 const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
4990 [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
4991 if (FirstWrongElt != M.end())
4994 // The index of an EXT is the first element if it is not UNDEF.
4995 // Watch out for the beginning UNDEFs. The EXT index should be the expected
4996 // value of the first element. E.g.
4997 // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
4998 // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
4999 // ExpectedElt is the last mask index plus 1.
5000 Imm = ExpectedElt.getZExtValue();
5002 // There are two difference cases requiring to reverse input vectors.
5003 // For example, for vector <4 x i32> we have the following cases,
5004 // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
5005 // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
5006 // For both cases, we finally use mask <5, 6, 7, 0>, which requires
5007 // to reverse two input vectors.
5016 /// isREVMask - Check if a vector shuffle corresponds to a REV
5017 /// instruction with the specified blocksize. (The order of the elements
5018 /// within each block of the vector is reversed.)
5019 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5020 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
5021 "Only possible block sizes for REV are: 16, 32, 64");
5023 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5027 unsigned NumElts = VT.getVectorNumElements();
5028 unsigned BlockElts = M[0] + 1;
5029 // If the first shuffle index is UNDEF, be optimistic.
5031 BlockElts = BlockSize / EltSz;
5033 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5036 for (unsigned i = 0; i < NumElts; ++i) {
5038 continue; // ignore UNDEF indices
5039 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
5046 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5047 unsigned NumElts = VT.getVectorNumElements();
5048 WhichResult = (M[0] == 0 ? 0 : 1);
5049 unsigned Idx = WhichResult * NumElts / 2;
5050 for (unsigned i = 0; i != NumElts; i += 2) {
5051 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5052 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
5060 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5061 unsigned NumElts = VT.getVectorNumElements();
5062 WhichResult = (M[0] == 0 ? 0 : 1);
5063 for (unsigned i = 0; i != NumElts; ++i) {
5065 continue; // ignore UNDEF indices
5066 if ((unsigned)M[i] != 2 * i + WhichResult)
5073 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5074 unsigned NumElts = VT.getVectorNumElements();
5075 WhichResult = (M[0] == 0 ? 0 : 1);
5076 for (unsigned i = 0; i < NumElts; i += 2) {
5077 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5078 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
5084 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
5085 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5086 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5087 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5088 unsigned NumElts = VT.getVectorNumElements();
5089 WhichResult = (M[0] == 0 ? 0 : 1);
5090 unsigned Idx = WhichResult * NumElts / 2;
5091 for (unsigned i = 0; i != NumElts; i += 2) {
5092 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5093 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
5101 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
5102 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5103 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5104 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5105 unsigned Half = VT.getVectorNumElements() / 2;
5106 WhichResult = (M[0] == 0 ? 0 : 1);
5107 for (unsigned j = 0; j != 2; ++j) {
5108 unsigned Idx = WhichResult;
5109 for (unsigned i = 0; i != Half; ++i) {
5110 int MIdx = M[i + j * Half];
5111 if (MIdx >= 0 && (unsigned)MIdx != Idx)
5120 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
5121 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5122 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5123 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5124 unsigned NumElts = VT.getVectorNumElements();
5125 WhichResult = (M[0] == 0 ? 0 : 1);
5126 for (unsigned i = 0; i < NumElts; i += 2) {
5127 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5128 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
5134 static bool isINSMask(ArrayRef<int> M, int NumInputElements,
5135 bool &DstIsLeft, int &Anomaly) {
5136 if (M.size() != static_cast<size_t>(NumInputElements))
5139 int NumLHSMatch = 0, NumRHSMatch = 0;
5140 int LastLHSMismatch = -1, LastRHSMismatch = -1;
5142 for (int i = 0; i < NumInputElements; ++i) {
5152 LastLHSMismatch = i;
5154 if (M[i] == i + NumInputElements)
5157 LastRHSMismatch = i;
5160 if (NumLHSMatch == NumInputElements - 1) {
5162 Anomaly = LastLHSMismatch;
5164 } else if (NumRHSMatch == NumInputElements - 1) {
5166 Anomaly = LastRHSMismatch;
5173 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
5174 if (VT.getSizeInBits() != 128)
5177 unsigned NumElts = VT.getVectorNumElements();
5179 for (int I = 0, E = NumElts / 2; I != E; I++) {
5184 int Offset = NumElts / 2;
5185 for (int I = NumElts / 2, E = NumElts; I != E; I++) {
5186 if (Mask[I] != I + SplitLHS * Offset)
5193 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
5195 EVT VT = Op.getValueType();
5196 SDValue V0 = Op.getOperand(0);
5197 SDValue V1 = Op.getOperand(1);
5198 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
5200 if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
5201 VT.getVectorElementType() != V1.getValueType().getVectorElementType())
5204 bool SplitV0 = V0.getValueType().getSizeInBits() == 128;
5206 if (!isConcatMask(Mask, VT, SplitV0))
5209 EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
5210 VT.getVectorNumElements() / 2);
5212 V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
5213 DAG.getConstant(0, DL, MVT::i64));
5215 if (V1.getValueType().getSizeInBits() == 128) {
5216 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
5217 DAG.getConstant(0, DL, MVT::i64));
5219 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
5222 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5223 /// the specified operations to build the shuffle.
5224 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5225 SDValue RHS, SelectionDAG &DAG,
5227 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5228 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
5229 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
5232 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5241 OP_VUZPL, // VUZP, left result
5242 OP_VUZPR, // VUZP, right result
5243 OP_VZIPL, // VZIP, left result
5244 OP_VZIPR, // VZIP, right result
5245 OP_VTRNL, // VTRN, left result
5246 OP_VTRNR // VTRN, right result
5249 if (OpNum == OP_COPY) {
5250 if (LHSID == (1 * 9 + 2) * 9 + 3)
5252 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
5256 SDValue OpLHS, OpRHS;
5257 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5258 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5259 EVT VT = OpLHS.getValueType();
5263 llvm_unreachable("Unknown shuffle opcode!");
5265 // VREV divides the vector in half and swaps within the half.
5266 if (VT.getVectorElementType() == MVT::i32 ||
5267 VT.getVectorElementType() == MVT::f32)
5268 return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
5269 // vrev <4 x i16> -> REV32
5270 if (VT.getVectorElementType() == MVT::i16 ||
5271 VT.getVectorElementType() == MVT::f16)
5272 return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
5273 // vrev <4 x i8> -> REV16
5274 assert(VT.getVectorElementType() == MVT::i8);
5275 return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
5280 EVT EltTy = VT.getVectorElementType();
5282 if (EltTy == MVT::i8)
5283 Opcode = AArch64ISD::DUPLANE8;
5284 else if (EltTy == MVT::i16 || EltTy == MVT::f16)
5285 Opcode = AArch64ISD::DUPLANE16;
5286 else if (EltTy == MVT::i32 || EltTy == MVT::f32)
5287 Opcode = AArch64ISD::DUPLANE32;
5288 else if (EltTy == MVT::i64 || EltTy == MVT::f64)
5289 Opcode = AArch64ISD::DUPLANE64;
5291 llvm_unreachable("Invalid vector element type?");
5293 if (VT.getSizeInBits() == 64)
5294 OpLHS = WidenVector(OpLHS, DAG);
5295 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
5296 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
5301 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
5302 return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
5303 DAG.getConstant(Imm, dl, MVT::i32));
5306 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
5309 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
5312 return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
5315 return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
5318 return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
5321 return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
5326 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
5327 SelectionDAG &DAG) {
5328 // Check to see if we can use the TBL instruction.
5329 SDValue V1 = Op.getOperand(0);
5330 SDValue V2 = Op.getOperand(1);
5333 EVT EltVT = Op.getValueType().getVectorElementType();
5334 unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
5336 SmallVector<SDValue, 8> TBLMask;
5337 for (int Val : ShuffleMask) {
5338 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
5339 unsigned Offset = Byte + Val * BytesPerElt;
5340 TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
5344 MVT IndexVT = MVT::v8i8;
5345 unsigned IndexLen = 8;
5346 if (Op.getValueType().getSizeInBits() == 128) {
5347 IndexVT = MVT::v16i8;
5351 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
5352 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
5355 if (V2.getNode()->getOpcode() == ISD::UNDEF) {
5357 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
5358 Shuffle = DAG.getNode(
5359 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5360 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
5361 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5362 makeArrayRef(TBLMask.data(), IndexLen)));
5364 if (IndexLen == 8) {
5365 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
5366 Shuffle = DAG.getNode(
5367 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5368 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
5369 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5370 makeArrayRef(TBLMask.data(), IndexLen)));
5372 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
5373 // cannot currently represent the register constraints on the input
5375 // Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
5376 // DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5377 // &TBLMask[0], IndexLen));
5378 Shuffle = DAG.getNode(
5379 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5380 DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32),
5382 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5383 makeArrayRef(TBLMask.data(), IndexLen)));
5386 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
5389 static unsigned getDUPLANEOp(EVT EltType) {
5390 if (EltType == MVT::i8)
5391 return AArch64ISD::DUPLANE8;
5392 if (EltType == MVT::i16 || EltType == MVT::f16)
5393 return AArch64ISD::DUPLANE16;
5394 if (EltType == MVT::i32 || EltType == MVT::f32)
5395 return AArch64ISD::DUPLANE32;
5396 if (EltType == MVT::i64 || EltType == MVT::f64)
5397 return AArch64ISD::DUPLANE64;
5399 llvm_unreachable("Invalid vector element type?");
5402 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5403 SelectionDAG &DAG) const {
5405 EVT VT = Op.getValueType();
5407 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5409 // Convert shuffles that are directly supported on NEON to target-specific
5410 // DAG nodes, instead of keeping them as shuffles and matching them again
5411 // during code selection. This is more efficient and avoids the possibility
5412 // of inconsistencies between legalization and selection.
5413 ArrayRef<int> ShuffleMask = SVN->getMask();
5415 SDValue V1 = Op.getOperand(0);
5416 SDValue V2 = Op.getOperand(1);
5418 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0],
5419 V1.getValueType().getSimpleVT())) {
5420 int Lane = SVN->getSplatIndex();
5421 // If this is undef splat, generate it via "just" vdup, if possible.
5425 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
5426 return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
5428 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
5429 // constant. If so, we can just reference the lane's definition directly.
5430 if (V1.getOpcode() == ISD::BUILD_VECTOR &&
5431 !isa<ConstantSDNode>(V1.getOperand(Lane)))
5432 return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
5434 // Otherwise, duplicate from the lane of the input vector.
5435 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
5437 // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
5438 // to make a vector of the same size as this SHUFFLE. We can ignore the
5439 // extract entirely, and canonicalise the concat using WidenVector.
5440 if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
5441 Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
5442 V1 = V1.getOperand(0);
5443 } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
5444 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
5445 Lane -= Idx * VT.getVectorNumElements() / 2;
5446 V1 = WidenVector(V1.getOperand(Idx), DAG);
5447 } else if (VT.getSizeInBits() == 64)
5448 V1 = WidenVector(V1, DAG);
5450 return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
5453 if (isREVMask(ShuffleMask, VT, 64))
5454 return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
5455 if (isREVMask(ShuffleMask, VT, 32))
5456 return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
5457 if (isREVMask(ShuffleMask, VT, 16))
5458 return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
5460 bool ReverseEXT = false;
5462 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
5465 Imm *= getExtFactor(V1);
5466 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
5467 DAG.getConstant(Imm, dl, MVT::i32));
5468 } else if (V2->getOpcode() == ISD::UNDEF &&
5469 isSingletonEXTMask(ShuffleMask, VT, Imm)) {
5470 Imm *= getExtFactor(V1);
5471 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
5472 DAG.getConstant(Imm, dl, MVT::i32));
5475 unsigned WhichResult;
5476 if (isZIPMask(ShuffleMask, VT, WhichResult)) {
5477 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5478 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5480 if (isUZPMask(ShuffleMask, VT, WhichResult)) {
5481 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5482 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5484 if (isTRNMask(ShuffleMask, VT, WhichResult)) {
5485 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5486 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5489 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5490 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5491 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5493 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5494 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5495 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5497 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5498 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5499 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5502 SDValue Concat = tryFormConcatFromShuffle(Op, DAG);
5503 if (Concat.getNode())
5508 int NumInputElements = V1.getValueType().getVectorNumElements();
5509 if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
5510 SDValue DstVec = DstIsLeft ? V1 : V2;
5511 SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
5513 SDValue SrcVec = V1;
5514 int SrcLane = ShuffleMask[Anomaly];
5515 if (SrcLane >= NumInputElements) {
5517 SrcLane -= VT.getVectorNumElements();
5519 SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
5521 EVT ScalarVT = VT.getVectorElementType();
5523 if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
5524 ScalarVT = MVT::i32;
5527 ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5528 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
5532 // If the shuffle is not directly supported and it has 4 elements, use
5533 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5534 unsigned NumElts = VT.getVectorNumElements();
5536 unsigned PFIndexes[4];
5537 for (unsigned i = 0; i != 4; ++i) {
5538 if (ShuffleMask[i] < 0)
5541 PFIndexes[i] = ShuffleMask[i];
5544 // Compute the index in the perfect shuffle table.
5545 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
5546 PFIndexes[2] * 9 + PFIndexes[3];
5547 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5548 unsigned Cost = (PFEntry >> 30);
5551 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5554 return GenerateTBL(Op, ShuffleMask, DAG);
5557 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
5559 EVT VT = BVN->getValueType(0);
5560 APInt SplatBits, SplatUndef;
5561 unsigned SplatBitSize;
5563 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5564 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
5566 for (unsigned i = 0; i < NumSplats; ++i) {
5567 CnstBits <<= SplatBitSize;
5568 UndefBits <<= SplatBitSize;
5569 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
5570 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
5579 SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op,
5580 SelectionDAG &DAG) const {
5581 BuildVectorSDNode *BVN =
5582 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5583 SDValue LHS = Op.getOperand(0);
5585 EVT VT = Op.getValueType();
5590 APInt CnstBits(VT.getSizeInBits(), 0);
5591 APInt UndefBits(VT.getSizeInBits(), 0);
5592 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5593 // We only have BIC vector immediate instruction, which is and-not.
5594 CnstBits = ~CnstBits;
5596 // We make use of a little bit of goto ickiness in order to avoid having to
5597 // duplicate the immediate matching logic for the undef toggled case.
5598 bool SecondTry = false;
5601 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5602 CnstBits = CnstBits.zextOrTrunc(64);
5603 uint64_t CnstVal = CnstBits.getZExtValue();
5605 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5606 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5607 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5608 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5609 DAG.getConstant(CnstVal, dl, MVT::i32),
5610 DAG.getConstant(0, dl, MVT::i32));
5611 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5614 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5615 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5616 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5617 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5618 DAG.getConstant(CnstVal, dl, MVT::i32),
5619 DAG.getConstant(8, dl, MVT::i32));
5620 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5623 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5624 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5625 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5626 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5627 DAG.getConstant(CnstVal, dl, MVT::i32),
5628 DAG.getConstant(16, dl, MVT::i32));
5629 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5632 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5633 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5634 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5635 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5636 DAG.getConstant(CnstVal, dl, MVT::i32),
5637 DAG.getConstant(24, dl, MVT::i32));
5638 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5641 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5642 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5643 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5644 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5645 DAG.getConstant(CnstVal, dl, MVT::i32),
5646 DAG.getConstant(0, dl, MVT::i32));
5647 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5650 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5651 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5652 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5653 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5654 DAG.getConstant(CnstVal, dl, MVT::i32),
5655 DAG.getConstant(8, dl, MVT::i32));
5656 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5663 CnstBits = ~UndefBits;
5667 // We can always fall back to a non-immediate AND.
5672 // Specialized code to quickly find if PotentialBVec is a BuildVector that
5673 // consists of only the same constant int value, returned in reference arg
5675 static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
5676 uint64_t &ConstVal) {
5677 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
5680 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
5683 EVT VT = Bvec->getValueType(0);
5684 unsigned NumElts = VT.getVectorNumElements();
5685 for (unsigned i = 1; i < NumElts; ++i)
5686 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
5688 ConstVal = FirstElt->getZExtValue();
5692 static unsigned getIntrinsicID(const SDNode *N) {
5693 unsigned Opcode = N->getOpcode();
5696 return Intrinsic::not_intrinsic;
5697 case ISD::INTRINSIC_WO_CHAIN: {
5698 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
5699 if (IID < Intrinsic::num_intrinsics)
5701 return Intrinsic::not_intrinsic;
5706 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
5707 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
5708 // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
5709 // Also, logical shift right -> sri, with the same structure.
5710 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
5711 EVT VT = N->getValueType(0);
5718 // Is the first op an AND?
5719 const SDValue And = N->getOperand(0);
5720 if (And.getOpcode() != ISD::AND)
5723 // Is the second op an shl or lshr?
5724 SDValue Shift = N->getOperand(1);
5725 // This will have been turned into: AArch64ISD::VSHL vector, #shift
5726 // or AArch64ISD::VLSHR vector, #shift
5727 unsigned ShiftOpc = Shift.getOpcode();
5728 if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
5730 bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
5732 // Is the shift amount constant?
5733 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
5737 // Is the and mask vector all constant?
5739 if (!isAllConstantBuildVector(And.getOperand(1), C1))
5742 // Is C1 == ~C2, taking into account how much one can shift elements of a
5744 uint64_t C2 = C2node->getZExtValue();
5745 unsigned ElemSizeInBits = VT.getVectorElementType().getSizeInBits();
5746 if (C2 > ElemSizeInBits)
5748 unsigned ElemMask = (1 << ElemSizeInBits) - 1;
5749 if ((C1 & ElemMask) != (~C2 & ElemMask))
5752 SDValue X = And.getOperand(0);
5753 SDValue Y = Shift.getOperand(0);
5756 IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
5758 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
5759 DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
5760 Shift.getOperand(1));
5762 DEBUG(dbgs() << "aarch64-lower: transformed: \n");
5763 DEBUG(N->dump(&DAG));
5764 DEBUG(dbgs() << "into: \n");
5765 DEBUG(ResultSLI->dump(&DAG));
5771 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
5772 SelectionDAG &DAG) const {
5773 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
5774 if (EnableAArch64SlrGeneration) {
5775 SDValue Res = tryLowerToSLI(Op.getNode(), DAG);
5780 BuildVectorSDNode *BVN =
5781 dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
5782 SDValue LHS = Op.getOperand(1);
5784 EVT VT = Op.getValueType();
5786 // OR commutes, so try swapping the operands.
5788 LHS = Op.getOperand(0);
5789 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5794 APInt CnstBits(VT.getSizeInBits(), 0);
5795 APInt UndefBits(VT.getSizeInBits(), 0);
5796 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5797 // We make use of a little bit of goto ickiness in order to avoid having to
5798 // duplicate the immediate matching logic for the undef toggled case.
5799 bool SecondTry = false;
5802 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5803 CnstBits = CnstBits.zextOrTrunc(64);
5804 uint64_t CnstVal = CnstBits.getZExtValue();
5806 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5807 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5808 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5809 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5810 DAG.getConstant(CnstVal, dl, MVT::i32),
5811 DAG.getConstant(0, dl, MVT::i32));
5812 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5815 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5816 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5817 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5818 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5819 DAG.getConstant(CnstVal, dl, MVT::i32),
5820 DAG.getConstant(8, dl, MVT::i32));
5821 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5824 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5825 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5826 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5827 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5828 DAG.getConstant(CnstVal, dl, MVT::i32),
5829 DAG.getConstant(16, dl, MVT::i32));
5830 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5833 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5834 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5835 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5836 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5837 DAG.getConstant(CnstVal, dl, MVT::i32),
5838 DAG.getConstant(24, dl, MVT::i32));
5839 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5842 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5843 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5844 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5845 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5846 DAG.getConstant(CnstVal, dl, MVT::i32),
5847 DAG.getConstant(0, dl, MVT::i32));
5848 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5851 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5852 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5853 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5854 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5855 DAG.getConstant(CnstVal, dl, MVT::i32),
5856 DAG.getConstant(8, dl, MVT::i32));
5857 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5864 CnstBits = UndefBits;
5868 // We can always fall back to a non-immediate OR.
5873 // Normalize the operands of BUILD_VECTOR. The value of constant operands will
5874 // be truncated to fit element width.
5875 static SDValue NormalizeBuildVector(SDValue Op,
5876 SelectionDAG &DAG) {
5877 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
5879 EVT VT = Op.getValueType();
5880 EVT EltTy= VT.getVectorElementType();
5882 if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
5885 SmallVector<SDValue, 16> Ops;
5886 for (SDValue Lane : Op->ops()) {
5887 if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
5888 APInt LowBits(EltTy.getSizeInBits(),
5889 CstLane->getZExtValue());
5890 Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
5892 Ops.push_back(Lane);
5894 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5897 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
5898 SelectionDAG &DAG) const {
5900 EVT VT = Op.getValueType();
5901 Op = NormalizeBuildVector(Op, DAG);
5902 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5904 APInt CnstBits(VT.getSizeInBits(), 0);
5905 APInt UndefBits(VT.getSizeInBits(), 0);
5906 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5907 // We make use of a little bit of goto ickiness in order to avoid having to
5908 // duplicate the immediate matching logic for the undef toggled case.
5909 bool SecondTry = false;
5912 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5913 CnstBits = CnstBits.zextOrTrunc(64);
5914 uint64_t CnstVal = CnstBits.getZExtValue();
5916 // Certain magic vector constants (used to express things like NOT
5917 // and NEG) are passed through unmodified. This allows codegen patterns
5918 // for these operations to match. Special-purpose patterns will lower
5919 // these immediates to MOVIs if it proves necessary.
5920 if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL))
5923 // The many faces of MOVI...
5924 if (AArch64_AM::isAdvSIMDModImmType10(CnstVal)) {
5925 CnstVal = AArch64_AM::encodeAdvSIMDModImmType10(CnstVal);
5926 if (VT.getSizeInBits() == 128) {
5927 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::v2i64,
5928 DAG.getConstant(CnstVal, dl, MVT::i32));
5929 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5932 // Support the V64 version via subregister insertion.
5933 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::f64,
5934 DAG.getConstant(CnstVal, dl, MVT::i32));
5935 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5938 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5939 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5940 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5941 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5942 DAG.getConstant(CnstVal, dl, MVT::i32),
5943 DAG.getConstant(0, dl, MVT::i32));
5944 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5947 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5948 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5949 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5950 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5951 DAG.getConstant(CnstVal, dl, MVT::i32),
5952 DAG.getConstant(8, dl, MVT::i32));
5953 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5956 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5957 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5958 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5959 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5960 DAG.getConstant(CnstVal, dl, MVT::i32),
5961 DAG.getConstant(16, dl, MVT::i32));
5962 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5965 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5966 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5967 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5968 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5969 DAG.getConstant(CnstVal, dl, MVT::i32),
5970 DAG.getConstant(24, dl, MVT::i32));
5971 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5974 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5975 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5976 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5977 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5978 DAG.getConstant(CnstVal, dl, MVT::i32),
5979 DAG.getConstant(0, dl, MVT::i32));
5980 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5983 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5984 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5985 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5986 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5987 DAG.getConstant(CnstVal, dl, MVT::i32),
5988 DAG.getConstant(8, dl, MVT::i32));
5989 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5992 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
5993 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
5994 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5995 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
5996 DAG.getConstant(CnstVal, dl, MVT::i32),
5997 DAG.getConstant(264, dl, MVT::i32));
5998 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6001 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6002 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6003 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6004 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
6005 DAG.getConstant(CnstVal, dl, MVT::i32),
6006 DAG.getConstant(272, dl, MVT::i32));
6007 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6010 if (AArch64_AM::isAdvSIMDModImmType9(CnstVal)) {
6011 CnstVal = AArch64_AM::encodeAdvSIMDModImmType9(CnstVal);
6012 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
6013 SDValue Mov = DAG.getNode(AArch64ISD::MOVI, dl, MovTy,
6014 DAG.getConstant(CnstVal, dl, MVT::i32));
6015 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6018 // The few faces of FMOV...
6019 if (AArch64_AM::isAdvSIMDModImmType11(CnstVal)) {
6020 CnstVal = AArch64_AM::encodeAdvSIMDModImmType11(CnstVal);
6021 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32;
6022 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MovTy,
6023 DAG.getConstant(CnstVal, dl, MVT::i32));
6024 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6027 if (AArch64_AM::isAdvSIMDModImmType12(CnstVal) &&
6028 VT.getSizeInBits() == 128) {
6029 CnstVal = AArch64_AM::encodeAdvSIMDModImmType12(CnstVal);
6030 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MVT::v2f64,
6031 DAG.getConstant(CnstVal, dl, MVT::i32));
6032 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6035 // The many faces of MVNI...
6037 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6038 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6039 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6040 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6041 DAG.getConstant(CnstVal, dl, MVT::i32),
6042 DAG.getConstant(0, dl, MVT::i32));
6043 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6046 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6047 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6048 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6049 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6050 DAG.getConstant(CnstVal, dl, MVT::i32),
6051 DAG.getConstant(8, dl, MVT::i32));
6052 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6055 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6056 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6057 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6058 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6059 DAG.getConstant(CnstVal, dl, MVT::i32),
6060 DAG.getConstant(16, dl, MVT::i32));
6061 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6064 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6065 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6066 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6067 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6068 DAG.getConstant(CnstVal, dl, MVT::i32),
6069 DAG.getConstant(24, dl, MVT::i32));
6070 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6073 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6074 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6075 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6076 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6077 DAG.getConstant(CnstVal, dl, MVT::i32),
6078 DAG.getConstant(0, dl, MVT::i32));
6079 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6082 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6083 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6084 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6085 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6086 DAG.getConstant(CnstVal, dl, MVT::i32),
6087 DAG.getConstant(8, dl, MVT::i32));
6088 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6091 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6092 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6093 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6094 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
6095 DAG.getConstant(CnstVal, dl, MVT::i32),
6096 DAG.getConstant(264, dl, MVT::i32));
6097 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6100 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6101 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6102 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6103 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
6104 DAG.getConstant(CnstVal, dl, MVT::i32),
6105 DAG.getConstant(272, dl, MVT::i32));
6106 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6113 CnstBits = UndefBits;
6118 // Scan through the operands to find some interesting properties we can
6120 // 1) If only one value is used, we can use a DUP, or
6121 // 2) if only the low element is not undef, we can just insert that, or
6122 // 3) if only one constant value is used (w/ some non-constant lanes),
6123 // we can splat the constant value into the whole vector then fill
6124 // in the non-constant lanes.
6125 // 4) FIXME: If different constant values are used, but we can intelligently
6126 // select the values we'll be overwriting for the non-constant
6127 // lanes such that we can directly materialize the vector
6128 // some other way (MOVI, e.g.), we can be sneaky.
6129 unsigned NumElts = VT.getVectorNumElements();
6130 bool isOnlyLowElement = true;
6131 bool usesOnlyOneValue = true;
6132 bool usesOnlyOneConstantValue = true;
6133 bool isConstant = true;
6134 unsigned NumConstantLanes = 0;
6136 SDValue ConstantValue;
6137 for (unsigned i = 0; i < NumElts; ++i) {
6138 SDValue V = Op.getOperand(i);
6139 if (V.getOpcode() == ISD::UNDEF)
6142 isOnlyLowElement = false;
6143 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6146 if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
6148 if (!ConstantValue.getNode())
6150 else if (ConstantValue != V)
6151 usesOnlyOneConstantValue = false;
6154 if (!Value.getNode())
6156 else if (V != Value)
6157 usesOnlyOneValue = false;
6160 if (!Value.getNode())
6161 return DAG.getUNDEF(VT);
6163 if (isOnlyLowElement)
6164 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
6166 // Use DUP for non-constant splats. For f32 constant splats, reduce to
6167 // i32 and try again.
6168 if (usesOnlyOneValue) {
6170 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6171 Value.getValueType() != VT)
6172 return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
6174 // This is actually a DUPLANExx operation, which keeps everything vectory.
6176 // DUPLANE works on 128-bit vectors, widen it if necessary.
6177 SDValue Lane = Value.getOperand(1);
6178 Value = Value.getOperand(0);
6179 if (Value.getValueType().getSizeInBits() == 64)
6180 Value = WidenVector(Value, DAG);
6182 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
6183 return DAG.getNode(Opcode, dl, VT, Value, Lane);
6186 if (VT.getVectorElementType().isFloatingPoint()) {
6187 SmallVector<SDValue, 8> Ops;
6188 EVT EltTy = VT.getVectorElementType();
6189 assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
6190 "Unsupported floating-point vector type");
6191 MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
6192 for (unsigned i = 0; i < NumElts; ++i)
6193 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
6194 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
6195 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
6196 Val = LowerBUILD_VECTOR(Val, DAG);
6198 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6202 // If there was only one constant value used and for more than one lane,
6203 // start by splatting that value, then replace the non-constant lanes. This
6204 // is better than the default, which will perform a separate initialization
6206 if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
6207 SDValue Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
6208 // Now insert the non-constant lanes.
6209 for (unsigned i = 0; i < NumElts; ++i) {
6210 SDValue V = Op.getOperand(i);
6211 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
6212 if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) {
6213 // Note that type legalization likely mucked about with the VT of the
6214 // source operand, so we may have to convert it here before inserting.
6215 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
6221 // If all elements are constants and the case above didn't get hit, fall back
6222 // to the default expansion, which will generate a load from the constant
6227 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6229 if (SDValue shuffle = ReconstructShuffle(Op, DAG))
6233 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6234 // know the default expansion would otherwise fall back on something even
6235 // worse. For a vector with one or two non-undef values, that's
6236 // scalar_to_vector for the elements followed by a shuffle (provided the
6237 // shuffle is valid for the target) and materialization element by element
6238 // on the stack followed by a load for everything else.
6239 if (!isConstant && !usesOnlyOneValue) {
6240 SDValue Vec = DAG.getUNDEF(VT);
6241 SDValue Op0 = Op.getOperand(0);
6242 unsigned ElemSize = VT.getVectorElementType().getSizeInBits();
6244 // For 32 and 64 bit types, use INSERT_SUBREG for lane zero to
6245 // a) Avoid a RMW dependency on the full vector register, and
6246 // b) Allow the register coalescer to fold away the copy if the
6247 // value is already in an S or D register.
6248 if (Op0.getOpcode() != ISD::UNDEF && (ElemSize == 32 || ElemSize == 64)) {
6249 unsigned SubIdx = ElemSize == 32 ? AArch64::ssub : AArch64::dsub;
6251 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl, VT, Vec, Op0,
6252 DAG.getTargetConstant(SubIdx, dl, MVT::i32));
6253 Vec = SDValue(N, 0);
6256 for (; i < NumElts; ++i) {
6257 SDValue V = Op.getOperand(i);
6258 if (V.getOpcode() == ISD::UNDEF)
6260 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
6261 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6266 // Just use the default expansion. We failed to find a better alternative.
6270 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
6271 SelectionDAG &DAG) const {
6272 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
6274 // Check for non-constant or out of range lane.
6275 EVT VT = Op.getOperand(0).getValueType();
6276 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
6277 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
6281 // Insertion/extraction are legal for V128 types.
6282 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
6283 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6287 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
6288 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
6291 // For V64 types, we perform insertion by expanding the value
6292 // to a V128 type and perform the insertion on that.
6294 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6295 EVT WideTy = WideVec.getValueType();
6297 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
6298 Op.getOperand(1), Op.getOperand(2));
6299 // Re-narrow the resultant vector.
6300 return NarrowVector(Node, DAG);
6304 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6305 SelectionDAG &DAG) const {
6306 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
6308 // Check for non-constant or out of range lane.
6309 EVT VT = Op.getOperand(0).getValueType();
6310 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6311 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
6315 // Insertion/extraction are legal for V128 types.
6316 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
6317 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6321 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
6322 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
6325 // For V64 types, we perform extraction by expanding the value
6326 // to a V128 type and perform the extraction on that.
6328 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6329 EVT WideTy = WideVec.getValueType();
6331 EVT ExtrTy = WideTy.getVectorElementType();
6332 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
6335 // For extractions, we just return the result directly.
6336 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
6340 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
6341 SelectionDAG &DAG) const {
6342 EVT VT = Op.getOperand(0).getValueType();
6348 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6351 unsigned Val = Cst->getZExtValue();
6353 unsigned Size = Op.getValueType().getSizeInBits();
6357 return DAG.getTargetExtractSubreg(AArch64::bsub, dl, Op.getValueType(),
6360 return DAG.getTargetExtractSubreg(AArch64::hsub, dl, Op.getValueType(),
6363 return DAG.getTargetExtractSubreg(AArch64::ssub, dl, Op.getValueType(),
6366 return DAG.getTargetExtractSubreg(AArch64::dsub, dl, Op.getValueType(),
6369 llvm_unreachable("Unexpected vector type in extract_subvector!");
6372 // If this is extracting the upper 64-bits of a 128-bit vector, we match
6374 if (Size == 64 && Val * VT.getVectorElementType().getSizeInBits() == 64)
6380 bool AArch64TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
6382 if (VT.getVectorNumElements() == 4 &&
6383 (VT.is128BitVector() || VT.is64BitVector())) {
6384 unsigned PFIndexes[4];
6385 for (unsigned i = 0; i != 4; ++i) {
6389 PFIndexes[i] = M[i];
6392 // Compute the index in the perfect shuffle table.
6393 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6394 PFIndexes[2] * 9 + PFIndexes[3];
6395 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6396 unsigned Cost = (PFEntry >> 30);
6404 unsigned DummyUnsigned;
6406 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
6407 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
6408 isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
6409 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
6410 isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
6411 isZIPMask(M, VT, DummyUnsigned) ||
6412 isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
6413 isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
6414 isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
6415 isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
6416 isConcatMask(M, VT, VT.getSizeInBits() == 128));
6419 /// getVShiftImm - Check if this is a valid build_vector for the immediate
6420 /// operand of a vector shift operation, where all the elements of the
6421 /// build_vector must have the same constant integer value.
6422 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
6423 // Ignore bit_converts.
6424 while (Op.getOpcode() == ISD::BITCAST)
6425 Op = Op.getOperand(0);
6426 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6427 APInt SplatBits, SplatUndef;
6428 unsigned SplatBitSize;
6430 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
6431 HasAnyUndefs, ElementBits) ||
6432 SplatBitSize > ElementBits)
6434 Cnt = SplatBits.getSExtValue();
6438 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
6439 /// operand of a vector shift left operation. That value must be in the range:
6440 /// 0 <= Value < ElementBits for a left shift; or
6441 /// 0 <= Value <= ElementBits for a long left shift.
6442 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
6443 assert(VT.isVector() && "vector shift count is not a vector type");
6444 int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
6445 if (!getVShiftImm(Op, ElementBits, Cnt))
6447 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
6450 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
6451 /// operand of a vector shift right operation. The value must be in the range:
6452 /// 1 <= Value <= ElementBits for a right shift; or
6453 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
6454 assert(VT.isVector() && "vector shift count is not a vector type");
6455 int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
6456 if (!getVShiftImm(Op, ElementBits, Cnt))
6458 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
6461 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
6462 SelectionDAG &DAG) const {
6463 EVT VT = Op.getValueType();
6467 if (!Op.getOperand(1).getValueType().isVector())
6469 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6471 switch (Op.getOpcode()) {
6473 llvm_unreachable("unexpected shift opcode");
6476 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
6477 return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
6478 DAG.getConstant(Cnt, DL, MVT::i32));
6479 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
6480 DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
6482 Op.getOperand(0), Op.getOperand(1));
6485 // Right shift immediate
6486 if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
6488 (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
6489 return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
6490 DAG.getConstant(Cnt, DL, MVT::i32));
6493 // Right shift register. Note, there is not a shift right register
6494 // instruction, but the shift left register instruction takes a signed
6495 // value, where negative numbers specify a right shift.
6496 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
6497 : Intrinsic::aarch64_neon_ushl;
6498 // negate the shift amount
6499 SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
6500 SDValue NegShiftLeft =
6501 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
6502 DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
6504 return NegShiftLeft;
6510 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
6511 AArch64CC::CondCode CC, bool NoNans, EVT VT,
6512 SDLoc dl, SelectionDAG &DAG) {
6513 EVT SrcVT = LHS.getValueType();
6514 assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
6515 "function only supposed to emit natural comparisons");
6517 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
6518 APInt CnstBits(VT.getSizeInBits(), 0);
6519 APInt UndefBits(VT.getSizeInBits(), 0);
6520 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
6521 bool IsZero = IsCnst && (CnstBits == 0);
6523 if (SrcVT.getVectorElementType().isFloatingPoint()) {
6527 case AArch64CC::NE: {
6530 Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6532 Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6533 return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
6537 return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6538 return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6541 return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
6542 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
6545 return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
6546 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
6549 return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
6550 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
6554 // If we ignore NaNs then we can use to the MI implementation.
6558 return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
6559 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
6566 case AArch64CC::NE: {
6569 Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6571 Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6572 return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
6576 return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6577 return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6580 return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
6581 return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
6584 return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
6585 return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
6588 return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
6589 return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
6591 return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
6593 return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
6596 return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
6597 return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
6599 return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
6601 return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
6605 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
6606 SelectionDAG &DAG) const {
6607 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6608 SDValue LHS = Op.getOperand(0);
6609 SDValue RHS = Op.getOperand(1);
6610 EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
6613 if (LHS.getValueType().getVectorElementType().isInteger()) {
6614 assert(LHS.getValueType() == RHS.getValueType());
6615 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
6617 EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
6618 return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
6621 assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
6622 LHS.getValueType().getVectorElementType() == MVT::f64);
6624 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
6625 // clean. Some of them require two branches to implement.
6626 AArch64CC::CondCode CC1, CC2;
6628 changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
6630 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
6632 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
6636 if (CC2 != AArch64CC::AL) {
6638 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
6639 if (!Cmp2.getNode())
6642 Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
6645 Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
6648 return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
6653 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
6654 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
6655 /// specified in the intrinsic calls.
6656 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
6658 unsigned Intrinsic) const {
6659 auto &DL = I.getModule()->getDataLayout();
6660 switch (Intrinsic) {
6661 case Intrinsic::aarch64_neon_ld2:
6662 case Intrinsic::aarch64_neon_ld3:
6663 case Intrinsic::aarch64_neon_ld4:
6664 case Intrinsic::aarch64_neon_ld1x2:
6665 case Intrinsic::aarch64_neon_ld1x3:
6666 case Intrinsic::aarch64_neon_ld1x4:
6667 case Intrinsic::aarch64_neon_ld2lane:
6668 case Intrinsic::aarch64_neon_ld3lane:
6669 case Intrinsic::aarch64_neon_ld4lane:
6670 case Intrinsic::aarch64_neon_ld2r:
6671 case Intrinsic::aarch64_neon_ld3r:
6672 case Intrinsic::aarch64_neon_ld4r: {
6673 Info.opc = ISD::INTRINSIC_W_CHAIN;
6674 // Conservatively set memVT to the entire set of vectors loaded.
6675 uint64_t NumElts = DL.getTypeAllocSize(I.getType()) / 8;
6676 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6677 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6680 Info.vol = false; // volatile loads with NEON intrinsics not supported
6681 Info.readMem = true;
6682 Info.writeMem = false;
6685 case Intrinsic::aarch64_neon_st2:
6686 case Intrinsic::aarch64_neon_st3:
6687 case Intrinsic::aarch64_neon_st4:
6688 case Intrinsic::aarch64_neon_st1x2:
6689 case Intrinsic::aarch64_neon_st1x3:
6690 case Intrinsic::aarch64_neon_st1x4:
6691 case Intrinsic::aarch64_neon_st2lane:
6692 case Intrinsic::aarch64_neon_st3lane:
6693 case Intrinsic::aarch64_neon_st4lane: {
6694 Info.opc = ISD::INTRINSIC_VOID;
6695 // Conservatively set memVT to the entire set of vectors stored.
6696 unsigned NumElts = 0;
6697 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
6698 Type *ArgTy = I.getArgOperand(ArgI)->getType();
6699 if (!ArgTy->isVectorTy())
6701 NumElts += DL.getTypeAllocSize(ArgTy) / 8;
6703 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6704 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6707 Info.vol = false; // volatile stores with NEON intrinsics not supported
6708 Info.readMem = false;
6709 Info.writeMem = true;
6712 case Intrinsic::aarch64_ldaxr:
6713 case Intrinsic::aarch64_ldxr: {
6714 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
6715 Info.opc = ISD::INTRINSIC_W_CHAIN;
6716 Info.memVT = MVT::getVT(PtrTy->getElementType());
6717 Info.ptrVal = I.getArgOperand(0);
6719 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
6721 Info.readMem = true;
6722 Info.writeMem = false;
6725 case Intrinsic::aarch64_stlxr:
6726 case Intrinsic::aarch64_stxr: {
6727 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
6728 Info.opc = ISD::INTRINSIC_W_CHAIN;
6729 Info.memVT = MVT::getVT(PtrTy->getElementType());
6730 Info.ptrVal = I.getArgOperand(1);
6732 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
6734 Info.readMem = false;
6735 Info.writeMem = true;
6738 case Intrinsic::aarch64_ldaxp:
6739 case Intrinsic::aarch64_ldxp: {
6740 Info.opc = ISD::INTRINSIC_W_CHAIN;
6741 Info.memVT = MVT::i128;
6742 Info.ptrVal = I.getArgOperand(0);
6746 Info.readMem = true;
6747 Info.writeMem = false;
6750 case Intrinsic::aarch64_stlxp:
6751 case Intrinsic::aarch64_stxp: {
6752 Info.opc = ISD::INTRINSIC_W_CHAIN;
6753 Info.memVT = MVT::i128;
6754 Info.ptrVal = I.getArgOperand(2);
6758 Info.readMem = false;
6759 Info.writeMem = true;
6769 // Truncations from 64-bit GPR to 32-bit GPR is free.
6770 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
6771 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6773 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6774 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6775 return NumBits1 > NumBits2;
6777 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
6778 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
6780 unsigned NumBits1 = VT1.getSizeInBits();
6781 unsigned NumBits2 = VT2.getSizeInBits();
6782 return NumBits1 > NumBits2;
6785 /// Check if it is profitable to hoist instruction in then/else to if.
6786 /// Not profitable if I and it's user can form a FMA instruction
6787 /// because we prefer FMSUB/FMADD.
6788 bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
6789 if (I->getOpcode() != Instruction::FMul)
6792 if (I->getNumUses() != 1)
6795 Instruction *User = I->user_back();
6798 !(User->getOpcode() == Instruction::FSub ||
6799 User->getOpcode() == Instruction::FAdd))
6802 const TargetOptions &Options = getTargetMachine().Options;
6803 const DataLayout &DL = I->getModule()->getDataLayout();
6804 EVT VT = getValueType(DL, User->getOperand(0)->getType());
6806 if (isFMAFasterThanFMulAndFAdd(VT) &&
6807 isOperationLegalOrCustom(ISD::FMA, VT) &&
6808 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath))
6814 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
6816 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
6817 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6819 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6820 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6821 return NumBits1 == 32 && NumBits2 == 64;
6823 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
6824 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
6826 unsigned NumBits1 = VT1.getSizeInBits();
6827 unsigned NumBits2 = VT2.getSizeInBits();
6828 return NumBits1 == 32 && NumBits2 == 64;
6831 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
6832 EVT VT1 = Val.getValueType();
6833 if (isZExtFree(VT1, VT2)) {
6837 if (Val.getOpcode() != ISD::LOAD)
6840 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
6841 return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
6842 VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
6843 VT1.getSizeInBits() <= 32);
6846 bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
6847 if (isa<FPExtInst>(Ext))
6850 // Vector types are next free.
6851 if (Ext->getType()->isVectorTy())
6854 for (const Use &U : Ext->uses()) {
6855 // The extension is free if we can fold it with a left shift in an
6856 // addressing mode or an arithmetic operation: add, sub, and cmp.
6858 // Is there a shift?
6859 const Instruction *Instr = cast<Instruction>(U.getUser());
6861 // Is this a constant shift?
6862 switch (Instr->getOpcode()) {
6863 case Instruction::Shl:
6864 if (!isa<ConstantInt>(Instr->getOperand(1)))
6867 case Instruction::GetElementPtr: {
6868 gep_type_iterator GTI = gep_type_begin(Instr);
6869 auto &DL = Ext->getModule()->getDataLayout();
6870 std::advance(GTI, U.getOperandNo());
6872 // This extension will end up with a shift because of the scaling factor.
6873 // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
6874 // Get the shift amount based on the scaling factor:
6875 // log2(sizeof(IdxTy)) - log2(8).
6877 countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3;
6878 // Is the constant foldable in the shift of the addressing mode?
6879 // I.e., shift amount is between 1 and 4 inclusive.
6880 if (ShiftAmt == 0 || ShiftAmt > 4)
6884 case Instruction::Trunc:
6885 // Check if this is a noop.
6886 // trunc(sext ty1 to ty2) to ty1.
6887 if (Instr->getType() == Ext->getOperand(0)->getType())
6894 // At this point we can use the bfm family, so this extension is free
6900 bool AArch64TargetLowering::hasPairedLoad(Type *LoadedType,
6901 unsigned &RequiredAligment) const {
6902 if (!LoadedType->isIntegerTy() && !LoadedType->isFloatTy())
6904 // Cyclone supports unaligned accesses.
6905 RequiredAligment = 0;
6906 unsigned NumBits = LoadedType->getPrimitiveSizeInBits();
6907 return NumBits == 32 || NumBits == 64;
6910 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
6911 unsigned &RequiredAligment) const {
6912 if (!LoadedType.isSimple() ||
6913 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
6915 // Cyclone supports unaligned accesses.
6916 RequiredAligment = 0;
6917 unsigned NumBits = LoadedType.getSizeInBits();
6918 return NumBits == 32 || NumBits == 64;
6921 /// \brief Lower an interleaved load into a ldN intrinsic.
6923 /// E.g. Lower an interleaved load (Factor = 2):
6924 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr
6925 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
6926 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
6929 /// %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
6930 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
6931 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
6932 bool AArch64TargetLowering::lowerInterleavedLoad(
6933 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
6934 ArrayRef<unsigned> Indices, unsigned Factor) const {
6935 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
6936 "Invalid interleave factor");
6937 assert(!Shuffles.empty() && "Empty shufflevector input");
6938 assert(Shuffles.size() == Indices.size() &&
6939 "Unmatched number of shufflevectors and indices");
6941 const DataLayout &DL = LI->getModule()->getDataLayout();
6943 VectorType *VecTy = Shuffles[0]->getType();
6944 unsigned VecSize = DL.getTypeAllocSizeInBits(VecTy);
6946 // Skip illegal vector types.
6947 if (VecSize != 64 && VecSize != 128)
6950 // A pointer vector can not be the return type of the ldN intrinsics. Need to
6951 // load integer vectors first and then convert to pointer vectors.
6952 Type *EltTy = VecTy->getVectorElementType();
6953 if (EltTy->isPointerTy())
6955 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
6957 Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
6958 Type *Tys[2] = {VecTy, PtrTy};
6959 static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
6960 Intrinsic::aarch64_neon_ld3,
6961 Intrinsic::aarch64_neon_ld4};
6963 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
6965 IRBuilder<> Builder(LI);
6966 Value *Ptr = Builder.CreateBitCast(LI->getPointerOperand(), PtrTy);
6968 CallInst *LdN = Builder.CreateCall(LdNFunc, Ptr, "ldN");
6970 // Replace uses of each shufflevector with the corresponding vector loaded
6972 for (unsigned i = 0; i < Shuffles.size(); i++) {
6973 ShuffleVectorInst *SVI = Shuffles[i];
6974 unsigned Index = Indices[i];
6976 Value *SubVec = Builder.CreateExtractValue(LdN, Index);
6978 // Convert the integer vector to pointer vector if the element is pointer.
6979 if (EltTy->isPointerTy())
6980 SubVec = Builder.CreateIntToPtr(SubVec, SVI->getType());
6982 SVI->replaceAllUsesWith(SubVec);
6988 /// \brief Get a mask consisting of sequential integers starting from \p Start.
6990 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
6991 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
6993 SmallVector<Constant *, 16> Mask;
6994 for (unsigned i = 0; i < NumElts; i++)
6995 Mask.push_back(Builder.getInt32(Start + i));
6997 return ConstantVector::get(Mask);
7000 /// \brief Lower an interleaved store into a stN intrinsic.
7002 /// E.g. Lower an interleaved store (Factor = 3):
7003 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
7004 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
7005 /// store <12 x i32> %i.vec, <12 x i32>* %ptr
7008 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
7009 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
7010 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
7011 /// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
7013 /// Note that the new shufflevectors will be removed and we'll only generate one
7014 /// st3 instruction in CodeGen.
7015 bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
7016 ShuffleVectorInst *SVI,
7017 unsigned Factor) const {
7018 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7019 "Invalid interleave factor");
7021 VectorType *VecTy = SVI->getType();
7022 assert(VecTy->getVectorNumElements() % Factor == 0 &&
7023 "Invalid interleaved store");
7025 unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
7026 Type *EltTy = VecTy->getVectorElementType();
7027 VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
7029 const DataLayout &DL = SI->getModule()->getDataLayout();
7030 unsigned SubVecSize = DL.getTypeAllocSizeInBits(SubVecTy);
7032 // Skip illegal vector types.
7033 if (SubVecSize != 64 && SubVecSize != 128)
7036 Value *Op0 = SVI->getOperand(0);
7037 Value *Op1 = SVI->getOperand(1);
7038 IRBuilder<> Builder(SI);
7040 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
7041 // vectors to integer vectors.
7042 if (EltTy->isPointerTy()) {
7043 Type *IntTy = DL.getIntPtrType(EltTy);
7044 unsigned NumOpElts =
7045 dyn_cast<VectorType>(Op0->getType())->getVectorNumElements();
7047 // Convert to the corresponding integer vector.
7048 Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
7049 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
7050 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
7052 SubVecTy = VectorType::get(IntTy, NumSubElts);
7055 Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
7056 Type *Tys[2] = {SubVecTy, PtrTy};
7057 static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
7058 Intrinsic::aarch64_neon_st3,
7059 Intrinsic::aarch64_neon_st4};
7061 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
7063 SmallVector<Value *, 5> Ops;
7065 // Split the shufflevector operands into sub vectors for the new stN call.
7066 for (unsigned i = 0; i < Factor; i++)
7067 Ops.push_back(Builder.CreateShuffleVector(
7068 Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
7070 Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), PtrTy));
7071 Builder.CreateCall(StNFunc, Ops);
7075 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
7076 unsigned AlignCheck) {
7077 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
7078 (DstAlign == 0 || DstAlign % AlignCheck == 0));
7081 EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
7082 unsigned SrcAlign, bool IsMemset,
7085 MachineFunction &MF) const {
7086 // Don't use AdvSIMD to implement 16-byte memset. It would have taken one
7087 // instruction to materialize the v2i64 zero and one store (with restrictive
7088 // addressing mode). Just do two i64 store of zero-registers.
7090 const Function *F = MF.getFunction();
7091 if (Subtarget->hasFPARMv8() && !IsMemset && Size >= 16 &&
7092 !F->hasFnAttribute(Attribute::NoImplicitFloat) &&
7093 (memOpAlign(SrcAlign, DstAlign, 16) ||
7094 (allowsMisalignedMemoryAccesses(MVT::f128, 0, 1, &Fast) && Fast)))
7098 (memOpAlign(SrcAlign, DstAlign, 8) ||
7099 (allowsMisalignedMemoryAccesses(MVT::i64, 0, 1, &Fast) && Fast)))
7103 (memOpAlign(SrcAlign, DstAlign, 4) ||
7104 (allowsMisalignedMemoryAccesses(MVT::i32, 0, 1, &Fast) && Fast)))
7110 // 12-bit optionally shifted immediates are legal for adds.
7111 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
7112 if ((Immed >> 12) == 0 || ((Immed & 0xfff) == 0 && Immed >> 24 == 0))
7117 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
7118 // immediates is the same as for an add or a sub.
7119 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
7122 return isLegalAddImmediate(Immed);
7125 /// isLegalAddressingMode - Return true if the addressing mode represented
7126 /// by AM is legal for this target, for a load/store of the specified type.
7127 bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
7128 const AddrMode &AM, Type *Ty,
7129 unsigned AS) const {
7130 // AArch64 has five basic addressing modes:
7132 // reg + 9-bit signed offset
7133 // reg + SIZE_IN_BYTES * 12-bit unsigned offset
7135 // reg + SIZE_IN_BYTES * reg
7137 // No global is ever allowed as a base.
7141 // No reg+reg+imm addressing.
7142 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
7145 // check reg + imm case:
7146 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
7147 uint64_t NumBytes = 0;
7148 if (Ty->isSized()) {
7149 uint64_t NumBits = DL.getTypeSizeInBits(Ty);
7150 NumBytes = NumBits / 8;
7151 if (!isPowerOf2_64(NumBits))
7156 int64_t Offset = AM.BaseOffs;
7158 // 9-bit signed offset
7159 if (Offset >= -(1LL << 9) && Offset <= (1LL << 9) - 1)
7162 // 12-bit unsigned offset
7163 unsigned shift = Log2_64(NumBytes);
7164 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
7165 // Must be a multiple of NumBytes (NumBytes is a power of 2)
7166 (Offset >> shift) << shift == Offset)
7171 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
7173 if (!AM.Scale || AM.Scale == 1 ||
7174 (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes))
7179 int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
7180 const AddrMode &AM, Type *Ty,
7181 unsigned AS) const {
7182 // Scaling factors are not free at all.
7183 // Operands | Rt Latency
7184 // -------------------------------------------
7186 // -------------------------------------------
7187 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5
7188 // Rt, [Xn, Wm, <extend> #imm] |
7189 if (isLegalAddressingMode(DL, AM, Ty, AS))
7190 // Scale represents reg2 * scale, thus account for 1 if
7191 // it is not equal to 0 or 1.
7192 return AM.Scale != 0 && AM.Scale != 1;
7196 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
7197 VT = VT.getScalarType();
7202 switch (VT.getSimpleVT().SimpleTy) {
7214 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
7215 // LR is a callee-save register, but we must treat it as clobbered by any call
7216 // site. Hence we include LR in the scratch registers, which are in turn added
7217 // as implicit-defs for stackmaps and patchpoints.
7218 static const MCPhysReg ScratchRegs[] = {
7219 AArch64::X16, AArch64::X17, AArch64::LR, 0
7225 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N) const {
7226 EVT VT = N->getValueType(0);
7227 // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
7228 // it with shift to let it be lowered to UBFX.
7229 if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
7230 isa<ConstantSDNode>(N->getOperand(1))) {
7231 uint64_t TruncMask = N->getConstantOperandVal(1);
7232 if (isMask_64(TruncMask) &&
7233 N->getOperand(0).getOpcode() == ISD::SRL &&
7234 isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
7240 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
7242 assert(Ty->isIntegerTy());
7244 unsigned BitSize = Ty->getPrimitiveSizeInBits();
7248 int64_t Val = Imm.getSExtValue();
7249 if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
7252 if ((int64_t)Val < 0)
7255 Val &= (1LL << 32) - 1;
7257 unsigned LZ = countLeadingZeros((uint64_t)Val);
7258 unsigned Shift = (63 - LZ) / 16;
7259 // MOVZ is free so return true for one or fewer MOVK.
7263 // Generate SUBS and CSEL for integer abs.
7264 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
7265 EVT VT = N->getValueType(0);
7267 SDValue N0 = N->getOperand(0);
7268 SDValue N1 = N->getOperand(1);
7271 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
7272 // and change it to SUB and CSEL.
7273 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
7274 N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
7275 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
7276 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
7277 if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
7278 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
7280 // Generate SUBS & CSEL.
7282 DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
7283 N0.getOperand(0), DAG.getConstant(0, DL, VT));
7284 return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
7285 DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
7286 SDValue(Cmp.getNode(), 1));
7291 // performXorCombine - Attempts to handle integer ABS.
7292 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
7293 TargetLowering::DAGCombinerInfo &DCI,
7294 const AArch64Subtarget *Subtarget) {
7295 if (DCI.isBeforeLegalizeOps())
7298 return performIntegerAbsCombine(N, DAG);
7302 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
7304 std::vector<SDNode *> *Created) const {
7305 // fold (sdiv X, pow2)
7306 EVT VT = N->getValueType(0);
7307 if ((VT != MVT::i32 && VT != MVT::i64) ||
7308 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
7312 SDValue N0 = N->getOperand(0);
7313 unsigned Lg2 = Divisor.countTrailingZeros();
7314 SDValue Zero = DAG.getConstant(0, DL, VT);
7315 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
7317 // Add (N0 < 0) ? Pow2 - 1 : 0;
7319 SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
7320 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
7321 SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
7324 Created->push_back(Cmp.getNode());
7325 Created->push_back(Add.getNode());
7326 Created->push_back(CSel.getNode());
7331 DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
7333 // If we're dividing by a positive value, we're done. Otherwise, we must
7334 // negate the result.
7335 if (Divisor.isNonNegative())
7339 Created->push_back(SRA.getNode());
7340 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
7343 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
7344 TargetLowering::DAGCombinerInfo &DCI,
7345 const AArch64Subtarget *Subtarget) {
7346 if (DCI.isBeforeLegalizeOps())
7349 // Multiplication of a power of two plus/minus one can be done more
7350 // cheaply as as shift+add/sub. For now, this is true unilaterally. If
7351 // future CPUs have a cheaper MADD instruction, this may need to be
7352 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
7353 // 64-bit is 5 cycles, so this is always a win.
7354 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
7355 APInt Value = C->getAPIntValue();
7356 EVT VT = N->getValueType(0);
7358 if (Value.isNonNegative()) {
7359 // (mul x, 2^N + 1) => (add (shl x, N), x)
7360 APInt VM1 = Value - 1;
7361 if (VM1.isPowerOf2()) {
7362 SDValue ShiftedVal =
7363 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7364 DAG.getConstant(VM1.logBase2(), DL, MVT::i64));
7365 return DAG.getNode(ISD::ADD, DL, VT, ShiftedVal,
7368 // (mul x, 2^N - 1) => (sub (shl x, N), x)
7369 APInt VP1 = Value + 1;
7370 if (VP1.isPowerOf2()) {
7371 SDValue ShiftedVal =
7372 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7373 DAG.getConstant(VP1.logBase2(), DL, MVT::i64));
7374 return DAG.getNode(ISD::SUB, DL, VT, ShiftedVal,
7378 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7379 APInt VNP1 = -Value + 1;
7380 if (VNP1.isPowerOf2()) {
7381 SDValue ShiftedVal =
7382 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7383 DAG.getConstant(VNP1.logBase2(), DL, MVT::i64));
7384 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0),
7387 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7388 APInt VNM1 = -Value - 1;
7389 if (VNM1.isPowerOf2()) {
7390 SDValue ShiftedVal =
7391 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7392 DAG.getConstant(VNM1.logBase2(), DL, MVT::i64));
7394 DAG.getNode(ISD::ADD, DL, VT, ShiftedVal, N->getOperand(0));
7395 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Add);
7402 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
7403 SelectionDAG &DAG) {
7404 // Take advantage of vector comparisons producing 0 or -1 in each lane to
7405 // optimize away operation when it's from a constant.
7407 // The general transformation is:
7408 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
7409 // AND(VECTOR_CMP(x,y), constant2)
7410 // constant2 = UNARYOP(constant)
7412 // Early exit if this isn't a vector operation, the operand of the
7413 // unary operation isn't a bitwise AND, or if the sizes of the operations
7415 EVT VT = N->getValueType(0);
7416 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
7417 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
7418 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
7421 // Now check that the other operand of the AND is a constant. We could
7422 // make the transformation for non-constant splats as well, but it's unclear
7423 // that would be a benefit as it would not eliminate any operations, just
7424 // perform one more step in scalar code before moving to the vector unit.
7425 if (BuildVectorSDNode *BV =
7426 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
7427 // Bail out if the vector isn't a constant.
7428 if (!BV->isConstant())
7431 // Everything checks out. Build up the new and improved node.
7433 EVT IntVT = BV->getValueType(0);
7434 // Create a new constant of the appropriate type for the transformed
7436 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
7437 // The AND node needs bitcasts to/from an integer vector type around it.
7438 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
7439 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
7440 N->getOperand(0)->getOperand(0), MaskConst);
7441 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
7448 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
7449 const AArch64Subtarget *Subtarget) {
7450 // First try to optimize away the conversion when it's conditionally from
7451 // a constant. Vectors only.
7452 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
7455 EVT VT = N->getValueType(0);
7456 if (VT != MVT::f32 && VT != MVT::f64)
7459 // Only optimize when the source and destination types have the same width.
7460 if (VT.getSizeInBits() != N->getOperand(0).getValueType().getSizeInBits())
7463 // If the result of an integer load is only used by an integer-to-float
7464 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
7465 // This eliminates an "integer-to-vector-move UOP and improve throughput.
7466 SDValue N0 = N->getOperand(0);
7467 if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7468 // Do not change the width of a volatile load.
7469 !cast<LoadSDNode>(N0)->isVolatile()) {
7470 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7471 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
7472 LN0->getPointerInfo(), LN0->isVolatile(),
7473 LN0->isNonTemporal(), LN0->isInvariant(),
7474 LN0->getAlignment());
7476 // Make sure successors of the original load stay after it by updating them
7477 // to use the new Chain.
7478 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
7481 (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
7482 return DAG.getNode(Opcode, SDLoc(N), VT, Load);
7488 /// An EXTR instruction is made up of two shifts, ORed together. This helper
7489 /// searches for and classifies those shifts.
7490 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
7492 if (N.getOpcode() == ISD::SHL)
7494 else if (N.getOpcode() == ISD::SRL)
7499 if (!isa<ConstantSDNode>(N.getOperand(1)))
7502 ShiftAmount = N->getConstantOperandVal(1);
7503 Src = N->getOperand(0);
7507 /// EXTR instruction extracts a contiguous chunk of bits from two existing
7508 /// registers viewed as a high/low pair. This function looks for the pattern:
7509 /// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an
7510 /// EXTR. Can't quite be done in TableGen because the two immediates aren't
7512 static SDValue tryCombineToEXTR(SDNode *N,
7513 TargetLowering::DAGCombinerInfo &DCI) {
7514 SelectionDAG &DAG = DCI.DAG;
7516 EVT VT = N->getValueType(0);
7518 assert(N->getOpcode() == ISD::OR && "Unexpected root");
7520 if (VT != MVT::i32 && VT != MVT::i64)
7524 uint32_t ShiftLHS = 0;
7526 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
7530 uint32_t ShiftRHS = 0;
7532 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
7535 // If they're both trying to come from the high part of the register, they're
7536 // not really an EXTR.
7537 if (LHSFromHi == RHSFromHi)
7540 if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
7544 std::swap(LHS, RHS);
7545 std::swap(ShiftLHS, ShiftRHS);
7548 return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
7549 DAG.getConstant(ShiftRHS, DL, MVT::i64));
7552 static SDValue tryCombineToBSL(SDNode *N,
7553 TargetLowering::DAGCombinerInfo &DCI) {
7554 EVT VT = N->getValueType(0);
7555 SelectionDAG &DAG = DCI.DAG;
7561 SDValue N0 = N->getOperand(0);
7562 if (N0.getOpcode() != ISD::AND)
7565 SDValue N1 = N->getOperand(1);
7566 if (N1.getOpcode() != ISD::AND)
7569 // We only have to look for constant vectors here since the general, variable
7570 // case can be handled in TableGen.
7571 unsigned Bits = VT.getVectorElementType().getSizeInBits();
7572 uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
7573 for (int i = 1; i >= 0; --i)
7574 for (int j = 1; j >= 0; --j) {
7575 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
7576 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
7580 bool FoundMatch = true;
7581 for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
7582 ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
7583 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
7585 CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
7592 return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
7593 N0->getOperand(1 - i), N1->getOperand(1 - j));
7599 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
7600 const AArch64Subtarget *Subtarget) {
7601 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
7602 if (!EnableAArch64ExtrGeneration)
7604 SelectionDAG &DAG = DCI.DAG;
7605 EVT VT = N->getValueType(0);
7607 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7610 SDValue Res = tryCombineToEXTR(N, DCI);
7614 Res = tryCombineToBSL(N, DCI);
7621 static SDValue performBitcastCombine(SDNode *N,
7622 TargetLowering::DAGCombinerInfo &DCI,
7623 SelectionDAG &DAG) {
7624 // Wait 'til after everything is legalized to try this. That way we have
7625 // legal vector types and such.
7626 if (DCI.isBeforeLegalizeOps())
7629 // Remove extraneous bitcasts around an extract_subvector.
7631 // (v4i16 (bitconvert
7632 // (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
7634 // (extract_subvector ((v8i16 ...), (i64 4)))
7636 // Only interested in 64-bit vectors as the ultimate result.
7637 EVT VT = N->getValueType(0);
7640 if (VT.getSimpleVT().getSizeInBits() != 64)
7642 // Is the operand an extract_subvector starting at the beginning or halfway
7643 // point of the vector? A low half may also come through as an
7644 // EXTRACT_SUBREG, so look for that, too.
7645 SDValue Op0 = N->getOperand(0);
7646 if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
7647 !(Op0->isMachineOpcode() &&
7648 Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
7650 uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
7651 if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
7652 if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
7654 } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
7655 if (idx != AArch64::dsub)
7657 // The dsub reference is equivalent to a lane zero subvector reference.
7660 // Look through the bitcast of the input to the extract.
7661 if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
7663 SDValue Source = Op0->getOperand(0)->getOperand(0);
7664 // If the source type has twice the number of elements as our destination
7665 // type, we know this is an extract of the high or low half of the vector.
7666 EVT SVT = Source->getValueType(0);
7667 if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
7670 DEBUG(dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
7672 // Create the simplified form to just extract the low or high half of the
7673 // vector directly rather than bothering with the bitcasts.
7675 unsigned NumElements = VT.getVectorNumElements();
7677 SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
7678 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
7680 SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
7681 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
7687 static SDValue performConcatVectorsCombine(SDNode *N,
7688 TargetLowering::DAGCombinerInfo &DCI,
7689 SelectionDAG &DAG) {
7691 EVT VT = N->getValueType(0);
7692 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
7694 // Optimize concat_vectors of truncated vectors, where the intermediate
7695 // type is illegal, to avoid said illegality, e.g.,
7696 // (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
7697 // (v2i16 (truncate (v2i64)))))
7699 // (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
7700 // (v4i32 (bitcast (v2i64))),
7702 // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
7703 // on both input and result type, so we might generate worse code.
7704 // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
7705 if (N->getNumOperands() == 2 &&
7706 N0->getOpcode() == ISD::TRUNCATE &&
7707 N1->getOpcode() == ISD::TRUNCATE) {
7708 SDValue N00 = N0->getOperand(0);
7709 SDValue N10 = N1->getOperand(0);
7710 EVT N00VT = N00.getValueType();
7712 if (N00VT == N10.getValueType() &&
7713 (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
7714 N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
7715 MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
7716 SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
7717 for (size_t i = 0; i < Mask.size(); ++i)
7719 return DAG.getNode(ISD::TRUNCATE, dl, VT,
7720 DAG.getVectorShuffle(
7722 DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
7723 DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
7727 // Wait 'til after everything is legalized to try this. That way we have
7728 // legal vector types and such.
7729 if (DCI.isBeforeLegalizeOps())
7732 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
7733 // splat. The indexed instructions are going to be expecting a DUPLANE64, so
7734 // canonicalise to that.
7735 if (N0 == N1 && VT.getVectorNumElements() == 2) {
7736 assert(VT.getVectorElementType().getSizeInBits() == 64);
7737 return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
7738 DAG.getConstant(0, dl, MVT::i64));
7741 // Canonicalise concat_vectors so that the right-hand vector has as few
7742 // bit-casts as possible before its real operation. The primary matching
7743 // destination for these operations will be the narrowing "2" instructions,
7744 // which depend on the operation being performed on this right-hand vector.
7746 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS))))
7748 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
7750 if (N1->getOpcode() != ISD::BITCAST)
7752 SDValue RHS = N1->getOperand(0);
7753 MVT RHSTy = RHS.getValueType().getSimpleVT();
7754 // If the RHS is not a vector, this is not the pattern we're looking for.
7755 if (!RHSTy.isVector())
7758 DEBUG(dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
7760 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
7761 RHSTy.getVectorNumElements() * 2);
7762 return DAG.getNode(ISD::BITCAST, dl, VT,
7763 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
7764 DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
7768 static SDValue tryCombineFixedPointConvert(SDNode *N,
7769 TargetLowering::DAGCombinerInfo &DCI,
7770 SelectionDAG &DAG) {
7771 // Wait 'til after everything is legalized to try this. That way we have
7772 // legal vector types and such.
7773 if (DCI.isBeforeLegalizeOps())
7775 // Transform a scalar conversion of a value from a lane extract into a
7776 // lane extract of a vector conversion. E.g., from foo1 to foo2:
7777 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
7778 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
7780 // The second form interacts better with instruction selection and the
7781 // register allocator to avoid cross-class register copies that aren't
7782 // coalescable due to a lane reference.
7784 // Check the operand and see if it originates from a lane extract.
7785 SDValue Op1 = N->getOperand(1);
7786 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7787 // Yep, no additional predication needed. Perform the transform.
7788 SDValue IID = N->getOperand(0);
7789 SDValue Shift = N->getOperand(2);
7790 SDValue Vec = Op1.getOperand(0);
7791 SDValue Lane = Op1.getOperand(1);
7792 EVT ResTy = N->getValueType(0);
7796 // The vector width should be 128 bits by the time we get here, even
7797 // if it started as 64 bits (the extract_vector handling will have
7799 assert(Vec.getValueType().getSizeInBits() == 128 &&
7800 "unexpected vector size on extract_vector_elt!");
7801 if (Vec.getValueType() == MVT::v4i32)
7802 VecResTy = MVT::v4f32;
7803 else if (Vec.getValueType() == MVT::v2i64)
7804 VecResTy = MVT::v2f64;
7806 llvm_unreachable("unexpected vector type!");
7809 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
7810 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
7815 // AArch64 high-vector "long" operations are formed by performing the non-high
7816 // version on an extract_subvector of each operand which gets the high half:
7818 // (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
7820 // However, there are cases which don't have an extract_high explicitly, but
7821 // have another operation that can be made compatible with one for free. For
7824 // (dupv64 scalar) --> (extract_high (dup128 scalar))
7826 // This routine does the actual conversion of such DUPs, once outer routines
7827 // have determined that everything else is in order.
7828 // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
7830 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
7831 switch (N.getOpcode()) {
7832 case AArch64ISD::DUP:
7833 case AArch64ISD::DUPLANE8:
7834 case AArch64ISD::DUPLANE16:
7835 case AArch64ISD::DUPLANE32:
7836 case AArch64ISD::DUPLANE64:
7837 case AArch64ISD::MOVI:
7838 case AArch64ISD::MOVIshift:
7839 case AArch64ISD::MOVIedit:
7840 case AArch64ISD::MOVImsl:
7841 case AArch64ISD::MVNIshift:
7842 case AArch64ISD::MVNImsl:
7845 // FMOV could be supported, but isn't very useful, as it would only occur
7846 // if you passed a bitcast' floating point immediate to an eligible long
7847 // integer op (addl, smull, ...).
7851 MVT NarrowTy = N.getSimpleValueType();
7852 if (!NarrowTy.is64BitVector())
7855 MVT ElementTy = NarrowTy.getVectorElementType();
7856 unsigned NumElems = NarrowTy.getVectorNumElements();
7857 MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
7860 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
7861 DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
7862 DAG.getConstant(NumElems, dl, MVT::i64));
7865 static bool isEssentiallyExtractSubvector(SDValue N) {
7866 if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
7869 return N.getOpcode() == ISD::BITCAST &&
7870 N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
7873 /// \brief Helper structure to keep track of ISD::SET_CC operands.
7874 struct GenericSetCCInfo {
7875 const SDValue *Opnd0;
7876 const SDValue *Opnd1;
7880 /// \brief Helper structure to keep track of a SET_CC lowered into AArch64 code.
7881 struct AArch64SetCCInfo {
7883 AArch64CC::CondCode CC;
7886 /// \brief Helper structure to keep track of SetCC information.
7888 GenericSetCCInfo Generic;
7889 AArch64SetCCInfo AArch64;
7892 /// \brief Helper structure to be able to read SetCC information. If set to
7893 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
7894 /// GenericSetCCInfo.
7895 struct SetCCInfoAndKind {
7900 /// \brief Check whether or not \p Op is a SET_CC operation, either a generic or
7902 /// AArch64 lowered one.
7903 /// \p SetCCInfo is filled accordingly.
7904 /// \post SetCCInfo is meanginfull only when this function returns true.
7905 /// \return True when Op is a kind of SET_CC operation.
7906 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
7907 // If this is a setcc, this is straight forward.
7908 if (Op.getOpcode() == ISD::SETCC) {
7909 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
7910 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
7911 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7912 SetCCInfo.IsAArch64 = false;
7915 // Otherwise, check if this is a matching csel instruction.
7919 if (Op.getOpcode() != AArch64ISD::CSEL)
7921 // Set the information about the operands.
7922 // TODO: we want the operands of the Cmp not the csel
7923 SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
7924 SetCCInfo.IsAArch64 = true;
7925 SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
7926 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
7928 // Check that the operands matches the constraints:
7929 // (1) Both operands must be constants.
7930 // (2) One must be 1 and the other must be 0.
7931 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
7932 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7935 if (!TValue || !FValue)
7939 if (!TValue->isOne()) {
7940 // Update the comparison when we are interested in !cc.
7941 std::swap(TValue, FValue);
7942 SetCCInfo.Info.AArch64.CC =
7943 AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
7945 return TValue->isOne() && FValue->isNullValue();
7948 // Returns true if Op is setcc or zext of setcc.
7949 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
7950 if (isSetCC(Op, Info))
7952 return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
7953 isSetCC(Op->getOperand(0), Info));
7956 // The folding we want to perform is:
7957 // (add x, [zext] (setcc cc ...) )
7959 // (csel x, (add x, 1), !cc ...)
7961 // The latter will get matched to a CSINC instruction.
7962 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
7963 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
7964 SDValue LHS = Op->getOperand(0);
7965 SDValue RHS = Op->getOperand(1);
7966 SetCCInfoAndKind InfoAndKind;
7968 // If neither operand is a SET_CC, give up.
7969 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
7970 std::swap(LHS, RHS);
7971 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
7975 // FIXME: This could be generatized to work for FP comparisons.
7976 EVT CmpVT = InfoAndKind.IsAArch64
7977 ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
7978 : InfoAndKind.Info.Generic.Opnd0->getValueType();
7979 if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
7985 if (InfoAndKind.IsAArch64) {
7986 CCVal = DAG.getConstant(
7987 AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
7989 Cmp = *InfoAndKind.Info.AArch64.Cmp;
7991 Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
7992 *InfoAndKind.Info.Generic.Opnd1,
7993 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
7996 EVT VT = Op->getValueType(0);
7997 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
7998 return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
8001 // The basic add/sub long vector instructions have variants with "2" on the end
8002 // which act on the high-half of their inputs. They are normally matched by
8005 // (add (zeroext (extract_high LHS)),
8006 // (zeroext (extract_high RHS)))
8007 // -> uaddl2 vD, vN, vM
8009 // However, if one of the extracts is something like a duplicate, this
8010 // instruction can still be used profitably. This function puts the DAG into a
8011 // more appropriate form for those patterns to trigger.
8012 static SDValue performAddSubLongCombine(SDNode *N,
8013 TargetLowering::DAGCombinerInfo &DCI,
8014 SelectionDAG &DAG) {
8015 if (DCI.isBeforeLegalizeOps())
8018 MVT VT = N->getSimpleValueType(0);
8019 if (!VT.is128BitVector()) {
8020 if (N->getOpcode() == ISD::ADD)
8021 return performSetccAddFolding(N, DAG);
8025 // Make sure both branches are extended in the same way.
8026 SDValue LHS = N->getOperand(0);
8027 SDValue RHS = N->getOperand(1);
8028 if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
8029 LHS.getOpcode() != ISD::SIGN_EXTEND) ||
8030 LHS.getOpcode() != RHS.getOpcode())
8033 unsigned ExtType = LHS.getOpcode();
8035 // It's not worth doing if at least one of the inputs isn't already an
8036 // extract, but we don't know which it'll be so we have to try both.
8037 if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
8038 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
8042 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
8043 } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
8044 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
8048 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
8051 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
8054 // Massage DAGs which we can use the high-half "long" operations on into
8055 // something isel will recognize better. E.g.
8057 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
8058 // (aarch64_neon_umull (extract_high (v2i64 vec)))
8059 // (extract_high (v2i64 (dup128 scalar)))))
8061 static SDValue tryCombineLongOpWithDup(SDNode *N,
8062 TargetLowering::DAGCombinerInfo &DCI,
8063 SelectionDAG &DAG) {
8064 if (DCI.isBeforeLegalizeOps())
8067 bool IsIntrinsic = N->getOpcode() == ISD::INTRINSIC_WO_CHAIN;
8068 SDValue LHS = N->getOperand(IsIntrinsic ? 1 : 0);
8069 SDValue RHS = N->getOperand(IsIntrinsic ? 2 : 1);
8070 assert(LHS.getValueType().is64BitVector() &&
8071 RHS.getValueType().is64BitVector() &&
8072 "unexpected shape for long operation");
8074 // Either node could be a DUP, but it's not worth doing both of them (you'd
8075 // just as well use the non-high version) so look for a corresponding extract
8076 // operation on the other "wing".
8077 if (isEssentiallyExtractSubvector(LHS)) {
8078 RHS = tryExtendDUPToExtractHigh(RHS, DAG);
8081 } else if (isEssentiallyExtractSubvector(RHS)) {
8082 LHS = tryExtendDUPToExtractHigh(LHS, DAG);
8087 // N could either be an intrinsic or a sabsdiff/uabsdiff node.
8089 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
8090 N->getOperand(0), LHS, RHS);
8092 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
8096 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
8097 MVT ElemTy = N->getSimpleValueType(0).getScalarType();
8098 unsigned ElemBits = ElemTy.getSizeInBits();
8100 int64_t ShiftAmount;
8101 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
8102 APInt SplatValue, SplatUndef;
8103 unsigned SplatBitSize;
8105 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
8106 HasAnyUndefs, ElemBits) ||
8107 SplatBitSize != ElemBits)
8110 ShiftAmount = SplatValue.getSExtValue();
8111 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
8112 ShiftAmount = CVN->getSExtValue();
8120 llvm_unreachable("Unknown shift intrinsic");
8121 case Intrinsic::aarch64_neon_sqshl:
8122 Opcode = AArch64ISD::SQSHL_I;
8123 IsRightShift = false;
8125 case Intrinsic::aarch64_neon_uqshl:
8126 Opcode = AArch64ISD::UQSHL_I;
8127 IsRightShift = false;
8129 case Intrinsic::aarch64_neon_srshl:
8130 Opcode = AArch64ISD::SRSHR_I;
8131 IsRightShift = true;
8133 case Intrinsic::aarch64_neon_urshl:
8134 Opcode = AArch64ISD::URSHR_I;
8135 IsRightShift = true;
8137 case Intrinsic::aarch64_neon_sqshlu:
8138 Opcode = AArch64ISD::SQSHLU_I;
8139 IsRightShift = false;
8143 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
8145 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8146 DAG.getConstant(-ShiftAmount, dl, MVT::i32));
8147 } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
8149 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8150 DAG.getConstant(ShiftAmount, dl, MVT::i32));
8156 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
8157 // the intrinsics must be legal and take an i32, this means there's almost
8158 // certainly going to be a zext in the DAG which we can eliminate.
8159 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
8160 SDValue AndN = N->getOperand(2);
8161 if (AndN.getOpcode() != ISD::AND)
8164 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
8165 if (!CMask || CMask->getZExtValue() != Mask)
8168 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
8169 N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
8172 static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
8173 SelectionDAG &DAG) {
8175 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
8176 DAG.getNode(Opc, dl,
8177 N->getOperand(1).getSimpleValueType(),
8179 DAG.getConstant(0, dl, MVT::i64));
8182 static SDValue performIntrinsicCombine(SDNode *N,
8183 TargetLowering::DAGCombinerInfo &DCI,
8184 const AArch64Subtarget *Subtarget) {
8185 SelectionDAG &DAG = DCI.DAG;
8186 unsigned IID = getIntrinsicID(N);
8190 case Intrinsic::aarch64_neon_vcvtfxs2fp:
8191 case Intrinsic::aarch64_neon_vcvtfxu2fp:
8192 return tryCombineFixedPointConvert(N, DCI, DAG);
8193 case Intrinsic::aarch64_neon_saddv:
8194 return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
8195 case Intrinsic::aarch64_neon_uaddv:
8196 return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
8197 case Intrinsic::aarch64_neon_sminv:
8198 return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
8199 case Intrinsic::aarch64_neon_uminv:
8200 return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
8201 case Intrinsic::aarch64_neon_smaxv:
8202 return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
8203 case Intrinsic::aarch64_neon_umaxv:
8204 return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
8205 case Intrinsic::aarch64_neon_fmax:
8206 return DAG.getNode(ISD::FMAXNAN, SDLoc(N), N->getValueType(0),
8207 N->getOperand(1), N->getOperand(2));
8208 case Intrinsic::aarch64_neon_fmin:
8209 return DAG.getNode(ISD::FMINNAN, SDLoc(N), N->getValueType(0),
8210 N->getOperand(1), N->getOperand(2));
8211 case Intrinsic::aarch64_neon_sabd:
8212 return DAG.getNode(ISD::SABSDIFF, SDLoc(N), N->getValueType(0),
8213 N->getOperand(1), N->getOperand(2));
8214 case Intrinsic::aarch64_neon_uabd:
8215 return DAG.getNode(ISD::UABSDIFF, SDLoc(N), N->getValueType(0),
8216 N->getOperand(1), N->getOperand(2));
8217 case Intrinsic::aarch64_neon_fmaxnm:
8218 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
8219 N->getOperand(1), N->getOperand(2));
8220 case Intrinsic::aarch64_neon_fminnm:
8221 return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
8222 N->getOperand(1), N->getOperand(2));
8223 case Intrinsic::aarch64_neon_smull:
8224 case Intrinsic::aarch64_neon_umull:
8225 case Intrinsic::aarch64_neon_pmull:
8226 case Intrinsic::aarch64_neon_sqdmull:
8227 return tryCombineLongOpWithDup(N, DCI, DAG);
8228 case Intrinsic::aarch64_neon_sqshl:
8229 case Intrinsic::aarch64_neon_uqshl:
8230 case Intrinsic::aarch64_neon_sqshlu:
8231 case Intrinsic::aarch64_neon_srshl:
8232 case Intrinsic::aarch64_neon_urshl:
8233 return tryCombineShiftImm(IID, N, DAG);
8234 case Intrinsic::aarch64_crc32b:
8235 case Intrinsic::aarch64_crc32cb:
8236 return tryCombineCRC32(0xff, N, DAG);
8237 case Intrinsic::aarch64_crc32h:
8238 case Intrinsic::aarch64_crc32ch:
8239 return tryCombineCRC32(0xffff, N, DAG);
8244 static SDValue performExtendCombine(SDNode *N,
8245 TargetLowering::DAGCombinerInfo &DCI,
8246 SelectionDAG &DAG) {
8247 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
8248 // we can convert that DUP into another extract_high (of a bigger DUP), which
8249 // helps the backend to decide that an sabdl2 would be useful, saving a real
8250 // extract_high operation.
8251 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
8252 (N->getOperand(0).getOpcode() == ISD::SABSDIFF ||
8253 N->getOperand(0).getOpcode() == ISD::UABSDIFF)) {
8254 SDNode *ABDNode = N->getOperand(0).getNode();
8255 SDValue NewABD = tryCombineLongOpWithDup(ABDNode, DCI, DAG);
8256 if (!NewABD.getNode())
8259 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
8263 // This is effectively a custom type legalization for AArch64.
8265 // Type legalization will split an extend of a small, legal, type to a larger
8266 // illegal type by first splitting the destination type, often creating
8267 // illegal source types, which then get legalized in isel-confusing ways,
8268 // leading to really terrible codegen. E.g.,
8269 // %result = v8i32 sext v8i8 %value
8271 // %losrc = extract_subreg %value, ...
8272 // %hisrc = extract_subreg %value, ...
8273 // %lo = v4i32 sext v4i8 %losrc
8274 // %hi = v4i32 sext v4i8 %hisrc
8275 // Things go rapidly downhill from there.
8277 // For AArch64, the [sz]ext vector instructions can only go up one element
8278 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
8279 // take two instructions.
8281 // This implies that the most efficient way to do the extend from v8i8
8282 // to two v4i32 values is to first extend the v8i8 to v8i16, then do
8283 // the normal splitting to happen for the v8i16->v8i32.
8285 // This is pre-legalization to catch some cases where the default
8286 // type legalization will create ill-tempered code.
8287 if (!DCI.isBeforeLegalizeOps())
8290 // We're only interested in cleaning things up for non-legal vector types
8291 // here. If both the source and destination are legal, things will just
8292 // work naturally without any fiddling.
8293 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8294 EVT ResVT = N->getValueType(0);
8295 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
8297 // If the vector type isn't a simple VT, it's beyond the scope of what
8298 // we're worried about here. Let legalization do its thing and hope for
8300 SDValue Src = N->getOperand(0);
8301 EVT SrcVT = Src->getValueType(0);
8302 if (!ResVT.isSimple() || !SrcVT.isSimple())
8305 // If the source VT is a 64-bit vector, we can play games and get the
8306 // better results we want.
8307 if (SrcVT.getSizeInBits() != 64)
8310 unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits();
8311 unsigned ElementCount = SrcVT.getVectorNumElements();
8312 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
8314 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
8316 // Now split the rest of the operation into two halves, each with a 64
8320 unsigned NumElements = ResVT.getVectorNumElements();
8321 assert(!(NumElements & 1) && "Splitting vector, but not in half!");
8322 LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
8323 ResVT.getVectorElementType(), NumElements / 2);
8325 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
8326 LoVT.getVectorNumElements());
8327 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
8328 DAG.getConstant(0, DL, MVT::i64));
8329 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
8330 DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
8331 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
8332 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
8334 // Now combine the parts back together so we still have a single result
8335 // like the combiner expects.
8336 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
8339 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
8340 /// value. The load store optimizer pass will merge them to store pair stores.
8341 /// This has better performance than a splat of the scalar followed by a split
8342 /// vector store. Even if the stores are not merged it is four stores vs a dup,
8343 /// followed by an ext.b and two stores.
8344 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode *St) {
8345 SDValue StVal = St->getValue();
8346 EVT VT = StVal.getValueType();
8348 // Don't replace floating point stores, they possibly won't be transformed to
8349 // stp because of the store pair suppress pass.
8350 if (VT.isFloatingPoint())
8353 // Check for insert vector elements.
8354 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
8357 // We can express a splat as store pair(s) for 2 or 4 elements.
8358 unsigned NumVecElts = VT.getVectorNumElements();
8359 if (NumVecElts != 4 && NumVecElts != 2)
8361 SDValue SplatVal = StVal.getOperand(1);
8362 unsigned RemainInsertElts = NumVecElts - 1;
8364 // Check that this is a splat.
8365 while (--RemainInsertElts) {
8366 SDValue NextInsertElt = StVal.getOperand(0);
8367 if (NextInsertElt.getOpcode() != ISD::INSERT_VECTOR_ELT)
8369 if (NextInsertElt.getOperand(1) != SplatVal)
8371 StVal = NextInsertElt;
8373 unsigned OrigAlignment = St->getAlignment();
8374 unsigned EltOffset = NumVecElts == 4 ? 4 : 8;
8375 unsigned Alignment = std::min(OrigAlignment, EltOffset);
8377 // Create scalar stores. This is at least as good as the code sequence for a
8378 // split unaligned store which is a dup.s, ext.b, and two stores.
8379 // Most of the time the three stores should be replaced by store pair
8380 // instructions (stp).
8382 SDValue BasePtr = St->getBasePtr();
8384 DAG.getStore(St->getChain(), DL, SplatVal, BasePtr, St->getPointerInfo(),
8385 St->isVolatile(), St->isNonTemporal(), St->getAlignment());
8387 unsigned Offset = EltOffset;
8388 while (--NumVecElts) {
8389 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
8390 DAG.getConstant(Offset, DL, MVT::i64));
8391 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
8392 St->getPointerInfo(), St->isVolatile(),
8393 St->isNonTemporal(), Alignment);
8394 Offset += EltOffset;
8399 static SDValue performSTORECombine(SDNode *N,
8400 TargetLowering::DAGCombinerInfo &DCI,
8402 const AArch64Subtarget *Subtarget) {
8403 if (!DCI.isBeforeLegalize())
8406 StoreSDNode *S = cast<StoreSDNode>(N);
8407 if (S->isVolatile())
8410 // Cyclone has bad performance on unaligned 16B stores when crossing line and
8411 // page boundaries. We want to split such stores.
8412 if (!Subtarget->isCyclone())
8415 // Don't split at -Oz.
8416 if (DAG.getMachineFunction().getFunction()->optForMinSize())
8419 SDValue StVal = S->getValue();
8420 EVT VT = StVal.getValueType();
8422 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
8423 // those up regresses performance on micro-benchmarks and olden/bh.
8424 if (!VT.isVector() || VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
8427 // Split unaligned 16B stores. They are terrible for performance.
8428 // Don't split stores with alignment of 1 or 2. Code that uses clang vector
8429 // extensions can use this to mark that it does not want splitting to happen
8430 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
8431 // eliminating alignment hazards is only 1 in 8 for alignment of 2.
8432 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
8433 S->getAlignment() <= 2)
8436 // If we get a splat of a scalar convert this vector store to a store of
8437 // scalars. They will be merged into store pairs thereby removing two
8439 if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, S))
8440 return ReplacedSplat;
8443 unsigned NumElts = VT.getVectorNumElements() / 2;
8444 // Split VT into two.
8446 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
8447 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
8448 DAG.getConstant(0, DL, MVT::i64));
8449 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
8450 DAG.getConstant(NumElts, DL, MVT::i64));
8451 SDValue BasePtr = S->getBasePtr();
8453 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
8454 S->isVolatile(), S->isNonTemporal(), S->getAlignment());
8455 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
8456 DAG.getConstant(8, DL, MVT::i64));
8457 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
8458 S->getPointerInfo(), S->isVolatile(), S->isNonTemporal(),
8462 /// Target-specific DAG combine function for post-increment LD1 (lane) and
8463 /// post-increment LD1R.
8464 static SDValue performPostLD1Combine(SDNode *N,
8465 TargetLowering::DAGCombinerInfo &DCI,
8467 if (DCI.isBeforeLegalizeOps())
8470 SelectionDAG &DAG = DCI.DAG;
8471 EVT VT = N->getValueType(0);
8473 unsigned LoadIdx = IsLaneOp ? 1 : 0;
8474 SDNode *LD = N->getOperand(LoadIdx).getNode();
8475 // If it is not LOAD, can not do such combine.
8476 if (LD->getOpcode() != ISD::LOAD)
8479 LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
8480 EVT MemVT = LoadSDN->getMemoryVT();
8481 // Check if memory operand is the same type as the vector element.
8482 if (MemVT != VT.getVectorElementType())
8485 // Check if there are other uses. If so, do not combine as it will introduce
8487 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
8489 if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
8495 SDValue Addr = LD->getOperand(1);
8496 SDValue Vector = N->getOperand(0);
8497 // Search for a use of the address operand that is an increment.
8498 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
8499 Addr.getNode()->use_end(); UI != UE; ++UI) {
8501 if (User->getOpcode() != ISD::ADD
8502 || UI.getUse().getResNo() != Addr.getResNo())
8505 // Check that the add is independent of the load. Otherwise, folding it
8506 // would create a cycle.
8507 if (User->isPredecessorOf(LD) || LD->isPredecessorOf(User))
8509 // Also check that add is not used in the vector operand. This would also
8511 if (User->isPredecessorOf(Vector.getNode()))
8514 // If the increment is a constant, it must match the memory ref size.
8515 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8516 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8517 uint32_t IncVal = CInc->getZExtValue();
8518 unsigned NumBytes = VT.getScalarSizeInBits() / 8;
8519 if (IncVal != NumBytes)
8521 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
8524 // Finally, check that the vector doesn't depend on the load.
8525 // Again, this would create a cycle.
8526 // The load depending on the vector is fine, as that's the case for the
8527 // LD1*post we'll eventually generate anyway.
8528 if (LoadSDN->isPredecessorOf(Vector.getNode()))
8531 SmallVector<SDValue, 8> Ops;
8532 Ops.push_back(LD->getOperand(0)); // Chain
8534 Ops.push_back(Vector); // The vector to be inserted
8535 Ops.push_back(N->getOperand(2)); // The lane to be inserted in the vector
8537 Ops.push_back(Addr);
8540 EVT Tys[3] = { VT, MVT::i64, MVT::Other };
8541 SDVTList SDTys = DAG.getVTList(Tys);
8542 unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
8543 SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
8545 LoadSDN->getMemOperand());
8548 SmallVector<SDValue, 2> NewResults;
8549 NewResults.push_back(SDValue(LD, 0)); // The result of load
8550 NewResults.push_back(SDValue(UpdN.getNode(), 2)); // Chain
8551 DCI.CombineTo(LD, NewResults);
8552 DCI.CombineTo(N, SDValue(UpdN.getNode(), 0)); // Dup/Inserted Result
8553 DCI.CombineTo(User, SDValue(UpdN.getNode(), 1)); // Write back register
8560 /// Target-specific DAG combine function for NEON load/store intrinsics
8561 /// to merge base address updates.
8562 static SDValue performNEONPostLDSTCombine(SDNode *N,
8563 TargetLowering::DAGCombinerInfo &DCI,
8564 SelectionDAG &DAG) {
8565 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8568 unsigned AddrOpIdx = N->getNumOperands() - 1;
8569 SDValue Addr = N->getOperand(AddrOpIdx);
8571 // Search for a use of the address operand that is an increment.
8572 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8573 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8575 if (User->getOpcode() != ISD::ADD ||
8576 UI.getUse().getResNo() != Addr.getResNo())
8579 // Check that the add is independent of the load/store. Otherwise, folding
8580 // it would create a cycle.
8581 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8584 // Find the new opcode for the updating load/store.
8585 bool IsStore = false;
8586 bool IsLaneOp = false;
8587 bool IsDupOp = false;
8588 unsigned NewOpc = 0;
8589 unsigned NumVecs = 0;
8590 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8592 default: llvm_unreachable("unexpected intrinsic for Neon base update");
8593 case Intrinsic::aarch64_neon_ld2: NewOpc = AArch64ISD::LD2post;
8595 case Intrinsic::aarch64_neon_ld3: NewOpc = AArch64ISD::LD3post;
8597 case Intrinsic::aarch64_neon_ld4: NewOpc = AArch64ISD::LD4post;
8599 case Intrinsic::aarch64_neon_st2: NewOpc = AArch64ISD::ST2post;
8600 NumVecs = 2; IsStore = true; break;
8601 case Intrinsic::aarch64_neon_st3: NewOpc = AArch64ISD::ST3post;
8602 NumVecs = 3; IsStore = true; break;
8603 case Intrinsic::aarch64_neon_st4: NewOpc = AArch64ISD::ST4post;
8604 NumVecs = 4; IsStore = true; break;
8605 case Intrinsic::aarch64_neon_ld1x2: NewOpc = AArch64ISD::LD1x2post;
8607 case Intrinsic::aarch64_neon_ld1x3: NewOpc = AArch64ISD::LD1x3post;
8609 case Intrinsic::aarch64_neon_ld1x4: NewOpc = AArch64ISD::LD1x4post;
8611 case Intrinsic::aarch64_neon_st1x2: NewOpc = AArch64ISD::ST1x2post;
8612 NumVecs = 2; IsStore = true; break;
8613 case Intrinsic::aarch64_neon_st1x3: NewOpc = AArch64ISD::ST1x3post;
8614 NumVecs = 3; IsStore = true; break;
8615 case Intrinsic::aarch64_neon_st1x4: NewOpc = AArch64ISD::ST1x4post;
8616 NumVecs = 4; IsStore = true; break;
8617 case Intrinsic::aarch64_neon_ld2r: NewOpc = AArch64ISD::LD2DUPpost;
8618 NumVecs = 2; IsDupOp = true; break;
8619 case Intrinsic::aarch64_neon_ld3r: NewOpc = AArch64ISD::LD3DUPpost;
8620 NumVecs = 3; IsDupOp = true; break;
8621 case Intrinsic::aarch64_neon_ld4r: NewOpc = AArch64ISD::LD4DUPpost;
8622 NumVecs = 4; IsDupOp = true; break;
8623 case Intrinsic::aarch64_neon_ld2lane: NewOpc = AArch64ISD::LD2LANEpost;
8624 NumVecs = 2; IsLaneOp = true; break;
8625 case Intrinsic::aarch64_neon_ld3lane: NewOpc = AArch64ISD::LD3LANEpost;
8626 NumVecs = 3; IsLaneOp = true; break;
8627 case Intrinsic::aarch64_neon_ld4lane: NewOpc = AArch64ISD::LD4LANEpost;
8628 NumVecs = 4; IsLaneOp = true; break;
8629 case Intrinsic::aarch64_neon_st2lane: NewOpc = AArch64ISD::ST2LANEpost;
8630 NumVecs = 2; IsStore = true; IsLaneOp = true; break;
8631 case Intrinsic::aarch64_neon_st3lane: NewOpc = AArch64ISD::ST3LANEpost;
8632 NumVecs = 3; IsStore = true; IsLaneOp = true; break;
8633 case Intrinsic::aarch64_neon_st4lane: NewOpc = AArch64ISD::ST4LANEpost;
8634 NumVecs = 4; IsStore = true; IsLaneOp = true; break;
8639 VecTy = N->getOperand(2).getValueType();
8641 VecTy = N->getValueType(0);
8643 // If the increment is a constant, it must match the memory ref size.
8644 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8645 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8646 uint32_t IncVal = CInc->getZExtValue();
8647 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8648 if (IsLaneOp || IsDupOp)
8649 NumBytes /= VecTy.getVectorNumElements();
8650 if (IncVal != NumBytes)
8652 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
8654 SmallVector<SDValue, 8> Ops;
8655 Ops.push_back(N->getOperand(0)); // Incoming chain
8656 // Load lane and store have vector list as input.
8657 if (IsLaneOp || IsStore)
8658 for (unsigned i = 2; i < AddrOpIdx; ++i)
8659 Ops.push_back(N->getOperand(i));
8660 Ops.push_back(Addr); // Base register
8665 unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
8667 for (n = 0; n < NumResultVecs; ++n)
8669 Tys[n++] = MVT::i64; // Type of write back register
8670 Tys[n] = MVT::Other; // Type of the chain
8671 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
8673 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8674 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
8675 MemInt->getMemoryVT(),
8676 MemInt->getMemOperand());
8679 std::vector<SDValue> NewResults;
8680 for (unsigned i = 0; i < NumResultVecs; ++i) {
8681 NewResults.push_back(SDValue(UpdN.getNode(), i));
8683 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
8684 DCI.CombineTo(N, NewResults);
8685 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8692 // Checks to see if the value is the prescribed width and returns information
8693 // about its extension mode.
8695 bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
8696 ExtType = ISD::NON_EXTLOAD;
8697 switch(V.getNode()->getOpcode()) {
8701 LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
8702 if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
8703 || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
8704 ExtType = LoadNode->getExtensionType();
8709 case ISD::AssertSext: {
8710 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
8711 if ((TypeNode->getVT() == MVT::i8 && width == 8)
8712 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
8713 ExtType = ISD::SEXTLOAD;
8718 case ISD::AssertZext: {
8719 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
8720 if ((TypeNode->getVT() == MVT::i8 && width == 8)
8721 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
8722 ExtType = ISD::ZEXTLOAD;
8728 case ISD::TargetConstant: {
8729 if (std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
8739 // This function does a whole lot of voodoo to determine if the tests are
8740 // equivalent without and with a mask. Essentially what happens is that given a
8743 // +-------------+ +-------------+ +-------------+ +-------------+
8744 // | Input | | AddConstant | | CompConstant| | CC |
8745 // +-------------+ +-------------+ +-------------+ +-------------+
8747 // V V | +----------+
8748 // +-------------+ +----+ | |
8749 // | ADD | |0xff| | |
8750 // +-------------+ +----+ | |
8753 // +-------------+ | |
8755 // +-------------+ | |
8764 // The AND node may be safely removed for some combinations of inputs. In
8765 // particular we need to take into account the extension type of the Input,
8766 // the exact values of AddConstant, CompConstant, and CC, along with the nominal
8767 // width of the input (this can work for any width inputs, the above graph is
8768 // specific to 8 bits.
8770 // The specific equations were worked out by generating output tables for each
8771 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
8772 // problem was simplified by working with 4 bit inputs, which means we only
8773 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
8774 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
8775 // patterns present in both extensions (0,7). For every distinct set of
8776 // AddConstant and CompConstants bit patterns we can consider the masked and
8777 // unmasked versions to be equivalent if the result of this function is true for
8778 // all 16 distinct bit patterns of for the current extension type of Input (w0).
8781 // and w10, w8, #0x0f
8783 // cset w9, AArch64CC
8785 // cset w11, AArch64CC
8790 // Since the above function shows when the outputs are equivalent it defines
8791 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
8792 // would be expensive to run during compiles. The equations below were written
8793 // in a test harness that confirmed they gave equivalent outputs to the above
8794 // for all inputs function, so they can be used determine if the removal is
8797 // isEquivalentMaskless() is the code for testing if the AND can be removed
8798 // factored out of the DAG recognition as the DAG can take several forms.
8801 bool isEquivalentMaskless(unsigned CC, unsigned width,
8802 ISD::LoadExtType ExtType, signed AddConstant,
8803 signed CompConstant) {
8804 // By being careful about our equations and only writing the in term
8805 // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
8806 // make them generally applicable to all bit widths.
8807 signed MaxUInt = (1 << width);
8809 // For the purposes of these comparisons sign extending the type is
8810 // equivalent to zero extending the add and displacing it by half the integer
8811 // width. Provided we are careful and make sure our equations are valid over
8812 // the whole range we can just adjust the input and avoid writing equations
8813 // for sign extended inputs.
8814 if (ExtType == ISD::SEXTLOAD)
8815 AddConstant -= (1 << (width-1));
8819 case AArch64CC::GT: {
8820 if ((AddConstant == 0) ||
8821 (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
8822 (AddConstant >= 0 && CompConstant < 0) ||
8823 (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
8827 case AArch64CC::GE: {
8828 if ((AddConstant == 0) ||
8829 (AddConstant >= 0 && CompConstant <= 0) ||
8830 (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
8834 case AArch64CC::LS: {
8835 if ((AddConstant >= 0 && CompConstant < 0) ||
8836 (AddConstant <= 0 && CompConstant >= -1 &&
8837 CompConstant < AddConstant + MaxUInt))
8841 case AArch64CC::MI: {
8842 if ((AddConstant == 0) ||
8843 (AddConstant > 0 && CompConstant <= 0) ||
8844 (AddConstant < 0 && CompConstant <= AddConstant))
8848 case AArch64CC::HS: {
8849 if ((AddConstant >= 0 && CompConstant <= 0) ||
8850 (AddConstant <= 0 && CompConstant >= 0 &&
8851 CompConstant <= AddConstant + MaxUInt))
8855 case AArch64CC::NE: {
8856 if ((AddConstant > 0 && CompConstant < 0) ||
8857 (AddConstant < 0 && CompConstant >= 0 &&
8858 CompConstant < AddConstant + MaxUInt) ||
8859 (AddConstant >= 0 && CompConstant >= 0 &&
8860 CompConstant >= AddConstant) ||
8861 (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
8870 case AArch64CC::Invalid:
8878 SDValue performCONDCombine(SDNode *N,
8879 TargetLowering::DAGCombinerInfo &DCI,
8880 SelectionDAG &DAG, unsigned CCIndex,
8881 unsigned CmpIndex) {
8882 unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
8883 SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
8884 unsigned CondOpcode = SubsNode->getOpcode();
8886 if (CondOpcode != AArch64ISD::SUBS)
8889 // There is a SUBS feeding this condition. Is it fed by a mask we can
8892 SDNode *AndNode = SubsNode->getOperand(0).getNode();
8893 unsigned MaskBits = 0;
8895 if (AndNode->getOpcode() != ISD::AND)
8898 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
8899 uint32_t CNV = CN->getZExtValue();
8902 else if (CNV == 65535)
8909 SDValue AddValue = AndNode->getOperand(0);
8911 if (AddValue.getOpcode() != ISD::ADD)
8914 // The basic dag structure is correct, grab the inputs and validate them.
8916 SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
8917 SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
8918 SDValue SubsInputValue = SubsNode->getOperand(1);
8920 // The mask is present and the provenance of all the values is a smaller type,
8921 // lets see if the mask is superfluous.
8923 if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
8924 !isa<ConstantSDNode>(SubsInputValue.getNode()))
8927 ISD::LoadExtType ExtType;
8929 if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
8930 !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
8931 !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
8934 if(!isEquivalentMaskless(CC, MaskBits, ExtType,
8935 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
8936 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
8939 // The AND is not necessary, remove it.
8941 SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
8942 SubsNode->getValueType(1));
8943 SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
8945 SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
8946 DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
8948 return SDValue(N, 0);
8951 // Optimize compare with zero and branch.
8952 static SDValue performBRCONDCombine(SDNode *N,
8953 TargetLowering::DAGCombinerInfo &DCI,
8954 SelectionDAG &DAG) {
8955 SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3);
8958 SDValue Chain = N->getOperand(0);
8959 SDValue Dest = N->getOperand(1);
8960 SDValue CCVal = N->getOperand(2);
8961 SDValue Cmp = N->getOperand(3);
8963 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
8964 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
8965 if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
8968 unsigned CmpOpc = Cmp.getOpcode();
8969 if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
8972 // Only attempt folding if there is only one use of the flag and no use of the
8974 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
8977 SDValue LHS = Cmp.getOperand(0);
8978 SDValue RHS = Cmp.getOperand(1);
8980 assert(LHS.getValueType() == RHS.getValueType() &&
8981 "Expected the value type to be the same for both operands!");
8982 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
8985 if (isa<ConstantSDNode>(LHS) && cast<ConstantSDNode>(LHS)->isNullValue())
8986 std::swap(LHS, RHS);
8988 if (!isa<ConstantSDNode>(RHS) || !cast<ConstantSDNode>(RHS)->isNullValue())
8991 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
8992 LHS.getOpcode() == ISD::SRL)
8995 // Fold the compare into the branch instruction.
8997 if (CC == AArch64CC::EQ)
8998 BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9000 BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9002 // Do not add new nodes to DAG combiner worklist.
9003 DCI.CombineTo(N, BR, false);
9008 // vselect (v1i1 setcc) ->
9009 // vselect (v1iXX setcc) (XX is the size of the compared operand type)
9010 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
9011 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
9013 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
9014 SDValue N0 = N->getOperand(0);
9015 EVT CCVT = N0.getValueType();
9017 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
9018 CCVT.getVectorElementType() != MVT::i1)
9021 EVT ResVT = N->getValueType(0);
9022 EVT CmpVT = N0.getOperand(0).getValueType();
9023 // Only combine when the result type is of the same size as the compared
9025 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
9028 SDValue IfTrue = N->getOperand(1);
9029 SDValue IfFalse = N->getOperand(2);
9031 DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
9032 N0.getOperand(0), N0.getOperand(1),
9033 cast<CondCodeSDNode>(N0.getOperand(2))->get());
9034 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
9038 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
9039 /// the compare-mask instructions rather than going via NZCV, even if LHS and
9040 /// RHS are really scalar. This replaces any scalar setcc in the above pattern
9041 /// with a vector one followed by a DUP shuffle on the result.
9042 static SDValue performSelectCombine(SDNode *N,
9043 TargetLowering::DAGCombinerInfo &DCI) {
9044 SelectionDAG &DAG = DCI.DAG;
9045 SDValue N0 = N->getOperand(0);
9046 EVT ResVT = N->getValueType(0);
9048 if (N0.getOpcode() != ISD::SETCC)
9051 // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
9052 // scalar SetCCResultType. We also don't expect vectors, because we assume
9053 // that selects fed by vector SETCCs are canonicalized to VSELECT.
9054 assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
9055 "Scalar-SETCC feeding SELECT has unexpected result type!");
9057 // If NumMaskElts == 0, the comparison is larger than select result. The
9058 // largest real NEON comparison is 64-bits per lane, which means the result is
9059 // at most 32-bits and an illegal vector. Just bail out for now.
9060 EVT SrcVT = N0.getOperand(0).getValueType();
9062 // Don't try to do this optimization when the setcc itself has i1 operands.
9063 // There are no legal vectors of i1, so this would be pointless.
9064 if (SrcVT == MVT::i1)
9067 int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
9068 if (!ResVT.isVector() || NumMaskElts == 0)
9071 SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
9072 EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
9074 // Also bail out if the vector CCVT isn't the same size as ResVT.
9075 // This can happen if the SETCC operand size doesn't divide the ResVT size
9076 // (e.g., f64 vs v3f32).
9077 if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
9080 // Make sure we didn't create illegal types, if we're not supposed to.
9081 assert(DCI.isBeforeLegalize() ||
9082 DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
9084 // First perform a vector comparison, where lane 0 is the one we're interested
9088 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
9090 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
9091 SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
9093 // Now duplicate the comparison mask we want across all other lanes.
9094 SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
9095 SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask.data());
9096 Mask = DAG.getNode(ISD::BITCAST, DL,
9097 ResVT.changeVectorElementTypeToInteger(), Mask);
9099 return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
9102 /// Get rid of unnecessary NVCASTs (that don't change the type).
9103 static SDValue performNVCASTCombine(SDNode *N) {
9104 if (N->getValueType(0) == N->getOperand(0).getValueType())
9105 return N->getOperand(0);
9110 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
9111 DAGCombinerInfo &DCI) const {
9112 SelectionDAG &DAG = DCI.DAG;
9113 switch (N->getOpcode()) {
9118 return performAddSubLongCombine(N, DCI, DAG);
9120 return performXorCombine(N, DAG, DCI, Subtarget);
9122 return performMulCombine(N, DAG, DCI, Subtarget);
9123 case ISD::SINT_TO_FP:
9124 case ISD::UINT_TO_FP:
9125 return performIntToFpCombine(N, DAG, Subtarget);
9127 return performORCombine(N, DCI, Subtarget);
9128 case ISD::INTRINSIC_WO_CHAIN:
9129 return performIntrinsicCombine(N, DCI, Subtarget);
9130 case ISD::ANY_EXTEND:
9131 case ISD::ZERO_EXTEND:
9132 case ISD::SIGN_EXTEND:
9133 return performExtendCombine(N, DCI, DAG);
9135 return performBitcastCombine(N, DCI, DAG);
9136 case ISD::CONCAT_VECTORS:
9137 return performConcatVectorsCombine(N, DCI, DAG);
9139 return performSelectCombine(N, DCI);
9141 return performVSelectCombine(N, DCI.DAG);
9143 return performSTORECombine(N, DCI, DAG, Subtarget);
9144 case AArch64ISD::BRCOND:
9145 return performBRCONDCombine(N, DCI, DAG);
9146 case AArch64ISD::CSEL:
9147 return performCONDCombine(N, DCI, DAG, 2, 3);
9148 case AArch64ISD::DUP:
9149 return performPostLD1Combine(N, DCI, false);
9150 case AArch64ISD::NVCAST:
9151 return performNVCASTCombine(N);
9152 case ISD::INSERT_VECTOR_ELT:
9153 return performPostLD1Combine(N, DCI, true);
9154 case ISD::INTRINSIC_VOID:
9155 case ISD::INTRINSIC_W_CHAIN:
9156 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9157 case Intrinsic::aarch64_neon_ld2:
9158 case Intrinsic::aarch64_neon_ld3:
9159 case Intrinsic::aarch64_neon_ld4:
9160 case Intrinsic::aarch64_neon_ld1x2:
9161 case Intrinsic::aarch64_neon_ld1x3:
9162 case Intrinsic::aarch64_neon_ld1x4:
9163 case Intrinsic::aarch64_neon_ld2lane:
9164 case Intrinsic::aarch64_neon_ld3lane:
9165 case Intrinsic::aarch64_neon_ld4lane:
9166 case Intrinsic::aarch64_neon_ld2r:
9167 case Intrinsic::aarch64_neon_ld3r:
9168 case Intrinsic::aarch64_neon_ld4r:
9169 case Intrinsic::aarch64_neon_st2:
9170 case Intrinsic::aarch64_neon_st3:
9171 case Intrinsic::aarch64_neon_st4:
9172 case Intrinsic::aarch64_neon_st1x2:
9173 case Intrinsic::aarch64_neon_st1x3:
9174 case Intrinsic::aarch64_neon_st1x4:
9175 case Intrinsic::aarch64_neon_st2lane:
9176 case Intrinsic::aarch64_neon_st3lane:
9177 case Intrinsic::aarch64_neon_st4lane:
9178 return performNEONPostLDSTCombine(N, DCI, DAG);
9186 // Check if the return value is used as only a return value, as otherwise
9187 // we can't perform a tail-call. In particular, we need to check for
9188 // target ISD nodes that are returns and any other "odd" constructs
9189 // that the generic analysis code won't necessarily catch.
9190 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
9191 SDValue &Chain) const {
9192 if (N->getNumValues() != 1)
9194 if (!N->hasNUsesOfValue(1, 0))
9197 SDValue TCChain = Chain;
9198 SDNode *Copy = *N->use_begin();
9199 if (Copy->getOpcode() == ISD::CopyToReg) {
9200 // If the copy has a glue operand, we conservatively assume it isn't safe to
9201 // perform a tail call.
9202 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
9205 TCChain = Copy->getOperand(0);
9206 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
9209 bool HasRet = false;
9210 for (SDNode *Node : Copy->uses()) {
9211 if (Node->getOpcode() != AArch64ISD::RET_FLAG)
9223 // Return whether the an instruction can potentially be optimized to a tail
9224 // call. This will cause the optimizers to attempt to move, or duplicate,
9225 // return instructions to help enable tail call optimizations for this
9227 bool AArch64TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
9228 if (!CI->isTailCall())
9234 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
9236 ISD::MemIndexedMode &AM,
9238 SelectionDAG &DAG) const {
9239 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
9242 Base = Op->getOperand(0);
9243 // All of the indexed addressing mode instructions take a signed
9244 // 9 bit immediate offset.
9245 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
9246 int64_t RHSC = (int64_t)RHS->getZExtValue();
9247 if (RHSC >= 256 || RHSC <= -256)
9249 IsInc = (Op->getOpcode() == ISD::ADD);
9250 Offset = Op->getOperand(1);
9256 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
9258 ISD::MemIndexedMode &AM,
9259 SelectionDAG &DAG) const {
9262 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9263 VT = LD->getMemoryVT();
9264 Ptr = LD->getBasePtr();
9265 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9266 VT = ST->getMemoryVT();
9267 Ptr = ST->getBasePtr();
9272 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
9274 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
9278 bool AArch64TargetLowering::getPostIndexedAddressParts(
9279 SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
9280 ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
9283 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9284 VT = LD->getMemoryVT();
9285 Ptr = LD->getBasePtr();
9286 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9287 VT = ST->getMemoryVT();
9288 Ptr = ST->getBasePtr();
9293 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
9295 // Post-indexing updates the base, so it's not a valid transform
9296 // if that's not the same as the load's pointer.
9299 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
9303 static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
9304 SelectionDAG &DAG) {
9306 SDValue Op = N->getOperand(0);
9308 if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
9312 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
9313 DAG.getUNDEF(MVT::i32), Op,
9314 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
9316 Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
9317 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
9320 void AArch64TargetLowering::ReplaceNodeResults(
9321 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
9322 switch (N->getOpcode()) {
9324 llvm_unreachable("Don't know how to custom expand this");
9326 ReplaceBITCASTResults(N, Results, DAG);
9328 case ISD::FP_TO_UINT:
9329 case ISD::FP_TO_SINT:
9330 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
9331 // Let normal code take care of it by not adding anything to Results.
9336 bool AArch64TargetLowering::useLoadStackGuardNode() const {
9340 unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
9341 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
9342 // reciprocal if there are three or more FDIVs.
9346 TargetLoweringBase::LegalizeTypeAction
9347 AArch64TargetLowering::getPreferredVectorAction(EVT VT) const {
9348 MVT SVT = VT.getSimpleVT();
9349 // During type legalization, we prefer to widen v1i8, v1i16, v1i32 to v8i8,
9350 // v4i16, v2i32 instead of to promote.
9351 if (SVT == MVT::v1i8 || SVT == MVT::v1i16 || SVT == MVT::v1i32
9352 || SVT == MVT::v1f32)
9353 return TypeWidenVector;
9355 return TargetLoweringBase::getPreferredVectorAction(VT);
9358 // Loads and stores less than 128-bits are already atomic; ones above that
9359 // are doomed anyway, so defer to the default libcall and blame the OS when
9361 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
9362 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
9366 // Loads and stores less than 128-bits are already atomic; ones above that
9367 // are doomed anyway, so defer to the default libcall and blame the OS when
9369 bool AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
9370 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
9374 // For the real atomic operations, we have ldxr/stxr up to 128 bits,
9375 TargetLoweringBase::AtomicRMWExpansionKind
9376 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
9377 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
9378 return Size <= 128 ? AtomicRMWExpansionKind::LLSC
9379 : AtomicRMWExpansionKind::None;
9382 bool AArch64TargetLowering::hasLoadLinkedStoreConditional() const {
9386 Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
9387 AtomicOrdering Ord) const {
9388 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
9389 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
9390 bool IsAcquire = isAtLeastAcquire(Ord);
9392 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
9393 // intrinsic must return {i64, i64} and we have to recombine them into a
9394 // single i128 here.
9395 if (ValTy->getPrimitiveSizeInBits() == 128) {
9397 IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
9398 Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int);
9400 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
9401 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
9403 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
9404 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
9405 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
9406 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
9407 return Builder.CreateOr(
9408 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
9411 Type *Tys[] = { Addr->getType() };
9413 IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
9414 Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int, Tys);
9416 return Builder.CreateTruncOrBitCast(
9417 Builder.CreateCall(Ldxr, Addr),
9418 cast<PointerType>(Addr->getType())->getElementType());
9421 Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
9422 Value *Val, Value *Addr,
9423 AtomicOrdering Ord) const {
9424 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
9425 bool IsRelease = isAtLeastRelease(Ord);
9427 // Since the intrinsics must have legal type, the i128 intrinsics take two
9428 // parameters: "i64, i64". We must marshal Val into the appropriate form
9430 if (Val->getType()->getPrimitiveSizeInBits() == 128) {
9432 IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
9433 Function *Stxr = Intrinsic::getDeclaration(M, Int);
9434 Type *Int64Ty = Type::getInt64Ty(M->getContext());
9436 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
9437 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
9438 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
9439 return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
9443 IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
9444 Type *Tys[] = { Addr->getType() };
9445 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
9447 return Builder.CreateCall(Stxr,
9448 {Builder.CreateZExtOrBitCast(
9449 Val, Stxr->getFunctionType()->getParamType(0)),
9453 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
9454 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
9455 return Ty->isArrayTy();
9458 bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,