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/Intrinsics.h"
29 #include "llvm/IR/Type.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Target/TargetOptions.h"
37 #define DEBUG_TYPE "aarch64-lower"
39 STATISTIC(NumTailCalls, "Number of tail calls");
40 STATISTIC(NumShiftInserts, "Number of vector shift inserts");
49 static cl::opt<AlignMode>
50 Align(cl::desc("Load/store alignment support"),
51 cl::Hidden, cl::init(NoStrictAlign),
53 clEnumValN(StrictAlign, "aarch64-strict-align",
54 "Disallow all unaligned memory accesses"),
55 clEnumValN(NoStrictAlign, "aarch64-no-strict-align",
56 "Allow unaligned memory accesses"),
59 // Place holder until extr generation is tested fully.
61 EnableAArch64ExtrGeneration("aarch64-extr-generation", cl::Hidden,
62 cl::desc("Allow AArch64 (or (shift)(shift))->extract"),
66 EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden,
67 cl::desc("Allow AArch64 SLI/SRI formation"),
70 // FIXME: The necessary dtprel relocations don't seem to be supported
71 // well in the GNU bfd and gold linkers at the moment. Therefore, by
72 // default, for now, fall back to GeneralDynamic code generation.
73 cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration(
74 "aarch64-elf-ldtls-generation", cl::Hidden,
75 cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
79 AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM)
80 : TargetLowering(TM) {
81 Subtarget = &TM.getSubtarget<AArch64Subtarget>();
83 // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
84 // we have to make something up. Arbitrarily, choose ZeroOrOne.
85 setBooleanContents(ZeroOrOneBooleanContent);
86 // When comparing vectors the result sets the different elements in the
87 // vector to all-one or all-zero.
88 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
90 // Set up the register classes.
91 addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
92 addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
94 if (Subtarget->hasFPARMv8()) {
95 addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
96 addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
97 addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
98 addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
101 if (Subtarget->hasNEON()) {
102 addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
103 addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
104 // Someone set us up the NEON.
105 addDRTypeForNEON(MVT::v2f32);
106 addDRTypeForNEON(MVT::v8i8);
107 addDRTypeForNEON(MVT::v4i16);
108 addDRTypeForNEON(MVT::v2i32);
109 addDRTypeForNEON(MVT::v1i64);
110 addDRTypeForNEON(MVT::v1f64);
111 addDRTypeForNEON(MVT::v4f16);
113 addQRTypeForNEON(MVT::v4f32);
114 addQRTypeForNEON(MVT::v2f64);
115 addQRTypeForNEON(MVT::v16i8);
116 addQRTypeForNEON(MVT::v8i16);
117 addQRTypeForNEON(MVT::v4i32);
118 addQRTypeForNEON(MVT::v2i64);
119 addQRTypeForNEON(MVT::v8f16);
122 // Compute derived properties from the register classes
123 computeRegisterProperties();
125 // Provide all sorts of operation actions
126 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
127 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
128 setOperationAction(ISD::SETCC, MVT::i32, Custom);
129 setOperationAction(ISD::SETCC, MVT::i64, Custom);
130 setOperationAction(ISD::SETCC, MVT::f32, Custom);
131 setOperationAction(ISD::SETCC, MVT::f64, Custom);
132 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
133 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
134 setOperationAction(ISD::BR_CC, MVT::i64, Custom);
135 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
136 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
137 setOperationAction(ISD::SELECT, MVT::i32, Custom);
138 setOperationAction(ISD::SELECT, MVT::i64, Custom);
139 setOperationAction(ISD::SELECT, MVT::f32, Custom);
140 setOperationAction(ISD::SELECT, MVT::f64, Custom);
141 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
142 setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
143 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
144 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
145 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
146 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
148 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
149 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
150 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
152 setOperationAction(ISD::FREM, MVT::f32, Expand);
153 setOperationAction(ISD::FREM, MVT::f64, Expand);
154 setOperationAction(ISD::FREM, MVT::f80, Expand);
156 // Custom lowering hooks are needed for XOR
157 // to fold it into CSINC/CSINV.
158 setOperationAction(ISD::XOR, MVT::i32, Custom);
159 setOperationAction(ISD::XOR, MVT::i64, Custom);
161 // Virtually no operation on f128 is legal, but LLVM can't expand them when
162 // there's a valid register class, so we need custom operations in most cases.
163 setOperationAction(ISD::FABS, MVT::f128, Expand);
164 setOperationAction(ISD::FADD, MVT::f128, Custom);
165 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
166 setOperationAction(ISD::FCOS, MVT::f128, Expand);
167 setOperationAction(ISD::FDIV, MVT::f128, Custom);
168 setOperationAction(ISD::FMA, MVT::f128, Expand);
169 setOperationAction(ISD::FMUL, MVT::f128, Custom);
170 setOperationAction(ISD::FNEG, MVT::f128, Expand);
171 setOperationAction(ISD::FPOW, MVT::f128, Expand);
172 setOperationAction(ISD::FREM, MVT::f128, Expand);
173 setOperationAction(ISD::FRINT, MVT::f128, Expand);
174 setOperationAction(ISD::FSIN, MVT::f128, Expand);
175 setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
176 setOperationAction(ISD::FSQRT, MVT::f128, Expand);
177 setOperationAction(ISD::FSUB, MVT::f128, Custom);
178 setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
179 setOperationAction(ISD::SETCC, MVT::f128, Custom);
180 setOperationAction(ISD::BR_CC, MVT::f128, Custom);
181 setOperationAction(ISD::SELECT, MVT::f128, Custom);
182 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
183 setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
185 // Lowering for many of the conversions is actually specified by the non-f128
186 // type. The LowerXXX function will be trivial when f128 isn't involved.
187 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
188 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
189 setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
190 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
191 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
192 setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
193 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
194 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
195 setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
196 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
197 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
198 setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
199 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
200 setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
202 // Variable arguments.
203 setOperationAction(ISD::VASTART, MVT::Other, Custom);
204 setOperationAction(ISD::VAARG, MVT::Other, Custom);
205 setOperationAction(ISD::VACOPY, MVT::Other, Custom);
206 setOperationAction(ISD::VAEND, MVT::Other, Expand);
208 // Variable-sized objects.
209 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
210 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
211 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
213 // Exception handling.
214 // FIXME: These are guesses. Has this been defined yet?
215 setExceptionPointerRegister(AArch64::X0);
216 setExceptionSelectorRegister(AArch64::X1);
218 // Constant pool entries
219 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
222 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
224 // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
225 setOperationAction(ISD::ADDC, MVT::i32, Custom);
226 setOperationAction(ISD::ADDE, MVT::i32, Custom);
227 setOperationAction(ISD::SUBC, MVT::i32, Custom);
228 setOperationAction(ISD::SUBE, MVT::i32, Custom);
229 setOperationAction(ISD::ADDC, MVT::i64, Custom);
230 setOperationAction(ISD::ADDE, MVT::i64, Custom);
231 setOperationAction(ISD::SUBC, MVT::i64, Custom);
232 setOperationAction(ISD::SUBE, MVT::i64, Custom);
234 // AArch64 lacks both left-rotate and popcount instructions.
235 setOperationAction(ISD::ROTL, MVT::i32, Expand);
236 setOperationAction(ISD::ROTL, MVT::i64, Expand);
238 // AArch64 doesn't have {U|S}MUL_LOHI.
239 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
240 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
243 // Expand the undefined-at-zero variants to cttz/ctlz to their defined-at-zero
244 // counterparts, which AArch64 supports directly.
245 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
246 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
247 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
248 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
250 setOperationAction(ISD::CTPOP, MVT::i32, Custom);
251 setOperationAction(ISD::CTPOP, MVT::i64, Custom);
253 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
254 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
255 setOperationAction(ISD::SREM, MVT::i32, Expand);
256 setOperationAction(ISD::SREM, MVT::i64, Expand);
257 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
258 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
259 setOperationAction(ISD::UREM, MVT::i32, Expand);
260 setOperationAction(ISD::UREM, MVT::i64, Expand);
262 // Custom lower Add/Sub/Mul with overflow.
263 setOperationAction(ISD::SADDO, MVT::i32, Custom);
264 setOperationAction(ISD::SADDO, MVT::i64, Custom);
265 setOperationAction(ISD::UADDO, MVT::i32, Custom);
266 setOperationAction(ISD::UADDO, MVT::i64, Custom);
267 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
268 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
269 setOperationAction(ISD::USUBO, MVT::i32, Custom);
270 setOperationAction(ISD::USUBO, MVT::i64, Custom);
271 setOperationAction(ISD::SMULO, MVT::i32, Custom);
272 setOperationAction(ISD::SMULO, MVT::i64, Custom);
273 setOperationAction(ISD::UMULO, MVT::i32, Custom);
274 setOperationAction(ISD::UMULO, MVT::i64, Custom);
276 setOperationAction(ISD::FSIN, MVT::f32, Expand);
277 setOperationAction(ISD::FSIN, MVT::f64, Expand);
278 setOperationAction(ISD::FCOS, MVT::f32, Expand);
279 setOperationAction(ISD::FCOS, MVT::f64, Expand);
280 setOperationAction(ISD::FPOW, MVT::f32, Expand);
281 setOperationAction(ISD::FPOW, MVT::f64, Expand);
282 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
283 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
285 // f16 is storage-only, so we promote operations to f32 if we know this is
286 // valid, and ignore them otherwise. The operations not mentioned here will
287 // fail to select, but this is not a major problem as no source language
288 // should be emitting native f16 operations yet.
289 setOperationAction(ISD::FADD, MVT::f16, Promote);
290 setOperationAction(ISD::FDIV, MVT::f16, Promote);
291 setOperationAction(ISD::FMUL, MVT::f16, Promote);
292 setOperationAction(ISD::FSUB, MVT::f16, Promote);
294 // v4f16 is also a storage-only type, so promote it to v4f32 when that is
296 setOperationAction(ISD::FADD, MVT::v4f16, Promote);
297 setOperationAction(ISD::FSUB, MVT::v4f16, Promote);
298 setOperationAction(ISD::FMUL, MVT::v4f16, Promote);
299 setOperationAction(ISD::FDIV, MVT::v4f16, Promote);
300 setOperationAction(ISD::FP_EXTEND, MVT::v4f16, Promote);
301 setOperationAction(ISD::FP_ROUND, MVT::v4f16, Promote);
302 AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32);
303 AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32);
304 AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32);
305 AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32);
306 AddPromotedToType(ISD::FP_EXTEND, MVT::v4f16, MVT::v4f32);
307 AddPromotedToType(ISD::FP_ROUND, MVT::v4f16, MVT::v4f32);
309 // Expand all other v4f16 operations.
310 // FIXME: We could generate better code by promoting some operations to
312 setOperationAction(ISD::FABS, MVT::v4f16, Expand);
313 setOperationAction(ISD::FCEIL, MVT::v4f16, Expand);
314 setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand);
315 setOperationAction(ISD::FCOS, MVT::v4f16, Expand);
316 setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand);
317 setOperationAction(ISD::FMA, MVT::v4f16, Expand);
318 setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand);
319 setOperationAction(ISD::FNEG, MVT::v4f16, Expand);
320 setOperationAction(ISD::FPOW, MVT::v4f16, Expand);
321 setOperationAction(ISD::FPOWI, MVT::v4f16, Expand);
322 setOperationAction(ISD::FREM, MVT::v4f16, Expand);
323 setOperationAction(ISD::FROUND, MVT::v4f16, Expand);
324 setOperationAction(ISD::FRINT, MVT::v4f16, Expand);
325 setOperationAction(ISD::FSIN, MVT::v4f16, Expand);
326 setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand);
327 setOperationAction(ISD::FSQRT, MVT::v4f16, Expand);
328 setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand);
329 setOperationAction(ISD::SETCC, MVT::v4f16, Expand);
330 setOperationAction(ISD::BR_CC, MVT::v4f16, Expand);
331 setOperationAction(ISD::SELECT, MVT::v4f16, Expand);
332 setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand);
333 setOperationAction(ISD::FEXP, MVT::v4f16, Expand);
334 setOperationAction(ISD::FEXP2, MVT::v4f16, Expand);
335 setOperationAction(ISD::FLOG, MVT::v4f16, Expand);
336 setOperationAction(ISD::FLOG2, MVT::v4f16, Expand);
337 setOperationAction(ISD::FLOG10, MVT::v4f16, Expand);
340 // v8f16 is also a storage-only type, so expand it.
341 setOperationAction(ISD::FABS, MVT::v8f16, Expand);
342 setOperationAction(ISD::FADD, MVT::v8f16, Expand);
343 setOperationAction(ISD::FCEIL, MVT::v8f16, Expand);
344 setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand);
345 setOperationAction(ISD::FCOS, MVT::v8f16, Expand);
346 setOperationAction(ISD::FDIV, MVT::v8f16, Expand);
347 setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand);
348 setOperationAction(ISD::FMA, MVT::v8f16, Expand);
349 setOperationAction(ISD::FMUL, MVT::v8f16, Expand);
350 setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand);
351 setOperationAction(ISD::FNEG, MVT::v8f16, Expand);
352 setOperationAction(ISD::FPOW, MVT::v8f16, Expand);
353 setOperationAction(ISD::FPOWI, MVT::v8f16, Expand);
354 setOperationAction(ISD::FREM, MVT::v8f16, Expand);
355 setOperationAction(ISD::FROUND, MVT::v8f16, Expand);
356 setOperationAction(ISD::FRINT, MVT::v8f16, Expand);
357 setOperationAction(ISD::FSIN, MVT::v8f16, Expand);
358 setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
359 setOperationAction(ISD::FSQRT, MVT::v8f16, Expand);
360 setOperationAction(ISD::FSUB, MVT::v8f16, Expand);
361 setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand);
362 setOperationAction(ISD::SETCC, MVT::v8f16, Expand);
363 setOperationAction(ISD::BR_CC, MVT::v8f16, Expand);
364 setOperationAction(ISD::SELECT, MVT::v8f16, Expand);
365 setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand);
366 setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand);
367 setOperationAction(ISD::FEXP, MVT::v8f16, Expand);
368 setOperationAction(ISD::FEXP2, MVT::v8f16, Expand);
369 setOperationAction(ISD::FLOG, MVT::v8f16, Expand);
370 setOperationAction(ISD::FLOG2, MVT::v8f16, Expand);
371 setOperationAction(ISD::FLOG10, MVT::v8f16, Expand);
373 // AArch64 has implementations of a lot of rounding-like FP operations.
374 static MVT RoundingTypes[] = { MVT::f32, MVT::f64};
375 for (unsigned I = 0; I < array_lengthof(RoundingTypes); ++I) {
376 MVT Ty = RoundingTypes[I];
377 setOperationAction(ISD::FFLOOR, Ty, Legal);
378 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
379 setOperationAction(ISD::FCEIL, Ty, Legal);
380 setOperationAction(ISD::FRINT, Ty, Legal);
381 setOperationAction(ISD::FTRUNC, Ty, Legal);
382 setOperationAction(ISD::FROUND, Ty, Legal);
385 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
387 if (Subtarget->isTargetMachO()) {
388 // For iOS, we don't want to the normal expansion of a libcall to
389 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
391 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
392 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
394 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
395 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
398 // Make floating-point constants legal for the large code model, so they don't
399 // become loads from the constant pool.
400 if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
401 setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
402 setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
405 // AArch64 does not have floating-point extending loads, i1 sign-extending
406 // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
407 for (MVT VT : MVT::fp_valuetypes()) {
408 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
409 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
410 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
411 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
413 for (MVT VT : MVT::integer_valuetypes())
414 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
416 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
417 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
418 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
419 setTruncStoreAction(MVT::f128, MVT::f80, Expand);
420 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
421 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
422 setTruncStoreAction(MVT::f128, MVT::f16, Expand);
424 setOperationAction(ISD::BITCAST, MVT::i16, Custom);
425 setOperationAction(ISD::BITCAST, MVT::f16, Custom);
427 // Indexed loads and stores are supported.
428 for (unsigned im = (unsigned)ISD::PRE_INC;
429 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
430 setIndexedLoadAction(im, MVT::i8, Legal);
431 setIndexedLoadAction(im, MVT::i16, Legal);
432 setIndexedLoadAction(im, MVT::i32, Legal);
433 setIndexedLoadAction(im, MVT::i64, Legal);
434 setIndexedLoadAction(im, MVT::f64, Legal);
435 setIndexedLoadAction(im, MVT::f32, Legal);
436 setIndexedStoreAction(im, MVT::i8, Legal);
437 setIndexedStoreAction(im, MVT::i16, Legal);
438 setIndexedStoreAction(im, MVT::i32, Legal);
439 setIndexedStoreAction(im, MVT::i64, Legal);
440 setIndexedStoreAction(im, MVT::f64, Legal);
441 setIndexedStoreAction(im, MVT::f32, Legal);
445 setOperationAction(ISD::TRAP, MVT::Other, Legal);
447 // We combine OR nodes for bitfield operations.
448 setTargetDAGCombine(ISD::OR);
450 // Vector add and sub nodes may conceal a high-half opportunity.
451 // Also, try to fold ADD into CSINC/CSINV..
452 setTargetDAGCombine(ISD::ADD);
453 setTargetDAGCombine(ISD::SUB);
455 setTargetDAGCombine(ISD::XOR);
456 setTargetDAGCombine(ISD::SINT_TO_FP);
457 setTargetDAGCombine(ISD::UINT_TO_FP);
459 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
461 setTargetDAGCombine(ISD::ANY_EXTEND);
462 setTargetDAGCombine(ISD::ZERO_EXTEND);
463 setTargetDAGCombine(ISD::SIGN_EXTEND);
464 setTargetDAGCombine(ISD::BITCAST);
465 setTargetDAGCombine(ISD::CONCAT_VECTORS);
466 setTargetDAGCombine(ISD::STORE);
468 setTargetDAGCombine(ISD::MUL);
470 setTargetDAGCombine(ISD::SELECT);
471 setTargetDAGCombine(ISD::VSELECT);
473 setTargetDAGCombine(ISD::INTRINSIC_VOID);
474 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
475 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
477 MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 8;
478 MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 4;
479 MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = 4;
481 setStackPointerRegisterToSaveRestore(AArch64::SP);
483 setSchedulingPreference(Sched::Hybrid);
486 MaskAndBranchFoldingIsLegal = true;
488 setMinFunctionAlignment(2);
490 RequireStrictAlign = (Align == StrictAlign);
492 setHasExtractBitsInsn(true);
494 if (Subtarget->hasNEON()) {
495 // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
496 // silliness like this:
497 setOperationAction(ISD::FABS, MVT::v1f64, Expand);
498 setOperationAction(ISD::FADD, MVT::v1f64, Expand);
499 setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
500 setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
501 setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
502 setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
503 setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
504 setOperationAction(ISD::FMA, MVT::v1f64, Expand);
505 setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
506 setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
507 setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
508 setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
509 setOperationAction(ISD::FREM, MVT::v1f64, Expand);
510 setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
511 setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
512 setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
513 setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
514 setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
515 setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
516 setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
517 setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
518 setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
519 setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
520 setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
521 setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
523 setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
524 setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
525 setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
526 setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
527 setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
529 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
531 // AArch64 doesn't have a direct vector ->f32 conversion instructions for
532 // elements smaller than i32, so promote the input to i32 first.
533 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Promote);
534 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Promote);
535 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Promote);
536 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Promote);
537 // Similarly, there is no direct i32 -> f64 vector conversion instruction.
538 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
539 setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
540 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
541 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
543 // AArch64 doesn't have MUL.2d:
544 setOperationAction(ISD::MUL, MVT::v2i64, Expand);
545 // Custom handling for some quad-vector types to detect MULL.
546 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
547 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
548 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
550 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
551 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
552 // Likewise, narrowing and extending vector loads/stores aren't handled
554 for (MVT VT : MVT::vector_valuetypes()) {
555 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
557 setOperationAction(ISD::MULHS, VT, Expand);
558 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
559 setOperationAction(ISD::MULHU, VT, Expand);
560 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
562 setOperationAction(ISD::BSWAP, VT, Expand);
564 for (MVT InnerVT : MVT::vector_valuetypes()) {
565 setTruncStoreAction(VT, InnerVT, Expand);
566 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
567 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
568 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
572 // AArch64 has implementations of a lot of rounding-like FP operations.
573 static MVT RoundingVecTypes[] = {MVT::v2f32, MVT::v4f32, MVT::v2f64 };
574 for (unsigned I = 0; I < array_lengthof(RoundingVecTypes); ++I) {
575 MVT Ty = RoundingVecTypes[I];
576 setOperationAction(ISD::FFLOOR, Ty, Legal);
577 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
578 setOperationAction(ISD::FCEIL, Ty, Legal);
579 setOperationAction(ISD::FRINT, Ty, Legal);
580 setOperationAction(ISD::FTRUNC, Ty, Legal);
581 setOperationAction(ISD::FROUND, Ty, Legal);
585 // Prefer likely predicted branches to selects on out-of-order cores.
586 if (Subtarget->isCortexA57())
587 PredictableSelectIsExpensive = true;
590 void AArch64TargetLowering::addTypeForNEON(EVT VT, EVT PromotedBitwiseVT) {
591 if (VT == MVT::v2f32 || VT == MVT::v4f16) {
592 setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
593 AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i32);
595 setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
596 AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i32);
597 } else if (VT == MVT::v2f64 || VT == MVT::v4f32 || VT == MVT::v8f16) {
598 setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
599 AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i64);
601 setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
602 AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i64);
605 // Mark vector float intrinsics as expand.
606 if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
607 setOperationAction(ISD::FSIN, VT.getSimpleVT(), Expand);
608 setOperationAction(ISD::FCOS, VT.getSimpleVT(), Expand);
609 setOperationAction(ISD::FPOWI, VT.getSimpleVT(), Expand);
610 setOperationAction(ISD::FPOW, VT.getSimpleVT(), Expand);
611 setOperationAction(ISD::FLOG, VT.getSimpleVT(), Expand);
612 setOperationAction(ISD::FLOG2, VT.getSimpleVT(), Expand);
613 setOperationAction(ISD::FLOG10, VT.getSimpleVT(), Expand);
614 setOperationAction(ISD::FEXP, VT.getSimpleVT(), Expand);
615 setOperationAction(ISD::FEXP2, VT.getSimpleVT(), Expand);
618 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT.getSimpleVT(), Custom);
619 setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getSimpleVT(), Custom);
620 setOperationAction(ISD::BUILD_VECTOR, VT.getSimpleVT(), Custom);
621 setOperationAction(ISD::VECTOR_SHUFFLE, VT.getSimpleVT(), Custom);
622 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT.getSimpleVT(), Custom);
623 setOperationAction(ISD::SRA, VT.getSimpleVT(), Custom);
624 setOperationAction(ISD::SRL, VT.getSimpleVT(), Custom);
625 setOperationAction(ISD::SHL, VT.getSimpleVT(), Custom);
626 setOperationAction(ISD::AND, VT.getSimpleVT(), Custom);
627 setOperationAction(ISD::OR, VT.getSimpleVT(), Custom);
628 setOperationAction(ISD::SETCC, VT.getSimpleVT(), Custom);
629 setOperationAction(ISD::CONCAT_VECTORS, VT.getSimpleVT(), Legal);
631 setOperationAction(ISD::SELECT, VT.getSimpleVT(), Expand);
632 setOperationAction(ISD::SELECT_CC, VT.getSimpleVT(), Expand);
633 setOperationAction(ISD::VSELECT, VT.getSimpleVT(), Expand);
634 for (MVT InnerVT : MVT::all_valuetypes())
635 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT.getSimpleVT(), Expand);
637 // CNT supports only B element sizes.
638 if (VT != MVT::v8i8 && VT != MVT::v16i8)
639 setOperationAction(ISD::CTPOP, VT.getSimpleVT(), Expand);
641 setOperationAction(ISD::UDIV, VT.getSimpleVT(), Expand);
642 setOperationAction(ISD::SDIV, VT.getSimpleVT(), Expand);
643 setOperationAction(ISD::UREM, VT.getSimpleVT(), Expand);
644 setOperationAction(ISD::SREM, VT.getSimpleVT(), Expand);
645 setOperationAction(ISD::FREM, VT.getSimpleVT(), Expand);
647 setOperationAction(ISD::FP_TO_SINT, VT.getSimpleVT(), Custom);
648 setOperationAction(ISD::FP_TO_UINT, VT.getSimpleVT(), Custom);
650 if (Subtarget->isLittleEndian()) {
651 for (unsigned im = (unsigned)ISD::PRE_INC;
652 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
653 setIndexedLoadAction(im, VT.getSimpleVT(), Legal);
654 setIndexedStoreAction(im, VT.getSimpleVT(), Legal);
659 void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
660 addRegisterClass(VT, &AArch64::FPR64RegClass);
661 addTypeForNEON(VT, MVT::v2i32);
664 void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
665 addRegisterClass(VT, &AArch64::FPR128RegClass);
666 addTypeForNEON(VT, MVT::v4i32);
669 EVT AArch64TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
672 return VT.changeVectorElementTypeToInteger();
675 /// computeKnownBitsForTargetNode - Determine which of the bits specified in
676 /// Mask are known to be either zero or one and return them in the
677 /// KnownZero/KnownOne bitsets.
678 void AArch64TargetLowering::computeKnownBitsForTargetNode(
679 const SDValue Op, APInt &KnownZero, APInt &KnownOne,
680 const SelectionDAG &DAG, unsigned Depth) const {
681 switch (Op.getOpcode()) {
684 case AArch64ISD::CSEL: {
685 APInt KnownZero2, KnownOne2;
686 DAG.computeKnownBits(Op->getOperand(0), KnownZero, KnownOne, Depth + 1);
687 DAG.computeKnownBits(Op->getOperand(1), KnownZero2, KnownOne2, Depth + 1);
688 KnownZero &= KnownZero2;
689 KnownOne &= KnownOne2;
692 case ISD::INTRINSIC_W_CHAIN: {
693 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
694 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
697 case Intrinsic::aarch64_ldaxr:
698 case Intrinsic::aarch64_ldxr: {
699 unsigned BitWidth = KnownOne.getBitWidth();
700 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
701 unsigned MemBits = VT.getScalarType().getSizeInBits();
702 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
708 case ISD::INTRINSIC_WO_CHAIN:
709 case ISD::INTRINSIC_VOID: {
710 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
714 case Intrinsic::aarch64_neon_umaxv:
715 case Intrinsic::aarch64_neon_uminv: {
716 // Figure out the datatype of the vector operand. The UMINV instruction
717 // will zero extend the result, so we can mark as known zero all the
718 // bits larger than the element datatype. 32-bit or larget doesn't need
719 // this as those are legal types and will be handled by isel directly.
720 MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
721 unsigned BitWidth = KnownZero.getBitWidth();
722 if (VT == MVT::v8i8 || VT == MVT::v16i8) {
723 assert(BitWidth >= 8 && "Unexpected width!");
724 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
726 } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
727 assert(BitWidth >= 16 && "Unexpected width!");
728 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
738 MVT AArch64TargetLowering::getScalarShiftAmountTy(EVT LHSTy) const {
742 unsigned AArch64TargetLowering::getMaximalGlobalOffset() const {
743 // FIXME: On AArch64, this depends on the type.
744 // Basically, the addressable offsets are up to 4095 * Ty.getSizeInBytes().
745 // and the offset has to be a multiple of the related size in bytes.
750 AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
751 const TargetLibraryInfo *libInfo) const {
752 return AArch64::createFastISel(funcInfo, libInfo);
755 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
759 case AArch64ISD::CALL: return "AArch64ISD::CALL";
760 case AArch64ISD::ADRP: return "AArch64ISD::ADRP";
761 case AArch64ISD::ADDlow: return "AArch64ISD::ADDlow";
762 case AArch64ISD::LOADgot: return "AArch64ISD::LOADgot";
763 case AArch64ISD::RET_FLAG: return "AArch64ISD::RET_FLAG";
764 case AArch64ISD::BRCOND: return "AArch64ISD::BRCOND";
765 case AArch64ISD::CSEL: return "AArch64ISD::CSEL";
766 case AArch64ISD::FCSEL: return "AArch64ISD::FCSEL";
767 case AArch64ISD::CSINV: return "AArch64ISD::CSINV";
768 case AArch64ISD::CSNEG: return "AArch64ISD::CSNEG";
769 case AArch64ISD::CSINC: return "AArch64ISD::CSINC";
770 case AArch64ISD::THREAD_POINTER: return "AArch64ISD::THREAD_POINTER";
771 case AArch64ISD::TLSDESC_CALLSEQ: return "AArch64ISD::TLSDESC_CALLSEQ";
772 case AArch64ISD::ADC: return "AArch64ISD::ADC";
773 case AArch64ISD::SBC: return "AArch64ISD::SBC";
774 case AArch64ISD::ADDS: return "AArch64ISD::ADDS";
775 case AArch64ISD::SUBS: return "AArch64ISD::SUBS";
776 case AArch64ISD::ADCS: return "AArch64ISD::ADCS";
777 case AArch64ISD::SBCS: return "AArch64ISD::SBCS";
778 case AArch64ISD::ANDS: return "AArch64ISD::ANDS";
779 case AArch64ISD::FCMP: return "AArch64ISD::FCMP";
780 case AArch64ISD::FMIN: return "AArch64ISD::FMIN";
781 case AArch64ISD::FMAX: return "AArch64ISD::FMAX";
782 case AArch64ISD::DUP: return "AArch64ISD::DUP";
783 case AArch64ISD::DUPLANE8: return "AArch64ISD::DUPLANE8";
784 case AArch64ISD::DUPLANE16: return "AArch64ISD::DUPLANE16";
785 case AArch64ISD::DUPLANE32: return "AArch64ISD::DUPLANE32";
786 case AArch64ISD::DUPLANE64: return "AArch64ISD::DUPLANE64";
787 case AArch64ISD::MOVI: return "AArch64ISD::MOVI";
788 case AArch64ISD::MOVIshift: return "AArch64ISD::MOVIshift";
789 case AArch64ISD::MOVIedit: return "AArch64ISD::MOVIedit";
790 case AArch64ISD::MOVImsl: return "AArch64ISD::MOVImsl";
791 case AArch64ISD::FMOV: return "AArch64ISD::FMOV";
792 case AArch64ISD::MVNIshift: return "AArch64ISD::MVNIshift";
793 case AArch64ISD::MVNImsl: return "AArch64ISD::MVNImsl";
794 case AArch64ISD::BICi: return "AArch64ISD::BICi";
795 case AArch64ISD::ORRi: return "AArch64ISD::ORRi";
796 case AArch64ISD::BSL: return "AArch64ISD::BSL";
797 case AArch64ISD::NEG: return "AArch64ISD::NEG";
798 case AArch64ISD::EXTR: return "AArch64ISD::EXTR";
799 case AArch64ISD::ZIP1: return "AArch64ISD::ZIP1";
800 case AArch64ISD::ZIP2: return "AArch64ISD::ZIP2";
801 case AArch64ISD::UZP1: return "AArch64ISD::UZP1";
802 case AArch64ISD::UZP2: return "AArch64ISD::UZP2";
803 case AArch64ISD::TRN1: return "AArch64ISD::TRN1";
804 case AArch64ISD::TRN2: return "AArch64ISD::TRN2";
805 case AArch64ISD::REV16: return "AArch64ISD::REV16";
806 case AArch64ISD::REV32: return "AArch64ISD::REV32";
807 case AArch64ISD::REV64: return "AArch64ISD::REV64";
808 case AArch64ISD::EXT: return "AArch64ISD::EXT";
809 case AArch64ISD::VSHL: return "AArch64ISD::VSHL";
810 case AArch64ISD::VLSHR: return "AArch64ISD::VLSHR";
811 case AArch64ISD::VASHR: return "AArch64ISD::VASHR";
812 case AArch64ISD::CMEQ: return "AArch64ISD::CMEQ";
813 case AArch64ISD::CMGE: return "AArch64ISD::CMGE";
814 case AArch64ISD::CMGT: return "AArch64ISD::CMGT";
815 case AArch64ISD::CMHI: return "AArch64ISD::CMHI";
816 case AArch64ISD::CMHS: return "AArch64ISD::CMHS";
817 case AArch64ISD::FCMEQ: return "AArch64ISD::FCMEQ";
818 case AArch64ISD::FCMGE: return "AArch64ISD::FCMGE";
819 case AArch64ISD::FCMGT: return "AArch64ISD::FCMGT";
820 case AArch64ISD::CMEQz: return "AArch64ISD::CMEQz";
821 case AArch64ISD::CMGEz: return "AArch64ISD::CMGEz";
822 case AArch64ISD::CMGTz: return "AArch64ISD::CMGTz";
823 case AArch64ISD::CMLEz: return "AArch64ISD::CMLEz";
824 case AArch64ISD::CMLTz: return "AArch64ISD::CMLTz";
825 case AArch64ISD::FCMEQz: return "AArch64ISD::FCMEQz";
826 case AArch64ISD::FCMGEz: return "AArch64ISD::FCMGEz";
827 case AArch64ISD::FCMGTz: return "AArch64ISD::FCMGTz";
828 case AArch64ISD::FCMLEz: return "AArch64ISD::FCMLEz";
829 case AArch64ISD::FCMLTz: return "AArch64ISD::FCMLTz";
830 case AArch64ISD::NOT: return "AArch64ISD::NOT";
831 case AArch64ISD::BIT: return "AArch64ISD::BIT";
832 case AArch64ISD::CBZ: return "AArch64ISD::CBZ";
833 case AArch64ISD::CBNZ: return "AArch64ISD::CBNZ";
834 case AArch64ISD::TBZ: return "AArch64ISD::TBZ";
835 case AArch64ISD::TBNZ: return "AArch64ISD::TBNZ";
836 case AArch64ISD::TC_RETURN: return "AArch64ISD::TC_RETURN";
837 case AArch64ISD::SITOF: return "AArch64ISD::SITOF";
838 case AArch64ISD::UITOF: return "AArch64ISD::UITOF";
839 case AArch64ISD::NVCAST: return "AArch64ISD::NVCAST";
840 case AArch64ISD::SQSHL_I: return "AArch64ISD::SQSHL_I";
841 case AArch64ISD::UQSHL_I: return "AArch64ISD::UQSHL_I";
842 case AArch64ISD::SRSHR_I: return "AArch64ISD::SRSHR_I";
843 case AArch64ISD::URSHR_I: return "AArch64ISD::URSHR_I";
844 case AArch64ISD::SQSHLU_I: return "AArch64ISD::SQSHLU_I";
845 case AArch64ISD::WrapperLarge: return "AArch64ISD::WrapperLarge";
846 case AArch64ISD::LD2post: return "AArch64ISD::LD2post";
847 case AArch64ISD::LD3post: return "AArch64ISD::LD3post";
848 case AArch64ISD::LD4post: return "AArch64ISD::LD4post";
849 case AArch64ISD::ST2post: return "AArch64ISD::ST2post";
850 case AArch64ISD::ST3post: return "AArch64ISD::ST3post";
851 case AArch64ISD::ST4post: return "AArch64ISD::ST4post";
852 case AArch64ISD::LD1x2post: return "AArch64ISD::LD1x2post";
853 case AArch64ISD::LD1x3post: return "AArch64ISD::LD1x3post";
854 case AArch64ISD::LD1x4post: return "AArch64ISD::LD1x4post";
855 case AArch64ISD::ST1x2post: return "AArch64ISD::ST1x2post";
856 case AArch64ISD::ST1x3post: return "AArch64ISD::ST1x3post";
857 case AArch64ISD::ST1x4post: return "AArch64ISD::ST1x4post";
858 case AArch64ISD::LD1DUPpost: return "AArch64ISD::LD1DUPpost";
859 case AArch64ISD::LD2DUPpost: return "AArch64ISD::LD2DUPpost";
860 case AArch64ISD::LD3DUPpost: return "AArch64ISD::LD3DUPpost";
861 case AArch64ISD::LD4DUPpost: return "AArch64ISD::LD4DUPpost";
862 case AArch64ISD::LD1LANEpost: return "AArch64ISD::LD1LANEpost";
863 case AArch64ISD::LD2LANEpost: return "AArch64ISD::LD2LANEpost";
864 case AArch64ISD::LD3LANEpost: return "AArch64ISD::LD3LANEpost";
865 case AArch64ISD::LD4LANEpost: return "AArch64ISD::LD4LANEpost";
866 case AArch64ISD::ST2LANEpost: return "AArch64ISD::ST2LANEpost";
867 case AArch64ISD::ST3LANEpost: return "AArch64ISD::ST3LANEpost";
868 case AArch64ISD::ST4LANEpost: return "AArch64ISD::ST4LANEpost";
869 case AArch64ISD::SMULL: return "AArch64ISD::SMULL";
870 case AArch64ISD::UMULL: return "AArch64ISD::UMULL";
875 AArch64TargetLowering::EmitF128CSEL(MachineInstr *MI,
876 MachineBasicBlock *MBB) const {
877 // We materialise the F128CSEL pseudo-instruction as some control flow and a
881 // [... previous instrs leading to comparison ...]
887 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
889 const TargetInstrInfo *TII =
890 getTargetMachine().getSubtargetImpl()->getInstrInfo();
891 MachineFunction *MF = MBB->getParent();
892 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
893 DebugLoc DL = MI->getDebugLoc();
894 MachineFunction::iterator It = MBB;
897 unsigned DestReg = MI->getOperand(0).getReg();
898 unsigned IfTrueReg = MI->getOperand(1).getReg();
899 unsigned IfFalseReg = MI->getOperand(2).getReg();
900 unsigned CondCode = MI->getOperand(3).getImm();
901 bool NZCVKilled = MI->getOperand(4).isKill();
903 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
904 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
905 MF->insert(It, TrueBB);
906 MF->insert(It, EndBB);
908 // Transfer rest of current basic-block to EndBB
909 EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
911 EndBB->transferSuccessorsAndUpdatePHIs(MBB);
913 BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
914 BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
915 MBB->addSuccessor(TrueBB);
916 MBB->addSuccessor(EndBB);
918 // TrueBB falls through to the end.
919 TrueBB->addSuccessor(EndBB);
922 TrueBB->addLiveIn(AArch64::NZCV);
923 EndBB->addLiveIn(AArch64::NZCV);
926 BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
932 MI->eraseFromParent();
937 AArch64TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
938 MachineBasicBlock *BB) const {
939 switch (MI->getOpcode()) {
944 llvm_unreachable("Unexpected instruction for custom inserter!");
946 case AArch64::F128CSEL:
947 return EmitF128CSEL(MI, BB);
949 case TargetOpcode::STACKMAP:
950 case TargetOpcode::PATCHPOINT:
951 return emitPatchPoint(MI, BB);
955 //===----------------------------------------------------------------------===//
956 // AArch64 Lowering private implementation.
957 //===----------------------------------------------------------------------===//
959 //===----------------------------------------------------------------------===//
961 //===----------------------------------------------------------------------===//
963 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
965 static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
968 llvm_unreachable("Unknown condition code!");
970 return AArch64CC::NE;
972 return AArch64CC::EQ;
974 return AArch64CC::GT;
976 return AArch64CC::GE;
978 return AArch64CC::LT;
980 return AArch64CC::LE;
982 return AArch64CC::HI;
984 return AArch64CC::HS;
986 return AArch64CC::LO;
988 return AArch64CC::LS;
992 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
993 static void changeFPCCToAArch64CC(ISD::CondCode CC,
994 AArch64CC::CondCode &CondCode,
995 AArch64CC::CondCode &CondCode2) {
996 CondCode2 = AArch64CC::AL;
999 llvm_unreachable("Unknown FP condition!");
1002 CondCode = AArch64CC::EQ;
1006 CondCode = AArch64CC::GT;
1010 CondCode = AArch64CC::GE;
1013 CondCode = AArch64CC::MI;
1016 CondCode = AArch64CC::LS;
1019 CondCode = AArch64CC::MI;
1020 CondCode2 = AArch64CC::GT;
1023 CondCode = AArch64CC::VC;
1026 CondCode = AArch64CC::VS;
1029 CondCode = AArch64CC::EQ;
1030 CondCode2 = AArch64CC::VS;
1033 CondCode = AArch64CC::HI;
1036 CondCode = AArch64CC::PL;
1040 CondCode = AArch64CC::LT;
1044 CondCode = AArch64CC::LE;
1048 CondCode = AArch64CC::NE;
1053 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1054 /// CC usable with the vector instructions. Fewer operations are available
1055 /// without a real NZCV register, so we have to use less efficient combinations
1056 /// to get the same effect.
1057 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1058 AArch64CC::CondCode &CondCode,
1059 AArch64CC::CondCode &CondCode2,
1064 // Mostly the scalar mappings work fine.
1065 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1068 Invert = true; // Fallthrough
1070 CondCode = AArch64CC::MI;
1071 CondCode2 = AArch64CC::GE;
1078 // All of the compare-mask comparisons are ordered, but we can switch
1079 // between the two by a double inversion. E.g. ULE == !OGT.
1081 changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1086 static bool isLegalArithImmed(uint64_t C) {
1087 // Matches AArch64DAGToDAGISel::SelectArithImmed().
1088 return (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1091 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1092 SDLoc dl, SelectionDAG &DAG) {
1093 EVT VT = LHS.getValueType();
1095 if (VT.isFloatingPoint())
1096 return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
1098 // The CMP instruction is just an alias for SUBS, and representing it as
1099 // SUBS means that it's possible to get CSE with subtract operations.
1100 // A later phase can perform the optimization of setting the destination
1101 // register to WZR/XZR if it ends up being unused.
1102 unsigned Opcode = AArch64ISD::SUBS;
1104 if (RHS.getOpcode() == ISD::SUB && isa<ConstantSDNode>(RHS.getOperand(0)) &&
1105 cast<ConstantSDNode>(RHS.getOperand(0))->getZExtValue() == 0 &&
1106 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1107 // We'd like to combine a (CMP op1, (sub 0, op2) into a CMN instruction on
1108 // the grounds that "op1 - (-op2) == op1 + op2". However, the C and V flags
1109 // can be set differently by this operation. It comes down to whether
1110 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1111 // everything is fine. If not then the optimization is wrong. Thus general
1112 // comparisons are only valid if op2 != 0.
1114 // So, finally, the only LLVM-native comparisons that don't mention C and V
1115 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1116 // the absence of information about op2.
1117 Opcode = AArch64ISD::ADDS;
1118 RHS = RHS.getOperand(1);
1119 } else if (LHS.getOpcode() == ISD::AND && isa<ConstantSDNode>(RHS) &&
1120 cast<ConstantSDNode>(RHS)->getZExtValue() == 0 &&
1121 !isUnsignedIntSetCC(CC)) {
1122 // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1123 // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1124 // of the signed comparisons.
1125 Opcode = AArch64ISD::ANDS;
1126 RHS = LHS.getOperand(1);
1127 LHS = LHS.getOperand(0);
1130 return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS)
1134 static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1135 SDValue &AArch64cc, SelectionDAG &DAG, SDLoc dl) {
1137 AArch64CC::CondCode AArch64CC;
1138 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1139 EVT VT = RHS.getValueType();
1140 uint64_t C = RHSC->getZExtValue();
1141 if (!isLegalArithImmed(C)) {
1142 // Constant does not fit, try adjusting it by one?
1148 if ((VT == MVT::i32 && C != 0x80000000 &&
1149 isLegalArithImmed((uint32_t)(C - 1))) ||
1150 (VT == MVT::i64 && C != 0x80000000ULL &&
1151 isLegalArithImmed(C - 1ULL))) {
1152 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1153 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1154 RHS = DAG.getConstant(C, VT);
1159 if ((VT == MVT::i32 && C != 0 &&
1160 isLegalArithImmed((uint32_t)(C - 1))) ||
1161 (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1162 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1163 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1164 RHS = DAG.getConstant(C, VT);
1169 if ((VT == MVT::i32 && C != INT32_MAX &&
1170 isLegalArithImmed((uint32_t)(C + 1))) ||
1171 (VT == MVT::i64 && C != INT64_MAX &&
1172 isLegalArithImmed(C + 1ULL))) {
1173 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1174 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1175 RHS = DAG.getConstant(C, VT);
1180 if ((VT == MVT::i32 && C != UINT32_MAX &&
1181 isLegalArithImmed((uint32_t)(C + 1))) ||
1182 (VT == MVT::i64 && C != UINT64_MAX &&
1183 isLegalArithImmed(C + 1ULL))) {
1184 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1185 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1186 RHS = DAG.getConstant(C, VT);
1192 // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
1193 // For the i8 operand, the largest immediate is 255, so this can be easily
1194 // encoded in the compare instruction. For the i16 operand, however, the
1195 // largest immediate cannot be encoded in the compare.
1196 // Therefore, use a sign extending load and cmn to avoid materializing the -1
1197 // constant. For example,
1199 // ldrh w0, [x0, #0]
1202 // ldrsh w0, [x0, #0]
1204 // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
1205 // if and only if (sext LHS) == (sext RHS). The checks are in place to ensure
1206 // both the LHS and RHS are truely zero extended and to make sure the
1207 // transformation is profitable.
1208 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
1209 if ((cast<ConstantSDNode>(RHS)->getZExtValue() >> 16 == 0) &&
1210 isa<LoadSDNode>(LHS)) {
1211 if (cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
1212 cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
1213 LHS.getNode()->hasNUsesOfValue(1, 0)) {
1214 int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
1215 if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
1217 DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
1218 DAG.getValueType(MVT::i16));
1219 Cmp = emitComparison(SExt,
1220 DAG.getConstant(ValueofRHS, RHS.getValueType()),
1222 AArch64CC = changeIntCCToAArch64CC(CC);
1223 AArch64cc = DAG.getConstant(AArch64CC, MVT::i32);
1229 Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
1230 AArch64CC = changeIntCCToAArch64CC(CC);
1231 AArch64cc = DAG.getConstant(AArch64CC, MVT::i32);
1235 static std::pair<SDValue, SDValue>
1236 getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
1237 assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
1238 "Unsupported value type");
1239 SDValue Value, Overflow;
1241 SDValue LHS = Op.getOperand(0);
1242 SDValue RHS = Op.getOperand(1);
1244 switch (Op.getOpcode()) {
1246 llvm_unreachable("Unknown overflow instruction!");
1248 Opc = AArch64ISD::ADDS;
1252 Opc = AArch64ISD::ADDS;
1256 Opc = AArch64ISD::SUBS;
1260 Opc = AArch64ISD::SUBS;
1263 // Multiply needs a little bit extra work.
1267 bool IsSigned = (Op.getOpcode() == ISD::SMULO) ? true : false;
1268 if (Op.getValueType() == MVT::i32) {
1269 unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1270 // For a 32 bit multiply with overflow check we want the instruction
1271 // selector to generate a widening multiply (SMADDL/UMADDL). For that we
1272 // need to generate the following pattern:
1273 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
1274 LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
1275 RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
1276 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1277 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
1278 DAG.getConstant(0, MVT::i64));
1279 // On AArch64 the upper 32 bits are always zero extended for a 32 bit
1280 // operation. We need to clear out the upper 32 bits, because we used a
1281 // widening multiply that wrote all 64 bits. In the end this should be a
1283 Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
1285 // The signed overflow check requires more than just a simple check for
1286 // any bit set in the upper 32 bits of the result. These bits could be
1287 // just the sign bits of a negative number. To perform the overflow
1288 // check we have to arithmetic shift right the 32nd bit of the result by
1289 // 31 bits. Then we compare the result to the upper 32 bits.
1290 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
1291 DAG.getConstant(32, MVT::i64));
1292 UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
1293 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
1294 DAG.getConstant(31, MVT::i64));
1295 // It is important that LowerBits is last, otherwise the arithmetic
1296 // shift will not be folded into the compare (SUBS).
1297 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
1298 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1301 // The overflow check for unsigned multiply is easy. We only need to
1302 // check if any of the upper 32 bits are set. This can be done with a
1303 // CMP (shifted register). For that we need to generate the following
1305 // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
1306 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
1307 DAG.getConstant(32, MVT::i64));
1308 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1310 DAG.getNode(AArch64ISD::SUBS, DL, VTs, DAG.getConstant(0, MVT::i64),
1311 UpperBits).getValue(1);
1315 assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
1316 // For the 64 bit multiply
1317 Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1319 SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
1320 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
1321 DAG.getConstant(63, MVT::i64));
1322 // It is important that LowerBits is last, otherwise the arithmetic
1323 // shift will not be folded into the compare (SUBS).
1324 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1325 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1328 SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
1329 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1331 DAG.getNode(AArch64ISD::SUBS, DL, VTs, DAG.getConstant(0, MVT::i64),
1332 UpperBits).getValue(1);
1339 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
1341 // Emit the AArch64 operation with overflow check.
1342 Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
1343 Overflow = Value.getValue(1);
1345 return std::make_pair(Value, Overflow);
1348 SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
1349 RTLIB::Libcall Call) const {
1350 SmallVector<SDValue, 2> Ops;
1351 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i)
1352 Ops.push_back(Op.getOperand(i));
1354 return makeLibCall(DAG, Call, MVT::f128, &Ops[0], Ops.size(), false,
1358 static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
1359 SDValue Sel = Op.getOperand(0);
1360 SDValue Other = Op.getOperand(1);
1362 // If neither operand is a SELECT_CC, give up.
1363 if (Sel.getOpcode() != ISD::SELECT_CC)
1364 std::swap(Sel, Other);
1365 if (Sel.getOpcode() != ISD::SELECT_CC)
1368 // The folding we want to perform is:
1369 // (xor x, (select_cc a, b, cc, 0, -1) )
1371 // (csel x, (xor x, -1), cc ...)
1373 // The latter will get matched to a CSINV instruction.
1375 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
1376 SDValue LHS = Sel.getOperand(0);
1377 SDValue RHS = Sel.getOperand(1);
1378 SDValue TVal = Sel.getOperand(2);
1379 SDValue FVal = Sel.getOperand(3);
1382 // FIXME: This could be generalized to non-integer comparisons.
1383 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
1386 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
1387 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
1389 // The the values aren't constants, this isn't the pattern we're looking for.
1390 if (!CFVal || !CTVal)
1393 // We can commute the SELECT_CC by inverting the condition. This
1394 // might be needed to make this fit into a CSINV pattern.
1395 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
1396 std::swap(TVal, FVal);
1397 std::swap(CTVal, CFVal);
1398 CC = ISD::getSetCCInverse(CC, true);
1401 // If the constants line up, perform the transform!
1402 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
1404 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
1407 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
1408 DAG.getConstant(-1ULL, Other.getValueType()));
1410 return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
1417 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
1418 EVT VT = Op.getValueType();
1420 // Let legalize expand this if it isn't a legal type yet.
1421 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
1424 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
1427 bool ExtraOp = false;
1428 switch (Op.getOpcode()) {
1430 llvm_unreachable("Invalid code");
1432 Opc = AArch64ISD::ADDS;
1435 Opc = AArch64ISD::SUBS;
1438 Opc = AArch64ISD::ADCS;
1442 Opc = AArch64ISD::SBCS;
1448 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
1449 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
1453 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
1454 // Let legalize expand this if it isn't a legal type yet.
1455 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
1458 AArch64CC::CondCode CC;
1459 // The actual operation that sets the overflow or carry flag.
1460 SDValue Value, Overflow;
1461 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
1463 // We use 0 and 1 as false and true values.
1464 SDValue TVal = DAG.getConstant(1, MVT::i32);
1465 SDValue FVal = DAG.getConstant(0, MVT::i32);
1467 // We use an inverted condition, because the conditional select is inverted
1468 // too. This will allow it to be selected to a single instruction:
1469 // CSINC Wd, WZR, WZR, invert(cond).
1470 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), MVT::i32);
1471 Overflow = DAG.getNode(AArch64ISD::CSEL, SDLoc(Op), MVT::i32, FVal, TVal,
1474 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
1475 return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), VTs, Value, Overflow);
1478 // Prefetch operands are:
1479 // 1: Address to prefetch
1481 // 3: int locality (0 = no locality ... 3 = extreme locality)
1482 // 4: bool isDataCache
1483 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
1485 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
1486 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
1487 unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
1489 bool IsStream = !Locality;
1490 // When the locality number is set
1492 // The front-end should have filtered out the out-of-range values
1493 assert(Locality <= 3 && "Prefetch locality out-of-range");
1494 // The locality degree is the opposite of the cache speed.
1495 // Put the number the other way around.
1496 // The encoding starts at 0 for level 1
1497 Locality = 3 - Locality;
1500 // built the mask value encoding the expected behavior.
1501 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit
1502 (!IsData << 3) | // IsDataCache bit
1503 (Locality << 1) | // Cache level bits
1504 (unsigned)IsStream; // Stream bit
1505 return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
1506 DAG.getConstant(PrfOp, MVT::i32), Op.getOperand(1));
1509 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
1510 SelectionDAG &DAG) const {
1511 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
1514 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
1516 return LowerF128Call(Op, DAG, LC);
1519 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
1520 SelectionDAG &DAG) const {
1521 if (Op.getOperand(0).getValueType() != MVT::f128) {
1522 // It's legal except when f128 is involved
1527 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
1529 // FP_ROUND node has a second operand indicating whether it is known to be
1530 // precise. That doesn't take part in the LibCall so we can't directly use
1532 SDValue SrcVal = Op.getOperand(0);
1533 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
1534 /*isSigned*/ false, SDLoc(Op)).first;
1537 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
1538 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1539 // Any additional optimization in this function should be recorded
1540 // in the cost tables.
1541 EVT InVT = Op.getOperand(0).getValueType();
1542 EVT VT = Op.getValueType();
1544 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
1547 DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
1549 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
1552 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
1555 MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
1556 VT.getVectorNumElements());
1557 SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
1558 return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
1561 // Type changing conversions are illegal.
1565 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
1566 SelectionDAG &DAG) const {
1567 if (Op.getOperand(0).getValueType().isVector())
1568 return LowerVectorFP_TO_INT(Op, DAG);
1570 if (Op.getOperand(0).getValueType() != MVT::f128) {
1571 // It's legal except when f128 is involved
1576 if (Op.getOpcode() == ISD::FP_TO_SINT)
1577 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
1579 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
1581 SmallVector<SDValue, 2> Ops;
1582 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i)
1583 Ops.push_back(Op.getOperand(i));
1585 return makeLibCall(DAG, LC, Op.getValueType(), &Ops[0], Ops.size(), false,
1589 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
1590 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1591 // Any additional optimization in this function should be recorded
1592 // in the cost tables.
1593 EVT VT = Op.getValueType();
1595 SDValue In = Op.getOperand(0);
1596 EVT InVT = In.getValueType();
1598 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
1600 MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
1601 InVT.getVectorNumElements());
1602 In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
1603 return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0));
1606 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
1608 Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1609 EVT CastVT = VT.changeVectorElementTypeToInteger();
1610 In = DAG.getNode(CastOpc, dl, CastVT, In);
1611 return DAG.getNode(Op.getOpcode(), dl, VT, In);
1617 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
1618 SelectionDAG &DAG) const {
1619 if (Op.getValueType().isVector())
1620 return LowerVectorINT_TO_FP(Op, DAG);
1622 // i128 conversions are libcalls.
1623 if (Op.getOperand(0).getValueType() == MVT::i128)
1626 // Other conversions are legal, unless it's to the completely software-based
1628 if (Op.getValueType() != MVT::f128)
1632 if (Op.getOpcode() == ISD::SINT_TO_FP)
1633 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
1635 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
1637 return LowerF128Call(Op, DAG, LC);
1640 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
1641 SelectionDAG &DAG) const {
1642 // For iOS, we want to call an alternative entry point: __sincos_stret,
1643 // which returns the values in two S / D registers.
1645 SDValue Arg = Op.getOperand(0);
1646 EVT ArgVT = Arg.getValueType();
1647 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
1654 Entry.isSExt = false;
1655 Entry.isZExt = false;
1656 Args.push_back(Entry);
1658 const char *LibcallName =
1659 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
1660 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
1662 StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
1663 TargetLowering::CallLoweringInfo CLI(DAG);
1664 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
1665 .setCallee(CallingConv::Fast, RetTy, Callee, std::move(Args), 0);
1667 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1668 return CallResult.first;
1671 static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
1672 if (Op.getValueType() != MVT::f16)
1675 assert(Op.getOperand(0).getValueType() == MVT::i16);
1678 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
1679 Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
1681 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
1682 DAG.getTargetConstant(AArch64::hsub, MVT::i32)),
1686 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
1687 if (OrigVT.getSizeInBits() >= 64)
1690 assert(OrigVT.isSimple() && "Expecting a simple value type");
1692 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
1693 switch (OrigSimpleTy) {
1694 default: llvm_unreachable("Unexpected Vector Type");
1703 static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
1706 unsigned ExtOpcode) {
1707 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
1708 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
1709 // 64-bits we need to insert a new extension so that it will be 64-bits.
1710 assert(ExtTy.is128BitVector() && "Unexpected extension size");
1711 if (OrigTy.getSizeInBits() >= 64)
1714 // Must extend size to at least 64 bits to be used as an operand for VMULL.
1715 EVT NewVT = getExtensionTo64Bits(OrigTy);
1717 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
1720 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
1722 EVT VT = N->getValueType(0);
1724 if (N->getOpcode() != ISD::BUILD_VECTOR)
1727 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1728 SDNode *Elt = N->getOperand(i).getNode();
1729 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
1730 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1731 unsigned HalfSize = EltSize / 2;
1733 if (!isIntN(HalfSize, C->getSExtValue()))
1736 if (!isUIntN(HalfSize, C->getZExtValue()))
1747 static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
1748 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
1749 return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
1750 N->getOperand(0)->getValueType(0),
1754 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
1755 EVT VT = N->getValueType(0);
1756 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
1757 unsigned NumElts = VT.getVectorNumElements();
1758 MVT TruncVT = MVT::getIntegerVT(EltSize);
1759 SmallVector<SDValue, 8> Ops;
1760 for (unsigned i = 0; i != NumElts; ++i) {
1761 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
1762 const APInt &CInt = C->getAPIntValue();
1763 // Element types smaller than 32 bits are not legal, so use i32 elements.
1764 // The values are implicitly truncated so sext vs. zext doesn't matter.
1765 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
1767 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
1768 MVT::getVectorVT(TruncVT, NumElts), Ops);
1771 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
1772 if (N->getOpcode() == ISD::SIGN_EXTEND)
1774 if (isExtendedBUILD_VECTOR(N, DAG, true))
1779 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
1780 if (N->getOpcode() == ISD::ZERO_EXTEND)
1782 if (isExtendedBUILD_VECTOR(N, DAG, false))
1787 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
1788 unsigned Opcode = N->getOpcode();
1789 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
1790 SDNode *N0 = N->getOperand(0).getNode();
1791 SDNode *N1 = N->getOperand(1).getNode();
1792 return N0->hasOneUse() && N1->hasOneUse() &&
1793 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
1798 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
1799 unsigned Opcode = N->getOpcode();
1800 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
1801 SDNode *N0 = N->getOperand(0).getNode();
1802 SDNode *N1 = N->getOperand(1).getNode();
1803 return N0->hasOneUse() && N1->hasOneUse() &&
1804 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
1809 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
1810 // Multiplications are only custom-lowered for 128-bit vectors so that
1811 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
1812 EVT VT = Op.getValueType();
1813 assert(VT.is128BitVector() && VT.isInteger() &&
1814 "unexpected type for custom-lowering ISD::MUL");
1815 SDNode *N0 = Op.getOperand(0).getNode();
1816 SDNode *N1 = Op.getOperand(1).getNode();
1817 unsigned NewOpc = 0;
1819 bool isN0SExt = isSignExtended(N0, DAG);
1820 bool isN1SExt = isSignExtended(N1, DAG);
1821 if (isN0SExt && isN1SExt)
1822 NewOpc = AArch64ISD::SMULL;
1824 bool isN0ZExt = isZeroExtended(N0, DAG);
1825 bool isN1ZExt = isZeroExtended(N1, DAG);
1826 if (isN0ZExt && isN1ZExt)
1827 NewOpc = AArch64ISD::UMULL;
1828 else if (isN1SExt || isN1ZExt) {
1829 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
1830 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
1831 if (isN1SExt && isAddSubSExt(N0, DAG)) {
1832 NewOpc = AArch64ISD::SMULL;
1834 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
1835 NewOpc = AArch64ISD::UMULL;
1837 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
1839 NewOpc = AArch64ISD::UMULL;
1845 if (VT == MVT::v2i64)
1846 // Fall through to expand this. It is not legal.
1849 // Other vector multiplications are legal.
1854 // Legalize to a S/UMULL instruction
1857 SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
1859 Op0 = skipExtensionForVectorMULL(N0, DAG);
1860 assert(Op0.getValueType().is64BitVector() &&
1861 Op1.getValueType().is64BitVector() &&
1862 "unexpected types for extended operands to VMULL");
1863 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
1865 // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
1866 // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
1867 // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
1868 SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
1869 SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
1870 EVT Op1VT = Op1.getValueType();
1871 return DAG.getNode(N0->getOpcode(), DL, VT,
1872 DAG.getNode(NewOpc, DL, VT,
1873 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
1874 DAG.getNode(NewOpc, DL, VT,
1875 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
1878 SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
1879 SelectionDAG &DAG) const {
1880 switch (Op.getOpcode()) {
1882 llvm_unreachable("unimplemented operand");
1885 return LowerBITCAST(Op, DAG);
1886 case ISD::GlobalAddress:
1887 return LowerGlobalAddress(Op, DAG);
1888 case ISD::GlobalTLSAddress:
1889 return LowerGlobalTLSAddress(Op, DAG);
1891 return LowerSETCC(Op, DAG);
1893 return LowerBR_CC(Op, DAG);
1895 return LowerSELECT(Op, DAG);
1896 case ISD::SELECT_CC:
1897 return LowerSELECT_CC(Op, DAG);
1898 case ISD::JumpTable:
1899 return LowerJumpTable(Op, DAG);
1900 case ISD::ConstantPool:
1901 return LowerConstantPool(Op, DAG);
1902 case ISD::BlockAddress:
1903 return LowerBlockAddress(Op, DAG);
1905 return LowerVASTART(Op, DAG);
1907 return LowerVACOPY(Op, DAG);
1909 return LowerVAARG(Op, DAG);
1914 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
1921 return LowerXALUO(Op, DAG);
1923 return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
1925 return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
1927 return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
1929 return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
1931 return LowerFP_ROUND(Op, DAG);
1932 case ISD::FP_EXTEND:
1933 return LowerFP_EXTEND(Op, DAG);
1934 case ISD::FRAMEADDR:
1935 return LowerFRAMEADDR(Op, DAG);
1936 case ISD::RETURNADDR:
1937 return LowerRETURNADDR(Op, DAG);
1938 case ISD::INSERT_VECTOR_ELT:
1939 return LowerINSERT_VECTOR_ELT(Op, DAG);
1940 case ISD::EXTRACT_VECTOR_ELT:
1941 return LowerEXTRACT_VECTOR_ELT(Op, DAG);
1942 case ISD::BUILD_VECTOR:
1943 return LowerBUILD_VECTOR(Op, DAG);
1944 case ISD::VECTOR_SHUFFLE:
1945 return LowerVECTOR_SHUFFLE(Op, DAG);
1946 case ISD::EXTRACT_SUBVECTOR:
1947 return LowerEXTRACT_SUBVECTOR(Op, DAG);
1951 return LowerVectorSRA_SRL_SHL(Op, DAG);
1952 case ISD::SHL_PARTS:
1953 return LowerShiftLeftParts(Op, DAG);
1954 case ISD::SRL_PARTS:
1955 case ISD::SRA_PARTS:
1956 return LowerShiftRightParts(Op, DAG);
1958 return LowerCTPOP(Op, DAG);
1959 case ISD::FCOPYSIGN:
1960 return LowerFCOPYSIGN(Op, DAG);
1962 return LowerVectorAND(Op, DAG);
1964 return LowerVectorOR(Op, DAG);
1966 return LowerXOR(Op, DAG);
1968 return LowerPREFETCH(Op, DAG);
1969 case ISD::SINT_TO_FP:
1970 case ISD::UINT_TO_FP:
1971 return LowerINT_TO_FP(Op, DAG);
1972 case ISD::FP_TO_SINT:
1973 case ISD::FP_TO_UINT:
1974 return LowerFP_TO_INT(Op, DAG);
1976 return LowerFSINCOS(Op, DAG);
1978 return LowerMUL(Op, DAG);
1982 /// getFunctionAlignment - Return the Log2 alignment of this function.
1983 unsigned AArch64TargetLowering::getFunctionAlignment(const Function *F) const {
1987 //===----------------------------------------------------------------------===//
1988 // Calling Convention Implementation
1989 //===----------------------------------------------------------------------===//
1991 #include "AArch64GenCallingConv.inc"
1993 /// Selects the correct CCAssignFn for a given CallingConvention value.
1994 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
1995 bool IsVarArg) const {
1998 llvm_unreachable("Unsupported calling convention.");
1999 case CallingConv::WebKit_JS:
2000 return CC_AArch64_WebKit_JS;
2001 case CallingConv::GHC:
2002 return CC_AArch64_GHC;
2003 case CallingConv::C:
2004 case CallingConv::Fast:
2005 if (!Subtarget->isTargetDarwin())
2006 return CC_AArch64_AAPCS;
2007 return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
2011 SDValue AArch64TargetLowering::LowerFormalArguments(
2012 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2013 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2014 SmallVectorImpl<SDValue> &InVals) const {
2015 MachineFunction &MF = DAG.getMachineFunction();
2016 MachineFrameInfo *MFI = MF.getFrameInfo();
2018 // Assign locations to all of the incoming arguments.
2019 SmallVector<CCValAssign, 16> ArgLocs;
2020 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2023 // At this point, Ins[].VT may already be promoted to i32. To correctly
2024 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2025 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2026 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
2027 // we use a special version of AnalyzeFormalArguments to pass in ValVT and
2029 unsigned NumArgs = Ins.size();
2030 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2031 unsigned CurArgIdx = 0;
2032 for (unsigned i = 0; i != NumArgs; ++i) {
2033 MVT ValVT = Ins[i].VT;
2034 std::advance(CurOrigArg, Ins[i].OrigArgIndex - CurArgIdx);
2035 CurArgIdx = Ins[i].OrigArgIndex;
2037 // Get type of the original argument.
2038 EVT ActualVT = getValueType(CurOrigArg->getType(), /*AllowUnknown*/ true);
2039 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
2040 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2041 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2043 else if (ActualMVT == MVT::i16)
2046 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2048 AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
2049 assert(!Res && "Call operand has unhandled type");
2052 assert(ArgLocs.size() == Ins.size());
2053 SmallVector<SDValue, 16> ArgValues;
2054 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2055 CCValAssign &VA = ArgLocs[i];
2057 if (Ins[i].Flags.isByVal()) {
2058 // Byval is used for HFAs in the PCS, but the system should work in a
2059 // non-compliant manner for larger structs.
2060 EVT PtrTy = getPointerTy();
2061 int Size = Ins[i].Flags.getByValSize();
2062 unsigned NumRegs = (Size + 7) / 8;
2064 // FIXME: This works on big-endian for composite byvals, which are the common
2065 // case. It should also work for fundamental types too.
2067 MFI->CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
2068 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrTy);
2069 InVals.push_back(FrameIdxN);
2074 if (VA.isRegLoc()) {
2075 // Arguments stored in registers.
2076 EVT RegVT = VA.getLocVT();
2079 const TargetRegisterClass *RC;
2081 if (RegVT == MVT::i32)
2082 RC = &AArch64::GPR32RegClass;
2083 else if (RegVT == MVT::i64)
2084 RC = &AArch64::GPR64RegClass;
2085 else if (RegVT == MVT::f16)
2086 RC = &AArch64::FPR16RegClass;
2087 else if (RegVT == MVT::f32)
2088 RC = &AArch64::FPR32RegClass;
2089 else if (RegVT == MVT::f64 || RegVT.is64BitVector())
2090 RC = &AArch64::FPR64RegClass;
2091 else if (RegVT == MVT::f128 || RegVT.is128BitVector())
2092 RC = &AArch64::FPR128RegClass;
2094 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2096 // Transform the arguments in physical registers into virtual ones.
2097 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2098 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2100 // If this is an 8, 16 or 32-bit value, it is really passed promoted
2101 // to 64 bits. Insert an assert[sz]ext to capture this, then
2102 // truncate to the right size.
2103 switch (VA.getLocInfo()) {
2105 llvm_unreachable("Unknown loc info!");
2106 case CCValAssign::Full:
2108 case CCValAssign::BCvt:
2109 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
2111 case CCValAssign::AExt:
2112 case CCValAssign::SExt:
2113 case CCValAssign::ZExt:
2114 // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
2115 // nodes after our lowering.
2116 assert(RegVT == Ins[i].VT && "incorrect register location selected");
2120 InVals.push_back(ArgValue);
2122 } else { // VA.isRegLoc()
2123 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
2124 unsigned ArgOffset = VA.getLocMemOffset();
2125 unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
2127 uint32_t BEAlign = 0;
2128 if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
2129 !Ins[i].Flags.isInConsecutiveRegs())
2130 BEAlign = 8 - ArgSize;
2132 int FI = MFI->CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
2134 // Create load nodes to retrieve arguments from the stack.
2135 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2138 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
2139 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
2140 MVT MemVT = VA.getValVT();
2142 switch (VA.getLocInfo()) {
2145 case CCValAssign::BCvt:
2146 MemVT = VA.getLocVT();
2148 case CCValAssign::SExt:
2149 ExtType = ISD::SEXTLOAD;
2151 case CCValAssign::ZExt:
2152 ExtType = ISD::ZEXTLOAD;
2154 case CCValAssign::AExt:
2155 ExtType = ISD::EXTLOAD;
2159 ArgValue = DAG.getExtLoad(ExtType, DL, VA.getLocVT(), Chain, FIN,
2160 MachinePointerInfo::getFixedStack(FI),
2161 MemVT, false, false, false, 0);
2163 InVals.push_back(ArgValue);
2169 if (!Subtarget->isTargetDarwin()) {
2170 // The AAPCS variadic function ABI is identical to the non-variadic
2171 // one. As a result there may be more arguments in registers and we should
2172 // save them for future reference.
2173 saveVarArgRegisters(CCInfo, DAG, DL, Chain);
2176 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
2177 // This will point to the next argument passed via stack.
2178 unsigned StackOffset = CCInfo.getNextStackOffset();
2179 // We currently pass all varargs at 8-byte alignment.
2180 StackOffset = ((StackOffset + 7) & ~7);
2181 AFI->setVarArgsStackIndex(MFI->CreateFixedObject(4, StackOffset, true));
2184 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2185 unsigned StackArgSize = CCInfo.getNextStackOffset();
2186 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2187 if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
2188 // This is a non-standard ABI so by fiat I say we're allowed to make full
2189 // use of the stack area to be popped, which must be aligned to 16 bytes in
2191 StackArgSize = RoundUpToAlignment(StackArgSize, 16);
2193 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
2194 // a multiple of 16.
2195 FuncInfo->setArgumentStackToRestore(StackArgSize);
2197 // This realignment carries over to the available bytes below. Our own
2198 // callers will guarantee the space is free by giving an aligned value to
2201 // Even if we're not expected to free up the space, it's useful to know how
2202 // much is there while considering tail calls (because we can reuse it).
2203 FuncInfo->setBytesInStackArgArea(StackArgSize);
2208 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
2209 SelectionDAG &DAG, SDLoc DL,
2210 SDValue &Chain) const {
2211 MachineFunction &MF = DAG.getMachineFunction();
2212 MachineFrameInfo *MFI = MF.getFrameInfo();
2213 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2215 SmallVector<SDValue, 8> MemOps;
2217 static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
2218 AArch64::X3, AArch64::X4, AArch64::X5,
2219 AArch64::X6, AArch64::X7 };
2220 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
2221 unsigned FirstVariadicGPR =
2222 CCInfo.getFirstUnallocated(GPRArgRegs, NumGPRArgRegs);
2224 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
2226 if (GPRSaveSize != 0) {
2227 GPRIdx = MFI->CreateStackObject(GPRSaveSize, 8, false);
2229 SDValue FIN = DAG.getFrameIndex(GPRIdx, getPointerTy());
2231 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
2232 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
2233 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
2235 DAG.getStore(Val.getValue(1), DL, Val, FIN,
2236 MachinePointerInfo::getStack(i * 8), false, false, 0);
2237 MemOps.push_back(Store);
2238 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), FIN,
2239 DAG.getConstant(8, getPointerTy()));
2242 FuncInfo->setVarArgsGPRIndex(GPRIdx);
2243 FuncInfo->setVarArgsGPRSize(GPRSaveSize);
2245 if (Subtarget->hasFPARMv8()) {
2246 static const MCPhysReg FPRArgRegs[] = {
2247 AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
2248 AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
2249 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
2250 unsigned FirstVariadicFPR =
2251 CCInfo.getFirstUnallocated(FPRArgRegs, NumFPRArgRegs);
2253 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
2255 if (FPRSaveSize != 0) {
2256 FPRIdx = MFI->CreateStackObject(FPRSaveSize, 16, false);
2258 SDValue FIN = DAG.getFrameIndex(FPRIdx, getPointerTy());
2260 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
2261 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
2262 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
2265 DAG.getStore(Val.getValue(1), DL, Val, FIN,
2266 MachinePointerInfo::getStack(i * 16), false, false, 0);
2267 MemOps.push_back(Store);
2268 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), FIN,
2269 DAG.getConstant(16, getPointerTy()));
2272 FuncInfo->setVarArgsFPRIndex(FPRIdx);
2273 FuncInfo->setVarArgsFPRSize(FPRSaveSize);
2276 if (!MemOps.empty()) {
2277 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
2281 /// LowerCallResult - Lower the result values of a call into the
2282 /// appropriate copies out of appropriate physical registers.
2283 SDValue AArch64TargetLowering::LowerCallResult(
2284 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
2285 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2286 SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
2287 SDValue ThisVal) const {
2288 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
2289 ? RetCC_AArch64_WebKit_JS
2290 : RetCC_AArch64_AAPCS;
2291 // Assign locations to each value returned by this call.
2292 SmallVector<CCValAssign, 16> RVLocs;
2293 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2295 CCInfo.AnalyzeCallResult(Ins, RetCC);
2297 // Copy all of the result registers out of their specified physreg.
2298 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2299 CCValAssign VA = RVLocs[i];
2301 // Pass 'this' value directly from the argument to return value, to avoid
2302 // reg unit interference
2303 if (i == 0 && isThisReturn) {
2304 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
2305 "unexpected return calling convention register assignment");
2306 InVals.push_back(ThisVal);
2311 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2312 Chain = Val.getValue(1);
2313 InFlag = Val.getValue(2);
2315 switch (VA.getLocInfo()) {
2317 llvm_unreachable("Unknown loc info!");
2318 case CCValAssign::Full:
2320 case CCValAssign::BCvt:
2321 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2325 InVals.push_back(Val);
2331 bool AArch64TargetLowering::isEligibleForTailCallOptimization(
2332 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
2333 bool isCalleeStructRet, bool isCallerStructRet,
2334 const SmallVectorImpl<ISD::OutputArg> &Outs,
2335 const SmallVectorImpl<SDValue> &OutVals,
2336 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2337 // For CallingConv::C this function knows whether the ABI needs
2338 // changing. That's not true for other conventions so they will have to opt in
2340 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
2343 const MachineFunction &MF = DAG.getMachineFunction();
2344 const Function *CallerF = MF.getFunction();
2345 CallingConv::ID CallerCC = CallerF->getCallingConv();
2346 bool CCMatch = CallerCC == CalleeCC;
2348 // Byval parameters hand the function a pointer directly into the stack area
2349 // we want to reuse during a tail call. Working around this *is* possible (see
2350 // X86) but less efficient and uglier in LowerCall.
2351 for (Function::const_arg_iterator i = CallerF->arg_begin(),
2352 e = CallerF->arg_end();
2354 if (i->hasByValAttr())
2357 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2358 if (IsTailCallConvention(CalleeCC) && CCMatch)
2363 // Externally-defined functions with weak linkage should not be
2364 // tail-called on AArch64 when the OS does not support dynamic
2365 // pre-emption of symbols, as the AAELF spec requires normal calls
2366 // to undefined weak functions to be replaced with a NOP or jump to the
2367 // next instruction. The behaviour of branch instructions in this
2368 // situation (as used for tail calls) is implementation-defined, so we
2369 // cannot rely on the linker replacing the tail call with a return.
2370 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2371 const GlobalValue *GV = G->getGlobal();
2372 const Triple TT(getTargetMachine().getTargetTriple());
2373 if (GV->hasExternalWeakLinkage() &&
2374 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2378 // Now we search for cases where we can use a tail call without changing the
2379 // ABI. Sibcall is used in some places (particularly gcc) to refer to this
2382 // I want anyone implementing a new calling convention to think long and hard
2383 // about this assert.
2384 assert((!isVarArg || CalleeCC == CallingConv::C) &&
2385 "Unexpected variadic calling convention");
2387 if (isVarArg && !Outs.empty()) {
2388 // At least two cases here: if caller is fastcc then we can't have any
2389 // memory arguments (we'd be expected to clean up the stack afterwards). If
2390 // caller is C then we could potentially use its argument area.
2392 // FIXME: for now we take the most conservative of these in both cases:
2393 // disallow all variadic memory operands.
2394 SmallVector<CCValAssign, 16> ArgLocs;
2395 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2398 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
2399 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2400 if (!ArgLocs[i].isRegLoc())
2404 // If the calling conventions do not match, then we'd better make sure the
2405 // results are returned in the same way as what the caller expects.
2407 SmallVector<CCValAssign, 16> RVLocs1;
2408 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2410 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForCall(CalleeCC, isVarArg));
2412 SmallVector<CCValAssign, 16> RVLocs2;
2413 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2415 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForCall(CallerCC, isVarArg));
2417 if (RVLocs1.size() != RVLocs2.size())
2419 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2420 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2422 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2424 if (RVLocs1[i].isRegLoc()) {
2425 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2428 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2434 // Nothing more to check if the callee is taking no arguments
2438 SmallVector<CCValAssign, 16> ArgLocs;
2439 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2442 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2444 const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2446 // If the stack arguments for this call would fit into our own save area then
2447 // the call can be made tail.
2448 return CCInfo.getNextStackOffset() <= FuncInfo->getBytesInStackArgArea();
2451 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
2453 MachineFrameInfo *MFI,
2454 int ClobberedFI) const {
2455 SmallVector<SDValue, 8> ArgChains;
2456 int64_t FirstByte = MFI->getObjectOffset(ClobberedFI);
2457 int64_t LastByte = FirstByte + MFI->getObjectSize(ClobberedFI) - 1;
2459 // Include the original chain at the beginning of the list. When this is
2460 // used by target LowerCall hooks, this helps legalize find the
2461 // CALLSEQ_BEGIN node.
2462 ArgChains.push_back(Chain);
2464 // Add a chain value for each stack argument corresponding
2465 for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
2466 UE = DAG.getEntryNode().getNode()->use_end();
2468 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
2469 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
2470 if (FI->getIndex() < 0) {
2471 int64_t InFirstByte = MFI->getObjectOffset(FI->getIndex());
2472 int64_t InLastByte = InFirstByte;
2473 InLastByte += MFI->getObjectSize(FI->getIndex()) - 1;
2475 if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
2476 (FirstByte <= InFirstByte && InFirstByte <= LastByte))
2477 ArgChains.push_back(SDValue(L, 1));
2480 // Build a tokenfactor for all the chains.
2481 return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
2484 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
2485 bool TailCallOpt) const {
2486 return CallCC == CallingConv::Fast && TailCallOpt;
2489 bool AArch64TargetLowering::IsTailCallConvention(CallingConv::ID CallCC) const {
2490 return CallCC == CallingConv::Fast;
2493 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
2494 /// and add input and output parameter nodes.
2496 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
2497 SmallVectorImpl<SDValue> &InVals) const {
2498 SelectionDAG &DAG = CLI.DAG;
2500 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2501 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2502 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2503 SDValue Chain = CLI.Chain;
2504 SDValue Callee = CLI.Callee;
2505 bool &IsTailCall = CLI.IsTailCall;
2506 CallingConv::ID CallConv = CLI.CallConv;
2507 bool IsVarArg = CLI.IsVarArg;
2509 MachineFunction &MF = DAG.getMachineFunction();
2510 bool IsStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
2511 bool IsThisReturn = false;
2513 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2514 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2515 bool IsSibCall = false;
2518 // Check if it's really possible to do a tail call.
2519 IsTailCall = isEligibleForTailCallOptimization(
2520 Callee, CallConv, IsVarArg, IsStructRet,
2521 MF.getFunction()->hasStructRetAttr(), Outs, OutVals, Ins, DAG);
2522 if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
2523 report_fatal_error("failed to perform tail call elimination on a call "
2524 "site marked musttail");
2526 // A sibling call is one where we're under the usual C ABI and not planning
2527 // to change that but can still do a tail call:
2528 if (!TailCallOpt && IsTailCall)
2535 // Analyze operands of the call, assigning locations to each operand.
2536 SmallVector<CCValAssign, 16> ArgLocs;
2537 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
2541 // Handle fixed and variable vector arguments differently.
2542 // Variable vector arguments always go into memory.
2543 unsigned NumArgs = Outs.size();
2545 for (unsigned i = 0; i != NumArgs; ++i) {
2546 MVT ArgVT = Outs[i].VT;
2547 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2548 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
2549 /*IsVarArg=*/ !Outs[i].IsFixed);
2550 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
2551 assert(!Res && "Call operand has unhandled type");
2555 // At this point, Outs[].VT may already be promoted to i32. To correctly
2556 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2557 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2558 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
2559 // we use a special version of AnalyzeCallOperands to pass in ValVT and
2561 unsigned NumArgs = Outs.size();
2562 for (unsigned i = 0; i != NumArgs; ++i) {
2563 MVT ValVT = Outs[i].VT;
2564 // Get type of the original argument.
2565 EVT ActualVT = getValueType(CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
2566 /*AllowUnknown*/ true);
2567 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
2568 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2569 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2570 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2572 else if (ActualMVT == MVT::i16)
2575 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2576 bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
2577 assert(!Res && "Call operand has unhandled type");
2582 // Get a count of how many bytes are to be pushed on the stack.
2583 unsigned NumBytes = CCInfo.getNextStackOffset();
2586 // Since we're not changing the ABI to make this a tail call, the memory
2587 // operands are already available in the caller's incoming argument space.
2591 // FPDiff is the byte offset of the call's argument area from the callee's.
2592 // Stores to callee stack arguments will be placed in FixedStackSlots offset
2593 // by this amount for a tail call. In a sibling call it must be 0 because the
2594 // caller will deallocate the entire stack and the callee still expects its
2595 // arguments to begin at SP+0. Completely unused for non-tail calls.
2598 if (IsTailCall && !IsSibCall) {
2599 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
2601 // Since callee will pop argument stack as a tail call, we must keep the
2602 // popped size 16-byte aligned.
2603 NumBytes = RoundUpToAlignment(NumBytes, 16);
2605 // FPDiff will be negative if this tail call requires more space than we
2606 // would automatically have in our incoming argument space. Positive if we
2607 // can actually shrink the stack.
2608 FPDiff = NumReusableBytes - NumBytes;
2610 // The stack pointer must be 16-byte aligned at all times it's used for a
2611 // memory operation, which in practice means at *all* times and in
2612 // particular across call boundaries. Therefore our own arguments started at
2613 // a 16-byte aligned SP and the delta applied for the tail call should
2614 // satisfy the same constraint.
2615 assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
2618 // Adjust the stack pointer for the new arguments...
2619 // These operations are automatically eliminated by the prolog/epilog pass
2622 DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true), DL);
2624 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP, getPointerTy());
2626 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2627 SmallVector<SDValue, 8> MemOpChains;
2629 // Walk the register/memloc assignments, inserting copies/loads.
2630 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
2631 ++i, ++realArgIdx) {
2632 CCValAssign &VA = ArgLocs[i];
2633 SDValue Arg = OutVals[realArgIdx];
2634 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2636 // Promote the value if needed.
2637 switch (VA.getLocInfo()) {
2639 llvm_unreachable("Unknown loc info!");
2640 case CCValAssign::Full:
2642 case CCValAssign::SExt:
2643 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2645 case CCValAssign::ZExt:
2646 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2648 case CCValAssign::AExt:
2649 if (Outs[realArgIdx].ArgVT == MVT::i1) {
2650 // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
2651 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
2652 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
2654 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2656 case CCValAssign::BCvt:
2657 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2659 case CCValAssign::FPExt:
2660 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
2664 if (VA.isRegLoc()) {
2665 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i64) {
2666 assert(VA.getLocVT() == MVT::i64 &&
2667 "unexpected calling convention register assignment");
2668 assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
2669 "unexpected use of 'returned'");
2670 IsThisReturn = true;
2672 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2674 assert(VA.isMemLoc());
2677 MachinePointerInfo DstInfo;
2679 // FIXME: This works on big-endian for composite byvals, which are the
2680 // common case. It should also work for fundamental types too.
2681 uint32_t BEAlign = 0;
2682 unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
2683 : VA.getValVT().getSizeInBits();
2684 OpSize = (OpSize + 7) / 8;
2685 if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
2686 !Flags.isInConsecutiveRegs()) {
2688 BEAlign = 8 - OpSize;
2690 unsigned LocMemOffset = VA.getLocMemOffset();
2691 int32_t Offset = LocMemOffset + BEAlign;
2692 SDValue PtrOff = DAG.getIntPtrConstant(Offset);
2693 PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr, PtrOff);
2696 Offset = Offset + FPDiff;
2697 int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2699 DstAddr = DAG.getFrameIndex(FI, getPointerTy());
2700 DstInfo = MachinePointerInfo::getFixedStack(FI);
2702 // Make sure any stack arguments overlapping with where we're storing
2703 // are loaded before this eventual operation. Otherwise they'll be
2705 Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
2707 SDValue PtrOff = DAG.getIntPtrConstant(Offset);
2709 DstAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr, PtrOff);
2710 DstInfo = MachinePointerInfo::getStack(LocMemOffset);
2713 if (Outs[i].Flags.isByVal()) {
2715 DAG.getConstant(Outs[i].Flags.getByValSize(), MVT::i64);
2716 SDValue Cpy = DAG.getMemcpy(
2717 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
2719 /*AlwaysInline = */ false, DstInfo, MachinePointerInfo());
2721 MemOpChains.push_back(Cpy);
2723 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
2724 // promoted to a legal register type i32, we should truncate Arg back to
2726 if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
2727 VA.getValVT() == MVT::i16)
2728 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
2731 DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, false, false, 0);
2732 MemOpChains.push_back(Store);
2737 if (!MemOpChains.empty())
2738 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2740 // Build a sequence of copy-to-reg nodes chained together with token chain
2741 // and flag operands which copy the outgoing args into the appropriate regs.
2743 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2744 Chain = DAG.getCopyToReg(Chain, DL, RegsToPass[i].first,
2745 RegsToPass[i].second, InFlag);
2746 InFlag = Chain.getValue(1);
2749 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2750 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2751 // node so that legalize doesn't hack it.
2752 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
2753 Subtarget->isTargetMachO()) {
2754 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2755 const GlobalValue *GV = G->getGlobal();
2756 bool InternalLinkage = GV->hasInternalLinkage();
2757 if (InternalLinkage)
2758 Callee = DAG.getTargetGlobalAddress(GV, DL, getPointerTy(), 0, 0);
2760 Callee = DAG.getTargetGlobalAddress(GV, DL, getPointerTy(), 0,
2762 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, getPointerTy(), Callee);
2764 } else if (ExternalSymbolSDNode *S =
2765 dyn_cast<ExternalSymbolSDNode>(Callee)) {
2766 const char *Sym = S->getSymbol();
2768 DAG.getTargetExternalSymbol(Sym, getPointerTy(), AArch64II::MO_GOT);
2769 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, getPointerTy(), Callee);
2771 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2772 const GlobalValue *GV = G->getGlobal();
2773 Callee = DAG.getTargetGlobalAddress(GV, DL, getPointerTy(), 0, 0);
2774 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2775 const char *Sym = S->getSymbol();
2776 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), 0);
2779 // We don't usually want to end the call-sequence here because we would tidy
2780 // the frame up *after* the call, however in the ABI-changing tail-call case
2781 // we've carefully laid out the parameters so that when sp is reset they'll be
2782 // in the correct location.
2783 if (IsTailCall && !IsSibCall) {
2784 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2785 DAG.getIntPtrConstant(0, true), InFlag, DL);
2786 InFlag = Chain.getValue(1);
2789 std::vector<SDValue> Ops;
2790 Ops.push_back(Chain);
2791 Ops.push_back(Callee);
2794 // Each tail call may have to adjust the stack by a different amount, so
2795 // this information must travel along with the operation for eventual
2796 // consumption by emitEpilogue.
2797 Ops.push_back(DAG.getTargetConstant(FPDiff, MVT::i32));
2800 // Add argument registers to the end of the list so that they are known live
2802 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2803 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2804 RegsToPass[i].second.getValueType()));
2806 // Add a register mask operand representing the call-preserved registers.
2807 const uint32_t *Mask;
2808 const TargetRegisterInfo *TRI =
2809 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
2810 const AArch64RegisterInfo *ARI =
2811 static_cast<const AArch64RegisterInfo *>(TRI);
2813 // For 'this' returns, use the X0-preserving mask if applicable
2814 Mask = ARI->getThisReturnPreservedMask(CallConv);
2816 IsThisReturn = false;
2817 Mask = ARI->getCallPreservedMask(CallConv);
2820 Mask = ARI->getCallPreservedMask(CallConv);
2822 assert(Mask && "Missing call preserved mask for calling convention");
2823 Ops.push_back(DAG.getRegisterMask(Mask));
2825 if (InFlag.getNode())
2826 Ops.push_back(InFlag);
2828 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2830 // If we're doing a tall call, use a TC_RETURN here rather than an
2831 // actual call instruction.
2833 return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
2835 // Returns a chain and a flag for retval copy to use.
2836 Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
2837 InFlag = Chain.getValue(1);
2839 uint64_t CalleePopBytes = DoesCalleeRestoreStack(CallConv, TailCallOpt)
2840 ? RoundUpToAlignment(NumBytes, 16)
2843 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2844 DAG.getIntPtrConstant(CalleePopBytes, true),
2847 InFlag = Chain.getValue(1);
2849 // Handle result values, copying them out of physregs into vregs that we
2851 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
2852 InVals, IsThisReturn,
2853 IsThisReturn ? OutVals[0] : SDValue());
2856 bool AArch64TargetLowering::CanLowerReturn(
2857 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
2858 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
2859 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
2860 ? RetCC_AArch64_WebKit_JS
2861 : RetCC_AArch64_AAPCS;
2862 SmallVector<CCValAssign, 16> RVLocs;
2863 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2864 return CCInfo.CheckReturn(Outs, RetCC);
2868 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2870 const SmallVectorImpl<ISD::OutputArg> &Outs,
2871 const SmallVectorImpl<SDValue> &OutVals,
2872 SDLoc DL, SelectionDAG &DAG) const {
2873 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
2874 ? RetCC_AArch64_WebKit_JS
2875 : RetCC_AArch64_AAPCS;
2876 SmallVector<CCValAssign, 16> RVLocs;
2877 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2879 CCInfo.AnalyzeReturn(Outs, RetCC);
2881 // Copy the result values into the output registers.
2883 SmallVector<SDValue, 4> RetOps(1, Chain);
2884 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
2885 ++i, ++realRVLocIdx) {
2886 CCValAssign &VA = RVLocs[i];
2887 assert(VA.isRegLoc() && "Can only return in registers!");
2888 SDValue Arg = OutVals[realRVLocIdx];
2890 switch (VA.getLocInfo()) {
2892 llvm_unreachable("Unknown loc info!");
2893 case CCValAssign::Full:
2894 if (Outs[i].ArgVT == MVT::i1) {
2895 // AAPCS requires i1 to be zero-extended to i8 by the producer of the
2896 // value. This is strictly redundant on Darwin (which uses "zeroext
2897 // i1"), but will be optimised out before ISel.
2898 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
2899 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2902 case CCValAssign::BCvt:
2903 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2907 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2908 Flag = Chain.getValue(1);
2909 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2912 RetOps[0] = Chain; // Update chain.
2914 // Add the flag if we have it.
2916 RetOps.push_back(Flag);
2918 return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
2921 //===----------------------------------------------------------------------===//
2922 // Other Lowering Code
2923 //===----------------------------------------------------------------------===//
2925 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
2926 SelectionDAG &DAG) const {
2927 EVT PtrVT = getPointerTy();
2929 const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
2930 const GlobalValue *GV = GN->getGlobal();
2931 unsigned char OpFlags =
2932 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
2934 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
2935 "unexpected offset in global node");
2937 // This also catched the large code model case for Darwin.
2938 if ((OpFlags & AArch64II::MO_GOT) != 0) {
2939 SDValue GotAddr = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
2940 // FIXME: Once remat is capable of dealing with instructions with register
2941 // operands, expand this into two nodes instead of using a wrapper node.
2942 return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
2945 if ((OpFlags & AArch64II::MO_CONSTPOOL) != 0) {
2946 assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
2947 "use of MO_CONSTPOOL only supported on small model");
2948 SDValue Hi = DAG.getTargetConstantPool(GV, PtrVT, 0, 0, AArch64II::MO_PAGE);
2949 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
2950 unsigned char LoFlags = AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
2951 SDValue Lo = DAG.getTargetConstantPool(GV, PtrVT, 0, 0, LoFlags);
2952 SDValue PoolAddr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
2953 SDValue GlobalAddr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), PoolAddr,
2954 MachinePointerInfo::getConstantPool(),
2955 /*isVolatile=*/ false,
2956 /*isNonTemporal=*/ true,
2957 /*isInvariant=*/ true, 8);
2958 if (GN->getOffset() != 0)
2959 return DAG.getNode(ISD::ADD, DL, PtrVT, GlobalAddr,
2960 DAG.getConstant(GN->getOffset(), PtrVT));
2964 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2965 const unsigned char MO_NC = AArch64II::MO_NC;
2967 AArch64ISD::WrapperLarge, DL, PtrVT,
2968 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G3),
2969 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
2970 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
2971 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
2973 // Use ADRP/ADD or ADRP/LDR for everything else: the small model on ELF and
2974 // the only correct model on Darwin.
2975 SDValue Hi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2976 OpFlags | AArch64II::MO_PAGE);
2977 unsigned char LoFlags = OpFlags | AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
2978 SDValue Lo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, LoFlags);
2980 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
2981 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
2985 /// \brief Convert a TLS address reference into the correct sequence of loads
2986 /// and calls to compute the variable's address (for Darwin, currently) and
2987 /// return an SDValue containing the final node.
2989 /// Darwin only has one TLS scheme which must be capable of dealing with the
2990 /// fully general situation, in the worst case. This means:
2991 /// + "extern __thread" declaration.
2992 /// + Defined in a possibly unknown dynamic library.
2994 /// The general system is that each __thread variable has a [3 x i64] descriptor
2995 /// which contains information used by the runtime to calculate the address. The
2996 /// only part of this the compiler needs to know about is the first xword, which
2997 /// contains a function pointer that must be called with the address of the
2998 /// entire descriptor in "x0".
3000 /// Since this descriptor may be in a different unit, in general even the
3001 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
3003 /// adrp x0, _var@TLVPPAGE
3004 /// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor
3005 /// ldr x1, [x0] ; x1 contains 1st entry of descriptor,
3006 /// ; the function pointer
3007 /// blr x1 ; Uses descriptor address in x0
3008 /// ; Address of _var is now in x0.
3010 /// If the address of _var's descriptor *is* known to the linker, then it can
3011 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
3012 /// a slight efficiency gain.
3014 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
3015 SelectionDAG &DAG) const {
3016 assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
3019 MVT PtrVT = getPointerTy();
3020 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3023 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3024 SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
3026 // The first entry in the descriptor is a function pointer that we must call
3027 // to obtain the address of the variable.
3028 SDValue Chain = DAG.getEntryNode();
3029 SDValue FuncTLVGet =
3030 DAG.getLoad(MVT::i64, DL, Chain, DescAddr, MachinePointerInfo::getGOT(),
3031 false, true, true, 8);
3032 Chain = FuncTLVGet.getValue(1);
3034 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3035 MFI->setAdjustsStack(true);
3037 // TLS calls preserve all registers except those that absolutely must be
3038 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
3040 const TargetRegisterInfo *TRI =
3041 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
3042 const AArch64RegisterInfo *ARI =
3043 static_cast<const AArch64RegisterInfo *>(TRI);
3044 const uint32_t *Mask = ARI->getTLSCallPreservedMask();
3046 // Finally, we can make the call. This is just a degenerate version of a
3047 // normal AArch64 call node: x0 takes the address of the descriptor, and
3048 // returns the address of the variable in this thread.
3049 Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
3051 DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3052 Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
3053 DAG.getRegisterMask(Mask), Chain.getValue(1));
3054 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
3057 /// When accessing thread-local variables under either the general-dynamic or
3058 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
3059 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
3060 /// is a function pointer to carry out the resolution.
3062 /// The sequence is:
3063 /// adrp x0, :tlsdesc:var
3064 /// ldr x1, [x0, #:tlsdesc_lo12:var]
3065 /// add x0, x0, #:tlsdesc_lo12:var
3066 /// .tlsdesccall var
3068 /// (TPIDR_EL0 offset now in x0)
3070 /// The above sequence must be produced unscheduled, to enable the linker to
3071 /// optimize/relax this sequence.
3072 /// Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
3073 /// above sequence, and expanded really late in the compilation flow, to ensure
3074 /// the sequence is produced as per above.
3075 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr, SDLoc DL,
3076 SelectionDAG &DAG) const {
3077 EVT PtrVT = getPointerTy();
3079 SDValue Chain = DAG.getEntryNode();
3080 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3082 SmallVector<SDValue, 2> Ops;
3083 Ops.push_back(Chain);
3084 Ops.push_back(SymAddr);
3086 Chain = DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, Ops);
3087 SDValue Glue = Chain.getValue(1);
3089 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
3093 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
3094 SelectionDAG &DAG) const {
3095 assert(Subtarget->isTargetELF() && "This function expects an ELF target");
3096 assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
3097 "ELF TLS only supported in small memory model");
3098 // Different choices can be made for the maximum size of the TLS area for a
3099 // module. For the small address model, the default TLS size is 16MiB and the
3100 // maximum TLS size is 4GiB.
3101 // FIXME: add -mtls-size command line option and make it control the 16MiB
3102 // vs. 4GiB code sequence generation.
3103 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3105 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
3106 if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
3107 if (Model == TLSModel::LocalDynamic)
3108 Model = TLSModel::GeneralDynamic;
3112 EVT PtrVT = getPointerTy();
3114 const GlobalValue *GV = GA->getGlobal();
3116 SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
3118 if (Model == TLSModel::LocalExec) {
3119 SDValue HiVar = DAG.getTargetGlobalAddress(
3120 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
3121 SDValue LoVar = DAG.getTargetGlobalAddress(
3123 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3125 SDValue TPWithOff_lo =
3126 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
3127 HiVar, DAG.getTargetConstant(0, MVT::i32)),
3130 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
3131 LoVar, DAG.getTargetConstant(0, MVT::i32)),
3134 } else if (Model == TLSModel::InitialExec) {
3135 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3136 TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
3137 } else if (Model == TLSModel::LocalDynamic) {
3138 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
3139 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
3140 // the beginning of the module's TLS region, followed by a DTPREL offset
3143 // These accesses will need deduplicating if there's more than one.
3144 AArch64FunctionInfo *MFI =
3145 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
3146 MFI->incNumLocalDynamicTLSAccesses();
3148 // The call needs a relocation too for linker relaxation. It doesn't make
3149 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3151 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
3154 // Now we can calculate the offset from TPIDR_EL0 to this module's
3155 // thread-local area.
3156 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
3158 // Now use :dtprel_whatever: operations to calculate this variable's offset
3159 // in its thread-storage area.
3160 SDValue HiVar = DAG.getTargetGlobalAddress(
3161 GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
3162 SDValue LoVar = DAG.getTargetGlobalAddress(
3163 GV, DL, MVT::i64, 0,
3164 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3166 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
3167 DAG.getTargetConstant(0, MVT::i32)),
3169 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
3170 DAG.getTargetConstant(0, MVT::i32)),
3172 } else if (Model == TLSModel::GeneralDynamic) {
3173 // The call needs a relocation too for linker relaxation. It doesn't make
3174 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3177 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3179 // Finally we can make a call to calculate the offset from tpidr_el0.
3180 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
3182 llvm_unreachable("Unsupported ELF TLS access model");
3184 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
3187 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
3188 SelectionDAG &DAG) const {
3189 if (Subtarget->isTargetDarwin())
3190 return LowerDarwinGlobalTLSAddress(Op, DAG);
3191 else if (Subtarget->isTargetELF())
3192 return LowerELFGlobalTLSAddress(Op, DAG);
3194 llvm_unreachable("Unexpected platform trying to use TLS");
3196 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3197 SDValue Chain = Op.getOperand(0);
3198 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3199 SDValue LHS = Op.getOperand(2);
3200 SDValue RHS = Op.getOperand(3);
3201 SDValue Dest = Op.getOperand(4);
3204 // Handle f128 first, since lowering it will result in comparing the return
3205 // value of a libcall against zero, which is just what the rest of LowerBR_CC
3206 // is expecting to deal with.
3207 if (LHS.getValueType() == MVT::f128) {
3208 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3210 // If softenSetCCOperands returned a scalar, we need to compare the result
3211 // against zero to select between true and false values.
3212 if (!RHS.getNode()) {
3213 RHS = DAG.getConstant(0, LHS.getValueType());
3218 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
3220 unsigned Opc = LHS.getOpcode();
3221 if (LHS.getResNo() == 1 && isa<ConstantSDNode>(RHS) &&
3222 cast<ConstantSDNode>(RHS)->isOne() &&
3223 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3224 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
3225 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
3226 "Unexpected condition code.");
3227 // Only lower legal XALUO ops.
3228 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
3231 // The actual operation with overflow check.
3232 AArch64CC::CondCode OFCC;
3233 SDValue Value, Overflow;
3234 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
3236 if (CC == ISD::SETNE)
3237 OFCC = getInvertedCondCode(OFCC);
3238 SDValue CCVal = DAG.getConstant(OFCC, MVT::i32);
3240 return DAG.getNode(AArch64ISD::BRCOND, SDLoc(LHS), MVT::Other, Chain, Dest,
3244 if (LHS.getValueType().isInteger()) {
3245 assert((LHS.getValueType() == RHS.getValueType()) &&
3246 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3248 // If the RHS of the comparison is zero, we can potentially fold this
3249 // to a specialized branch.
3250 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
3251 if (RHSC && RHSC->getZExtValue() == 0) {
3252 if (CC == ISD::SETEQ) {
3253 // See if we can use a TBZ to fold in an AND as well.
3254 // TBZ has a smaller branch displacement than CBZ. If the offset is
3255 // out of bounds, a late MI-layer pass rewrites branches.
3256 // 403.gcc is an example that hits this case.
3257 if (LHS.getOpcode() == ISD::AND &&
3258 isa<ConstantSDNode>(LHS.getOperand(1)) &&
3259 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3260 SDValue Test = LHS.getOperand(0);
3261 uint64_t Mask = LHS.getConstantOperandVal(1);
3262 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
3263 DAG.getConstant(Log2_64(Mask), MVT::i64), Dest);
3266 return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
3267 } else if (CC == ISD::SETNE) {
3268 // See if we can use a TBZ to fold in an AND as well.
3269 // TBZ has a smaller branch displacement than CBZ. If the offset is
3270 // out of bounds, a late MI-layer pass rewrites branches.
3271 // 403.gcc is an example that hits this case.
3272 if (LHS.getOpcode() == ISD::AND &&
3273 isa<ConstantSDNode>(LHS.getOperand(1)) &&
3274 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3275 SDValue Test = LHS.getOperand(0);
3276 uint64_t Mask = LHS.getConstantOperandVal(1);
3277 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
3278 DAG.getConstant(Log2_64(Mask), MVT::i64), Dest);
3281 return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
3282 } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
3283 // Don't combine AND since emitComparison converts the AND to an ANDS
3284 // (a.k.a. TST) and the test in the test bit and branch instruction
3285 // becomes redundant. This would also increase register pressure.
3286 uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
3287 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
3288 DAG.getConstant(Mask, MVT::i64), Dest);
3291 if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
3292 LHS.getOpcode() != ISD::AND) {
3293 // Don't combine AND since emitComparison converts the AND to an ANDS
3294 // (a.k.a. TST) and the test in the test bit and branch instruction
3295 // becomes redundant. This would also increase register pressure.
3296 uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
3297 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
3298 DAG.getConstant(Mask, MVT::i64), Dest);
3302 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3303 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3307 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3309 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
3310 // clean. Some of them require two branches to implement.
3311 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3312 AArch64CC::CondCode CC1, CC2;
3313 changeFPCCToAArch64CC(CC, CC1, CC2);
3314 SDValue CC1Val = DAG.getConstant(CC1, MVT::i32);
3316 DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
3317 if (CC2 != AArch64CC::AL) {
3318 SDValue CC2Val = DAG.getConstant(CC2, MVT::i32);
3319 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
3326 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
3327 SelectionDAG &DAG) const {
3328 EVT VT = Op.getValueType();
3331 SDValue In1 = Op.getOperand(0);
3332 SDValue In2 = Op.getOperand(1);
3333 EVT SrcVT = In2.getValueType();
3335 if (SrcVT == MVT::f32 && VT == MVT::f64)
3336 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
3337 else if (SrcVT == MVT::f64 && VT == MVT::f32)
3338 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0));
3340 // FIXME: Src type is different, bail out for now. Can VT really be a
3347 SDValue EltMask, VecVal1, VecVal2;
3348 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
3351 EltMask = DAG.getConstant(0x80000000ULL, EltVT);
3353 if (!VT.isVector()) {
3354 VecVal1 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3355 DAG.getUNDEF(VecVT), In1);
3356 VecVal2 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3357 DAG.getUNDEF(VecVT), In2);
3359 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3360 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3362 } else if (VT == MVT::f64 || VT == MVT::v2f64) {
3366 // We want to materialize a mask with the the high bit set, but the AdvSIMD
3367 // immediate moves cannot materialize that in a single instruction for
3368 // 64-bit elements. Instead, materialize zero and then negate it.
3369 EltMask = DAG.getConstant(0, EltVT);
3371 if (!VT.isVector()) {
3372 VecVal1 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3373 DAG.getUNDEF(VecVT), In1);
3374 VecVal2 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3375 DAG.getUNDEF(VecVT), In2);
3377 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3378 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3381 llvm_unreachable("Invalid type for copysign!");
3384 std::vector<SDValue> BuildVectorOps;
3385 for (unsigned i = 0; i < VecVT.getVectorNumElements(); ++i)
3386 BuildVectorOps.push_back(EltMask);
3388 SDValue BuildVec = DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, BuildVectorOps);
3390 // If we couldn't materialize the mask above, then the mask vector will be
3391 // the zero vector, and we need to negate it here.
3392 if (VT == MVT::f64 || VT == MVT::v2f64) {
3393 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
3394 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
3395 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
3399 DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
3402 return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
3403 else if (VT == MVT::f64)
3404 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
3406 return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
3409 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
3410 if (DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
3411 AttributeSet::FunctionIndex, Attribute::NoImplicitFloat))
3414 if (!Subtarget->hasNEON())
3417 // While there is no integer popcount instruction, it can
3418 // be more efficiently lowered to the following sequence that uses
3419 // AdvSIMD registers/instructions as long as the copies to/from
3420 // the AdvSIMD registers are cheap.
3421 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd
3422 // CNT V0.8B, V0.8B // 8xbyte pop-counts
3423 // ADDV B0, V0.8B // sum 8xbyte pop-counts
3424 // UMOV X0, V0.B[0] // copy byte result back to integer reg
3425 SDValue Val = Op.getOperand(0);
3427 EVT VT = Op.getValueType();
3428 SDValue ZeroVec = DAG.getUNDEF(MVT::v8i8);
3431 if (VT == MVT::i32) {
3432 VecVal = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val);
3433 VecVal = DAG.getTargetInsertSubreg(AArch64::ssub, DL, MVT::v8i8, ZeroVec,
3436 VecVal = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
3439 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, VecVal);
3440 SDValue UaddLV = DAG.getNode(
3441 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
3442 DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, MVT::i32), CtPop);
3445 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
3449 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3451 if (Op.getValueType().isVector())
3452 return LowerVSETCC(Op, DAG);
3454 SDValue LHS = Op.getOperand(0);
3455 SDValue RHS = Op.getOperand(1);
3456 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3459 // We chose ZeroOrOneBooleanContents, so use zero and one.
3460 EVT VT = Op.getValueType();
3461 SDValue TVal = DAG.getConstant(1, VT);
3462 SDValue FVal = DAG.getConstant(0, VT);
3464 // Handle f128 first, since one possible outcome is a normal integer
3465 // comparison which gets picked up by the next if statement.
3466 if (LHS.getValueType() == MVT::f128) {
3467 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3469 // If softenSetCCOperands returned a scalar, use it.
3470 if (!RHS.getNode()) {
3471 assert(LHS.getValueType() == Op.getValueType() &&
3472 "Unexpected setcc expansion!");
3477 if (LHS.getValueType().isInteger()) {
3480 getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
3482 // Note that we inverted the condition above, so we reverse the order of
3483 // the true and false operands here. This will allow the setcc to be
3484 // matched to a single CSINC instruction.
3485 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
3488 // Now we know we're dealing with FP values.
3489 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3491 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
3492 // and do the comparison.
3493 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3495 AArch64CC::CondCode CC1, CC2;
3496 changeFPCCToAArch64CC(CC, CC1, CC2);
3497 if (CC2 == AArch64CC::AL) {
3498 changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
3499 SDValue CC1Val = DAG.getConstant(CC1, MVT::i32);
3501 // Note that we inverted the condition above, so we reverse the order of
3502 // the true and false operands here. This will allow the setcc to be
3503 // matched to a single CSINC instruction.
3504 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
3506 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
3507 // totally clean. Some of them require two CSELs to implement. As is in
3508 // this case, we emit the first CSEL and then emit a second using the output
3509 // of the first as the RHS. We're effectively OR'ing the two CC's together.
3511 // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
3512 SDValue CC1Val = DAG.getConstant(CC1, MVT::i32);
3514 DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3516 SDValue CC2Val = DAG.getConstant(CC2, MVT::i32);
3517 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3521 /// A SELECT_CC operation is really some kind of max or min if both values being
3522 /// compared are, in some sense, equal to the results in either case. However,
3523 /// it is permissible to compare f32 values and produce directly extended f64
3526 /// Extending the comparison operands would also be allowed, but is less likely
3527 /// to happen in practice since their use is right here. Note that truncate
3528 /// operations would *not* be semantically equivalent.
3529 static bool selectCCOpsAreFMaxCompatible(SDValue Cmp, SDValue Result) {
3533 ConstantFPSDNode *CCmp = dyn_cast<ConstantFPSDNode>(Cmp);
3534 ConstantFPSDNode *CResult = dyn_cast<ConstantFPSDNode>(Result);
3535 if (CCmp && CResult && Cmp.getValueType() == MVT::f32 &&
3536 Result.getValueType() == MVT::f64) {
3538 APFloat CmpVal = CCmp->getValueAPF();
3539 CmpVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &Lossy);
3540 return CResult->getValueAPF().bitwiseIsEqual(CmpVal);
3543 return Result->getOpcode() == ISD::FP_EXTEND && Result->getOperand(0) == Cmp;
3546 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
3547 SelectionDAG &DAG) const {
3548 SDValue CC = Op->getOperand(0);
3549 SDValue TVal = Op->getOperand(1);
3550 SDValue FVal = Op->getOperand(2);
3553 unsigned Opc = CC.getOpcode();
3554 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
3556 if (CC.getResNo() == 1 &&
3557 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3558 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
3559 // Only lower legal XALUO ops.
3560 if (!DAG.getTargetLoweringInfo().isTypeLegal(CC->getValueType(0)))
3563 AArch64CC::CondCode OFCC;
3564 SDValue Value, Overflow;
3565 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CC.getValue(0), DAG);
3566 SDValue CCVal = DAG.getConstant(OFCC, MVT::i32);
3568 return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
3572 if (CC.getOpcode() == ISD::SETCC)
3573 return DAG.getSelectCC(DL, CC.getOperand(0), CC.getOperand(1), TVal, FVal,
3574 cast<CondCodeSDNode>(CC.getOperand(2))->get());
3576 return DAG.getSelectCC(DL, CC, DAG.getConstant(0, CC.getValueType()), TVal,
3580 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
3581 SelectionDAG &DAG) const {
3582 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3583 SDValue LHS = Op.getOperand(0);
3584 SDValue RHS = Op.getOperand(1);
3585 SDValue TVal = Op.getOperand(2);
3586 SDValue FVal = Op.getOperand(3);
3589 // Handle f128 first, because it will result in a comparison of some RTLIB
3590 // call result against zero.
3591 if (LHS.getValueType() == MVT::f128) {
3592 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3594 // If softenSetCCOperands returned a scalar, we need to compare the result
3595 // against zero to select between true and false values.
3596 if (!RHS.getNode()) {
3597 RHS = DAG.getConstant(0, LHS.getValueType());
3602 // Handle integers first.
3603 if (LHS.getValueType().isInteger()) {
3604 assert((LHS.getValueType() == RHS.getValueType()) &&
3605 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3607 unsigned Opcode = AArch64ISD::CSEL;
3609 // If both the TVal and the FVal are constants, see if we can swap them in
3610 // order to for a CSINV or CSINC out of them.
3611 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
3612 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
3614 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
3615 std::swap(TVal, FVal);
3616 std::swap(CTVal, CFVal);
3617 CC = ISD::getSetCCInverse(CC, true);
3618 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
3619 std::swap(TVal, FVal);
3620 std::swap(CTVal, CFVal);
3621 CC = ISD::getSetCCInverse(CC, true);
3622 } else if (TVal.getOpcode() == ISD::XOR) {
3623 // If TVal is a NOT we want to swap TVal and FVal so that we can match
3624 // with a CSINV rather than a CSEL.
3625 ConstantSDNode *CVal = dyn_cast<ConstantSDNode>(TVal.getOperand(1));
3627 if (CVal && CVal->isAllOnesValue()) {
3628 std::swap(TVal, FVal);
3629 std::swap(CTVal, CFVal);
3630 CC = ISD::getSetCCInverse(CC, true);
3632 } else if (TVal.getOpcode() == ISD::SUB) {
3633 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
3634 // that we can match with a CSNEG rather than a CSEL.
3635 ConstantSDNode *CVal = dyn_cast<ConstantSDNode>(TVal.getOperand(0));
3637 if (CVal && CVal->isNullValue()) {
3638 std::swap(TVal, FVal);
3639 std::swap(CTVal, CFVal);
3640 CC = ISD::getSetCCInverse(CC, true);
3642 } else if (CTVal && CFVal) {
3643 const int64_t TrueVal = CTVal->getSExtValue();
3644 const int64_t FalseVal = CFVal->getSExtValue();
3647 // If both TVal and FVal are constants, see if FVal is the
3648 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
3649 // instead of a CSEL in that case.
3650 if (TrueVal == ~FalseVal) {
3651 Opcode = AArch64ISD::CSINV;
3652 } else if (TrueVal == -FalseVal) {
3653 Opcode = AArch64ISD::CSNEG;
3654 } else if (TVal.getValueType() == MVT::i32) {
3655 // If our operands are only 32-bit wide, make sure we use 32-bit
3656 // arithmetic for the check whether we can use CSINC. This ensures that
3657 // the addition in the check will wrap around properly in case there is
3658 // an overflow (which would not be the case if we do the check with
3659 // 64-bit arithmetic).
3660 const uint32_t TrueVal32 = CTVal->getZExtValue();
3661 const uint32_t FalseVal32 = CFVal->getZExtValue();
3663 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
3664 Opcode = AArch64ISD::CSINC;
3666 if (TrueVal32 > FalseVal32) {
3670 // 64-bit check whether we can use CSINC.
3671 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
3672 Opcode = AArch64ISD::CSINC;
3674 if (TrueVal > FalseVal) {
3679 // Swap TVal and FVal if necessary.
3681 std::swap(TVal, FVal);
3682 std::swap(CTVal, CFVal);
3683 CC = ISD::getSetCCInverse(CC, true);
3686 if (Opcode != AArch64ISD::CSEL) {
3687 // Drop FVal since we can get its value by simply inverting/negating
3694 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3696 EVT VT = Op.getValueType();
3697 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
3700 // Now we know we're dealing with FP values.
3701 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3702 assert(LHS.getValueType() == RHS.getValueType());
3703 EVT VT = Op.getValueType();
3705 // Try to match this select into a max/min operation, which have dedicated
3706 // opcode in the instruction set.
3707 // FIXME: This is not correct in the presence of NaNs, so we only enable this
3709 if (getTargetMachine().Options.NoNaNsFPMath) {
3710 SDValue MinMaxLHS = TVal, MinMaxRHS = FVal;
3711 if (selectCCOpsAreFMaxCompatible(LHS, MinMaxRHS) &&
3712 selectCCOpsAreFMaxCompatible(RHS, MinMaxLHS)) {
3713 CC = ISD::getSetCCSwappedOperands(CC);
3714 std::swap(MinMaxLHS, MinMaxRHS);
3717 if (selectCCOpsAreFMaxCompatible(LHS, MinMaxLHS) &&
3718 selectCCOpsAreFMaxCompatible(RHS, MinMaxRHS)) {
3728 return DAG.getNode(AArch64ISD::FMAX, dl, VT, MinMaxLHS, MinMaxRHS);
3736 return DAG.getNode(AArch64ISD::FMIN, dl, VT, MinMaxLHS, MinMaxRHS);
3742 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
3743 // and do the comparison.
3744 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3746 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
3747 // clean. Some of them require two CSELs to implement.
3748 AArch64CC::CondCode CC1, CC2;
3749 changeFPCCToAArch64CC(CC, CC1, CC2);
3750 SDValue CC1Val = DAG.getConstant(CC1, MVT::i32);
3751 SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3753 // If we need a second CSEL, emit it, using the output of the first as the
3754 // RHS. We're effectively OR'ing the two CC's together.
3755 if (CC2 != AArch64CC::AL) {
3756 SDValue CC2Val = DAG.getConstant(CC2, MVT::i32);
3757 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3760 // Otherwise, return the output of the first CSEL.
3764 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
3765 SelectionDAG &DAG) const {
3766 // Jump table entries as PC relative offsets. No additional tweaking
3767 // is necessary here. Just get the address of the jump table.
3768 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
3769 EVT PtrVT = getPointerTy();
3772 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3773 !Subtarget->isTargetMachO()) {
3774 const unsigned char MO_NC = AArch64II::MO_NC;
3776 AArch64ISD::WrapperLarge, DL, PtrVT,
3777 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G3),
3778 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G2 | MO_NC),
3779 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G1 | MO_NC),
3780 DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
3781 AArch64II::MO_G0 | MO_NC));
3785 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_PAGE);
3786 SDValue Lo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
3787 AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3788 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3789 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3792 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
3793 SelectionDAG &DAG) const {
3794 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3795 EVT PtrVT = getPointerTy();
3798 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
3799 // Use the GOT for the large code model on iOS.
3800 if (Subtarget->isTargetMachO()) {
3801 SDValue GotAddr = DAG.getTargetConstantPool(
3802 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
3804 return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
3807 const unsigned char MO_NC = AArch64II::MO_NC;
3809 AArch64ISD::WrapperLarge, DL, PtrVT,
3810 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3811 CP->getOffset(), AArch64II::MO_G3),
3812 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3813 CP->getOffset(), AArch64II::MO_G2 | MO_NC),
3814 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3815 CP->getOffset(), AArch64II::MO_G1 | MO_NC),
3816 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3817 CP->getOffset(), AArch64II::MO_G0 | MO_NC));
3819 // Use ADRP/ADD or ADRP/LDR for everything else: the small memory model on
3820 // ELF, the only valid one on Darwin.
3822 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3823 CP->getOffset(), AArch64II::MO_PAGE);
3824 SDValue Lo = DAG.getTargetConstantPool(
3825 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
3826 AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3828 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3829 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3833 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
3834 SelectionDAG &DAG) const {
3835 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
3836 EVT PtrVT = getPointerTy();
3838 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3839 !Subtarget->isTargetMachO()) {
3840 const unsigned char MO_NC = AArch64II::MO_NC;
3842 AArch64ISD::WrapperLarge, DL, PtrVT,
3843 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G3),
3844 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
3845 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
3846 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
3848 SDValue Hi = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGE);
3849 SDValue Lo = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGEOFF |
3851 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3852 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3856 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
3857 SelectionDAG &DAG) const {
3858 AArch64FunctionInfo *FuncInfo =
3859 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
3863 DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), getPointerTy());
3864 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3865 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
3866 MachinePointerInfo(SV), false, false, 0);
3869 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
3870 SelectionDAG &DAG) const {
3871 // The layout of the va_list struct is specified in the AArch64 Procedure Call
3872 // Standard, section B.3.
3873 MachineFunction &MF = DAG.getMachineFunction();
3874 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3877 SDValue Chain = Op.getOperand(0);
3878 SDValue VAList = Op.getOperand(1);
3879 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3880 SmallVector<SDValue, 4> MemOps;
3882 // void *__stack at offset 0
3884 DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), getPointerTy());
3885 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
3886 MachinePointerInfo(SV), false, false, 8));
3888 // void *__gr_top at offset 8
3889 int GPRSize = FuncInfo->getVarArgsGPRSize();
3891 SDValue GRTop, GRTopAddr;
3893 GRTopAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3894 DAG.getConstant(8, getPointerTy()));
3896 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), getPointerTy());
3897 GRTop = DAG.getNode(ISD::ADD, DL, getPointerTy(), GRTop,
3898 DAG.getConstant(GPRSize, getPointerTy()));
3900 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
3901 MachinePointerInfo(SV, 8), false, false, 8));
3904 // void *__vr_top at offset 16
3905 int FPRSize = FuncInfo->getVarArgsFPRSize();
3907 SDValue VRTop, VRTopAddr;
3908 VRTopAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3909 DAG.getConstant(16, getPointerTy()));
3911 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), getPointerTy());
3912 VRTop = DAG.getNode(ISD::ADD, DL, getPointerTy(), VRTop,
3913 DAG.getConstant(FPRSize, getPointerTy()));
3915 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
3916 MachinePointerInfo(SV, 16), false, false, 8));
3919 // int __gr_offs at offset 24
3920 SDValue GROffsAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3921 DAG.getConstant(24, getPointerTy()));
3922 MemOps.push_back(DAG.getStore(Chain, DL, DAG.getConstant(-GPRSize, MVT::i32),
3923 GROffsAddr, MachinePointerInfo(SV, 24), false,
3926 // int __vr_offs at offset 28
3927 SDValue VROffsAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3928 DAG.getConstant(28, getPointerTy()));
3929 MemOps.push_back(DAG.getStore(Chain, DL, DAG.getConstant(-FPRSize, MVT::i32),
3930 VROffsAddr, MachinePointerInfo(SV, 28), false,
3933 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
3936 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
3937 SelectionDAG &DAG) const {
3938 return Subtarget->isTargetDarwin() ? LowerDarwin_VASTART(Op, DAG)
3939 : LowerAAPCS_VASTART(Op, DAG);
3942 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
3943 SelectionDAG &DAG) const {
3944 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
3946 unsigned VaListSize = Subtarget->isTargetDarwin() ? 8 : 32;
3947 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
3948 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
3950 return DAG.getMemcpy(Op.getOperand(0), SDLoc(Op), Op.getOperand(1),
3951 Op.getOperand(2), DAG.getConstant(VaListSize, MVT::i32),
3952 8, false, false, MachinePointerInfo(DestSV),
3953 MachinePointerInfo(SrcSV));
3956 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
3957 assert(Subtarget->isTargetDarwin() &&
3958 "automatic va_arg instruction only works on Darwin");
3960 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3961 EVT VT = Op.getValueType();
3963 SDValue Chain = Op.getOperand(0);
3964 SDValue Addr = Op.getOperand(1);
3965 unsigned Align = Op.getConstantOperandVal(3);
3967 SDValue VAList = DAG.getLoad(getPointerTy(), DL, Chain, Addr,
3968 MachinePointerInfo(V), false, false, false, 0);
3969 Chain = VAList.getValue(1);
3972 assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
3973 VAList = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3974 DAG.getConstant(Align - 1, getPointerTy()));
3975 VAList = DAG.getNode(ISD::AND, DL, getPointerTy(), VAList,
3976 DAG.getConstant(-(int64_t)Align, getPointerTy()));
3979 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
3980 uint64_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
3982 // Scalar integer and FP values smaller than 64 bits are implicitly extended
3983 // up to 64 bits. At the very least, we have to increase the striding of the
3984 // vaargs list to match this, and for FP values we need to introduce
3985 // FP_ROUND nodes as well.
3986 if (VT.isInteger() && !VT.isVector())
3988 bool NeedFPTrunc = false;
3989 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
3994 // Increment the pointer, VAList, to the next vaarg
3995 SDValue VANext = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3996 DAG.getConstant(ArgSize, getPointerTy()));
3997 // Store the incremented VAList to the legalized pointer
3998 SDValue APStore = DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V),
4001 // Load the actual argument out of the pointer VAList
4003 // Load the value as an f64.
4004 SDValue WideFP = DAG.getLoad(MVT::f64, DL, APStore, VAList,
4005 MachinePointerInfo(), false, false, false, 0);
4006 // Round the value down to an f32.
4007 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
4008 DAG.getIntPtrConstant(1));
4009 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
4010 // Merge the rounded value with the chain output of the load.
4011 return DAG.getMergeValues(Ops, DL);
4014 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo(), false,
4018 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
4019 SelectionDAG &DAG) const {
4020 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4021 MFI->setFrameAddressIsTaken(true);
4023 EVT VT = Op.getValueType();
4025 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4027 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
4029 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
4030 MachinePointerInfo(), false, false, false, 0);
4034 // FIXME? Maybe this could be a TableGen attribute on some registers and
4035 // this table could be generated automatically from RegInfo.
4036 unsigned AArch64TargetLowering::getRegisterByName(const char* RegName,
4038 unsigned Reg = StringSwitch<unsigned>(RegName)
4039 .Case("sp", AArch64::SP)
4043 report_fatal_error("Invalid register name global variable");
4046 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
4047 SelectionDAG &DAG) const {
4048 MachineFunction &MF = DAG.getMachineFunction();
4049 MachineFrameInfo *MFI = MF.getFrameInfo();
4050 MFI->setReturnAddressIsTaken(true);
4052 EVT VT = Op.getValueType();
4054 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4056 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4057 SDValue Offset = DAG.getConstant(8, getPointerTy());
4058 return DAG.getLoad(VT, DL, DAG.getEntryNode(),
4059 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
4060 MachinePointerInfo(), false, false, false, 0);
4063 // Return LR, which contains the return address. Mark it an implicit live-in.
4064 unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
4065 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4068 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4069 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
4070 SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
4071 SelectionDAG &DAG) const {
4072 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4073 EVT VT = Op.getValueType();
4074 unsigned VTBits = VT.getSizeInBits();
4076 SDValue ShOpLo = Op.getOperand(0);
4077 SDValue ShOpHi = Op.getOperand(1);
4078 SDValue ShAmt = Op.getOperand(2);
4080 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4082 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4084 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
4085 DAG.getConstant(VTBits, MVT::i64), ShAmt);
4086 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4087 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
4088 DAG.getConstant(VTBits, MVT::i64));
4089 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4091 SDValue Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, MVT::i64),
4092 ISD::SETGE, dl, DAG);
4093 SDValue CCVal = DAG.getConstant(AArch64CC::GE, MVT::i32);
4095 SDValue FalseValLo = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4096 SDValue TrueValLo = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4098 DAG.getNode(AArch64ISD::CSEL, dl, VT, TrueValLo, FalseValLo, CCVal, Cmp);
4100 // AArch64 shifts larger than the register width are wrapped rather than
4101 // clamped, so we can't just emit "hi >> x".
4102 SDValue FalseValHi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4103 SDValue TrueValHi = Opc == ISD::SRA
4104 ? DAG.getNode(Opc, dl, VT, ShOpHi,
4105 DAG.getConstant(VTBits - 1, MVT::i64))
4106 : DAG.getConstant(0, VT);
4108 DAG.getNode(AArch64ISD::CSEL, dl, VT, TrueValHi, FalseValHi, CCVal, Cmp);
4110 SDValue Ops[2] = { Lo, Hi };
4111 return DAG.getMergeValues(Ops, dl);
4114 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4115 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
4116 SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
4117 SelectionDAG &DAG) const {
4118 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4119 EVT VT = Op.getValueType();
4120 unsigned VTBits = VT.getSizeInBits();
4122 SDValue ShOpLo = Op.getOperand(0);
4123 SDValue ShOpHi = Op.getOperand(1);
4124 SDValue ShAmt = Op.getOperand(2);
4127 assert(Op.getOpcode() == ISD::SHL_PARTS);
4128 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
4129 DAG.getConstant(VTBits, MVT::i64), ShAmt);
4130 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4131 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
4132 DAG.getConstant(VTBits, MVT::i64));
4133 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4134 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4136 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4138 SDValue Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, MVT::i64),
4139 ISD::SETGE, dl, DAG);
4140 SDValue CCVal = DAG.getConstant(AArch64CC::GE, MVT::i32);
4142 DAG.getNode(AArch64ISD::CSEL, dl, VT, Tmp3, FalseVal, CCVal, Cmp);
4144 // AArch64 shifts of larger than register sizes are wrapped rather than
4145 // clamped, so we can't just emit "lo << a" if a is too big.
4146 SDValue TrueValLo = DAG.getConstant(0, VT);
4147 SDValue FalseValLo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4149 DAG.getNode(AArch64ISD::CSEL, dl, VT, TrueValLo, FalseValLo, CCVal, Cmp);
4151 SDValue Ops[2] = { Lo, Hi };
4152 return DAG.getMergeValues(Ops, dl);
4155 bool AArch64TargetLowering::isOffsetFoldingLegal(
4156 const GlobalAddressSDNode *GA) const {
4157 // The AArch64 target doesn't support folding offsets into global addresses.
4161 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4162 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
4163 // FIXME: We should be able to handle f128 as well with a clever lowering.
4164 if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32))
4168 return AArch64_AM::getFP64Imm(Imm) != -1;
4169 else if (VT == MVT::f32)
4170 return AArch64_AM::getFP32Imm(Imm) != -1;
4174 //===----------------------------------------------------------------------===//
4175 // AArch64 Optimization Hooks
4176 //===----------------------------------------------------------------------===//
4178 //===----------------------------------------------------------------------===//
4179 // AArch64 Inline Assembly Support
4180 //===----------------------------------------------------------------------===//
4182 // Table of Constraints
4183 // TODO: This is the current set of constraints supported by ARM for the
4184 // compiler, not all of them may make sense, e.g. S may be difficult to support.
4186 // r - A general register
4187 // w - An FP/SIMD register of some size in the range v0-v31
4188 // x - An FP/SIMD register of some size in the range v0-v15
4189 // I - Constant that can be used with an ADD instruction
4190 // J - Constant that can be used with a SUB instruction
4191 // K - Constant that can be used with a 32-bit logical instruction
4192 // L - Constant that can be used with a 64-bit logical instruction
4193 // M - Constant that can be used as a 32-bit MOV immediate
4194 // N - Constant that can be used as a 64-bit MOV immediate
4195 // Q - A memory reference with base register and no offset
4196 // S - A symbolic address
4197 // Y - Floating point constant zero
4198 // Z - Integer constant zero
4200 // Note that general register operands will be output using their 64-bit x
4201 // register name, whatever the size of the variable, unless the asm operand
4202 // is prefixed by the %w modifier. Floating-point and SIMD register operands
4203 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
4206 /// getConstraintType - Given a constraint letter, return the type of
4207 /// constraint it is for this target.
4208 AArch64TargetLowering::ConstraintType
4209 AArch64TargetLowering::getConstraintType(const std::string &Constraint) const {
4210 if (Constraint.size() == 1) {
4211 switch (Constraint[0]) {
4218 return C_RegisterClass;
4219 // An address with a single base register. Due to the way we
4220 // currently handle addresses it is the same as 'r'.
4225 return TargetLowering::getConstraintType(Constraint);
4228 /// Examine constraint type and operand type and determine a weight value.
4229 /// This object must already have been set up with the operand type
4230 /// and the current alternative constraint selected.
4231 TargetLowering::ConstraintWeight
4232 AArch64TargetLowering::getSingleConstraintMatchWeight(
4233 AsmOperandInfo &info, const char *constraint) const {
4234 ConstraintWeight weight = CW_Invalid;
4235 Value *CallOperandVal = info.CallOperandVal;
4236 // If we don't have a value, we can't do a match,
4237 // but allow it at the lowest weight.
4238 if (!CallOperandVal)
4240 Type *type = CallOperandVal->getType();
4241 // Look at the constraint type.
4242 switch (*constraint) {
4244 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
4248 if (type->isFloatingPointTy() || type->isVectorTy())
4249 weight = CW_Register;
4252 weight = CW_Constant;
4258 std::pair<unsigned, const TargetRegisterClass *>
4259 AArch64TargetLowering::getRegForInlineAsmConstraint(
4260 const std::string &Constraint, MVT VT) const {
4261 if (Constraint.size() == 1) {
4262 switch (Constraint[0]) {
4264 if (VT.getSizeInBits() == 64)
4265 return std::make_pair(0U, &AArch64::GPR64commonRegClass);
4266 return std::make_pair(0U, &AArch64::GPR32commonRegClass);
4269 return std::make_pair(0U, &AArch64::FPR32RegClass);
4270 if (VT.getSizeInBits() == 64)
4271 return std::make_pair(0U, &AArch64::FPR64RegClass);
4272 if (VT.getSizeInBits() == 128)
4273 return std::make_pair(0U, &AArch64::FPR128RegClass);
4275 // The instructions that this constraint is designed for can
4276 // only take 128-bit registers so just use that regclass.
4278 if (VT.getSizeInBits() == 128)
4279 return std::make_pair(0U, &AArch64::FPR128_loRegClass);
4283 if (StringRef("{cc}").equals_lower(Constraint))
4284 return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
4286 // Use the default implementation in TargetLowering to convert the register
4287 // constraint into a member of a register class.
4288 std::pair<unsigned, const TargetRegisterClass *> Res;
4289 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
4291 // Not found as a standard register?
4293 unsigned Size = Constraint.size();
4294 if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
4295 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
4296 const std::string Reg =
4297 std::string(&Constraint[2], &Constraint[Size - 1]);
4298 int RegNo = atoi(Reg.c_str());
4299 if (RegNo >= 0 && RegNo <= 31) {
4300 // v0 - v31 are aliases of q0 - q31.
4301 // By default we'll emit v0-v31 for this unless there's a modifier where
4302 // we'll emit the correct register as well.
4303 Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
4304 Res.second = &AArch64::FPR128RegClass;
4312 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
4313 /// vector. If it is invalid, don't add anything to Ops.
4314 void AArch64TargetLowering::LowerAsmOperandForConstraint(
4315 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
4316 SelectionDAG &DAG) const {
4319 // Currently only support length 1 constraints.
4320 if (Constraint.length() != 1)
4323 char ConstraintLetter = Constraint[0];
4324 switch (ConstraintLetter) {
4328 // This set of constraints deal with valid constants for various instructions.
4329 // Validate and return a target constant for them if we can.
4331 // 'z' maps to xzr or wzr so it needs an input of 0.
4332 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4333 if (!C || C->getZExtValue() != 0)
4336 if (Op.getValueType() == MVT::i64)
4337 Result = DAG.getRegister(AArch64::XZR, MVT::i64);
4339 Result = DAG.getRegister(AArch64::WZR, MVT::i32);
4349 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4353 // Grab the value and do some validation.
4354 uint64_t CVal = C->getZExtValue();
4355 switch (ConstraintLetter) {
4356 // The I constraint applies only to simple ADD or SUB immediate operands:
4357 // i.e. 0 to 4095 with optional shift by 12
4358 // The J constraint applies only to ADD or SUB immediates that would be
4359 // valid when negated, i.e. if [an add pattern] were to be output as a SUB
4360 // instruction [or vice versa], in other words -1 to -4095 with optional
4361 // left shift by 12.
4363 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
4367 uint64_t NVal = -C->getSExtValue();
4368 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
4369 CVal = C->getSExtValue();
4374 // The K and L constraints apply *only* to logical immediates, including
4375 // what used to be the MOVI alias for ORR (though the MOVI alias has now
4376 // been removed and MOV should be used). So these constraints have to
4377 // distinguish between bit patterns that are valid 32-bit or 64-bit
4378 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
4379 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
4382 if (AArch64_AM::isLogicalImmediate(CVal, 32))
4386 if (AArch64_AM::isLogicalImmediate(CVal, 64))
4389 // The M and N constraints are a superset of K and L respectively, for use
4390 // with the MOV (immediate) alias. As well as the logical immediates they
4391 // also match 32 or 64-bit immediates that can be loaded either using a
4392 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
4393 // (M) or 64-bit 0x1234000000000000 (N) etc.
4394 // As a note some of this code is liberally stolen from the asm parser.
4396 if (!isUInt<32>(CVal))
4398 if (AArch64_AM::isLogicalImmediate(CVal, 32))
4400 if ((CVal & 0xFFFF) == CVal)
4402 if ((CVal & 0xFFFF0000ULL) == CVal)
4404 uint64_t NCVal = ~(uint32_t)CVal;
4405 if ((NCVal & 0xFFFFULL) == NCVal)
4407 if ((NCVal & 0xFFFF0000ULL) == NCVal)
4412 if (AArch64_AM::isLogicalImmediate(CVal, 64))
4414 if ((CVal & 0xFFFFULL) == CVal)
4416 if ((CVal & 0xFFFF0000ULL) == CVal)
4418 if ((CVal & 0xFFFF00000000ULL) == CVal)
4420 if ((CVal & 0xFFFF000000000000ULL) == CVal)
4422 uint64_t NCVal = ~CVal;
4423 if ((NCVal & 0xFFFFULL) == NCVal)
4425 if ((NCVal & 0xFFFF0000ULL) == NCVal)
4427 if ((NCVal & 0xFFFF00000000ULL) == NCVal)
4429 if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
4437 // All assembler immediates are 64-bit integers.
4438 Result = DAG.getTargetConstant(CVal, MVT::i64);
4442 if (Result.getNode()) {
4443 Ops.push_back(Result);
4447 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
4450 //===----------------------------------------------------------------------===//
4451 // AArch64 Advanced SIMD Support
4452 //===----------------------------------------------------------------------===//
4454 /// WidenVector - Given a value in the V64 register class, produce the
4455 /// equivalent value in the V128 register class.
4456 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
4457 EVT VT = V64Reg.getValueType();
4458 unsigned NarrowSize = VT.getVectorNumElements();
4459 MVT EltTy = VT.getVectorElementType().getSimpleVT();
4460 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
4463 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
4464 V64Reg, DAG.getConstant(0, MVT::i32));
4467 /// getExtFactor - Determine the adjustment factor for the position when
4468 /// generating an "extract from vector registers" instruction.
4469 static unsigned getExtFactor(SDValue &V) {
4470 EVT EltType = V.getValueType().getVectorElementType();
4471 return EltType.getSizeInBits() / 8;
4474 /// NarrowVector - Given a value in the V128 register class, produce the
4475 /// equivalent value in the V64 register class.
4476 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
4477 EVT VT = V128Reg.getValueType();
4478 unsigned WideSize = VT.getVectorNumElements();
4479 MVT EltTy = VT.getVectorElementType().getSimpleVT();
4480 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
4483 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
4486 // Gather data to see if the operation can be modelled as a
4487 // shuffle in combination with VEXTs.
4488 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
4489 SelectionDAG &DAG) const {
4490 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
4492 EVT VT = Op.getValueType();
4493 unsigned NumElts = VT.getVectorNumElements();
4495 struct ShuffleSourceInfo {
4500 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
4501 // be compatible with the shuffle we intend to construct. As a result
4502 // ShuffleVec will be some sliding window into the original Vec.
4505 // Code should guarantee that element i in Vec starts at element "WindowBase
4506 // + i * WindowScale in ShuffleVec".
4510 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
4511 ShuffleSourceInfo(SDValue Vec)
4512 : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
4516 // First gather all vectors used as an immediate source for this BUILD_VECTOR
4518 SmallVector<ShuffleSourceInfo, 2> Sources;
4519 for (unsigned i = 0; i < NumElts; ++i) {
4520 SDValue V = Op.getOperand(i);
4521 if (V.getOpcode() == ISD::UNDEF)
4523 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4524 // A shuffle can only come from building a vector from various
4525 // elements of other vectors.
4529 // Add this element source to the list if it's not already there.
4530 SDValue SourceVec = V.getOperand(0);
4531 auto Source = std::find(Sources.begin(), Sources.end(), SourceVec);
4532 if (Source == Sources.end())
4533 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
4535 // Update the minimum and maximum lane number seen.
4536 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4537 Source->MinElt = std::min(Source->MinElt, EltNo);
4538 Source->MaxElt = std::max(Source->MaxElt, EltNo);
4541 // Currently only do something sane when at most two source vectors
4543 if (Sources.size() > 2)
4546 // Find out the smallest element size among result and two sources, and use
4547 // it as element size to build the shuffle_vector.
4548 EVT SmallestEltTy = VT.getVectorElementType();
4549 for (auto &Source : Sources) {
4550 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
4551 if (SrcEltTy.bitsLT(SmallestEltTy)) {
4552 SmallestEltTy = SrcEltTy;
4555 unsigned ResMultiplier =
4556 VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
4557 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
4558 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
4560 // If the source vector is too wide or too narrow, we may nevertheless be able
4561 // to construct a compatible shuffle either by concatenating it with UNDEF or
4562 // extracting a suitable range of elements.
4563 for (auto &Src : Sources) {
4564 EVT SrcVT = Src.ShuffleVec.getValueType();
4566 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
4569 // This stage of the search produces a source with the same element type as
4570 // the original, but with a total width matching the BUILD_VECTOR output.
4571 EVT EltVT = SrcVT.getVectorElementType();
4572 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
4573 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
4575 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
4576 assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
4577 // We can pad out the smaller vector for free, so if it's part of a
4580 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
4581 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
4585 assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
4587 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
4588 // Span too large for a VEXT to cope
4592 if (Src.MinElt >= NumSrcElts) {
4593 // The extraction can just take the second half
4595 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4596 DAG.getConstant(NumSrcElts, MVT::i64));
4597 Src.WindowBase = -NumSrcElts;
4598 } else if (Src.MaxElt < NumSrcElts) {
4599 // The extraction can just take the first half
4601 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4602 DAG.getConstant(0, MVT::i64));
4604 // An actual VEXT is needed
4606 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4607 DAG.getConstant(0, MVT::i64));
4609 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4610 DAG.getConstant(NumSrcElts, MVT::i64));
4611 unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
4613 Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
4614 VEXTSrc2, DAG.getConstant(Imm, MVT::i32));
4615 Src.WindowBase = -Src.MinElt;
4619 // Another possible incompatibility occurs from the vector element types. We
4620 // can fix this by bitcasting the source vectors to the same type we intend
4622 for (auto &Src : Sources) {
4623 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
4624 if (SrcEltTy == SmallestEltTy)
4626 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
4627 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
4628 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
4629 Src.WindowBase *= Src.WindowScale;
4632 // Final sanity check before we try to actually produce a shuffle.
4634 for (auto Src : Sources)
4635 assert(Src.ShuffleVec.getValueType() == ShuffleVT);
4638 // The stars all align, our next step is to produce the mask for the shuffle.
4639 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
4640 int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
4641 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
4642 SDValue Entry = Op.getOperand(i);
4643 if (Entry.getOpcode() == ISD::UNDEF)
4646 auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0));
4647 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
4649 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
4650 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
4652 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
4653 int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
4654 VT.getVectorElementType().getSizeInBits());
4655 int LanesDefined = BitsDefined / BitsPerShuffleLane;
4657 // This source is expected to fill ResMultiplier lanes of the final shuffle,
4658 // starting at the appropriate offset.
4659 int *LaneMask = &Mask[i * ResMultiplier];
4661 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
4662 ExtractBase += NumElts * (Src - Sources.begin());
4663 for (int j = 0; j < LanesDefined; ++j)
4664 LaneMask[j] = ExtractBase + j;
4667 // Final check before we try to produce nonsense...
4668 if (!isShuffleMaskLegal(Mask, ShuffleVT))
4671 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
4672 for (unsigned i = 0; i < Sources.size(); ++i)
4673 ShuffleOps[i] = Sources[i].ShuffleVec;
4675 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
4676 ShuffleOps[1], &Mask[0]);
4677 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
4680 // check if an EXT instruction can handle the shuffle mask when the
4681 // vector sources of the shuffle are the same.
4682 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4683 unsigned NumElts = VT.getVectorNumElements();
4685 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4691 // If this is a VEXT shuffle, the immediate value is the index of the first
4692 // element. The other shuffle indices must be the successive elements after
4694 unsigned ExpectedElt = Imm;
4695 for (unsigned i = 1; i < NumElts; ++i) {
4696 // Increment the expected index. If it wraps around, just follow it
4697 // back to index zero and keep going.
4699 if (ExpectedElt == NumElts)
4703 continue; // ignore UNDEF indices
4704 if (ExpectedElt != static_cast<unsigned>(M[i]))
4711 // check if an EXT instruction can handle the shuffle mask when the
4712 // vector sources of the shuffle are different.
4713 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
4715 // Look for the first non-undef element.
4716 const int *FirstRealElt = std::find_if(M.begin(), M.end(),
4717 [](int Elt) {return Elt >= 0;});
4719 // Benefit form APInt to handle overflow when calculating expected element.
4720 unsigned NumElts = VT.getVectorNumElements();
4721 unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
4722 APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
4723 // The following shuffle indices must be the successive elements after the
4724 // first real element.
4725 const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
4726 [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
4727 if (FirstWrongElt != M.end())
4730 // The index of an EXT is the first element if it is not UNDEF.
4731 // Watch out for the beginning UNDEFs. The EXT index should be the expected
4732 // value of the first element. E.g.
4733 // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
4734 // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
4735 // ExpectedElt is the last mask index plus 1.
4736 Imm = ExpectedElt.getZExtValue();
4738 // There are two difference cases requiring to reverse input vectors.
4739 // For example, for vector <4 x i32> we have the following cases,
4740 // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
4741 // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
4742 // For both cases, we finally use mask <5, 6, 7, 0>, which requires
4743 // to reverse two input vectors.
4752 /// isREVMask - Check if a vector shuffle corresponds to a REV
4753 /// instruction with the specified blocksize. (The order of the elements
4754 /// within each block of the vector is reversed.)
4755 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4756 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
4757 "Only possible block sizes for REV are: 16, 32, 64");
4759 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4763 unsigned NumElts = VT.getVectorNumElements();
4764 unsigned BlockElts = M[0] + 1;
4765 // If the first shuffle index is UNDEF, be optimistic.
4767 BlockElts = BlockSize / EltSz;
4769 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4772 for (unsigned i = 0; i < NumElts; ++i) {
4774 continue; // ignore UNDEF indices
4775 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
4782 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4783 unsigned NumElts = VT.getVectorNumElements();
4784 WhichResult = (M[0] == 0 ? 0 : 1);
4785 unsigned Idx = WhichResult * NumElts / 2;
4786 for (unsigned i = 0; i != NumElts; i += 2) {
4787 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
4788 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
4796 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4797 unsigned NumElts = VT.getVectorNumElements();
4798 WhichResult = (M[0] == 0 ? 0 : 1);
4799 for (unsigned i = 0; i != NumElts; ++i) {
4801 continue; // ignore UNDEF indices
4802 if ((unsigned)M[i] != 2 * i + WhichResult)
4809 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4810 unsigned NumElts = VT.getVectorNumElements();
4811 WhichResult = (M[0] == 0 ? 0 : 1);
4812 for (unsigned i = 0; i < NumElts; i += 2) {
4813 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
4814 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
4820 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
4821 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4822 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4823 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4824 unsigned NumElts = VT.getVectorNumElements();
4825 WhichResult = (M[0] == 0 ? 0 : 1);
4826 unsigned Idx = WhichResult * NumElts / 2;
4827 for (unsigned i = 0; i != NumElts; i += 2) {
4828 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
4829 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
4837 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
4838 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4839 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4840 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4841 unsigned Half = VT.getVectorNumElements() / 2;
4842 WhichResult = (M[0] == 0 ? 0 : 1);
4843 for (unsigned j = 0; j != 2; ++j) {
4844 unsigned Idx = WhichResult;
4845 for (unsigned i = 0; i != Half; ++i) {
4846 int MIdx = M[i + j * Half];
4847 if (MIdx >= 0 && (unsigned)MIdx != Idx)
4856 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
4857 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4858 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4859 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4860 unsigned NumElts = VT.getVectorNumElements();
4861 WhichResult = (M[0] == 0 ? 0 : 1);
4862 for (unsigned i = 0; i < NumElts; i += 2) {
4863 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
4864 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
4870 static bool isINSMask(ArrayRef<int> M, int NumInputElements,
4871 bool &DstIsLeft, int &Anomaly) {
4872 if (M.size() != static_cast<size_t>(NumInputElements))
4875 int NumLHSMatch = 0, NumRHSMatch = 0;
4876 int LastLHSMismatch = -1, LastRHSMismatch = -1;
4878 for (int i = 0; i < NumInputElements; ++i) {
4888 LastLHSMismatch = i;
4890 if (M[i] == i + NumInputElements)
4893 LastRHSMismatch = i;
4896 if (NumLHSMatch == NumInputElements - 1) {
4898 Anomaly = LastLHSMismatch;
4900 } else if (NumRHSMatch == NumInputElements - 1) {
4902 Anomaly = LastRHSMismatch;
4909 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
4910 if (VT.getSizeInBits() != 128)
4913 unsigned NumElts = VT.getVectorNumElements();
4915 for (int I = 0, E = NumElts / 2; I != E; I++) {
4920 int Offset = NumElts / 2;
4921 for (int I = NumElts / 2, E = NumElts; I != E; I++) {
4922 if (Mask[I] != I + SplitLHS * Offset)
4929 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
4931 EVT VT = Op.getValueType();
4932 SDValue V0 = Op.getOperand(0);
4933 SDValue V1 = Op.getOperand(1);
4934 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
4936 if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
4937 VT.getVectorElementType() != V1.getValueType().getVectorElementType())
4940 bool SplitV0 = V0.getValueType().getSizeInBits() == 128;
4942 if (!isConcatMask(Mask, VT, SplitV0))
4945 EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
4946 VT.getVectorNumElements() / 2);
4948 V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
4949 DAG.getConstant(0, MVT::i64));
4951 if (V1.getValueType().getSizeInBits() == 128) {
4952 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
4953 DAG.getConstant(0, MVT::i64));
4955 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
4958 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
4959 /// the specified operations to build the shuffle.
4960 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
4961 SDValue RHS, SelectionDAG &DAG,
4963 unsigned OpNum = (PFEntry >> 26) & 0x0F;
4964 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
4965 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
4968 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
4977 OP_VUZPL, // VUZP, left result
4978 OP_VUZPR, // VUZP, right result
4979 OP_VZIPL, // VZIP, left result
4980 OP_VZIPR, // VZIP, right result
4981 OP_VTRNL, // VTRN, left result
4982 OP_VTRNR // VTRN, right result
4985 if (OpNum == OP_COPY) {
4986 if (LHSID == (1 * 9 + 2) * 9 + 3)
4988 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
4992 SDValue OpLHS, OpRHS;
4993 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
4994 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
4995 EVT VT = OpLHS.getValueType();
4999 llvm_unreachable("Unknown shuffle opcode!");
5001 // VREV divides the vector in half and swaps within the half.
5002 if (VT.getVectorElementType() == MVT::i32 ||
5003 VT.getVectorElementType() == MVT::f32)
5004 return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
5005 // vrev <4 x i16> -> REV32
5006 if (VT.getVectorElementType() == MVT::i16 ||
5007 VT.getVectorElementType() == MVT::f16)
5008 return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
5009 // vrev <4 x i8> -> REV16
5010 assert(VT.getVectorElementType() == MVT::i8);
5011 return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
5016 EVT EltTy = VT.getVectorElementType();
5018 if (EltTy == MVT::i8)
5019 Opcode = AArch64ISD::DUPLANE8;
5020 else if (EltTy == MVT::i16)
5021 Opcode = AArch64ISD::DUPLANE16;
5022 else if (EltTy == MVT::i32 || EltTy == MVT::f32)
5023 Opcode = AArch64ISD::DUPLANE32;
5024 else if (EltTy == MVT::i64 || EltTy == MVT::f64)
5025 Opcode = AArch64ISD::DUPLANE64;
5027 llvm_unreachable("Invalid vector element type?");
5029 if (VT.getSizeInBits() == 64)
5030 OpLHS = WidenVector(OpLHS, DAG);
5031 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, MVT::i64);
5032 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
5037 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
5038 return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
5039 DAG.getConstant(Imm, MVT::i32));
5042 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
5045 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
5048 return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
5051 return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
5054 return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
5057 return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
5062 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
5063 SelectionDAG &DAG) {
5064 // Check to see if we can use the TBL instruction.
5065 SDValue V1 = Op.getOperand(0);
5066 SDValue V2 = Op.getOperand(1);
5069 EVT EltVT = Op.getValueType().getVectorElementType();
5070 unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
5072 SmallVector<SDValue, 8> TBLMask;
5073 for (int Val : ShuffleMask) {
5074 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
5075 unsigned Offset = Byte + Val * BytesPerElt;
5076 TBLMask.push_back(DAG.getConstant(Offset, MVT::i32));
5080 MVT IndexVT = MVT::v8i8;
5081 unsigned IndexLen = 8;
5082 if (Op.getValueType().getSizeInBits() == 128) {
5083 IndexVT = MVT::v16i8;
5087 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
5088 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
5091 if (V2.getNode()->getOpcode() == ISD::UNDEF) {
5093 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
5094 Shuffle = DAG.getNode(
5095 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5096 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, MVT::i32), V1Cst,
5097 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5098 makeArrayRef(TBLMask.data(), IndexLen)));
5100 if (IndexLen == 8) {
5101 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
5102 Shuffle = DAG.getNode(
5103 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5104 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, MVT::i32), V1Cst,
5105 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5106 makeArrayRef(TBLMask.data(), IndexLen)));
5108 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
5109 // cannot currently represent the register constraints on the input
5111 // Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
5112 // DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5113 // &TBLMask[0], IndexLen));
5114 Shuffle = DAG.getNode(
5115 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5116 DAG.getConstant(Intrinsic::aarch64_neon_tbl2, MVT::i32), V1Cst, V2Cst,
5117 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5118 makeArrayRef(TBLMask.data(), IndexLen)));
5121 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
5124 static unsigned getDUPLANEOp(EVT EltType) {
5125 if (EltType == MVT::i8)
5126 return AArch64ISD::DUPLANE8;
5127 if (EltType == MVT::i16 || EltType == MVT::f16)
5128 return AArch64ISD::DUPLANE16;
5129 if (EltType == MVT::i32 || EltType == MVT::f32)
5130 return AArch64ISD::DUPLANE32;
5131 if (EltType == MVT::i64 || EltType == MVT::f64)
5132 return AArch64ISD::DUPLANE64;
5134 llvm_unreachable("Invalid vector element type?");
5137 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5138 SelectionDAG &DAG) const {
5140 EVT VT = Op.getValueType();
5142 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5144 // Convert shuffles that are directly supported on NEON to target-specific
5145 // DAG nodes, instead of keeping them as shuffles and matching them again
5146 // during code selection. This is more efficient and avoids the possibility
5147 // of inconsistencies between legalization and selection.
5148 ArrayRef<int> ShuffleMask = SVN->getMask();
5150 SDValue V1 = Op.getOperand(0);
5151 SDValue V2 = Op.getOperand(1);
5153 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0],
5154 V1.getValueType().getSimpleVT())) {
5155 int Lane = SVN->getSplatIndex();
5156 // If this is undef splat, generate it via "just" vdup, if possible.
5160 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
5161 return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
5163 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
5164 // constant. If so, we can just reference the lane's definition directly.
5165 if (V1.getOpcode() == ISD::BUILD_VECTOR &&
5166 !isa<ConstantSDNode>(V1.getOperand(Lane)))
5167 return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
5169 // Otherwise, duplicate from the lane of the input vector.
5170 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
5172 // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
5173 // to make a vector of the same size as this SHUFFLE. We can ignore the
5174 // extract entirely, and canonicalise the concat using WidenVector.
5175 if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
5176 Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
5177 V1 = V1.getOperand(0);
5178 } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
5179 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
5180 Lane -= Idx * VT.getVectorNumElements() / 2;
5181 V1 = WidenVector(V1.getOperand(Idx), DAG);
5182 } else if (VT.getSizeInBits() == 64)
5183 V1 = WidenVector(V1, DAG);
5185 return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, MVT::i64));
5188 if (isREVMask(ShuffleMask, VT, 64))
5189 return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
5190 if (isREVMask(ShuffleMask, VT, 32))
5191 return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
5192 if (isREVMask(ShuffleMask, VT, 16))
5193 return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
5195 bool ReverseEXT = false;
5197 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
5200 Imm *= getExtFactor(V1);
5201 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
5202 DAG.getConstant(Imm, MVT::i32));
5203 } else if (V2->getOpcode() == ISD::UNDEF &&
5204 isSingletonEXTMask(ShuffleMask, VT, Imm)) {
5205 Imm *= getExtFactor(V1);
5206 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
5207 DAG.getConstant(Imm, MVT::i32));
5210 unsigned WhichResult;
5211 if (isZIPMask(ShuffleMask, VT, WhichResult)) {
5212 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5213 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5215 if (isUZPMask(ShuffleMask, VT, WhichResult)) {
5216 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5217 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5219 if (isTRNMask(ShuffleMask, VT, WhichResult)) {
5220 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5221 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5224 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5225 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5226 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5228 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5229 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5230 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5232 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5233 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5234 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5237 SDValue Concat = tryFormConcatFromShuffle(Op, DAG);
5238 if (Concat.getNode())
5243 int NumInputElements = V1.getValueType().getVectorNumElements();
5244 if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
5245 SDValue DstVec = DstIsLeft ? V1 : V2;
5246 SDValue DstLaneV = DAG.getConstant(Anomaly, MVT::i64);
5248 SDValue SrcVec = V1;
5249 int SrcLane = ShuffleMask[Anomaly];
5250 if (SrcLane >= NumInputElements) {
5252 SrcLane -= VT.getVectorNumElements();
5254 SDValue SrcLaneV = DAG.getConstant(SrcLane, MVT::i64);
5256 EVT ScalarVT = VT.getVectorElementType();
5258 if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
5259 ScalarVT = MVT::i32;
5262 ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5263 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
5267 // If the shuffle is not directly supported and it has 4 elements, use
5268 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5269 unsigned NumElts = VT.getVectorNumElements();
5271 unsigned PFIndexes[4];
5272 for (unsigned i = 0; i != 4; ++i) {
5273 if (ShuffleMask[i] < 0)
5276 PFIndexes[i] = ShuffleMask[i];
5279 // Compute the index in the perfect shuffle table.
5280 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
5281 PFIndexes[2] * 9 + PFIndexes[3];
5282 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5283 unsigned Cost = (PFEntry >> 30);
5286 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5289 return GenerateTBL(Op, ShuffleMask, DAG);
5292 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
5294 EVT VT = BVN->getValueType(0);
5295 APInt SplatBits, SplatUndef;
5296 unsigned SplatBitSize;
5298 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5299 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
5301 for (unsigned i = 0; i < NumSplats; ++i) {
5302 CnstBits <<= SplatBitSize;
5303 UndefBits <<= SplatBitSize;
5304 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
5305 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
5314 SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op,
5315 SelectionDAG &DAG) const {
5316 BuildVectorSDNode *BVN =
5317 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5318 SDValue LHS = Op.getOperand(0);
5320 EVT VT = Op.getValueType();
5325 APInt CnstBits(VT.getSizeInBits(), 0);
5326 APInt UndefBits(VT.getSizeInBits(), 0);
5327 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5328 // We only have BIC vector immediate instruction, which is and-not.
5329 CnstBits = ~CnstBits;
5331 // We make use of a little bit of goto ickiness in order to avoid having to
5332 // duplicate the immediate matching logic for the undef toggled case.
5333 bool SecondTry = false;
5336 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5337 CnstBits = CnstBits.zextOrTrunc(64);
5338 uint64_t CnstVal = CnstBits.getZExtValue();
5340 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5341 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5342 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5343 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5344 DAG.getConstant(CnstVal, MVT::i32),
5345 DAG.getConstant(0, MVT::i32));
5346 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5349 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5350 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5351 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5352 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5353 DAG.getConstant(CnstVal, MVT::i32),
5354 DAG.getConstant(8, MVT::i32));
5355 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5358 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5359 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5360 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5361 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5362 DAG.getConstant(CnstVal, MVT::i32),
5363 DAG.getConstant(16, MVT::i32));
5364 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5367 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5368 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5369 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5370 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5371 DAG.getConstant(CnstVal, MVT::i32),
5372 DAG.getConstant(24, MVT::i32));
5373 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5376 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5377 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5378 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5379 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5380 DAG.getConstant(CnstVal, MVT::i32),
5381 DAG.getConstant(0, MVT::i32));
5382 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5385 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5386 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5387 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5388 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5389 DAG.getConstant(CnstVal, MVT::i32),
5390 DAG.getConstant(8, MVT::i32));
5391 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5398 CnstBits = ~UndefBits;
5402 // We can always fall back to a non-immediate AND.
5407 // Specialized code to quickly find if PotentialBVec is a BuildVector that
5408 // consists of only the same constant int value, returned in reference arg
5410 static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
5411 uint64_t &ConstVal) {
5412 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
5415 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
5418 EVT VT = Bvec->getValueType(0);
5419 unsigned NumElts = VT.getVectorNumElements();
5420 for (unsigned i = 1; i < NumElts; ++i)
5421 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
5423 ConstVal = FirstElt->getZExtValue();
5427 static unsigned getIntrinsicID(const SDNode *N) {
5428 unsigned Opcode = N->getOpcode();
5431 return Intrinsic::not_intrinsic;
5432 case ISD::INTRINSIC_WO_CHAIN: {
5433 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
5434 if (IID < Intrinsic::num_intrinsics)
5436 return Intrinsic::not_intrinsic;
5441 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
5442 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
5443 // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
5444 // Also, logical shift right -> sri, with the same structure.
5445 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
5446 EVT VT = N->getValueType(0);
5453 // Is the first op an AND?
5454 const SDValue And = N->getOperand(0);
5455 if (And.getOpcode() != ISD::AND)
5458 // Is the second op an shl or lshr?
5459 SDValue Shift = N->getOperand(1);
5460 // This will have been turned into: AArch64ISD::VSHL vector, #shift
5461 // or AArch64ISD::VLSHR vector, #shift
5462 unsigned ShiftOpc = Shift.getOpcode();
5463 if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
5465 bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
5467 // Is the shift amount constant?
5468 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
5472 // Is the and mask vector all constant?
5474 if (!isAllConstantBuildVector(And.getOperand(1), C1))
5477 // Is C1 == ~C2, taking into account how much one can shift elements of a
5479 uint64_t C2 = C2node->getZExtValue();
5480 unsigned ElemSizeInBits = VT.getVectorElementType().getSizeInBits();
5481 if (C2 > ElemSizeInBits)
5483 unsigned ElemMask = (1 << ElemSizeInBits) - 1;
5484 if ((C1 & ElemMask) != (~C2 & ElemMask))
5487 SDValue X = And.getOperand(0);
5488 SDValue Y = Shift.getOperand(0);
5491 IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
5493 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
5494 DAG.getConstant(Intrin, MVT::i32), X, Y, Shift.getOperand(1));
5496 DEBUG(dbgs() << "aarch64-lower: transformed: \n");
5497 DEBUG(N->dump(&DAG));
5498 DEBUG(dbgs() << "into: \n");
5499 DEBUG(ResultSLI->dump(&DAG));
5505 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
5506 SelectionDAG &DAG) const {
5507 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
5508 if (EnableAArch64SlrGeneration) {
5509 SDValue Res = tryLowerToSLI(Op.getNode(), DAG);
5514 BuildVectorSDNode *BVN =
5515 dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
5516 SDValue LHS = Op.getOperand(1);
5518 EVT VT = Op.getValueType();
5520 // OR commutes, so try swapping the operands.
5522 LHS = Op.getOperand(0);
5523 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5528 APInt CnstBits(VT.getSizeInBits(), 0);
5529 APInt UndefBits(VT.getSizeInBits(), 0);
5530 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5531 // We make use of a little bit of goto ickiness in order to avoid having to
5532 // duplicate the immediate matching logic for the undef toggled case.
5533 bool SecondTry = false;
5536 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5537 CnstBits = CnstBits.zextOrTrunc(64);
5538 uint64_t CnstVal = CnstBits.getZExtValue();
5540 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5541 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5542 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5543 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5544 DAG.getConstant(CnstVal, MVT::i32),
5545 DAG.getConstant(0, MVT::i32));
5546 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5549 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5550 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5551 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5552 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5553 DAG.getConstant(CnstVal, MVT::i32),
5554 DAG.getConstant(8, MVT::i32));
5555 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5558 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5559 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5560 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5561 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5562 DAG.getConstant(CnstVal, MVT::i32),
5563 DAG.getConstant(16, MVT::i32));
5564 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5567 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5568 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5569 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5570 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5571 DAG.getConstant(CnstVal, MVT::i32),
5572 DAG.getConstant(24, MVT::i32));
5573 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5576 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5577 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5578 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5579 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5580 DAG.getConstant(CnstVal, MVT::i32),
5581 DAG.getConstant(0, MVT::i32));
5582 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5585 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5586 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5587 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5588 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5589 DAG.getConstant(CnstVal, MVT::i32),
5590 DAG.getConstant(8, MVT::i32));
5591 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5598 CnstBits = UndefBits;
5602 // We can always fall back to a non-immediate OR.
5607 // Normalize the operands of BUILD_VECTOR. The value of constant operands will
5608 // be truncated to fit element width.
5609 static SDValue NormalizeBuildVector(SDValue Op,
5610 SelectionDAG &DAG) {
5611 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
5613 EVT VT = Op.getValueType();
5614 EVT EltTy= VT.getVectorElementType();
5616 if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
5619 SmallVector<SDValue, 16> Ops;
5620 for (unsigned I = 0, E = VT.getVectorNumElements(); I != E; ++I) {
5621 SDValue Lane = Op.getOperand(I);
5622 if (Lane.getOpcode() == ISD::Constant) {
5623 APInt LowBits(EltTy.getSizeInBits(),
5624 cast<ConstantSDNode>(Lane)->getZExtValue());
5625 Lane = DAG.getConstant(LowBits.getZExtValue(), MVT::i32);
5627 Ops.push_back(Lane);
5629 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5632 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
5633 SelectionDAG &DAG) const {
5635 EVT VT = Op.getValueType();
5636 Op = NormalizeBuildVector(Op, DAG);
5637 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5639 APInt CnstBits(VT.getSizeInBits(), 0);
5640 APInt UndefBits(VT.getSizeInBits(), 0);
5641 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5642 // We make use of a little bit of goto ickiness in order to avoid having to
5643 // duplicate the immediate matching logic for the undef toggled case.
5644 bool SecondTry = false;
5647 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5648 CnstBits = CnstBits.zextOrTrunc(64);
5649 uint64_t CnstVal = CnstBits.getZExtValue();
5651 // Certain magic vector constants (used to express things like NOT
5652 // and NEG) are passed through unmodified. This allows codegen patterns
5653 // for these operations to match. Special-purpose patterns will lower
5654 // these immediates to MOVIs if it proves necessary.
5655 if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL))
5658 // The many faces of MOVI...
5659 if (AArch64_AM::isAdvSIMDModImmType10(CnstVal)) {
5660 CnstVal = AArch64_AM::encodeAdvSIMDModImmType10(CnstVal);
5661 if (VT.getSizeInBits() == 128) {
5662 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::v2i64,
5663 DAG.getConstant(CnstVal, MVT::i32));
5664 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5667 // Support the V64 version via subregister insertion.
5668 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::f64,
5669 DAG.getConstant(CnstVal, MVT::i32));
5670 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5673 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5674 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5675 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5676 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5677 DAG.getConstant(CnstVal, MVT::i32),
5678 DAG.getConstant(0, MVT::i32));
5679 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5682 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5683 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5684 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5685 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5686 DAG.getConstant(CnstVal, MVT::i32),
5687 DAG.getConstant(8, MVT::i32));
5688 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5691 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5692 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5693 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5694 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5695 DAG.getConstant(CnstVal, MVT::i32),
5696 DAG.getConstant(16, MVT::i32));
5697 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5700 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5701 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5702 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5703 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5704 DAG.getConstant(CnstVal, MVT::i32),
5705 DAG.getConstant(24, MVT::i32));
5706 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5709 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5710 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5711 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5712 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5713 DAG.getConstant(CnstVal, MVT::i32),
5714 DAG.getConstant(0, MVT::i32));
5715 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5718 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5719 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5720 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5721 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5722 DAG.getConstant(CnstVal, MVT::i32),
5723 DAG.getConstant(8, MVT::i32));
5724 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5727 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
5728 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
5729 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5730 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
5731 DAG.getConstant(CnstVal, MVT::i32),
5732 DAG.getConstant(264, MVT::i32));
5733 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5736 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
5737 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
5738 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5739 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
5740 DAG.getConstant(CnstVal, MVT::i32),
5741 DAG.getConstant(272, MVT::i32));
5742 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5745 if (AArch64_AM::isAdvSIMDModImmType9(CnstVal)) {
5746 CnstVal = AArch64_AM::encodeAdvSIMDModImmType9(CnstVal);
5747 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
5748 SDValue Mov = DAG.getNode(AArch64ISD::MOVI, dl, MovTy,
5749 DAG.getConstant(CnstVal, MVT::i32));
5750 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5753 // The few faces of FMOV...
5754 if (AArch64_AM::isAdvSIMDModImmType11(CnstVal)) {
5755 CnstVal = AArch64_AM::encodeAdvSIMDModImmType11(CnstVal);
5756 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32;
5757 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MovTy,
5758 DAG.getConstant(CnstVal, MVT::i32));
5759 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5762 if (AArch64_AM::isAdvSIMDModImmType12(CnstVal) &&
5763 VT.getSizeInBits() == 128) {
5764 CnstVal = AArch64_AM::encodeAdvSIMDModImmType12(CnstVal);
5765 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MVT::v2f64,
5766 DAG.getConstant(CnstVal, MVT::i32));
5767 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5770 // The many faces of MVNI...
5772 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5773 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5774 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5775 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
5776 DAG.getConstant(CnstVal, MVT::i32),
5777 DAG.getConstant(0, MVT::i32));
5778 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5781 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5782 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5783 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5784 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
5785 DAG.getConstant(CnstVal, MVT::i32),
5786 DAG.getConstant(8, MVT::i32));
5787 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5790 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5791 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5792 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5793 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
5794 DAG.getConstant(CnstVal, MVT::i32),
5795 DAG.getConstant(16, MVT::i32));
5796 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5799 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5800 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5801 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5802 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
5803 DAG.getConstant(CnstVal, MVT::i32),
5804 DAG.getConstant(24, MVT::i32));
5805 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5808 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5809 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5810 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5811 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
5812 DAG.getConstant(CnstVal, MVT::i32),
5813 DAG.getConstant(0, MVT::i32));
5814 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5817 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5818 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5819 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5820 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
5821 DAG.getConstant(CnstVal, MVT::i32),
5822 DAG.getConstant(8, MVT::i32));
5823 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5826 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
5827 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
5828 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5829 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
5830 DAG.getConstant(CnstVal, MVT::i32),
5831 DAG.getConstant(264, MVT::i32));
5832 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5835 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
5836 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
5837 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5838 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
5839 DAG.getConstant(CnstVal, MVT::i32),
5840 DAG.getConstant(272, MVT::i32));
5841 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5848 CnstBits = UndefBits;
5853 // Scan through the operands to find some interesting properties we can
5855 // 1) If only one value is used, we can use a DUP, or
5856 // 2) if only the low element is not undef, we can just insert that, or
5857 // 3) if only one constant value is used (w/ some non-constant lanes),
5858 // we can splat the constant value into the whole vector then fill
5859 // in the non-constant lanes.
5860 // 4) FIXME: If different constant values are used, but we can intelligently
5861 // select the values we'll be overwriting for the non-constant
5862 // lanes such that we can directly materialize the vector
5863 // some other way (MOVI, e.g.), we can be sneaky.
5864 unsigned NumElts = VT.getVectorNumElements();
5865 bool isOnlyLowElement = true;
5866 bool usesOnlyOneValue = true;
5867 bool usesOnlyOneConstantValue = true;
5868 bool isConstant = true;
5869 unsigned NumConstantLanes = 0;
5871 SDValue ConstantValue;
5872 for (unsigned i = 0; i < NumElts; ++i) {
5873 SDValue V = Op.getOperand(i);
5874 if (V.getOpcode() == ISD::UNDEF)
5877 isOnlyLowElement = false;
5878 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5881 if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
5883 if (!ConstantValue.getNode())
5885 else if (ConstantValue != V)
5886 usesOnlyOneConstantValue = false;
5889 if (!Value.getNode())
5891 else if (V != Value)
5892 usesOnlyOneValue = false;
5895 if (!Value.getNode())
5896 return DAG.getUNDEF(VT);
5898 if (isOnlyLowElement)
5899 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5901 // Use DUP for non-constant splats. For f32 constant splats, reduce to
5902 // i32 and try again.
5903 if (usesOnlyOneValue) {
5905 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5906 Value.getValueType() != VT)
5907 return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
5909 // This is actually a DUPLANExx operation, which keeps everything vectory.
5911 // DUPLANE works on 128-bit vectors, widen it if necessary.
5912 SDValue Lane = Value.getOperand(1);
5913 Value = Value.getOperand(0);
5914 if (Value.getValueType().getSizeInBits() == 64)
5915 Value = WidenVector(Value, DAG);
5917 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
5918 return DAG.getNode(Opcode, dl, VT, Value, Lane);
5921 if (VT.getVectorElementType().isFloatingPoint()) {
5922 SmallVector<SDValue, 8> Ops;
5924 (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
5925 for (unsigned i = 0; i < NumElts; ++i)
5926 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
5927 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
5928 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5929 Val = LowerBUILD_VECTOR(Val, DAG);
5931 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5935 // If there was only one constant value used and for more than one lane,
5936 // start by splatting that value, then replace the non-constant lanes. This
5937 // is better than the default, which will perform a separate initialization
5939 if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
5940 SDValue Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
5941 // Now insert the non-constant lanes.
5942 for (unsigned i = 0; i < NumElts; ++i) {
5943 SDValue V = Op.getOperand(i);
5944 SDValue LaneIdx = DAG.getConstant(i, MVT::i64);
5945 if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) {
5946 // Note that type legalization likely mucked about with the VT of the
5947 // source operand, so we may have to convert it here before inserting.
5948 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
5954 // If all elements are constants and the case above didn't get hit, fall back
5955 // to the default expansion, which will generate a load from the constant
5960 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5962 SDValue shuffle = ReconstructShuffle(Op, DAG);
5963 if (shuffle != SDValue())
5967 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5968 // know the default expansion would otherwise fall back on something even
5969 // worse. For a vector with one or two non-undef values, that's
5970 // scalar_to_vector for the elements followed by a shuffle (provided the
5971 // shuffle is valid for the target) and materialization element by element
5972 // on the stack followed by a load for everything else.
5973 if (!isConstant && !usesOnlyOneValue) {
5974 SDValue Vec = DAG.getUNDEF(VT);
5975 SDValue Op0 = Op.getOperand(0);
5976 unsigned ElemSize = VT.getVectorElementType().getSizeInBits();
5978 // For 32 and 64 bit types, use INSERT_SUBREG for lane zero to
5979 // a) Avoid a RMW dependency on the full vector register, and
5980 // b) Allow the register coalescer to fold away the copy if the
5981 // value is already in an S or D register.
5982 if (Op0.getOpcode() != ISD::UNDEF && (ElemSize == 32 || ElemSize == 64)) {
5983 unsigned SubIdx = ElemSize == 32 ? AArch64::ssub : AArch64::dsub;
5985 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl, VT, Vec, Op0,
5986 DAG.getTargetConstant(SubIdx, MVT::i32));
5987 Vec = SDValue(N, 0);
5990 for (; i < NumElts; ++i) {
5991 SDValue V = Op.getOperand(i);
5992 if (V.getOpcode() == ISD::UNDEF)
5994 SDValue LaneIdx = DAG.getConstant(i, MVT::i64);
5995 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6000 // Just use the default expansion. We failed to find a better alternative.
6004 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
6005 SelectionDAG &DAG) const {
6006 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
6008 // Check for non-constant or out of range lane.
6009 EVT VT = Op.getOperand(0).getValueType();
6010 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
6011 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
6015 // Insertion/extraction are legal for V128 types.
6016 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
6017 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6021 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
6022 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
6025 // For V64 types, we perform insertion by expanding the value
6026 // to a V128 type and perform the insertion on that.
6028 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6029 EVT WideTy = WideVec.getValueType();
6031 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
6032 Op.getOperand(1), Op.getOperand(2));
6033 // Re-narrow the resultant vector.
6034 return NarrowVector(Node, DAG);
6038 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6039 SelectionDAG &DAG) const {
6040 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
6042 // Check for non-constant or out of range lane.
6043 EVT VT = Op.getOperand(0).getValueType();
6044 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6045 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
6049 // Insertion/extraction are legal for V128 types.
6050 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
6051 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6055 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
6056 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
6059 // For V64 types, we perform extraction by expanding the value
6060 // to a V128 type and perform the extraction on that.
6062 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6063 EVT WideTy = WideVec.getValueType();
6065 EVT ExtrTy = WideTy.getVectorElementType();
6066 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
6069 // For extractions, we just return the result directly.
6070 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
6074 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
6075 SelectionDAG &DAG) const {
6076 EVT VT = Op.getOperand(0).getValueType();
6082 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6085 unsigned Val = Cst->getZExtValue();
6087 unsigned Size = Op.getValueType().getSizeInBits();
6091 return DAG.getTargetExtractSubreg(AArch64::bsub, dl, Op.getValueType(),
6094 return DAG.getTargetExtractSubreg(AArch64::hsub, dl, Op.getValueType(),
6097 return DAG.getTargetExtractSubreg(AArch64::ssub, dl, Op.getValueType(),
6100 return DAG.getTargetExtractSubreg(AArch64::dsub, dl, Op.getValueType(),
6103 llvm_unreachable("Unexpected vector type in extract_subvector!");
6106 // If this is extracting the upper 64-bits of a 128-bit vector, we match
6108 if (Size == 64 && Val * VT.getVectorElementType().getSizeInBits() == 64)
6114 bool AArch64TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
6116 if (VT.getVectorNumElements() == 4 &&
6117 (VT.is128BitVector() || VT.is64BitVector())) {
6118 unsigned PFIndexes[4];
6119 for (unsigned i = 0; i != 4; ++i) {
6123 PFIndexes[i] = M[i];
6126 // Compute the index in the perfect shuffle table.
6127 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6128 PFIndexes[2] * 9 + PFIndexes[3];
6129 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6130 unsigned Cost = (PFEntry >> 30);
6138 unsigned DummyUnsigned;
6140 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
6141 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
6142 isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
6143 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
6144 isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
6145 isZIPMask(M, VT, DummyUnsigned) ||
6146 isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
6147 isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
6148 isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
6149 isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
6150 isConcatMask(M, VT, VT.getSizeInBits() == 128));
6153 /// getVShiftImm - Check if this is a valid build_vector for the immediate
6154 /// operand of a vector shift operation, where all the elements of the
6155 /// build_vector must have the same constant integer value.
6156 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
6157 // Ignore bit_converts.
6158 while (Op.getOpcode() == ISD::BITCAST)
6159 Op = Op.getOperand(0);
6160 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6161 APInt SplatBits, SplatUndef;
6162 unsigned SplatBitSize;
6164 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
6165 HasAnyUndefs, ElementBits) ||
6166 SplatBitSize > ElementBits)
6168 Cnt = SplatBits.getSExtValue();
6172 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
6173 /// operand of a vector shift left operation. That value must be in the range:
6174 /// 0 <= Value < ElementBits for a left shift; or
6175 /// 0 <= Value <= ElementBits for a long left shift.
6176 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
6177 assert(VT.isVector() && "vector shift count is not a vector type");
6178 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
6179 if (!getVShiftImm(Op, ElementBits, Cnt))
6181 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
6184 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
6185 /// operand of a vector shift right operation. For a shift opcode, the value
6186 /// is positive, but for an intrinsic the value count must be negative. The
6187 /// absolute value must be in the range:
6188 /// 1 <= |Value| <= ElementBits for a right shift; or
6189 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
6190 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
6192 assert(VT.isVector() && "vector shift count is not a vector type");
6193 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
6194 if (!getVShiftImm(Op, ElementBits, Cnt))
6198 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
6201 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
6202 SelectionDAG &DAG) const {
6203 EVT VT = Op.getValueType();
6207 if (!Op.getOperand(1).getValueType().isVector())
6209 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6211 switch (Op.getOpcode()) {
6213 llvm_unreachable("unexpected shift opcode");
6216 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
6217 return DAG.getNode(AArch64ISD::VSHL, SDLoc(Op), VT, Op.getOperand(0),
6218 DAG.getConstant(Cnt, MVT::i32));
6219 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
6220 DAG.getConstant(Intrinsic::aarch64_neon_ushl, MVT::i32),
6221 Op.getOperand(0), Op.getOperand(1));
6224 // Right shift immediate
6225 if (isVShiftRImm(Op.getOperand(1), VT, false, false, Cnt) &&
6228 (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
6229 return DAG.getNode(Opc, SDLoc(Op), VT, Op.getOperand(0),
6230 DAG.getConstant(Cnt, MVT::i32));
6233 // Right shift register. Note, there is not a shift right register
6234 // instruction, but the shift left register instruction takes a signed
6235 // value, where negative numbers specify a right shift.
6236 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
6237 : Intrinsic::aarch64_neon_ushl;
6238 // negate the shift amount
6239 SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
6240 SDValue NegShiftLeft =
6241 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
6242 DAG.getConstant(Opc, MVT::i32), Op.getOperand(0), NegShift);
6243 return NegShiftLeft;
6249 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
6250 AArch64CC::CondCode CC, bool NoNans, EVT VT,
6251 SDLoc dl, SelectionDAG &DAG) {
6252 EVT SrcVT = LHS.getValueType();
6253 assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
6254 "function only supposed to emit natural comparisons");
6256 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
6257 APInt CnstBits(VT.getSizeInBits(), 0);
6258 APInt UndefBits(VT.getSizeInBits(), 0);
6259 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
6260 bool IsZero = IsCnst && (CnstBits == 0);
6262 if (SrcVT.getVectorElementType().isFloatingPoint()) {
6266 case AArch64CC::NE: {
6269 Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6271 Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6272 return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
6276 return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6277 return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6280 return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
6281 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
6284 return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
6285 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
6288 return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
6289 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
6293 // If we ignore NaNs then we can use to the MI implementation.
6297 return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
6298 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
6305 case AArch64CC::NE: {
6308 Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6310 Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6311 return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
6315 return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6316 return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6319 return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
6320 return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
6323 return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
6324 return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
6327 return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
6328 return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
6330 return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
6332 return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
6335 return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
6336 return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
6338 return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
6340 return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
6344 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
6345 SelectionDAG &DAG) const {
6346 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6347 SDValue LHS = Op.getOperand(0);
6348 SDValue RHS = Op.getOperand(1);
6349 EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
6352 if (LHS.getValueType().getVectorElementType().isInteger()) {
6353 assert(LHS.getValueType() == RHS.getValueType());
6354 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
6356 EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
6357 return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
6360 assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
6361 LHS.getValueType().getVectorElementType() == MVT::f64);
6363 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
6364 // clean. Some of them require two branches to implement.
6365 AArch64CC::CondCode CC1, CC2;
6367 changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
6369 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
6371 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
6375 if (CC2 != AArch64CC::AL) {
6377 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
6378 if (!Cmp2.getNode())
6381 Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
6384 Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
6387 return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
6392 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
6393 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
6394 /// specified in the intrinsic calls.
6395 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
6397 unsigned Intrinsic) const {
6398 switch (Intrinsic) {
6399 case Intrinsic::aarch64_neon_ld2:
6400 case Intrinsic::aarch64_neon_ld3:
6401 case Intrinsic::aarch64_neon_ld4:
6402 case Intrinsic::aarch64_neon_ld1x2:
6403 case Intrinsic::aarch64_neon_ld1x3:
6404 case Intrinsic::aarch64_neon_ld1x4:
6405 case Intrinsic::aarch64_neon_ld2lane:
6406 case Intrinsic::aarch64_neon_ld3lane:
6407 case Intrinsic::aarch64_neon_ld4lane:
6408 case Intrinsic::aarch64_neon_ld2r:
6409 case Intrinsic::aarch64_neon_ld3r:
6410 case Intrinsic::aarch64_neon_ld4r: {
6411 Info.opc = ISD::INTRINSIC_W_CHAIN;
6412 // Conservatively set memVT to the entire set of vectors loaded.
6413 uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
6414 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6415 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6418 Info.vol = false; // volatile loads with NEON intrinsics not supported
6419 Info.readMem = true;
6420 Info.writeMem = false;
6423 case Intrinsic::aarch64_neon_st2:
6424 case Intrinsic::aarch64_neon_st3:
6425 case Intrinsic::aarch64_neon_st4:
6426 case Intrinsic::aarch64_neon_st1x2:
6427 case Intrinsic::aarch64_neon_st1x3:
6428 case Intrinsic::aarch64_neon_st1x4:
6429 case Intrinsic::aarch64_neon_st2lane:
6430 case Intrinsic::aarch64_neon_st3lane:
6431 case Intrinsic::aarch64_neon_st4lane: {
6432 Info.opc = ISD::INTRINSIC_VOID;
6433 // Conservatively set memVT to the entire set of vectors stored.
6434 unsigned NumElts = 0;
6435 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
6436 Type *ArgTy = I.getArgOperand(ArgI)->getType();
6437 if (!ArgTy->isVectorTy())
6439 NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
6441 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6442 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6445 Info.vol = false; // volatile stores with NEON intrinsics not supported
6446 Info.readMem = false;
6447 Info.writeMem = true;
6450 case Intrinsic::aarch64_ldaxr:
6451 case Intrinsic::aarch64_ldxr: {
6452 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
6453 Info.opc = ISD::INTRINSIC_W_CHAIN;
6454 Info.memVT = MVT::getVT(PtrTy->getElementType());
6455 Info.ptrVal = I.getArgOperand(0);
6457 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
6459 Info.readMem = true;
6460 Info.writeMem = false;
6463 case Intrinsic::aarch64_stlxr:
6464 case Intrinsic::aarch64_stxr: {
6465 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
6466 Info.opc = ISD::INTRINSIC_W_CHAIN;
6467 Info.memVT = MVT::getVT(PtrTy->getElementType());
6468 Info.ptrVal = I.getArgOperand(1);
6470 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
6472 Info.readMem = false;
6473 Info.writeMem = true;
6476 case Intrinsic::aarch64_ldaxp:
6477 case Intrinsic::aarch64_ldxp: {
6478 Info.opc = ISD::INTRINSIC_W_CHAIN;
6479 Info.memVT = MVT::i128;
6480 Info.ptrVal = I.getArgOperand(0);
6484 Info.readMem = true;
6485 Info.writeMem = false;
6488 case Intrinsic::aarch64_stlxp:
6489 case Intrinsic::aarch64_stxp: {
6490 Info.opc = ISD::INTRINSIC_W_CHAIN;
6491 Info.memVT = MVT::i128;
6492 Info.ptrVal = I.getArgOperand(2);
6496 Info.readMem = false;
6497 Info.writeMem = true;
6507 // Truncations from 64-bit GPR to 32-bit GPR is free.
6508 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
6509 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6511 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6512 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6513 return NumBits1 > NumBits2;
6515 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
6516 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
6518 unsigned NumBits1 = VT1.getSizeInBits();
6519 unsigned NumBits2 = VT2.getSizeInBits();
6520 return NumBits1 > NumBits2;
6523 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
6525 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
6526 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6528 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6529 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6530 return NumBits1 == 32 && NumBits2 == 64;
6532 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
6533 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
6535 unsigned NumBits1 = VT1.getSizeInBits();
6536 unsigned NumBits2 = VT2.getSizeInBits();
6537 return NumBits1 == 32 && NumBits2 == 64;
6540 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
6541 EVT VT1 = Val.getValueType();
6542 if (isZExtFree(VT1, VT2)) {
6546 if (Val.getOpcode() != ISD::LOAD)
6549 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
6550 return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
6551 VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
6552 VT1.getSizeInBits() <= 32);
6555 bool AArch64TargetLowering::hasPairedLoad(Type *LoadedType,
6556 unsigned &RequiredAligment) const {
6557 if (!LoadedType->isIntegerTy() && !LoadedType->isFloatTy())
6559 // Cyclone supports unaligned accesses.
6560 RequiredAligment = 0;
6561 unsigned NumBits = LoadedType->getPrimitiveSizeInBits();
6562 return NumBits == 32 || NumBits == 64;
6565 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
6566 unsigned &RequiredAligment) const {
6567 if (!LoadedType.isSimple() ||
6568 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
6570 // Cyclone supports unaligned accesses.
6571 RequiredAligment = 0;
6572 unsigned NumBits = LoadedType.getSizeInBits();
6573 return NumBits == 32 || NumBits == 64;
6576 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
6577 unsigned AlignCheck) {
6578 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
6579 (DstAlign == 0 || DstAlign % AlignCheck == 0));
6582 EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
6583 unsigned SrcAlign, bool IsMemset,
6586 MachineFunction &MF) const {
6587 // Don't use AdvSIMD to implement 16-byte memset. It would have taken one
6588 // instruction to materialize the v2i64 zero and one store (with restrictive
6589 // addressing mode). Just do two i64 store of zero-registers.
6591 const Function *F = MF.getFunction();
6592 if (Subtarget->hasFPARMv8() && !IsMemset && Size >= 16 &&
6593 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
6594 Attribute::NoImplicitFloat) &&
6595 (memOpAlign(SrcAlign, DstAlign, 16) ||
6596 (allowsMisalignedMemoryAccesses(MVT::f128, 0, 1, &Fast) && Fast)))
6599 return Size >= 8 ? MVT::i64 : MVT::i32;
6602 // 12-bit optionally shifted immediates are legal for adds.
6603 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
6604 if ((Immed >> 12) == 0 || ((Immed & 0xfff) == 0 && Immed >> 24 == 0))
6609 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
6610 // immediates is the same as for an add or a sub.
6611 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
6614 return isLegalAddImmediate(Immed);
6617 /// isLegalAddressingMode - Return true if the addressing mode represented
6618 /// by AM is legal for this target, for a load/store of the specified type.
6619 bool AArch64TargetLowering::isLegalAddressingMode(const AddrMode &AM,
6621 // AArch64 has five basic addressing modes:
6623 // reg + 9-bit signed offset
6624 // reg + SIZE_IN_BYTES * 12-bit unsigned offset
6626 // reg + SIZE_IN_BYTES * reg
6628 // No global is ever allowed as a base.
6632 // No reg+reg+imm addressing.
6633 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
6636 // check reg + imm case:
6637 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
6638 uint64_t NumBytes = 0;
6639 if (Ty->isSized()) {
6640 uint64_t NumBits = getDataLayout()->getTypeSizeInBits(Ty);
6641 NumBytes = NumBits / 8;
6642 if (!isPowerOf2_64(NumBits))
6647 int64_t Offset = AM.BaseOffs;
6649 // 9-bit signed offset
6650 if (Offset >= -(1LL << 9) && Offset <= (1LL << 9) - 1)
6653 // 12-bit unsigned offset
6654 unsigned shift = Log2_64(NumBytes);
6655 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
6656 // Must be a multiple of NumBytes (NumBytes is a power of 2)
6657 (Offset >> shift) << shift == Offset)
6662 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
6664 if (!AM.Scale || AM.Scale == 1 ||
6665 (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes))
6670 int AArch64TargetLowering::getScalingFactorCost(const AddrMode &AM,
6672 // Scaling factors are not free at all.
6673 // Operands | Rt Latency
6674 // -------------------------------------------
6676 // -------------------------------------------
6677 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5
6678 // Rt, [Xn, Wm, <extend> #imm] |
6679 if (isLegalAddressingMode(AM, Ty))
6680 // Scale represents reg2 * scale, thus account for 1 if
6681 // it is not equal to 0 or 1.
6682 return AM.Scale != 0 && AM.Scale != 1;
6686 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
6687 VT = VT.getScalarType();
6692 switch (VT.getSimpleVT().SimpleTy) {
6704 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
6705 // LR is a callee-save register, but we must treat it as clobbered by any call
6706 // site. Hence we include LR in the scratch registers, which are in turn added
6707 // as implicit-defs for stackmaps and patchpoints.
6708 static const MCPhysReg ScratchRegs[] = {
6709 AArch64::X16, AArch64::X17, AArch64::LR, 0
6715 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N) const {
6716 EVT VT = N->getValueType(0);
6717 // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
6718 // it with shift to let it be lowered to UBFX.
6719 if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
6720 isa<ConstantSDNode>(N->getOperand(1))) {
6721 uint64_t TruncMask = N->getConstantOperandVal(1);
6722 if (isMask_64(TruncMask) &&
6723 N->getOperand(0).getOpcode() == ISD::SRL &&
6724 isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
6730 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
6732 assert(Ty->isIntegerTy());
6734 unsigned BitSize = Ty->getPrimitiveSizeInBits();
6738 int64_t Val = Imm.getSExtValue();
6739 if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
6742 if ((int64_t)Val < 0)
6745 Val &= (1LL << 32) - 1;
6747 unsigned LZ = countLeadingZeros((uint64_t)Val);
6748 unsigned Shift = (63 - LZ) / 16;
6749 // MOVZ is free so return true for one or fewer MOVK.
6750 return (Shift < 3) ? true : false;
6753 // Generate SUBS and CSEL for integer abs.
6754 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
6755 EVT VT = N->getValueType(0);
6757 SDValue N0 = N->getOperand(0);
6758 SDValue N1 = N->getOperand(1);
6761 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
6762 // and change it to SUB and CSEL.
6763 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
6764 N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
6765 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
6766 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
6767 if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
6768 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, VT),
6770 // Generate SUBS & CSEL.
6772 DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
6773 N0.getOperand(0), DAG.getConstant(0, VT));
6774 return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
6775 DAG.getConstant(AArch64CC::PL, MVT::i32),
6776 SDValue(Cmp.getNode(), 1));
6781 // performXorCombine - Attempts to handle integer ABS.
6782 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
6783 TargetLowering::DAGCombinerInfo &DCI,
6784 const AArch64Subtarget *Subtarget) {
6785 if (DCI.isBeforeLegalizeOps())
6788 return performIntegerAbsCombine(N, DAG);
6792 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
6794 std::vector<SDNode *> *Created) const {
6795 // fold (sdiv X, pow2)
6796 EVT VT = N->getValueType(0);
6797 if ((VT != MVT::i32 && VT != MVT::i64) ||
6798 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
6802 SDValue N0 = N->getOperand(0);
6803 unsigned Lg2 = Divisor.countTrailingZeros();
6804 SDValue Zero = DAG.getConstant(0, VT);
6805 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, VT);
6807 // Add (N0 < 0) ? Pow2 - 1 : 0;
6809 SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
6810 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
6811 SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
6814 Created->push_back(Cmp.getNode());
6815 Created->push_back(Add.getNode());
6816 Created->push_back(CSel.getNode());
6821 DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, MVT::i64));
6823 // If we're dividing by a positive value, we're done. Otherwise, we must
6824 // negate the result.
6825 if (Divisor.isNonNegative())
6829 Created->push_back(SRA.getNode());
6830 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, VT), SRA);
6833 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
6834 TargetLowering::DAGCombinerInfo &DCI,
6835 const AArch64Subtarget *Subtarget) {
6836 if (DCI.isBeforeLegalizeOps())
6839 // Multiplication of a power of two plus/minus one can be done more
6840 // cheaply as as shift+add/sub. For now, this is true unilaterally. If
6841 // future CPUs have a cheaper MADD instruction, this may need to be
6842 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
6843 // 64-bit is 5 cycles, so this is always a win.
6844 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
6845 APInt Value = C->getAPIntValue();
6846 EVT VT = N->getValueType(0);
6847 if (Value.isNonNegative()) {
6848 // (mul x, 2^N + 1) => (add (shl x, N), x)
6849 APInt VM1 = Value - 1;
6850 if (VM1.isPowerOf2()) {
6851 SDValue ShiftedVal =
6852 DAG.getNode(ISD::SHL, SDLoc(N), VT, N->getOperand(0),
6853 DAG.getConstant(VM1.logBase2(), MVT::i64));
6854 return DAG.getNode(ISD::ADD, SDLoc(N), VT, ShiftedVal,
6857 // (mul x, 2^N - 1) => (sub (shl x, N), x)
6858 APInt VP1 = Value + 1;
6859 if (VP1.isPowerOf2()) {
6860 SDValue ShiftedVal =
6861 DAG.getNode(ISD::SHL, SDLoc(N), VT, N->getOperand(0),
6862 DAG.getConstant(VP1.logBase2(), MVT::i64));
6863 return DAG.getNode(ISD::SUB, SDLoc(N), VT, ShiftedVal,
6867 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
6868 APInt VNM1 = -Value - 1;
6869 if (VNM1.isPowerOf2()) {
6870 SDValue ShiftedVal =
6871 DAG.getNode(ISD::SHL, SDLoc(N), VT, N->getOperand(0),
6872 DAG.getConstant(VNM1.logBase2(), MVT::i64));
6874 DAG.getNode(ISD::ADD, SDLoc(N), VT, ShiftedVal, N->getOperand(0));
6875 return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), Add);
6877 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
6878 APInt VNP1 = -Value + 1;
6879 if (VNP1.isPowerOf2()) {
6880 SDValue ShiftedVal =
6881 DAG.getNode(ISD::SHL, SDLoc(N), VT, N->getOperand(0),
6882 DAG.getConstant(VNP1.logBase2(), MVT::i64));
6883 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N->getOperand(0),
6891 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
6892 SelectionDAG &DAG) {
6893 // Take advantage of vector comparisons producing 0 or -1 in each lane to
6894 // optimize away operation when it's from a constant.
6896 // The general transformation is:
6897 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
6898 // AND(VECTOR_CMP(x,y), constant2)
6899 // constant2 = UNARYOP(constant)
6901 // Early exit if this isn't a vector operation, the operand of the
6902 // unary operation isn't a bitwise AND, or if the sizes of the operations
6904 EVT VT = N->getValueType(0);
6905 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
6906 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
6907 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
6910 // Now check that the other operand of the AND is a constant. We could
6911 // make the transformation for non-constant splats as well, but it's unclear
6912 // that would be a benefit as it would not eliminate any operations, just
6913 // perform one more step in scalar code before moving to the vector unit.
6914 if (BuildVectorSDNode *BV =
6915 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
6916 // Bail out if the vector isn't a constant.
6917 if (!BV->isConstant())
6920 // Everything checks out. Build up the new and improved node.
6922 EVT IntVT = BV->getValueType(0);
6923 // Create a new constant of the appropriate type for the transformed
6925 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
6926 // The AND node needs bitcasts to/from an integer vector type around it.
6927 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
6928 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
6929 N->getOperand(0)->getOperand(0), MaskConst);
6930 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
6937 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
6938 const AArch64Subtarget *Subtarget) {
6939 // First try to optimize away the conversion when it's conditionally from
6940 // a constant. Vectors only.
6941 SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
6942 if (Res != SDValue())
6945 EVT VT = N->getValueType(0);
6946 if (VT != MVT::f32 && VT != MVT::f64)
6949 // Only optimize when the source and destination types have the same width.
6950 if (VT.getSizeInBits() != N->getOperand(0).getValueType().getSizeInBits())
6953 // If the result of an integer load is only used by an integer-to-float
6954 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
6955 // This eliminates an "integer-to-vector-move UOP and improve throughput.
6956 SDValue N0 = N->getOperand(0);
6957 if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6958 // Do not change the width of a volatile load.
6959 !cast<LoadSDNode>(N0)->isVolatile()) {
6960 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6961 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
6962 LN0->getPointerInfo(), LN0->isVolatile(),
6963 LN0->isNonTemporal(), LN0->isInvariant(),
6964 LN0->getAlignment());
6966 // Make sure successors of the original load stay after it by updating them
6967 // to use the new Chain.
6968 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
6971 (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
6972 return DAG.getNode(Opcode, SDLoc(N), VT, Load);
6978 /// An EXTR instruction is made up of two shifts, ORed together. This helper
6979 /// searches for and classifies those shifts.
6980 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
6982 if (N.getOpcode() == ISD::SHL)
6984 else if (N.getOpcode() == ISD::SRL)
6989 if (!isa<ConstantSDNode>(N.getOperand(1)))
6992 ShiftAmount = N->getConstantOperandVal(1);
6993 Src = N->getOperand(0);
6997 /// EXTR instruction extracts a contiguous chunk of bits from two existing
6998 /// registers viewed as a high/low pair. This function looks for the pattern:
6999 /// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an
7000 /// EXTR. Can't quite be done in TableGen because the two immediates aren't
7002 static SDValue tryCombineToEXTR(SDNode *N,
7003 TargetLowering::DAGCombinerInfo &DCI) {
7004 SelectionDAG &DAG = DCI.DAG;
7006 EVT VT = N->getValueType(0);
7008 assert(N->getOpcode() == ISD::OR && "Unexpected root");
7010 if (VT != MVT::i32 && VT != MVT::i64)
7014 uint32_t ShiftLHS = 0;
7016 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
7020 uint32_t ShiftRHS = 0;
7022 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
7025 // If they're both trying to come from the high part of the register, they're
7026 // not really an EXTR.
7027 if (LHSFromHi == RHSFromHi)
7030 if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
7034 std::swap(LHS, RHS);
7035 std::swap(ShiftLHS, ShiftRHS);
7038 return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
7039 DAG.getConstant(ShiftRHS, MVT::i64));
7042 static SDValue tryCombineToBSL(SDNode *N,
7043 TargetLowering::DAGCombinerInfo &DCI) {
7044 EVT VT = N->getValueType(0);
7045 SelectionDAG &DAG = DCI.DAG;
7051 SDValue N0 = N->getOperand(0);
7052 if (N0.getOpcode() != ISD::AND)
7055 SDValue N1 = N->getOperand(1);
7056 if (N1.getOpcode() != ISD::AND)
7059 // We only have to look for constant vectors here since the general, variable
7060 // case can be handled in TableGen.
7061 unsigned Bits = VT.getVectorElementType().getSizeInBits();
7062 uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
7063 for (int i = 1; i >= 0; --i)
7064 for (int j = 1; j >= 0; --j) {
7065 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
7066 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
7070 bool FoundMatch = true;
7071 for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
7072 ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
7073 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
7075 CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
7082 return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
7083 N0->getOperand(1 - i), N1->getOperand(1 - j));
7089 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
7090 const AArch64Subtarget *Subtarget) {
7091 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
7092 if (!EnableAArch64ExtrGeneration)
7094 SelectionDAG &DAG = DCI.DAG;
7095 EVT VT = N->getValueType(0);
7097 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7100 SDValue Res = tryCombineToEXTR(N, DCI);
7104 Res = tryCombineToBSL(N, DCI);
7111 static SDValue performBitcastCombine(SDNode *N,
7112 TargetLowering::DAGCombinerInfo &DCI,
7113 SelectionDAG &DAG) {
7114 // Wait 'til after everything is legalized to try this. That way we have
7115 // legal vector types and such.
7116 if (DCI.isBeforeLegalizeOps())
7119 // Remove extraneous bitcasts around an extract_subvector.
7121 // (v4i16 (bitconvert
7122 // (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
7124 // (extract_subvector ((v8i16 ...), (i64 4)))
7126 // Only interested in 64-bit vectors as the ultimate result.
7127 EVT VT = N->getValueType(0);
7130 if (VT.getSimpleVT().getSizeInBits() != 64)
7132 // Is the operand an extract_subvector starting at the beginning or halfway
7133 // point of the vector? A low half may also come through as an
7134 // EXTRACT_SUBREG, so look for that, too.
7135 SDValue Op0 = N->getOperand(0);
7136 if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
7137 !(Op0->isMachineOpcode() &&
7138 Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
7140 uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
7141 if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
7142 if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
7144 } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
7145 if (idx != AArch64::dsub)
7147 // The dsub reference is equivalent to a lane zero subvector reference.
7150 // Look through the bitcast of the input to the extract.
7151 if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
7153 SDValue Source = Op0->getOperand(0)->getOperand(0);
7154 // If the source type has twice the number of elements as our destination
7155 // type, we know this is an extract of the high or low half of the vector.
7156 EVT SVT = Source->getValueType(0);
7157 if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
7160 DEBUG(dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
7162 // Create the simplified form to just extract the low or high half of the
7163 // vector directly rather than bothering with the bitcasts.
7165 unsigned NumElements = VT.getVectorNumElements();
7167 SDValue HalfIdx = DAG.getConstant(NumElements, MVT::i64);
7168 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
7170 SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, MVT::i32);
7171 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
7177 static SDValue performConcatVectorsCombine(SDNode *N,
7178 TargetLowering::DAGCombinerInfo &DCI,
7179 SelectionDAG &DAG) {
7180 // Wait 'til after everything is legalized to try this. That way we have
7181 // legal vector types and such.
7182 if (DCI.isBeforeLegalizeOps())
7186 EVT VT = N->getValueType(0);
7188 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
7189 // splat. The indexed instructions are going to be expecting a DUPLANE64, so
7190 // canonicalise to that.
7191 if (N->getOperand(0) == N->getOperand(1) && VT.getVectorNumElements() == 2) {
7192 assert(VT.getVectorElementType().getSizeInBits() == 64);
7193 return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT,
7194 WidenVector(N->getOperand(0), DAG),
7195 DAG.getConstant(0, MVT::i64));
7198 // Canonicalise concat_vectors so that the right-hand vector has as few
7199 // bit-casts as possible before its real operation. The primary matching
7200 // destination for these operations will be the narrowing "2" instructions,
7201 // which depend on the operation being performed on this right-hand vector.
7203 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS))))
7205 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
7207 SDValue Op1 = N->getOperand(1);
7208 if (Op1->getOpcode() != ISD::BITCAST)
7210 SDValue RHS = Op1->getOperand(0);
7211 MVT RHSTy = RHS.getValueType().getSimpleVT();
7212 // If the RHS is not a vector, this is not the pattern we're looking for.
7213 if (!RHSTy.isVector())
7216 DEBUG(dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
7218 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
7219 RHSTy.getVectorNumElements() * 2);
7221 ISD::BITCAST, dl, VT,
7222 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
7223 DAG.getNode(ISD::BITCAST, dl, RHSTy, N->getOperand(0)), RHS));
7226 static SDValue tryCombineFixedPointConvert(SDNode *N,
7227 TargetLowering::DAGCombinerInfo &DCI,
7228 SelectionDAG &DAG) {
7229 // Wait 'til after everything is legalized to try this. That way we have
7230 // legal vector types and such.
7231 if (DCI.isBeforeLegalizeOps())
7233 // Transform a scalar conversion of a value from a lane extract into a
7234 // lane extract of a vector conversion. E.g., from foo1 to foo2:
7235 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
7236 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
7238 // The second form interacts better with instruction selection and the
7239 // register allocator to avoid cross-class register copies that aren't
7240 // coalescable due to a lane reference.
7242 // Check the operand and see if it originates from a lane extract.
7243 SDValue Op1 = N->getOperand(1);
7244 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7245 // Yep, no additional predication needed. Perform the transform.
7246 SDValue IID = N->getOperand(0);
7247 SDValue Shift = N->getOperand(2);
7248 SDValue Vec = Op1.getOperand(0);
7249 SDValue Lane = Op1.getOperand(1);
7250 EVT ResTy = N->getValueType(0);
7254 // The vector width should be 128 bits by the time we get here, even
7255 // if it started as 64 bits (the extract_vector handling will have
7257 assert(Vec.getValueType().getSizeInBits() == 128 &&
7258 "unexpected vector size on extract_vector_elt!");
7259 if (Vec.getValueType() == MVT::v4i32)
7260 VecResTy = MVT::v4f32;
7261 else if (Vec.getValueType() == MVT::v2i64)
7262 VecResTy = MVT::v2f64;
7264 llvm_unreachable("unexpected vector type!");
7267 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
7268 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
7273 // AArch64 high-vector "long" operations are formed by performing the non-high
7274 // version on an extract_subvector of each operand which gets the high half:
7276 // (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
7278 // However, there are cases which don't have an extract_high explicitly, but
7279 // have another operation that can be made compatible with one for free. For
7282 // (dupv64 scalar) --> (extract_high (dup128 scalar))
7284 // This routine does the actual conversion of such DUPs, once outer routines
7285 // have determined that everything else is in order.
7286 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
7287 // We can handle most types of duplicate, but the lane ones have an extra
7288 // operand saying *which* lane, so we need to know.
7290 switch (N.getOpcode()) {
7291 case AArch64ISD::DUP:
7294 case AArch64ISD::DUPLANE8:
7295 case AArch64ISD::DUPLANE16:
7296 case AArch64ISD::DUPLANE32:
7297 case AArch64ISD::DUPLANE64:
7304 MVT NarrowTy = N.getSimpleValueType();
7305 if (!NarrowTy.is64BitVector())
7308 MVT ElementTy = NarrowTy.getVectorElementType();
7309 unsigned NumElems = NarrowTy.getVectorNumElements();
7310 MVT NewDUPVT = MVT::getVectorVT(ElementTy, NumElems * 2);
7314 NewDUP = DAG.getNode(N.getOpcode(), SDLoc(N), NewDUPVT, N.getOperand(0),
7317 NewDUP = DAG.getNode(AArch64ISD::DUP, SDLoc(N), NewDUPVT, N.getOperand(0));
7319 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N.getNode()), NarrowTy,
7320 NewDUP, DAG.getConstant(NumElems, MVT::i64));
7323 static bool isEssentiallyExtractSubvector(SDValue N) {
7324 if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
7327 return N.getOpcode() == ISD::BITCAST &&
7328 N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
7331 /// \brief Helper structure to keep track of ISD::SET_CC operands.
7332 struct GenericSetCCInfo {
7333 const SDValue *Opnd0;
7334 const SDValue *Opnd1;
7338 /// \brief Helper structure to keep track of a SET_CC lowered into AArch64 code.
7339 struct AArch64SetCCInfo {
7341 AArch64CC::CondCode CC;
7344 /// \brief Helper structure to keep track of SetCC information.
7346 GenericSetCCInfo Generic;
7347 AArch64SetCCInfo AArch64;
7350 /// \brief Helper structure to be able to read SetCC information. If set to
7351 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
7352 /// GenericSetCCInfo.
7353 struct SetCCInfoAndKind {
7358 /// \brief Check whether or not \p Op is a SET_CC operation, either a generic or
7360 /// AArch64 lowered one.
7361 /// \p SetCCInfo is filled accordingly.
7362 /// \post SetCCInfo is meanginfull only when this function returns true.
7363 /// \return True when Op is a kind of SET_CC operation.
7364 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
7365 // If this is a setcc, this is straight forward.
7366 if (Op.getOpcode() == ISD::SETCC) {
7367 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
7368 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
7369 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7370 SetCCInfo.IsAArch64 = false;
7373 // Otherwise, check if this is a matching csel instruction.
7377 if (Op.getOpcode() != AArch64ISD::CSEL)
7379 // Set the information about the operands.
7380 // TODO: we want the operands of the Cmp not the csel
7381 SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
7382 SetCCInfo.IsAArch64 = true;
7383 SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
7384 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
7386 // Check that the operands matches the constraints:
7387 // (1) Both operands must be constants.
7388 // (2) One must be 1 and the other must be 0.
7389 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
7390 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7393 if (!TValue || !FValue)
7397 if (!TValue->isOne()) {
7398 // Update the comparison when we are interested in !cc.
7399 std::swap(TValue, FValue);
7400 SetCCInfo.Info.AArch64.CC =
7401 AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
7403 return TValue->isOne() && FValue->isNullValue();
7406 // Returns true if Op is setcc or zext of setcc.
7407 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
7408 if (isSetCC(Op, Info))
7410 return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
7411 isSetCC(Op->getOperand(0), Info));
7414 // The folding we want to perform is:
7415 // (add x, [zext] (setcc cc ...) )
7417 // (csel x, (add x, 1), !cc ...)
7419 // The latter will get matched to a CSINC instruction.
7420 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
7421 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
7422 SDValue LHS = Op->getOperand(0);
7423 SDValue RHS = Op->getOperand(1);
7424 SetCCInfoAndKind InfoAndKind;
7426 // If neither operand is a SET_CC, give up.
7427 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
7428 std::swap(LHS, RHS);
7429 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
7433 // FIXME: This could be generatized to work for FP comparisons.
7434 EVT CmpVT = InfoAndKind.IsAArch64
7435 ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
7436 : InfoAndKind.Info.Generic.Opnd0->getValueType();
7437 if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
7443 if (InfoAndKind.IsAArch64) {
7444 CCVal = DAG.getConstant(
7445 AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), MVT::i32);
7446 Cmp = *InfoAndKind.Info.AArch64.Cmp;
7448 Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
7449 *InfoAndKind.Info.Generic.Opnd1,
7450 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
7453 EVT VT = Op->getValueType(0);
7454 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, VT));
7455 return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
7458 // The basic add/sub long vector instructions have variants with "2" on the end
7459 // which act on the high-half of their inputs. They are normally matched by
7462 // (add (zeroext (extract_high LHS)),
7463 // (zeroext (extract_high RHS)))
7464 // -> uaddl2 vD, vN, vM
7466 // However, if one of the extracts is something like a duplicate, this
7467 // instruction can still be used profitably. This function puts the DAG into a
7468 // more appropriate form for those patterns to trigger.
7469 static SDValue performAddSubLongCombine(SDNode *N,
7470 TargetLowering::DAGCombinerInfo &DCI,
7471 SelectionDAG &DAG) {
7472 if (DCI.isBeforeLegalizeOps())
7475 MVT VT = N->getSimpleValueType(0);
7476 if (!VT.is128BitVector()) {
7477 if (N->getOpcode() == ISD::ADD)
7478 return performSetccAddFolding(N, DAG);
7482 // Make sure both branches are extended in the same way.
7483 SDValue LHS = N->getOperand(0);
7484 SDValue RHS = N->getOperand(1);
7485 if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
7486 LHS.getOpcode() != ISD::SIGN_EXTEND) ||
7487 LHS.getOpcode() != RHS.getOpcode())
7490 unsigned ExtType = LHS.getOpcode();
7492 // It's not worth doing if at least one of the inputs isn't already an
7493 // extract, but we don't know which it'll be so we have to try both.
7494 if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
7495 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
7499 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
7500 } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
7501 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
7505 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
7508 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
7511 // Massage DAGs which we can use the high-half "long" operations on into
7512 // something isel will recognize better. E.g.
7514 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
7515 // (aarch64_neon_umull (extract_high (v2i64 vec)))
7516 // (extract_high (v2i64 (dup128 scalar)))))
7518 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
7519 TargetLowering::DAGCombinerInfo &DCI,
7520 SelectionDAG &DAG) {
7521 if (DCI.isBeforeLegalizeOps())
7524 SDValue LHS = N->getOperand(1);
7525 SDValue RHS = N->getOperand(2);
7526 assert(LHS.getValueType().is64BitVector() &&
7527 RHS.getValueType().is64BitVector() &&
7528 "unexpected shape for long operation");
7530 // Either node could be a DUP, but it's not worth doing both of them (you'd
7531 // just as well use the non-high version) so look for a corresponding extract
7532 // operation on the other "wing".
7533 if (isEssentiallyExtractSubvector(LHS)) {
7534 RHS = tryExtendDUPToExtractHigh(RHS, DAG);
7537 } else if (isEssentiallyExtractSubvector(RHS)) {
7538 LHS = tryExtendDUPToExtractHigh(LHS, DAG);
7543 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
7544 N->getOperand(0), LHS, RHS);
7547 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
7548 MVT ElemTy = N->getSimpleValueType(0).getScalarType();
7549 unsigned ElemBits = ElemTy.getSizeInBits();
7551 int64_t ShiftAmount;
7552 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
7553 APInt SplatValue, SplatUndef;
7554 unsigned SplatBitSize;
7556 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
7557 HasAnyUndefs, ElemBits) ||
7558 SplatBitSize != ElemBits)
7561 ShiftAmount = SplatValue.getSExtValue();
7562 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
7563 ShiftAmount = CVN->getSExtValue();
7571 llvm_unreachable("Unknown shift intrinsic");
7572 case Intrinsic::aarch64_neon_sqshl:
7573 Opcode = AArch64ISD::SQSHL_I;
7574 IsRightShift = false;
7576 case Intrinsic::aarch64_neon_uqshl:
7577 Opcode = AArch64ISD::UQSHL_I;
7578 IsRightShift = false;
7580 case Intrinsic::aarch64_neon_srshl:
7581 Opcode = AArch64ISD::SRSHR_I;
7582 IsRightShift = true;
7584 case Intrinsic::aarch64_neon_urshl:
7585 Opcode = AArch64ISD::URSHR_I;
7586 IsRightShift = true;
7588 case Intrinsic::aarch64_neon_sqshlu:
7589 Opcode = AArch64ISD::SQSHLU_I;
7590 IsRightShift = false;
7594 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits)
7595 return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), N->getOperand(1),
7596 DAG.getConstant(-ShiftAmount, MVT::i32));
7597 else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits)
7598 return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), N->getOperand(1),
7599 DAG.getConstant(ShiftAmount, MVT::i32));
7604 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
7605 // the intrinsics must be legal and take an i32, this means there's almost
7606 // certainly going to be a zext in the DAG which we can eliminate.
7607 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
7608 SDValue AndN = N->getOperand(2);
7609 if (AndN.getOpcode() != ISD::AND)
7612 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
7613 if (!CMask || CMask->getZExtValue() != Mask)
7616 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
7617 N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
7620 static SDValue performIntrinsicCombine(SDNode *N,
7621 TargetLowering::DAGCombinerInfo &DCI,
7622 const AArch64Subtarget *Subtarget) {
7623 SelectionDAG &DAG = DCI.DAG;
7624 unsigned IID = getIntrinsicID(N);
7628 case Intrinsic::aarch64_neon_vcvtfxs2fp:
7629 case Intrinsic::aarch64_neon_vcvtfxu2fp:
7630 return tryCombineFixedPointConvert(N, DCI, DAG);
7632 case Intrinsic::aarch64_neon_fmax:
7633 return DAG.getNode(AArch64ISD::FMAX, SDLoc(N), N->getValueType(0),
7634 N->getOperand(1), N->getOperand(2));
7635 case Intrinsic::aarch64_neon_fmin:
7636 return DAG.getNode(AArch64ISD::FMIN, SDLoc(N), N->getValueType(0),
7637 N->getOperand(1), N->getOperand(2));
7638 case Intrinsic::aarch64_neon_smull:
7639 case Intrinsic::aarch64_neon_umull:
7640 case Intrinsic::aarch64_neon_pmull:
7641 case Intrinsic::aarch64_neon_sqdmull:
7642 return tryCombineLongOpWithDup(IID, N, DCI, DAG);
7643 case Intrinsic::aarch64_neon_sqshl:
7644 case Intrinsic::aarch64_neon_uqshl:
7645 case Intrinsic::aarch64_neon_sqshlu:
7646 case Intrinsic::aarch64_neon_srshl:
7647 case Intrinsic::aarch64_neon_urshl:
7648 return tryCombineShiftImm(IID, N, DAG);
7649 case Intrinsic::aarch64_crc32b:
7650 case Intrinsic::aarch64_crc32cb:
7651 return tryCombineCRC32(0xff, N, DAG);
7652 case Intrinsic::aarch64_crc32h:
7653 case Intrinsic::aarch64_crc32ch:
7654 return tryCombineCRC32(0xffff, N, DAG);
7659 static SDValue performExtendCombine(SDNode *N,
7660 TargetLowering::DAGCombinerInfo &DCI,
7661 SelectionDAG &DAG) {
7662 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
7663 // we can convert that DUP into another extract_high (of a bigger DUP), which
7664 // helps the backend to decide that an sabdl2 would be useful, saving a real
7665 // extract_high operation.
7666 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
7667 N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
7668 SDNode *ABDNode = N->getOperand(0).getNode();
7669 unsigned IID = getIntrinsicID(ABDNode);
7670 if (IID == Intrinsic::aarch64_neon_sabd ||
7671 IID == Intrinsic::aarch64_neon_uabd) {
7672 SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
7673 if (!NewABD.getNode())
7676 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
7681 // This is effectively a custom type legalization for AArch64.
7683 // Type legalization will split an extend of a small, legal, type to a larger
7684 // illegal type by first splitting the destination type, often creating
7685 // illegal source types, which then get legalized in isel-confusing ways,
7686 // leading to really terrible codegen. E.g.,
7687 // %result = v8i32 sext v8i8 %value
7689 // %losrc = extract_subreg %value, ...
7690 // %hisrc = extract_subreg %value, ...
7691 // %lo = v4i32 sext v4i8 %losrc
7692 // %hi = v4i32 sext v4i8 %hisrc
7693 // Things go rapidly downhill from there.
7695 // For AArch64, the [sz]ext vector instructions can only go up one element
7696 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
7697 // take two instructions.
7699 // This implies that the most efficient way to do the extend from v8i8
7700 // to two v4i32 values is to first extend the v8i8 to v8i16, then do
7701 // the normal splitting to happen for the v8i16->v8i32.
7703 // This is pre-legalization to catch some cases where the default
7704 // type legalization will create ill-tempered code.
7705 if (!DCI.isBeforeLegalizeOps())
7708 // We're only interested in cleaning things up for non-legal vector types
7709 // here. If both the source and destination are legal, things will just
7710 // work naturally without any fiddling.
7711 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7712 EVT ResVT = N->getValueType(0);
7713 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
7715 // If the vector type isn't a simple VT, it's beyond the scope of what
7716 // we're worried about here. Let legalization do its thing and hope for
7718 SDValue Src = N->getOperand(0);
7719 EVT SrcVT = Src->getValueType(0);
7720 if (!ResVT.isSimple() || !SrcVT.isSimple())
7723 // If the source VT is a 64-bit vector, we can play games and get the
7724 // better results we want.
7725 if (SrcVT.getSizeInBits() != 64)
7728 unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits();
7729 unsigned ElementCount = SrcVT.getVectorNumElements();
7730 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
7732 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
7734 // Now split the rest of the operation into two halves, each with a 64
7738 unsigned NumElements = ResVT.getVectorNumElements();
7739 assert(!(NumElements & 1) && "Splitting vector, but not in half!");
7740 LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
7741 ResVT.getVectorElementType(), NumElements / 2);
7743 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
7744 LoVT.getVectorNumElements());
7745 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
7746 DAG.getConstant(0, MVT::i64));
7747 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
7748 DAG.getConstant(InNVT.getVectorNumElements(), MVT::i64));
7749 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
7750 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
7752 // Now combine the parts back together so we still have a single result
7753 // like the combiner expects.
7754 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
7757 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
7758 /// value. The load store optimizer pass will merge them to store pair stores.
7759 /// This has better performance than a splat of the scalar followed by a split
7760 /// vector store. Even if the stores are not merged it is four stores vs a dup,
7761 /// followed by an ext.b and two stores.
7762 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode *St) {
7763 SDValue StVal = St->getValue();
7764 EVT VT = StVal.getValueType();
7766 // Don't replace floating point stores, they possibly won't be transformed to
7767 // stp because of the store pair suppress pass.
7768 if (VT.isFloatingPoint())
7771 // Check for insert vector elements.
7772 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
7775 // We can express a splat as store pair(s) for 2 or 4 elements.
7776 unsigned NumVecElts = VT.getVectorNumElements();
7777 if (NumVecElts != 4 && NumVecElts != 2)
7779 SDValue SplatVal = StVal.getOperand(1);
7780 unsigned RemainInsertElts = NumVecElts - 1;
7782 // Check that this is a splat.
7783 while (--RemainInsertElts) {
7784 SDValue NextInsertElt = StVal.getOperand(0);
7785 if (NextInsertElt.getOpcode() != ISD::INSERT_VECTOR_ELT)
7787 if (NextInsertElt.getOperand(1) != SplatVal)
7789 StVal = NextInsertElt;
7791 unsigned OrigAlignment = St->getAlignment();
7792 unsigned EltOffset = NumVecElts == 4 ? 4 : 8;
7793 unsigned Alignment = std::min(OrigAlignment, EltOffset);
7795 // Create scalar stores. This is at least as good as the code sequence for a
7796 // split unaligned store wich is a dup.s, ext.b, and two stores.
7797 // Most of the time the three stores should be replaced by store pair
7798 // instructions (stp).
7800 SDValue BasePtr = St->getBasePtr();
7802 DAG.getStore(St->getChain(), DL, SplatVal, BasePtr, St->getPointerInfo(),
7803 St->isVolatile(), St->isNonTemporal(), St->getAlignment());
7805 unsigned Offset = EltOffset;
7806 while (--NumVecElts) {
7807 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
7808 DAG.getConstant(Offset, MVT::i64));
7809 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
7810 St->getPointerInfo(), St->isVolatile(),
7811 St->isNonTemporal(), Alignment);
7812 Offset += EltOffset;
7817 static SDValue performSTORECombine(SDNode *N,
7818 TargetLowering::DAGCombinerInfo &DCI,
7820 const AArch64Subtarget *Subtarget) {
7821 if (!DCI.isBeforeLegalize())
7824 StoreSDNode *S = cast<StoreSDNode>(N);
7825 if (S->isVolatile())
7828 // Cyclone has bad performance on unaligned 16B stores when crossing line and
7829 // page boundries. We want to split such stores.
7830 if (!Subtarget->isCyclone())
7833 // Don't split at Oz.
7834 MachineFunction &MF = DAG.getMachineFunction();
7835 bool IsMinSize = MF.getFunction()->getAttributes().hasAttribute(
7836 AttributeSet::FunctionIndex, Attribute::MinSize);
7840 SDValue StVal = S->getValue();
7841 EVT VT = StVal.getValueType();
7843 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
7844 // those up regresses performance on micro-benchmarks and olden/bh.
7845 if (!VT.isVector() || VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
7848 // Split unaligned 16B stores. They are terrible for performance.
7849 // Don't split stores with alignment of 1 or 2. Code that uses clang vector
7850 // extensions can use this to mark that it does not want splitting to happen
7851 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
7852 // eliminating alignment hazards is only 1 in 8 for alignment of 2.
7853 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
7854 S->getAlignment() <= 2)
7857 // If we get a splat of a scalar convert this vector store to a store of
7858 // scalars. They will be merged into store pairs thereby removing two
7860 SDValue ReplacedSplat = replaceSplatVectorStore(DAG, S);
7861 if (ReplacedSplat != SDValue())
7862 return ReplacedSplat;
7865 unsigned NumElts = VT.getVectorNumElements() / 2;
7866 // Split VT into two.
7868 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
7869 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
7870 DAG.getConstant(0, MVT::i64));
7871 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
7872 DAG.getConstant(NumElts, MVT::i64));
7873 SDValue BasePtr = S->getBasePtr();
7875 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
7876 S->isVolatile(), S->isNonTemporal(), S->getAlignment());
7877 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
7878 DAG.getConstant(8, MVT::i64));
7879 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
7880 S->getPointerInfo(), S->isVolatile(), S->isNonTemporal(),
7884 /// Target-specific DAG combine function for post-increment LD1 (lane) and
7885 /// post-increment LD1R.
7886 static SDValue performPostLD1Combine(SDNode *N,
7887 TargetLowering::DAGCombinerInfo &DCI,
7889 if (DCI.isBeforeLegalizeOps())
7892 SelectionDAG &DAG = DCI.DAG;
7893 EVT VT = N->getValueType(0);
7895 unsigned LoadIdx = IsLaneOp ? 1 : 0;
7896 SDNode *LD = N->getOperand(LoadIdx).getNode();
7897 // If it is not LOAD, can not do such combine.
7898 if (LD->getOpcode() != ISD::LOAD)
7901 LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
7902 EVT MemVT = LoadSDN->getMemoryVT();
7903 // Check if memory operand is the same type as the vector element.
7904 if (MemVT != VT.getVectorElementType())
7907 // Check if there are other uses. If so, do not combine as it will introduce
7909 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
7911 if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
7917 SDValue Addr = LD->getOperand(1);
7918 SDValue Vector = N->getOperand(0);
7919 // Search for a use of the address operand that is an increment.
7920 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
7921 Addr.getNode()->use_end(); UI != UE; ++UI) {
7923 if (User->getOpcode() != ISD::ADD
7924 || UI.getUse().getResNo() != Addr.getResNo())
7927 // Check that the add is independent of the load. Otherwise, folding it
7928 // would create a cycle.
7929 if (User->isPredecessorOf(LD) || LD->isPredecessorOf(User))
7931 // Also check that add is not used in the vector operand. This would also
7933 if (User->isPredecessorOf(Vector.getNode()))
7936 // If the increment is a constant, it must match the memory ref size.
7937 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
7938 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
7939 uint32_t IncVal = CInc->getZExtValue();
7940 unsigned NumBytes = VT.getScalarSizeInBits() / 8;
7941 if (IncVal != NumBytes)
7943 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
7946 SmallVector<SDValue, 8> Ops;
7947 Ops.push_back(LD->getOperand(0)); // Chain
7949 Ops.push_back(Vector); // The vector to be inserted
7950 Ops.push_back(N->getOperand(2)); // The lane to be inserted in the vector
7952 Ops.push_back(Addr);
7955 EVT Tys[3] = { VT, MVT::i64, MVT::Other };
7956 SDVTList SDTys = DAG.getVTList(Tys);
7957 unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
7958 SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
7960 LoadSDN->getMemOperand());
7963 std::vector<SDValue> NewResults;
7964 NewResults.push_back(SDValue(LD, 0)); // The result of load
7965 NewResults.push_back(SDValue(UpdN.getNode(), 2)); // Chain
7966 DCI.CombineTo(LD, NewResults);
7967 DCI.CombineTo(N, SDValue(UpdN.getNode(), 0)); // Dup/Inserted Result
7968 DCI.CombineTo(User, SDValue(UpdN.getNode(), 1)); // Write back register
7975 /// Target-specific DAG combine function for NEON load/store intrinsics
7976 /// to merge base address updates.
7977 static SDValue performNEONPostLDSTCombine(SDNode *N,
7978 TargetLowering::DAGCombinerInfo &DCI,
7979 SelectionDAG &DAG) {
7980 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
7983 unsigned AddrOpIdx = N->getNumOperands() - 1;
7984 SDValue Addr = N->getOperand(AddrOpIdx);
7986 // Search for a use of the address operand that is an increment.
7987 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
7988 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
7990 if (User->getOpcode() != ISD::ADD ||
7991 UI.getUse().getResNo() != Addr.getResNo())
7994 // Check that the add is independent of the load/store. Otherwise, folding
7995 // it would create a cycle.
7996 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
7999 // Find the new opcode for the updating load/store.
8000 bool IsStore = false;
8001 bool IsLaneOp = false;
8002 bool IsDupOp = false;
8003 unsigned NewOpc = 0;
8004 unsigned NumVecs = 0;
8005 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8007 default: llvm_unreachable("unexpected intrinsic for Neon base update");
8008 case Intrinsic::aarch64_neon_ld2: NewOpc = AArch64ISD::LD2post;
8010 case Intrinsic::aarch64_neon_ld3: NewOpc = AArch64ISD::LD3post;
8012 case Intrinsic::aarch64_neon_ld4: NewOpc = AArch64ISD::LD4post;
8014 case Intrinsic::aarch64_neon_st2: NewOpc = AArch64ISD::ST2post;
8015 NumVecs = 2; IsStore = true; break;
8016 case Intrinsic::aarch64_neon_st3: NewOpc = AArch64ISD::ST3post;
8017 NumVecs = 3; IsStore = true; break;
8018 case Intrinsic::aarch64_neon_st4: NewOpc = AArch64ISD::ST4post;
8019 NumVecs = 4; IsStore = true; break;
8020 case Intrinsic::aarch64_neon_ld1x2: NewOpc = AArch64ISD::LD1x2post;
8022 case Intrinsic::aarch64_neon_ld1x3: NewOpc = AArch64ISD::LD1x3post;
8024 case Intrinsic::aarch64_neon_ld1x4: NewOpc = AArch64ISD::LD1x4post;
8026 case Intrinsic::aarch64_neon_st1x2: NewOpc = AArch64ISD::ST1x2post;
8027 NumVecs = 2; IsStore = true; break;
8028 case Intrinsic::aarch64_neon_st1x3: NewOpc = AArch64ISD::ST1x3post;
8029 NumVecs = 3; IsStore = true; break;
8030 case Intrinsic::aarch64_neon_st1x4: NewOpc = AArch64ISD::ST1x4post;
8031 NumVecs = 4; IsStore = true; break;
8032 case Intrinsic::aarch64_neon_ld2r: NewOpc = AArch64ISD::LD2DUPpost;
8033 NumVecs = 2; IsDupOp = true; break;
8034 case Intrinsic::aarch64_neon_ld3r: NewOpc = AArch64ISD::LD3DUPpost;
8035 NumVecs = 3; IsDupOp = true; break;
8036 case Intrinsic::aarch64_neon_ld4r: NewOpc = AArch64ISD::LD4DUPpost;
8037 NumVecs = 4; IsDupOp = true; break;
8038 case Intrinsic::aarch64_neon_ld2lane: NewOpc = AArch64ISD::LD2LANEpost;
8039 NumVecs = 2; IsLaneOp = true; break;
8040 case Intrinsic::aarch64_neon_ld3lane: NewOpc = AArch64ISD::LD3LANEpost;
8041 NumVecs = 3; IsLaneOp = true; break;
8042 case Intrinsic::aarch64_neon_ld4lane: NewOpc = AArch64ISD::LD4LANEpost;
8043 NumVecs = 4; IsLaneOp = true; break;
8044 case Intrinsic::aarch64_neon_st2lane: NewOpc = AArch64ISD::ST2LANEpost;
8045 NumVecs = 2; IsStore = true; IsLaneOp = true; break;
8046 case Intrinsic::aarch64_neon_st3lane: NewOpc = AArch64ISD::ST3LANEpost;
8047 NumVecs = 3; IsStore = true; IsLaneOp = true; break;
8048 case Intrinsic::aarch64_neon_st4lane: NewOpc = AArch64ISD::ST4LANEpost;
8049 NumVecs = 4; IsStore = true; IsLaneOp = true; break;
8054 VecTy = N->getOperand(2).getValueType();
8056 VecTy = N->getValueType(0);
8058 // If the increment is a constant, it must match the memory ref size.
8059 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8060 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8061 uint32_t IncVal = CInc->getZExtValue();
8062 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8063 if (IsLaneOp || IsDupOp)
8064 NumBytes /= VecTy.getVectorNumElements();
8065 if (IncVal != NumBytes)
8067 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
8069 SmallVector<SDValue, 8> Ops;
8070 Ops.push_back(N->getOperand(0)); // Incoming chain
8071 // Load lane and store have vector list as input.
8072 if (IsLaneOp || IsStore)
8073 for (unsigned i = 2; i < AddrOpIdx; ++i)
8074 Ops.push_back(N->getOperand(i));
8075 Ops.push_back(Addr); // Base register
8080 unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
8082 for (n = 0; n < NumResultVecs; ++n)
8084 Tys[n++] = MVT::i64; // Type of write back register
8085 Tys[n] = MVT::Other; // Type of the chain
8086 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
8088 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8089 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
8090 MemInt->getMemoryVT(),
8091 MemInt->getMemOperand());
8094 std::vector<SDValue> NewResults;
8095 for (unsigned i = 0; i < NumResultVecs; ++i) {
8096 NewResults.push_back(SDValue(UpdN.getNode(), i));
8098 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
8099 DCI.CombineTo(N, NewResults);
8100 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8107 // Checks to see if the value is the prescribed width and returns information
8108 // about its extension mode.
8110 bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
8111 ExtType = ISD::NON_EXTLOAD;
8112 switch(V.getNode()->getOpcode()) {
8116 LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
8117 if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
8118 || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
8119 ExtType = LoadNode->getExtensionType();
8124 case ISD::AssertSext: {
8125 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
8126 if ((TypeNode->getVT() == MVT::i8 && width == 8)
8127 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
8128 ExtType = ISD::SEXTLOAD;
8133 case ISD::AssertZext: {
8134 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
8135 if ((TypeNode->getVT() == MVT::i8 && width == 8)
8136 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
8137 ExtType = ISD::ZEXTLOAD;
8143 case ISD::TargetConstant: {
8144 if (std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
8154 // This function does a whole lot of voodoo to determine if the tests are
8155 // equivalent without and with a mask. Essentially what happens is that given a
8158 // +-------------+ +-------------+ +-------------+ +-------------+
8159 // | Input | | AddConstant | | CompConstant| | CC |
8160 // +-------------+ +-------------+ +-------------+ +-------------+
8162 // V V | +----------+
8163 // +-------------+ +----+ | |
8164 // | ADD | |0xff| | |
8165 // +-------------+ +----+ | |
8168 // +-------------+ | |
8170 // +-------------+ | |
8179 // The AND node may be safely removed for some combinations of inputs. In
8180 // particular we need to take into account the extension type of the Input,
8181 // the exact values of AddConstant, CompConstant, and CC, along with the nominal
8182 // width of the input (this can work for any width inputs, the above graph is
8183 // specific to 8 bits.
8185 // The specific equations were worked out by generating output tables for each
8186 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
8187 // problem was simplified by working with 4 bit inputs, which means we only
8188 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
8189 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
8190 // patterns present in both extensions (0,7). For every distinct set of
8191 // AddConstant and CompConstants bit patterns we can consider the masked and
8192 // unmasked versions to be equivalent if the result of this function is true for
8193 // all 16 distinct bit patterns of for the current extension type of Input (w0).
8196 // and w10, w8, #0x0f
8198 // cset w9, AArch64CC
8200 // cset w11, AArch64CC
8205 // Since the above function shows when the outputs are equivalent it defines
8206 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
8207 // would be expensive to run during compiles. The equations below were written
8208 // in a test harness that confirmed they gave equivalent outputs to the above
8209 // for all inputs function, so they can be used determine if the removal is
8212 // isEquivalentMaskless() is the code for testing if the AND can be removed
8213 // factored out of the DAG recognition as the DAG can take several forms.
8216 bool isEquivalentMaskless(unsigned CC, unsigned width,
8217 ISD::LoadExtType ExtType, signed AddConstant,
8218 signed CompConstant) {
8219 // By being careful about our equations and only writing the in term
8220 // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
8221 // make them generally applicable to all bit widths.
8222 signed MaxUInt = (1 << width);
8224 // For the purposes of these comparisons sign extending the type is
8225 // equivalent to zero extending the add and displacing it by half the integer
8226 // width. Provided we are careful and make sure our equations are valid over
8227 // the whole range we can just adjust the input and avoid writing equations
8228 // for sign extended inputs.
8229 if (ExtType == ISD::SEXTLOAD)
8230 AddConstant -= (1 << (width-1));
8234 case AArch64CC::GT: {
8235 if ((AddConstant == 0) ||
8236 (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
8237 (AddConstant >= 0 && CompConstant < 0) ||
8238 (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
8242 case AArch64CC::GE: {
8243 if ((AddConstant == 0) ||
8244 (AddConstant >= 0 && CompConstant <= 0) ||
8245 (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
8249 case AArch64CC::LS: {
8250 if ((AddConstant >= 0 && CompConstant < 0) ||
8251 (AddConstant <= 0 && CompConstant >= -1 &&
8252 CompConstant < AddConstant + MaxUInt))
8256 case AArch64CC::MI: {
8257 if ((AddConstant == 0) ||
8258 (AddConstant > 0 && CompConstant <= 0) ||
8259 (AddConstant < 0 && CompConstant <= AddConstant))
8263 case AArch64CC::HS: {
8264 if ((AddConstant >= 0 && CompConstant <= 0) ||
8265 (AddConstant <= 0 && CompConstant >= 0 &&
8266 CompConstant <= AddConstant + MaxUInt))
8270 case AArch64CC::NE: {
8271 if ((AddConstant > 0 && CompConstant < 0) ||
8272 (AddConstant < 0 && CompConstant >= 0 &&
8273 CompConstant < AddConstant + MaxUInt) ||
8274 (AddConstant >= 0 && CompConstant >= 0 &&
8275 CompConstant >= AddConstant) ||
8276 (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
8285 case AArch64CC::Invalid:
8293 SDValue performCONDCombine(SDNode *N,
8294 TargetLowering::DAGCombinerInfo &DCI,
8295 SelectionDAG &DAG, unsigned CCIndex,
8296 unsigned CmpIndex) {
8297 unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
8298 SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
8299 unsigned CondOpcode = SubsNode->getOpcode();
8301 if (CondOpcode != AArch64ISD::SUBS)
8304 // There is a SUBS feeding this condition. Is it fed by a mask we can
8307 SDNode *AndNode = SubsNode->getOperand(0).getNode();
8308 unsigned MaskBits = 0;
8310 if (AndNode->getOpcode() != ISD::AND)
8313 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
8314 uint32_t CNV = CN->getZExtValue();
8317 else if (CNV == 65535)
8324 SDValue AddValue = AndNode->getOperand(0);
8326 if (AddValue.getOpcode() != ISD::ADD)
8329 // The basic dag structure is correct, grab the inputs and validate them.
8331 SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
8332 SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
8333 SDValue SubsInputValue = SubsNode->getOperand(1);
8335 // The mask is present and the provenance of all the values is a smaller type,
8336 // lets see if the mask is superfluous.
8338 if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
8339 !isa<ConstantSDNode>(SubsInputValue.getNode()))
8342 ISD::LoadExtType ExtType;
8344 if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
8345 !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
8346 !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
8349 if(!isEquivalentMaskless(CC, MaskBits, ExtType,
8350 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
8351 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
8354 // The AND is not necessary, remove it.
8356 SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
8357 SubsNode->getValueType(1));
8358 SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
8360 SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
8361 DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
8363 return SDValue(N, 0);
8366 // Optimize compare with zero and branch.
8367 static SDValue performBRCONDCombine(SDNode *N,
8368 TargetLowering::DAGCombinerInfo &DCI,
8369 SelectionDAG &DAG) {
8370 SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3);
8373 SDValue Chain = N->getOperand(0);
8374 SDValue Dest = N->getOperand(1);
8375 SDValue CCVal = N->getOperand(2);
8376 SDValue Cmp = N->getOperand(3);
8378 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
8379 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
8380 if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
8383 unsigned CmpOpc = Cmp.getOpcode();
8384 if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
8387 // Only attempt folding if there is only one use of the flag and no use of the
8389 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
8392 SDValue LHS = Cmp.getOperand(0);
8393 SDValue RHS = Cmp.getOperand(1);
8395 assert(LHS.getValueType() == RHS.getValueType() &&
8396 "Expected the value type to be the same for both operands!");
8397 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
8400 if (isa<ConstantSDNode>(LHS) && cast<ConstantSDNode>(LHS)->isNullValue())
8401 std::swap(LHS, RHS);
8403 if (!isa<ConstantSDNode>(RHS) || !cast<ConstantSDNode>(RHS)->isNullValue())
8406 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
8407 LHS.getOpcode() == ISD::SRL)
8410 // Fold the compare into the branch instruction.
8412 if (CC == AArch64CC::EQ)
8413 BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
8415 BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
8417 // Do not add new nodes to DAG combiner worklist.
8418 DCI.CombineTo(N, BR, false);
8423 // vselect (v1i1 setcc) ->
8424 // vselect (v1iXX setcc) (XX is the size of the compared operand type)
8425 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
8426 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
8428 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
8429 SDValue N0 = N->getOperand(0);
8430 EVT CCVT = N0.getValueType();
8432 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
8433 CCVT.getVectorElementType() != MVT::i1)
8436 EVT ResVT = N->getValueType(0);
8437 EVT CmpVT = N0.getOperand(0).getValueType();
8438 // Only combine when the result type is of the same size as the compared
8440 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
8443 SDValue IfTrue = N->getOperand(1);
8444 SDValue IfFalse = N->getOperand(2);
8446 DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
8447 N0.getOperand(0), N0.getOperand(1),
8448 cast<CondCodeSDNode>(N0.getOperand(2))->get());
8449 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
8453 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
8454 /// the compare-mask instructions rather than going via NZCV, even if LHS and
8455 /// RHS are really scalar. This replaces any scalar setcc in the above pattern
8456 /// with a vector one followed by a DUP shuffle on the result.
8457 static SDValue performSelectCombine(SDNode *N, SelectionDAG &DAG) {
8458 SDValue N0 = N->getOperand(0);
8459 EVT ResVT = N->getValueType(0);
8461 if (N0.getOpcode() != ISD::SETCC || N0.getValueType() != MVT::i1)
8464 // If NumMaskElts == 0, the comparison is larger than select result. The
8465 // largest real NEON comparison is 64-bits per lane, which means the result is
8466 // at most 32-bits and an illegal vector. Just bail out for now.
8467 EVT SrcVT = N0.getOperand(0).getValueType();
8469 // Don't try to do this optimization when the setcc itself has i1 operands.
8470 // There are no legal vectors of i1, so this would be pointless.
8471 if (SrcVT == MVT::i1)
8474 int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
8475 if (!ResVT.isVector() || NumMaskElts == 0)
8478 SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
8479 EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
8481 // First perform a vector comparison, where lane 0 is the one we're interested
8485 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
8487 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
8488 SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
8490 // Now duplicate the comparison mask we want across all other lanes.
8491 SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
8492 SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask.data());
8493 Mask = DAG.getNode(ISD::BITCAST, DL,
8494 ResVT.changeVectorElementTypeToInteger(), Mask);
8496 return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
8499 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
8500 DAGCombinerInfo &DCI) const {
8501 SelectionDAG &DAG = DCI.DAG;
8502 switch (N->getOpcode()) {
8507 return performAddSubLongCombine(N, DCI, DAG);
8509 return performXorCombine(N, DAG, DCI, Subtarget);
8511 return performMulCombine(N, DAG, DCI, Subtarget);
8512 case ISD::SINT_TO_FP:
8513 case ISD::UINT_TO_FP:
8514 return performIntToFpCombine(N, DAG, Subtarget);
8516 return performORCombine(N, DCI, Subtarget);
8517 case ISD::INTRINSIC_WO_CHAIN:
8518 return performIntrinsicCombine(N, DCI, Subtarget);
8519 case ISD::ANY_EXTEND:
8520 case ISD::ZERO_EXTEND:
8521 case ISD::SIGN_EXTEND:
8522 return performExtendCombine(N, DCI, DAG);
8524 return performBitcastCombine(N, DCI, DAG);
8525 case ISD::CONCAT_VECTORS:
8526 return performConcatVectorsCombine(N, DCI, DAG);
8528 return performSelectCombine(N, DAG);
8530 return performVSelectCombine(N, DCI.DAG);
8532 return performSTORECombine(N, DCI, DAG, Subtarget);
8533 case AArch64ISD::BRCOND:
8534 return performBRCONDCombine(N, DCI, DAG);
8535 case AArch64ISD::CSEL:
8536 return performCONDCombine(N, DCI, DAG, 2, 3);
8537 case AArch64ISD::DUP:
8538 return performPostLD1Combine(N, DCI, false);
8539 case ISD::INSERT_VECTOR_ELT:
8540 return performPostLD1Combine(N, DCI, true);
8541 case ISD::INTRINSIC_VOID:
8542 case ISD::INTRINSIC_W_CHAIN:
8543 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
8544 case Intrinsic::aarch64_neon_ld2:
8545 case Intrinsic::aarch64_neon_ld3:
8546 case Intrinsic::aarch64_neon_ld4:
8547 case Intrinsic::aarch64_neon_ld1x2:
8548 case Intrinsic::aarch64_neon_ld1x3:
8549 case Intrinsic::aarch64_neon_ld1x4:
8550 case Intrinsic::aarch64_neon_ld2lane:
8551 case Intrinsic::aarch64_neon_ld3lane:
8552 case Intrinsic::aarch64_neon_ld4lane:
8553 case Intrinsic::aarch64_neon_ld2r:
8554 case Intrinsic::aarch64_neon_ld3r:
8555 case Intrinsic::aarch64_neon_ld4r:
8556 case Intrinsic::aarch64_neon_st2:
8557 case Intrinsic::aarch64_neon_st3:
8558 case Intrinsic::aarch64_neon_st4:
8559 case Intrinsic::aarch64_neon_st1x2:
8560 case Intrinsic::aarch64_neon_st1x3:
8561 case Intrinsic::aarch64_neon_st1x4:
8562 case Intrinsic::aarch64_neon_st2lane:
8563 case Intrinsic::aarch64_neon_st3lane:
8564 case Intrinsic::aarch64_neon_st4lane:
8565 return performNEONPostLDSTCombine(N, DCI, DAG);
8573 // Check if the return value is used as only a return value, as otherwise
8574 // we can't perform a tail-call. In particular, we need to check for
8575 // target ISD nodes that are returns and any other "odd" constructs
8576 // that the generic analysis code won't necessarily catch.
8577 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
8578 SDValue &Chain) const {
8579 if (N->getNumValues() != 1)
8581 if (!N->hasNUsesOfValue(1, 0))
8584 SDValue TCChain = Chain;
8585 SDNode *Copy = *N->use_begin();
8586 if (Copy->getOpcode() == ISD::CopyToReg) {
8587 // If the copy has a glue operand, we conservatively assume it isn't safe to
8588 // perform a tail call.
8589 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
8592 TCChain = Copy->getOperand(0);
8593 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
8596 bool HasRet = false;
8597 for (SDNode *Node : Copy->uses()) {
8598 if (Node->getOpcode() != AArch64ISD::RET_FLAG)
8610 // Return whether the an instruction can potentially be optimized to a tail
8611 // call. This will cause the optimizers to attempt to move, or duplicate,
8612 // return instructions to help enable tail call optimizations for this
8614 bool AArch64TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
8615 if (!CI->isTailCall())
8621 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
8623 ISD::MemIndexedMode &AM,
8625 SelectionDAG &DAG) const {
8626 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
8629 Base = Op->getOperand(0);
8630 // All of the indexed addressing mode instructions take a signed
8631 // 9 bit immediate offset.
8632 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
8633 int64_t RHSC = (int64_t)RHS->getZExtValue();
8634 if (RHSC >= 256 || RHSC <= -256)
8636 IsInc = (Op->getOpcode() == ISD::ADD);
8637 Offset = Op->getOperand(1);
8643 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
8645 ISD::MemIndexedMode &AM,
8646 SelectionDAG &DAG) const {
8649 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8650 VT = LD->getMemoryVT();
8651 Ptr = LD->getBasePtr();
8652 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
8653 VT = ST->getMemoryVT();
8654 Ptr = ST->getBasePtr();
8659 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
8661 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
8665 bool AArch64TargetLowering::getPostIndexedAddressParts(
8666 SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
8667 ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
8670 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8671 VT = LD->getMemoryVT();
8672 Ptr = LD->getBasePtr();
8673 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
8674 VT = ST->getMemoryVT();
8675 Ptr = ST->getBasePtr();
8680 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
8682 // Post-indexing updates the base, so it's not a valid transform
8683 // if that's not the same as the load's pointer.
8686 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
8690 static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
8691 SelectionDAG &DAG) {
8693 SDValue Op = N->getOperand(0);
8695 if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
8699 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
8700 DAG.getUNDEF(MVT::i32), Op,
8701 DAG.getTargetConstant(AArch64::hsub, MVT::i32)),
8703 Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
8704 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
8707 void AArch64TargetLowering::ReplaceNodeResults(
8708 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
8709 switch (N->getOpcode()) {
8711 llvm_unreachable("Don't know how to custom expand this");
8713 ReplaceBITCASTResults(N, Results, DAG);
8715 case ISD::FP_TO_UINT:
8716 case ISD::FP_TO_SINT:
8717 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
8718 // Let normal code take care of it by not adding anything to Results.
8723 bool AArch64TargetLowering::useLoadStackGuardNode() const {
8727 bool AArch64TargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
8728 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8729 // reciprocal if there are three or more FDIVs.
8730 return NumUsers > 2;
8733 TargetLoweringBase::LegalizeTypeAction
8734 AArch64TargetLowering::getPreferredVectorAction(EVT VT) const {
8735 MVT SVT = VT.getSimpleVT();
8736 // During type legalization, we prefer to widen v1i8, v1i16, v1i32 to v8i8,
8737 // v4i16, v2i32 instead of to promote.
8738 if (SVT == MVT::v1i8 || SVT == MVT::v1i16 || SVT == MVT::v1i32
8739 || SVT == MVT::v1f32)
8740 return TypeWidenVector;
8742 return TargetLoweringBase::getPreferredVectorAction(VT);
8745 // Loads and stores less than 128-bits are already atomic; ones above that
8746 // are doomed anyway, so defer to the default libcall and blame the OS when
8748 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
8749 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
8753 // Loads and stores less than 128-bits are already atomic; ones above that
8754 // are doomed anyway, so defer to the default libcall and blame the OS when
8756 bool AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
8757 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
8761 // For the real atomic operations, we have ldxr/stxr up to 128 bits,
8762 bool AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
8763 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
8767 bool AArch64TargetLowering::hasLoadLinkedStoreConditional() const {
8771 Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
8772 AtomicOrdering Ord) const {
8773 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
8774 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
8775 bool IsAcquire = isAtLeastAcquire(Ord);
8777 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
8778 // intrinsic must return {i64, i64} and we have to recombine them into a
8779 // single i128 here.
8780 if (ValTy->getPrimitiveSizeInBits() == 128) {
8782 IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
8783 Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int);
8785 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
8786 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
8788 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
8789 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
8790 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
8791 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
8792 return Builder.CreateOr(
8793 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
8796 Type *Tys[] = { Addr->getType() };
8798 IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
8799 Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int, Tys);
8801 return Builder.CreateTruncOrBitCast(
8802 Builder.CreateCall(Ldxr, Addr),
8803 cast<PointerType>(Addr->getType())->getElementType());
8806 Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
8807 Value *Val, Value *Addr,
8808 AtomicOrdering Ord) const {
8809 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
8810 bool IsRelease = isAtLeastRelease(Ord);
8812 // Since the intrinsics must have legal type, the i128 intrinsics take two
8813 // parameters: "i64, i64". We must marshal Val into the appropriate form
8815 if (Val->getType()->getPrimitiveSizeInBits() == 128) {
8817 IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
8818 Function *Stxr = Intrinsic::getDeclaration(M, Int);
8819 Type *Int64Ty = Type::getInt64Ty(M->getContext());
8821 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
8822 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
8823 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
8824 return Builder.CreateCall3(Stxr, Lo, Hi, Addr);
8828 IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
8829 Type *Tys[] = { Addr->getType() };
8830 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
8832 return Builder.CreateCall2(
8833 Stxr, Builder.CreateZExtOrBitCast(
8834 Val, Stxr->getFunctionType()->getParamType(0)),
8838 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
8839 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
8840 return Ty->isArrayTy();