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"),
78 AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
79 const AArch64Subtarget &STI)
80 : TargetLowering(TM), Subtarget(&STI) {
82 // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
83 // we have to make something up. Arbitrarily, choose ZeroOrOne.
84 setBooleanContents(ZeroOrOneBooleanContent);
85 // When comparing vectors the result sets the different elements in the
86 // vector to all-one or all-zero.
87 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
89 // Set up the register classes.
90 addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
91 addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
93 if (Subtarget->hasFPARMv8()) {
94 addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
95 addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
96 addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
97 addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
100 if (Subtarget->hasNEON()) {
101 addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
102 addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
103 // Someone set us up the NEON.
104 addDRTypeForNEON(MVT::v2f32);
105 addDRTypeForNEON(MVT::v8i8);
106 addDRTypeForNEON(MVT::v4i16);
107 addDRTypeForNEON(MVT::v2i32);
108 addDRTypeForNEON(MVT::v1i64);
109 addDRTypeForNEON(MVT::v1f64);
110 addDRTypeForNEON(MVT::v4f16);
112 addQRTypeForNEON(MVT::v4f32);
113 addQRTypeForNEON(MVT::v2f64);
114 addQRTypeForNEON(MVT::v16i8);
115 addQRTypeForNEON(MVT::v8i16);
116 addQRTypeForNEON(MVT::v4i32);
117 addQRTypeForNEON(MVT::v2i64);
118 addQRTypeForNEON(MVT::v8f16);
121 // Compute derived properties from the register classes
122 computeRegisterProperties(Subtarget->getRegisterInfo());
124 // Provide all sorts of operation actions
125 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
126 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
127 setOperationAction(ISD::SETCC, MVT::i32, Custom);
128 setOperationAction(ISD::SETCC, MVT::i64, Custom);
129 setOperationAction(ISD::SETCC, MVT::f32, Custom);
130 setOperationAction(ISD::SETCC, MVT::f64, Custom);
131 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
132 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
133 setOperationAction(ISD::BR_CC, MVT::i64, Custom);
134 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
135 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
136 setOperationAction(ISD::SELECT, MVT::i32, Custom);
137 setOperationAction(ISD::SELECT, MVT::i64, Custom);
138 setOperationAction(ISD::SELECT, MVT::f32, Custom);
139 setOperationAction(ISD::SELECT, MVT::f64, Custom);
140 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
141 setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
142 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
143 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
144 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
145 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
147 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
148 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
149 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
151 setOperationAction(ISD::FREM, MVT::f32, Expand);
152 setOperationAction(ISD::FREM, MVT::f64, Expand);
153 setOperationAction(ISD::FREM, MVT::f80, Expand);
155 // Custom lowering hooks are needed for XOR
156 // to fold it into CSINC/CSINV.
157 setOperationAction(ISD::XOR, MVT::i32, Custom);
158 setOperationAction(ISD::XOR, MVT::i64, Custom);
160 // Virtually no operation on f128 is legal, but LLVM can't expand them when
161 // there's a valid register class, so we need custom operations in most cases.
162 setOperationAction(ISD::FABS, MVT::f128, Expand);
163 setOperationAction(ISD::FADD, MVT::f128, Custom);
164 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
165 setOperationAction(ISD::FCOS, MVT::f128, Expand);
166 setOperationAction(ISD::FDIV, MVT::f128, Custom);
167 setOperationAction(ISD::FMA, MVT::f128, Expand);
168 setOperationAction(ISD::FMUL, MVT::f128, Custom);
169 setOperationAction(ISD::FNEG, MVT::f128, Expand);
170 setOperationAction(ISD::FPOW, MVT::f128, Expand);
171 setOperationAction(ISD::FREM, MVT::f128, Expand);
172 setOperationAction(ISD::FRINT, MVT::f128, Expand);
173 setOperationAction(ISD::FSIN, MVT::f128, Expand);
174 setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
175 setOperationAction(ISD::FSQRT, MVT::f128, Expand);
176 setOperationAction(ISD::FSUB, MVT::f128, Custom);
177 setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
178 setOperationAction(ISD::SETCC, MVT::f128, Custom);
179 setOperationAction(ISD::BR_CC, MVT::f128, Custom);
180 setOperationAction(ISD::SELECT, MVT::f128, Custom);
181 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
182 setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
184 // Lowering for many of the conversions is actually specified by the non-f128
185 // type. The LowerXXX function will be trivial when f128 isn't involved.
186 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
187 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
188 setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
189 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
190 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
191 setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
192 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
193 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
194 setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
195 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
196 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
197 setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
198 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
199 setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
201 // Variable arguments.
202 setOperationAction(ISD::VASTART, MVT::Other, Custom);
203 setOperationAction(ISD::VAARG, MVT::Other, Custom);
204 setOperationAction(ISD::VACOPY, MVT::Other, Custom);
205 setOperationAction(ISD::VAEND, MVT::Other, Expand);
207 // Variable-sized objects.
208 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
209 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
210 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
212 // Exception handling.
213 // FIXME: These are guesses. Has this been defined yet?
214 setExceptionPointerRegister(AArch64::X0);
215 setExceptionSelectorRegister(AArch64::X1);
217 // Constant pool entries
218 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
221 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
223 // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
224 setOperationAction(ISD::ADDC, MVT::i32, Custom);
225 setOperationAction(ISD::ADDE, MVT::i32, Custom);
226 setOperationAction(ISD::SUBC, MVT::i32, Custom);
227 setOperationAction(ISD::SUBE, MVT::i32, Custom);
228 setOperationAction(ISD::ADDC, MVT::i64, Custom);
229 setOperationAction(ISD::ADDE, MVT::i64, Custom);
230 setOperationAction(ISD::SUBC, MVT::i64, Custom);
231 setOperationAction(ISD::SUBE, MVT::i64, Custom);
233 // AArch64 lacks both left-rotate and popcount instructions.
234 setOperationAction(ISD::ROTL, MVT::i32, Expand);
235 setOperationAction(ISD::ROTL, MVT::i64, Expand);
237 // AArch64 doesn't have {U|S}MUL_LOHI.
238 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
239 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
242 // Expand the undefined-at-zero variants to cttz/ctlz to their defined-at-zero
243 // counterparts, which AArch64 supports directly.
244 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
245 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
246 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
247 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
249 setOperationAction(ISD::CTPOP, MVT::i32, Custom);
250 setOperationAction(ISD::CTPOP, MVT::i64, Custom);
252 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
253 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
254 setOperationAction(ISD::SREM, MVT::i32, Expand);
255 setOperationAction(ISD::SREM, MVT::i64, Expand);
256 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
257 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
258 setOperationAction(ISD::UREM, MVT::i32, Expand);
259 setOperationAction(ISD::UREM, MVT::i64, Expand);
261 // Custom lower Add/Sub/Mul with overflow.
262 setOperationAction(ISD::SADDO, MVT::i32, Custom);
263 setOperationAction(ISD::SADDO, MVT::i64, Custom);
264 setOperationAction(ISD::UADDO, MVT::i32, Custom);
265 setOperationAction(ISD::UADDO, MVT::i64, Custom);
266 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
267 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
268 setOperationAction(ISD::USUBO, MVT::i32, Custom);
269 setOperationAction(ISD::USUBO, MVT::i64, Custom);
270 setOperationAction(ISD::SMULO, MVT::i32, Custom);
271 setOperationAction(ISD::SMULO, MVT::i64, Custom);
272 setOperationAction(ISD::UMULO, MVT::i32, Custom);
273 setOperationAction(ISD::UMULO, MVT::i64, Custom);
275 setOperationAction(ISD::FSIN, MVT::f32, Expand);
276 setOperationAction(ISD::FSIN, MVT::f64, Expand);
277 setOperationAction(ISD::FCOS, MVT::f32, Expand);
278 setOperationAction(ISD::FCOS, MVT::f64, Expand);
279 setOperationAction(ISD::FPOW, MVT::f32, Expand);
280 setOperationAction(ISD::FPOW, MVT::f64, Expand);
281 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
282 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
284 // f16 is storage-only, so we promote operations to f32 if we know this is
285 // valid, and ignore them otherwise. The operations not mentioned here will
286 // fail to select, but this is not a major problem as no source language
287 // should be emitting native f16 operations yet.
288 setOperationAction(ISD::FADD, MVT::f16, Promote);
289 setOperationAction(ISD::FDIV, MVT::f16, Promote);
290 setOperationAction(ISD::FMUL, MVT::f16, Promote);
291 setOperationAction(ISD::FSUB, MVT::f16, Promote);
293 // v4f16 is also a storage-only type, so promote it to v4f32 when that is
295 setOperationAction(ISD::FADD, MVT::v4f16, Promote);
296 setOperationAction(ISD::FSUB, MVT::v4f16, Promote);
297 setOperationAction(ISD::FMUL, MVT::v4f16, Promote);
298 setOperationAction(ISD::FDIV, MVT::v4f16, Promote);
299 setOperationAction(ISD::FP_EXTEND, MVT::v4f16, Promote);
300 setOperationAction(ISD::FP_ROUND, MVT::v4f16, Promote);
301 AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32);
302 AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32);
303 AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32);
304 AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32);
305 AddPromotedToType(ISD::FP_EXTEND, MVT::v4f16, MVT::v4f32);
306 AddPromotedToType(ISD::FP_ROUND, MVT::v4f16, MVT::v4f32);
308 // Expand all other v4f16 operations.
309 // FIXME: We could generate better code by promoting some operations to
311 setOperationAction(ISD::FABS, MVT::v4f16, Expand);
312 setOperationAction(ISD::FCEIL, MVT::v4f16, Expand);
313 setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand);
314 setOperationAction(ISD::FCOS, MVT::v4f16, Expand);
315 setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand);
316 setOperationAction(ISD::FMA, MVT::v4f16, Expand);
317 setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand);
318 setOperationAction(ISD::FNEG, MVT::v4f16, Expand);
319 setOperationAction(ISD::FPOW, MVT::v4f16, Expand);
320 setOperationAction(ISD::FPOWI, MVT::v4f16, Expand);
321 setOperationAction(ISD::FREM, MVT::v4f16, Expand);
322 setOperationAction(ISD::FROUND, MVT::v4f16, Expand);
323 setOperationAction(ISD::FRINT, MVT::v4f16, Expand);
324 setOperationAction(ISD::FSIN, MVT::v4f16, Expand);
325 setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand);
326 setOperationAction(ISD::FSQRT, MVT::v4f16, Expand);
327 setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand);
328 setOperationAction(ISD::SETCC, MVT::v4f16, Expand);
329 setOperationAction(ISD::BR_CC, MVT::v4f16, Expand);
330 setOperationAction(ISD::SELECT, MVT::v4f16, Expand);
331 setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand);
332 setOperationAction(ISD::FEXP, MVT::v4f16, Expand);
333 setOperationAction(ISD::FEXP2, MVT::v4f16, Expand);
334 setOperationAction(ISD::FLOG, MVT::v4f16, Expand);
335 setOperationAction(ISD::FLOG2, MVT::v4f16, Expand);
336 setOperationAction(ISD::FLOG10, MVT::v4f16, Expand);
339 // v8f16 is also a storage-only type, so expand it.
340 setOperationAction(ISD::FABS, MVT::v8f16, Expand);
341 setOperationAction(ISD::FADD, MVT::v8f16, Expand);
342 setOperationAction(ISD::FCEIL, MVT::v8f16, Expand);
343 setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand);
344 setOperationAction(ISD::FCOS, MVT::v8f16, Expand);
345 setOperationAction(ISD::FDIV, MVT::v8f16, Expand);
346 setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand);
347 setOperationAction(ISD::FMA, MVT::v8f16, Expand);
348 setOperationAction(ISD::FMUL, MVT::v8f16, Expand);
349 setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand);
350 setOperationAction(ISD::FNEG, MVT::v8f16, Expand);
351 setOperationAction(ISD::FPOW, MVT::v8f16, Expand);
352 setOperationAction(ISD::FPOWI, MVT::v8f16, Expand);
353 setOperationAction(ISD::FREM, MVT::v8f16, Expand);
354 setOperationAction(ISD::FROUND, MVT::v8f16, Expand);
355 setOperationAction(ISD::FRINT, MVT::v8f16, Expand);
356 setOperationAction(ISD::FSIN, MVT::v8f16, Expand);
357 setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
358 setOperationAction(ISD::FSQRT, MVT::v8f16, Expand);
359 setOperationAction(ISD::FSUB, MVT::v8f16, Expand);
360 setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand);
361 setOperationAction(ISD::SETCC, MVT::v8f16, Expand);
362 setOperationAction(ISD::BR_CC, MVT::v8f16, Expand);
363 setOperationAction(ISD::SELECT, MVT::v8f16, Expand);
364 setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand);
365 setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand);
366 setOperationAction(ISD::FEXP, MVT::v8f16, Expand);
367 setOperationAction(ISD::FEXP2, MVT::v8f16, Expand);
368 setOperationAction(ISD::FLOG, MVT::v8f16, Expand);
369 setOperationAction(ISD::FLOG2, MVT::v8f16, Expand);
370 setOperationAction(ISD::FLOG10, MVT::v8f16, Expand);
372 // AArch64 has implementations of a lot of rounding-like FP operations.
373 for (MVT Ty : {MVT::f32, MVT::f64}) {
374 setOperationAction(ISD::FFLOOR, Ty, Legal);
375 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
376 setOperationAction(ISD::FCEIL, Ty, Legal);
377 setOperationAction(ISD::FRINT, Ty, Legal);
378 setOperationAction(ISD::FTRUNC, Ty, Legal);
379 setOperationAction(ISD::FROUND, Ty, Legal);
382 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
384 if (Subtarget->isTargetMachO()) {
385 // For iOS, we don't want to the normal expansion of a libcall to
386 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
388 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
389 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
391 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
392 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
395 // Make floating-point constants legal for the large code model, so they don't
396 // become loads from the constant pool.
397 if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
398 setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
399 setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
402 // AArch64 does not have floating-point extending loads, i1 sign-extending
403 // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
404 for (MVT VT : MVT::fp_valuetypes()) {
405 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
406 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
407 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
408 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
410 for (MVT VT : MVT::integer_valuetypes())
411 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
413 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
414 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
415 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
416 setTruncStoreAction(MVT::f128, MVT::f80, Expand);
417 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
418 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
419 setTruncStoreAction(MVT::f128, MVT::f16, Expand);
421 setOperationAction(ISD::BITCAST, MVT::i16, Custom);
422 setOperationAction(ISD::BITCAST, MVT::f16, Custom);
424 // Indexed loads and stores are supported.
425 for (unsigned im = (unsigned)ISD::PRE_INC;
426 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
427 setIndexedLoadAction(im, MVT::i8, Legal);
428 setIndexedLoadAction(im, MVT::i16, Legal);
429 setIndexedLoadAction(im, MVT::i32, Legal);
430 setIndexedLoadAction(im, MVT::i64, Legal);
431 setIndexedLoadAction(im, MVT::f64, Legal);
432 setIndexedLoadAction(im, MVT::f32, Legal);
433 setIndexedStoreAction(im, MVT::i8, Legal);
434 setIndexedStoreAction(im, MVT::i16, Legal);
435 setIndexedStoreAction(im, MVT::i32, Legal);
436 setIndexedStoreAction(im, MVT::i64, Legal);
437 setIndexedStoreAction(im, MVT::f64, Legal);
438 setIndexedStoreAction(im, MVT::f32, Legal);
442 setOperationAction(ISD::TRAP, MVT::Other, Legal);
444 // We combine OR nodes for bitfield operations.
445 setTargetDAGCombine(ISD::OR);
447 // Vector add and sub nodes may conceal a high-half opportunity.
448 // Also, try to fold ADD into CSINC/CSINV..
449 setTargetDAGCombine(ISD::ADD);
450 setTargetDAGCombine(ISD::SUB);
452 setTargetDAGCombine(ISD::XOR);
453 setTargetDAGCombine(ISD::SINT_TO_FP);
454 setTargetDAGCombine(ISD::UINT_TO_FP);
456 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
458 setTargetDAGCombine(ISD::ANY_EXTEND);
459 setTargetDAGCombine(ISD::ZERO_EXTEND);
460 setTargetDAGCombine(ISD::SIGN_EXTEND);
461 setTargetDAGCombine(ISD::BITCAST);
462 setTargetDAGCombine(ISD::CONCAT_VECTORS);
463 setTargetDAGCombine(ISD::STORE);
465 setTargetDAGCombine(ISD::MUL);
467 setTargetDAGCombine(ISD::SELECT);
468 setTargetDAGCombine(ISD::VSELECT);
470 setTargetDAGCombine(ISD::INTRINSIC_VOID);
471 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
472 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
474 MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 8;
475 MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 4;
476 MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = 4;
478 setStackPointerRegisterToSaveRestore(AArch64::SP);
480 setSchedulingPreference(Sched::Hybrid);
483 MaskAndBranchFoldingIsLegal = true;
485 setMinFunctionAlignment(2);
487 RequireStrictAlign = (Align == StrictAlign);
489 setHasExtractBitsInsn(true);
491 if (Subtarget->hasNEON()) {
492 // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
493 // silliness like this:
494 setOperationAction(ISD::FABS, MVT::v1f64, Expand);
495 setOperationAction(ISD::FADD, MVT::v1f64, Expand);
496 setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
497 setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
498 setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
499 setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
500 setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
501 setOperationAction(ISD::FMA, MVT::v1f64, Expand);
502 setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
503 setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
504 setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
505 setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
506 setOperationAction(ISD::FREM, MVT::v1f64, Expand);
507 setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
508 setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
509 setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
510 setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
511 setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
512 setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
513 setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
514 setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
515 setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
516 setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
517 setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
518 setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
520 setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
521 setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
522 setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
523 setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
524 setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
526 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
528 // AArch64 doesn't have a direct vector ->f32 conversion instructions for
529 // elements smaller than i32, so promote the input to i32 first.
530 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Promote);
531 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Promote);
532 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Promote);
533 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Promote);
534 // Similarly, there is no direct i32 -> f64 vector conversion instruction.
535 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
536 setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
537 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
538 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
540 // AArch64 doesn't have MUL.2d:
541 setOperationAction(ISD::MUL, MVT::v2i64, Expand);
542 // Custom handling for some quad-vector types to detect MULL.
543 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
544 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
545 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
547 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
548 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
549 // Likewise, narrowing and extending vector loads/stores aren't handled
551 for (MVT VT : MVT::vector_valuetypes()) {
552 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
554 setOperationAction(ISD::MULHS, VT, Expand);
555 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
556 setOperationAction(ISD::MULHU, VT, Expand);
557 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
559 setOperationAction(ISD::BSWAP, VT, Expand);
561 for (MVT InnerVT : MVT::vector_valuetypes()) {
562 setTruncStoreAction(VT, InnerVT, Expand);
563 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
564 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
565 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
569 // AArch64 has implementations of a lot of rounding-like FP operations.
570 for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
571 setOperationAction(ISD::FFLOOR, Ty, Legal);
572 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
573 setOperationAction(ISD::FCEIL, Ty, Legal);
574 setOperationAction(ISD::FRINT, Ty, Legal);
575 setOperationAction(ISD::FTRUNC, Ty, Legal);
576 setOperationAction(ISD::FROUND, Ty, Legal);
580 // Prefer likely predicted branches to selects on out-of-order cores.
581 if (Subtarget->isCortexA57())
582 PredictableSelectIsExpensive = true;
585 void AArch64TargetLowering::addTypeForNEON(EVT VT, EVT PromotedBitwiseVT) {
586 if (VT == MVT::v2f32 || VT == MVT::v4f16) {
587 setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
588 AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i32);
590 setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
591 AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i32);
592 } else if (VT == MVT::v2f64 || VT == MVT::v4f32 || VT == MVT::v8f16) {
593 setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
594 AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i64);
596 setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
597 AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i64);
600 // Mark vector float intrinsics as expand.
601 if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
602 setOperationAction(ISD::FSIN, VT.getSimpleVT(), Expand);
603 setOperationAction(ISD::FCOS, VT.getSimpleVT(), Expand);
604 setOperationAction(ISD::FPOWI, VT.getSimpleVT(), Expand);
605 setOperationAction(ISD::FPOW, VT.getSimpleVT(), Expand);
606 setOperationAction(ISD::FLOG, VT.getSimpleVT(), Expand);
607 setOperationAction(ISD::FLOG2, VT.getSimpleVT(), Expand);
608 setOperationAction(ISD::FLOG10, VT.getSimpleVT(), Expand);
609 setOperationAction(ISD::FEXP, VT.getSimpleVT(), Expand);
610 setOperationAction(ISD::FEXP2, VT.getSimpleVT(), Expand);
613 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT.getSimpleVT(), Custom);
614 setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getSimpleVT(), Custom);
615 setOperationAction(ISD::BUILD_VECTOR, VT.getSimpleVT(), Custom);
616 setOperationAction(ISD::VECTOR_SHUFFLE, VT.getSimpleVT(), Custom);
617 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT.getSimpleVT(), Custom);
618 setOperationAction(ISD::SRA, VT.getSimpleVT(), Custom);
619 setOperationAction(ISD::SRL, VT.getSimpleVT(), Custom);
620 setOperationAction(ISD::SHL, VT.getSimpleVT(), Custom);
621 setOperationAction(ISD::AND, VT.getSimpleVT(), Custom);
622 setOperationAction(ISD::OR, VT.getSimpleVT(), Custom);
623 setOperationAction(ISD::SETCC, VT.getSimpleVT(), Custom);
624 setOperationAction(ISD::CONCAT_VECTORS, VT.getSimpleVT(), Legal);
626 setOperationAction(ISD::SELECT, VT.getSimpleVT(), Expand);
627 setOperationAction(ISD::SELECT_CC, VT.getSimpleVT(), Expand);
628 setOperationAction(ISD::VSELECT, VT.getSimpleVT(), Expand);
629 for (MVT InnerVT : MVT::all_valuetypes())
630 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT.getSimpleVT(), Expand);
632 // CNT supports only B element sizes.
633 if (VT != MVT::v8i8 && VT != MVT::v16i8)
634 setOperationAction(ISD::CTPOP, VT.getSimpleVT(), Expand);
636 setOperationAction(ISD::UDIV, VT.getSimpleVT(), Expand);
637 setOperationAction(ISD::SDIV, VT.getSimpleVT(), Expand);
638 setOperationAction(ISD::UREM, VT.getSimpleVT(), Expand);
639 setOperationAction(ISD::SREM, VT.getSimpleVT(), Expand);
640 setOperationAction(ISD::FREM, VT.getSimpleVT(), Expand);
642 setOperationAction(ISD::FP_TO_SINT, VT.getSimpleVT(), Custom);
643 setOperationAction(ISD::FP_TO_UINT, VT.getSimpleVT(), Custom);
645 if (Subtarget->isLittleEndian()) {
646 for (unsigned im = (unsigned)ISD::PRE_INC;
647 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
648 setIndexedLoadAction(im, VT.getSimpleVT(), Legal);
649 setIndexedStoreAction(im, VT.getSimpleVT(), Legal);
654 void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
655 addRegisterClass(VT, &AArch64::FPR64RegClass);
656 addTypeForNEON(VT, MVT::v2i32);
659 void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
660 addRegisterClass(VT, &AArch64::FPR128RegClass);
661 addTypeForNEON(VT, MVT::v4i32);
664 EVT AArch64TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
667 return VT.changeVectorElementTypeToInteger();
670 /// computeKnownBitsForTargetNode - Determine which of the bits specified in
671 /// Mask are known to be either zero or one and return them in the
672 /// KnownZero/KnownOne bitsets.
673 void AArch64TargetLowering::computeKnownBitsForTargetNode(
674 const SDValue Op, APInt &KnownZero, APInt &KnownOne,
675 const SelectionDAG &DAG, unsigned Depth) const {
676 switch (Op.getOpcode()) {
679 case AArch64ISD::CSEL: {
680 APInt KnownZero2, KnownOne2;
681 DAG.computeKnownBits(Op->getOperand(0), KnownZero, KnownOne, Depth + 1);
682 DAG.computeKnownBits(Op->getOperand(1), KnownZero2, KnownOne2, Depth + 1);
683 KnownZero &= KnownZero2;
684 KnownOne &= KnownOne2;
687 case ISD::INTRINSIC_W_CHAIN: {
688 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
689 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
692 case Intrinsic::aarch64_ldaxr:
693 case Intrinsic::aarch64_ldxr: {
694 unsigned BitWidth = KnownOne.getBitWidth();
695 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
696 unsigned MemBits = VT.getScalarType().getSizeInBits();
697 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
703 case ISD::INTRINSIC_WO_CHAIN:
704 case ISD::INTRINSIC_VOID: {
705 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
709 case Intrinsic::aarch64_neon_umaxv:
710 case Intrinsic::aarch64_neon_uminv: {
711 // Figure out the datatype of the vector operand. The UMINV instruction
712 // will zero extend the result, so we can mark as known zero all the
713 // bits larger than the element datatype. 32-bit or larget doesn't need
714 // this as those are legal types and will be handled by isel directly.
715 MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
716 unsigned BitWidth = KnownZero.getBitWidth();
717 if (VT == MVT::v8i8 || VT == MVT::v16i8) {
718 assert(BitWidth >= 8 && "Unexpected width!");
719 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
721 } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
722 assert(BitWidth >= 16 && "Unexpected width!");
723 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
733 MVT AArch64TargetLowering::getScalarShiftAmountTy(EVT LHSTy) const {
738 AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
739 const TargetLibraryInfo *libInfo) const {
740 return AArch64::createFastISel(funcInfo, libInfo);
743 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
747 case AArch64ISD::CALL: return "AArch64ISD::CALL";
748 case AArch64ISD::ADRP: return "AArch64ISD::ADRP";
749 case AArch64ISD::ADDlow: return "AArch64ISD::ADDlow";
750 case AArch64ISD::LOADgot: return "AArch64ISD::LOADgot";
751 case AArch64ISD::RET_FLAG: return "AArch64ISD::RET_FLAG";
752 case AArch64ISD::BRCOND: return "AArch64ISD::BRCOND";
753 case AArch64ISD::CSEL: return "AArch64ISD::CSEL";
754 case AArch64ISD::FCSEL: return "AArch64ISD::FCSEL";
755 case AArch64ISD::CSINV: return "AArch64ISD::CSINV";
756 case AArch64ISD::CSNEG: return "AArch64ISD::CSNEG";
757 case AArch64ISD::CSINC: return "AArch64ISD::CSINC";
758 case AArch64ISD::THREAD_POINTER: return "AArch64ISD::THREAD_POINTER";
759 case AArch64ISD::TLSDESC_CALLSEQ: return "AArch64ISD::TLSDESC_CALLSEQ";
760 case AArch64ISD::ADC: return "AArch64ISD::ADC";
761 case AArch64ISD::SBC: return "AArch64ISD::SBC";
762 case AArch64ISD::ADDS: return "AArch64ISD::ADDS";
763 case AArch64ISD::SUBS: return "AArch64ISD::SUBS";
764 case AArch64ISD::ADCS: return "AArch64ISD::ADCS";
765 case AArch64ISD::SBCS: return "AArch64ISD::SBCS";
766 case AArch64ISD::ANDS: return "AArch64ISD::ANDS";
767 case AArch64ISD::FCMP: return "AArch64ISD::FCMP";
768 case AArch64ISD::FMIN: return "AArch64ISD::FMIN";
769 case AArch64ISD::FMAX: return "AArch64ISD::FMAX";
770 case AArch64ISD::DUP: return "AArch64ISD::DUP";
771 case AArch64ISD::DUPLANE8: return "AArch64ISD::DUPLANE8";
772 case AArch64ISD::DUPLANE16: return "AArch64ISD::DUPLANE16";
773 case AArch64ISD::DUPLANE32: return "AArch64ISD::DUPLANE32";
774 case AArch64ISD::DUPLANE64: return "AArch64ISD::DUPLANE64";
775 case AArch64ISD::MOVI: return "AArch64ISD::MOVI";
776 case AArch64ISD::MOVIshift: return "AArch64ISD::MOVIshift";
777 case AArch64ISD::MOVIedit: return "AArch64ISD::MOVIedit";
778 case AArch64ISD::MOVImsl: return "AArch64ISD::MOVImsl";
779 case AArch64ISD::FMOV: return "AArch64ISD::FMOV";
780 case AArch64ISD::MVNIshift: return "AArch64ISD::MVNIshift";
781 case AArch64ISD::MVNImsl: return "AArch64ISD::MVNImsl";
782 case AArch64ISD::BICi: return "AArch64ISD::BICi";
783 case AArch64ISD::ORRi: return "AArch64ISD::ORRi";
784 case AArch64ISD::BSL: return "AArch64ISD::BSL";
785 case AArch64ISD::NEG: return "AArch64ISD::NEG";
786 case AArch64ISD::EXTR: return "AArch64ISD::EXTR";
787 case AArch64ISD::ZIP1: return "AArch64ISD::ZIP1";
788 case AArch64ISD::ZIP2: return "AArch64ISD::ZIP2";
789 case AArch64ISD::UZP1: return "AArch64ISD::UZP1";
790 case AArch64ISD::UZP2: return "AArch64ISD::UZP2";
791 case AArch64ISD::TRN1: return "AArch64ISD::TRN1";
792 case AArch64ISD::TRN2: return "AArch64ISD::TRN2";
793 case AArch64ISD::REV16: return "AArch64ISD::REV16";
794 case AArch64ISD::REV32: return "AArch64ISD::REV32";
795 case AArch64ISD::REV64: return "AArch64ISD::REV64";
796 case AArch64ISD::EXT: return "AArch64ISD::EXT";
797 case AArch64ISD::VSHL: return "AArch64ISD::VSHL";
798 case AArch64ISD::VLSHR: return "AArch64ISD::VLSHR";
799 case AArch64ISD::VASHR: return "AArch64ISD::VASHR";
800 case AArch64ISD::CMEQ: return "AArch64ISD::CMEQ";
801 case AArch64ISD::CMGE: return "AArch64ISD::CMGE";
802 case AArch64ISD::CMGT: return "AArch64ISD::CMGT";
803 case AArch64ISD::CMHI: return "AArch64ISD::CMHI";
804 case AArch64ISD::CMHS: return "AArch64ISD::CMHS";
805 case AArch64ISD::FCMEQ: return "AArch64ISD::FCMEQ";
806 case AArch64ISD::FCMGE: return "AArch64ISD::FCMGE";
807 case AArch64ISD::FCMGT: return "AArch64ISD::FCMGT";
808 case AArch64ISD::CMEQz: return "AArch64ISD::CMEQz";
809 case AArch64ISD::CMGEz: return "AArch64ISD::CMGEz";
810 case AArch64ISD::CMGTz: return "AArch64ISD::CMGTz";
811 case AArch64ISD::CMLEz: return "AArch64ISD::CMLEz";
812 case AArch64ISD::CMLTz: return "AArch64ISD::CMLTz";
813 case AArch64ISD::FCMEQz: return "AArch64ISD::FCMEQz";
814 case AArch64ISD::FCMGEz: return "AArch64ISD::FCMGEz";
815 case AArch64ISD::FCMGTz: return "AArch64ISD::FCMGTz";
816 case AArch64ISD::FCMLEz: return "AArch64ISD::FCMLEz";
817 case AArch64ISD::FCMLTz: return "AArch64ISD::FCMLTz";
818 case AArch64ISD::NOT: return "AArch64ISD::NOT";
819 case AArch64ISD::BIT: return "AArch64ISD::BIT";
820 case AArch64ISD::CBZ: return "AArch64ISD::CBZ";
821 case AArch64ISD::CBNZ: return "AArch64ISD::CBNZ";
822 case AArch64ISD::TBZ: return "AArch64ISD::TBZ";
823 case AArch64ISD::TBNZ: return "AArch64ISD::TBNZ";
824 case AArch64ISD::TC_RETURN: return "AArch64ISD::TC_RETURN";
825 case AArch64ISD::SITOF: return "AArch64ISD::SITOF";
826 case AArch64ISD::UITOF: return "AArch64ISD::UITOF";
827 case AArch64ISD::NVCAST: return "AArch64ISD::NVCAST";
828 case AArch64ISD::SQSHL_I: return "AArch64ISD::SQSHL_I";
829 case AArch64ISD::UQSHL_I: return "AArch64ISD::UQSHL_I";
830 case AArch64ISD::SRSHR_I: return "AArch64ISD::SRSHR_I";
831 case AArch64ISD::URSHR_I: return "AArch64ISD::URSHR_I";
832 case AArch64ISD::SQSHLU_I: return "AArch64ISD::SQSHLU_I";
833 case AArch64ISD::WrapperLarge: return "AArch64ISD::WrapperLarge";
834 case AArch64ISD::LD2post: return "AArch64ISD::LD2post";
835 case AArch64ISD::LD3post: return "AArch64ISD::LD3post";
836 case AArch64ISD::LD4post: return "AArch64ISD::LD4post";
837 case AArch64ISD::ST2post: return "AArch64ISD::ST2post";
838 case AArch64ISD::ST3post: return "AArch64ISD::ST3post";
839 case AArch64ISD::ST4post: return "AArch64ISD::ST4post";
840 case AArch64ISD::LD1x2post: return "AArch64ISD::LD1x2post";
841 case AArch64ISD::LD1x3post: return "AArch64ISD::LD1x3post";
842 case AArch64ISD::LD1x4post: return "AArch64ISD::LD1x4post";
843 case AArch64ISD::ST1x2post: return "AArch64ISD::ST1x2post";
844 case AArch64ISD::ST1x3post: return "AArch64ISD::ST1x3post";
845 case AArch64ISD::ST1x4post: return "AArch64ISD::ST1x4post";
846 case AArch64ISD::LD1DUPpost: return "AArch64ISD::LD1DUPpost";
847 case AArch64ISD::LD2DUPpost: return "AArch64ISD::LD2DUPpost";
848 case AArch64ISD::LD3DUPpost: return "AArch64ISD::LD3DUPpost";
849 case AArch64ISD::LD4DUPpost: return "AArch64ISD::LD4DUPpost";
850 case AArch64ISD::LD1LANEpost: return "AArch64ISD::LD1LANEpost";
851 case AArch64ISD::LD2LANEpost: return "AArch64ISD::LD2LANEpost";
852 case AArch64ISD::LD3LANEpost: return "AArch64ISD::LD3LANEpost";
853 case AArch64ISD::LD4LANEpost: return "AArch64ISD::LD4LANEpost";
854 case AArch64ISD::ST2LANEpost: return "AArch64ISD::ST2LANEpost";
855 case AArch64ISD::ST3LANEpost: return "AArch64ISD::ST3LANEpost";
856 case AArch64ISD::ST4LANEpost: return "AArch64ISD::ST4LANEpost";
857 case AArch64ISD::SMULL: return "AArch64ISD::SMULL";
858 case AArch64ISD::UMULL: return "AArch64ISD::UMULL";
863 AArch64TargetLowering::EmitF128CSEL(MachineInstr *MI,
864 MachineBasicBlock *MBB) const {
865 // We materialise the F128CSEL pseudo-instruction as some control flow and a
869 // [... previous instrs leading to comparison ...]
875 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
877 MachineFunction *MF = MBB->getParent();
878 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
879 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
880 DebugLoc DL = MI->getDebugLoc();
881 MachineFunction::iterator It = MBB;
884 unsigned DestReg = MI->getOperand(0).getReg();
885 unsigned IfTrueReg = MI->getOperand(1).getReg();
886 unsigned IfFalseReg = MI->getOperand(2).getReg();
887 unsigned CondCode = MI->getOperand(3).getImm();
888 bool NZCVKilled = MI->getOperand(4).isKill();
890 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
891 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
892 MF->insert(It, TrueBB);
893 MF->insert(It, EndBB);
895 // Transfer rest of current basic-block to EndBB
896 EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
898 EndBB->transferSuccessorsAndUpdatePHIs(MBB);
900 BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
901 BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
902 MBB->addSuccessor(TrueBB);
903 MBB->addSuccessor(EndBB);
905 // TrueBB falls through to the end.
906 TrueBB->addSuccessor(EndBB);
909 TrueBB->addLiveIn(AArch64::NZCV);
910 EndBB->addLiveIn(AArch64::NZCV);
913 BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
919 MI->eraseFromParent();
924 AArch64TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
925 MachineBasicBlock *BB) const {
926 switch (MI->getOpcode()) {
931 llvm_unreachable("Unexpected instruction for custom inserter!");
933 case AArch64::F128CSEL:
934 return EmitF128CSEL(MI, BB);
936 case TargetOpcode::STACKMAP:
937 case TargetOpcode::PATCHPOINT:
938 return emitPatchPoint(MI, BB);
942 //===----------------------------------------------------------------------===//
943 // AArch64 Lowering private implementation.
944 //===----------------------------------------------------------------------===//
946 //===----------------------------------------------------------------------===//
948 //===----------------------------------------------------------------------===//
950 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
952 static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
955 llvm_unreachable("Unknown condition code!");
957 return AArch64CC::NE;
959 return AArch64CC::EQ;
961 return AArch64CC::GT;
963 return AArch64CC::GE;
965 return AArch64CC::LT;
967 return AArch64CC::LE;
969 return AArch64CC::HI;
971 return AArch64CC::HS;
973 return AArch64CC::LO;
975 return AArch64CC::LS;
979 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
980 static void changeFPCCToAArch64CC(ISD::CondCode CC,
981 AArch64CC::CondCode &CondCode,
982 AArch64CC::CondCode &CondCode2) {
983 CondCode2 = AArch64CC::AL;
986 llvm_unreachable("Unknown FP condition!");
989 CondCode = AArch64CC::EQ;
993 CondCode = AArch64CC::GT;
997 CondCode = AArch64CC::GE;
1000 CondCode = AArch64CC::MI;
1003 CondCode = AArch64CC::LS;
1006 CondCode = AArch64CC::MI;
1007 CondCode2 = AArch64CC::GT;
1010 CondCode = AArch64CC::VC;
1013 CondCode = AArch64CC::VS;
1016 CondCode = AArch64CC::EQ;
1017 CondCode2 = AArch64CC::VS;
1020 CondCode = AArch64CC::HI;
1023 CondCode = AArch64CC::PL;
1027 CondCode = AArch64CC::LT;
1031 CondCode = AArch64CC::LE;
1035 CondCode = AArch64CC::NE;
1040 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1041 /// CC usable with the vector instructions. Fewer operations are available
1042 /// without a real NZCV register, so we have to use less efficient combinations
1043 /// to get the same effect.
1044 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1045 AArch64CC::CondCode &CondCode,
1046 AArch64CC::CondCode &CondCode2,
1051 // Mostly the scalar mappings work fine.
1052 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1055 Invert = true; // Fallthrough
1057 CondCode = AArch64CC::MI;
1058 CondCode2 = AArch64CC::GE;
1065 // All of the compare-mask comparisons are ordered, but we can switch
1066 // between the two by a double inversion. E.g. ULE == !OGT.
1068 changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1073 static bool isLegalArithImmed(uint64_t C) {
1074 // Matches AArch64DAGToDAGISel::SelectArithImmed().
1075 return (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1078 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1079 SDLoc dl, SelectionDAG &DAG) {
1080 EVT VT = LHS.getValueType();
1082 if (VT.isFloatingPoint())
1083 return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
1085 // The CMP instruction is just an alias for SUBS, and representing it as
1086 // SUBS means that it's possible to get CSE with subtract operations.
1087 // A later phase can perform the optimization of setting the destination
1088 // register to WZR/XZR if it ends up being unused.
1089 unsigned Opcode = AArch64ISD::SUBS;
1091 if (RHS.getOpcode() == ISD::SUB && isa<ConstantSDNode>(RHS.getOperand(0)) &&
1092 cast<ConstantSDNode>(RHS.getOperand(0))->getZExtValue() == 0 &&
1093 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1094 // We'd like to combine a (CMP op1, (sub 0, op2) into a CMN instruction on
1095 // the grounds that "op1 - (-op2) == op1 + op2". However, the C and V flags
1096 // can be set differently by this operation. It comes down to whether
1097 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1098 // everything is fine. If not then the optimization is wrong. Thus general
1099 // comparisons are only valid if op2 != 0.
1101 // So, finally, the only LLVM-native comparisons that don't mention C and V
1102 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1103 // the absence of information about op2.
1104 Opcode = AArch64ISD::ADDS;
1105 RHS = RHS.getOperand(1);
1106 } else if (LHS.getOpcode() == ISD::AND && isa<ConstantSDNode>(RHS) &&
1107 cast<ConstantSDNode>(RHS)->getZExtValue() == 0 &&
1108 !isUnsignedIntSetCC(CC)) {
1109 // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1110 // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1111 // of the signed comparisons.
1112 Opcode = AArch64ISD::ANDS;
1113 RHS = LHS.getOperand(1);
1114 LHS = LHS.getOperand(0);
1117 return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS)
1121 static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1122 SDValue &AArch64cc, SelectionDAG &DAG, SDLoc dl) {
1124 AArch64CC::CondCode AArch64CC;
1125 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1126 EVT VT = RHS.getValueType();
1127 uint64_t C = RHSC->getZExtValue();
1128 if (!isLegalArithImmed(C)) {
1129 // Constant does not fit, try adjusting it by one?
1135 if ((VT == MVT::i32 && C != 0x80000000 &&
1136 isLegalArithImmed((uint32_t)(C - 1))) ||
1137 (VT == MVT::i64 && C != 0x80000000ULL &&
1138 isLegalArithImmed(C - 1ULL))) {
1139 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1140 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1141 RHS = DAG.getConstant(C, VT);
1146 if ((VT == MVT::i32 && C != 0 &&
1147 isLegalArithImmed((uint32_t)(C - 1))) ||
1148 (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1149 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1150 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1151 RHS = DAG.getConstant(C, VT);
1156 if ((VT == MVT::i32 && C != INT32_MAX &&
1157 isLegalArithImmed((uint32_t)(C + 1))) ||
1158 (VT == MVT::i64 && C != INT64_MAX &&
1159 isLegalArithImmed(C + 1ULL))) {
1160 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1161 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1162 RHS = DAG.getConstant(C, VT);
1167 if ((VT == MVT::i32 && C != UINT32_MAX &&
1168 isLegalArithImmed((uint32_t)(C + 1))) ||
1169 (VT == MVT::i64 && C != UINT64_MAX &&
1170 isLegalArithImmed(C + 1ULL))) {
1171 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1172 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1173 RHS = DAG.getConstant(C, VT);
1179 // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
1180 // For the i8 operand, the largest immediate is 255, so this can be easily
1181 // encoded in the compare instruction. For the i16 operand, however, the
1182 // largest immediate cannot be encoded in the compare.
1183 // Therefore, use a sign extending load and cmn to avoid materializing the -1
1184 // constant. For example,
1186 // ldrh w0, [x0, #0]
1189 // ldrsh w0, [x0, #0]
1191 // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
1192 // if and only if (sext LHS) == (sext RHS). The checks are in place to ensure
1193 // both the LHS and RHS are truely zero extended and to make sure the
1194 // transformation is profitable.
1195 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
1196 if ((cast<ConstantSDNode>(RHS)->getZExtValue() >> 16 == 0) &&
1197 isa<LoadSDNode>(LHS)) {
1198 if (cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
1199 cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
1200 LHS.getNode()->hasNUsesOfValue(1, 0)) {
1201 int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
1202 if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
1204 DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
1205 DAG.getValueType(MVT::i16));
1206 Cmp = emitComparison(SExt,
1207 DAG.getConstant(ValueofRHS, RHS.getValueType()),
1209 AArch64CC = changeIntCCToAArch64CC(CC);
1210 AArch64cc = DAG.getConstant(AArch64CC, MVT::i32);
1216 Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
1217 AArch64CC = changeIntCCToAArch64CC(CC);
1218 AArch64cc = DAG.getConstant(AArch64CC, MVT::i32);
1222 static std::pair<SDValue, SDValue>
1223 getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
1224 assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
1225 "Unsupported value type");
1226 SDValue Value, Overflow;
1228 SDValue LHS = Op.getOperand(0);
1229 SDValue RHS = Op.getOperand(1);
1231 switch (Op.getOpcode()) {
1233 llvm_unreachable("Unknown overflow instruction!");
1235 Opc = AArch64ISD::ADDS;
1239 Opc = AArch64ISD::ADDS;
1243 Opc = AArch64ISD::SUBS;
1247 Opc = AArch64ISD::SUBS;
1250 // Multiply needs a little bit extra work.
1254 bool IsSigned = (Op.getOpcode() == ISD::SMULO) ? true : false;
1255 if (Op.getValueType() == MVT::i32) {
1256 unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1257 // For a 32 bit multiply with overflow check we want the instruction
1258 // selector to generate a widening multiply (SMADDL/UMADDL). For that we
1259 // need to generate the following pattern:
1260 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
1261 LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
1262 RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
1263 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1264 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
1265 DAG.getConstant(0, MVT::i64));
1266 // On AArch64 the upper 32 bits are always zero extended for a 32 bit
1267 // operation. We need to clear out the upper 32 bits, because we used a
1268 // widening multiply that wrote all 64 bits. In the end this should be a
1270 Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
1272 // The signed overflow check requires more than just a simple check for
1273 // any bit set in the upper 32 bits of the result. These bits could be
1274 // just the sign bits of a negative number. To perform the overflow
1275 // check we have to arithmetic shift right the 32nd bit of the result by
1276 // 31 bits. Then we compare the result to the upper 32 bits.
1277 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
1278 DAG.getConstant(32, MVT::i64));
1279 UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
1280 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
1281 DAG.getConstant(31, MVT::i64));
1282 // It is important that LowerBits is last, otherwise the arithmetic
1283 // shift will not be folded into the compare (SUBS).
1284 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
1285 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1288 // The overflow check for unsigned multiply is easy. We only need to
1289 // check if any of the upper 32 bits are set. This can be done with a
1290 // CMP (shifted register). For that we need to generate the following
1292 // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
1293 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
1294 DAG.getConstant(32, MVT::i64));
1295 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1297 DAG.getNode(AArch64ISD::SUBS, DL, VTs, DAG.getConstant(0, MVT::i64),
1298 UpperBits).getValue(1);
1302 assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
1303 // For the 64 bit multiply
1304 Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1306 SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
1307 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
1308 DAG.getConstant(63, MVT::i64));
1309 // It is important that LowerBits is last, otherwise the arithmetic
1310 // shift will not be folded into the compare (SUBS).
1311 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1312 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1315 SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
1316 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1318 DAG.getNode(AArch64ISD::SUBS, DL, VTs, DAG.getConstant(0, MVT::i64),
1319 UpperBits).getValue(1);
1326 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
1328 // Emit the AArch64 operation with overflow check.
1329 Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
1330 Overflow = Value.getValue(1);
1332 return std::make_pair(Value, Overflow);
1335 SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
1336 RTLIB::Libcall Call) const {
1337 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
1338 return makeLibCall(DAG, Call, MVT::f128, &Ops[0], Ops.size(), false,
1342 static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
1343 SDValue Sel = Op.getOperand(0);
1344 SDValue Other = Op.getOperand(1);
1346 // If neither operand is a SELECT_CC, give up.
1347 if (Sel.getOpcode() != ISD::SELECT_CC)
1348 std::swap(Sel, Other);
1349 if (Sel.getOpcode() != ISD::SELECT_CC)
1352 // The folding we want to perform is:
1353 // (xor x, (select_cc a, b, cc, 0, -1) )
1355 // (csel x, (xor x, -1), cc ...)
1357 // The latter will get matched to a CSINV instruction.
1359 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
1360 SDValue LHS = Sel.getOperand(0);
1361 SDValue RHS = Sel.getOperand(1);
1362 SDValue TVal = Sel.getOperand(2);
1363 SDValue FVal = Sel.getOperand(3);
1366 // FIXME: This could be generalized to non-integer comparisons.
1367 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
1370 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
1371 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
1373 // The the values aren't constants, this isn't the pattern we're looking for.
1374 if (!CFVal || !CTVal)
1377 // We can commute the SELECT_CC by inverting the condition. This
1378 // might be needed to make this fit into a CSINV pattern.
1379 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
1380 std::swap(TVal, FVal);
1381 std::swap(CTVal, CFVal);
1382 CC = ISD::getSetCCInverse(CC, true);
1385 // If the constants line up, perform the transform!
1386 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
1388 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
1391 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
1392 DAG.getConstant(-1ULL, Other.getValueType()));
1394 return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
1401 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
1402 EVT VT = Op.getValueType();
1404 // Let legalize expand this if it isn't a legal type yet.
1405 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
1408 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
1411 bool ExtraOp = false;
1412 switch (Op.getOpcode()) {
1414 llvm_unreachable("Invalid code");
1416 Opc = AArch64ISD::ADDS;
1419 Opc = AArch64ISD::SUBS;
1422 Opc = AArch64ISD::ADCS;
1426 Opc = AArch64ISD::SBCS;
1432 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
1433 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
1437 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
1438 // Let legalize expand this if it isn't a legal type yet.
1439 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
1442 AArch64CC::CondCode CC;
1443 // The actual operation that sets the overflow or carry flag.
1444 SDValue Value, Overflow;
1445 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
1447 // We use 0 and 1 as false and true values.
1448 SDValue TVal = DAG.getConstant(1, MVT::i32);
1449 SDValue FVal = DAG.getConstant(0, MVT::i32);
1451 // We use an inverted condition, because the conditional select is inverted
1452 // too. This will allow it to be selected to a single instruction:
1453 // CSINC Wd, WZR, WZR, invert(cond).
1454 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), MVT::i32);
1455 Overflow = DAG.getNode(AArch64ISD::CSEL, SDLoc(Op), MVT::i32, FVal, TVal,
1458 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
1459 return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), VTs, Value, Overflow);
1462 // Prefetch operands are:
1463 // 1: Address to prefetch
1465 // 3: int locality (0 = no locality ... 3 = extreme locality)
1466 // 4: bool isDataCache
1467 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
1469 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
1470 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
1471 unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
1473 bool IsStream = !Locality;
1474 // When the locality number is set
1476 // The front-end should have filtered out the out-of-range values
1477 assert(Locality <= 3 && "Prefetch locality out-of-range");
1478 // The locality degree is the opposite of the cache speed.
1479 // Put the number the other way around.
1480 // The encoding starts at 0 for level 1
1481 Locality = 3 - Locality;
1484 // built the mask value encoding the expected behavior.
1485 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit
1486 (!IsData << 3) | // IsDataCache bit
1487 (Locality << 1) | // Cache level bits
1488 (unsigned)IsStream; // Stream bit
1489 return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
1490 DAG.getConstant(PrfOp, MVT::i32), Op.getOperand(1));
1493 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
1494 SelectionDAG &DAG) const {
1495 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
1498 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
1500 return LowerF128Call(Op, DAG, LC);
1503 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
1504 SelectionDAG &DAG) const {
1505 if (Op.getOperand(0).getValueType() != MVT::f128) {
1506 // It's legal except when f128 is involved
1511 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
1513 // FP_ROUND node has a second operand indicating whether it is known to be
1514 // precise. That doesn't take part in the LibCall so we can't directly use
1516 SDValue SrcVal = Op.getOperand(0);
1517 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
1518 /*isSigned*/ false, SDLoc(Op)).first;
1521 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
1522 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1523 // Any additional optimization in this function should be recorded
1524 // in the cost tables.
1525 EVT InVT = Op.getOperand(0).getValueType();
1526 EVT VT = Op.getValueType();
1528 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
1531 DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
1533 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
1536 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
1539 MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
1540 VT.getVectorNumElements());
1541 SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
1542 return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
1545 // Type changing conversions are illegal.
1549 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
1550 SelectionDAG &DAG) const {
1551 if (Op.getOperand(0).getValueType().isVector())
1552 return LowerVectorFP_TO_INT(Op, DAG);
1554 if (Op.getOperand(0).getValueType() != MVT::f128) {
1555 // It's legal except when f128 is involved
1560 if (Op.getOpcode() == ISD::FP_TO_SINT)
1561 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
1563 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
1565 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
1566 return makeLibCall(DAG, LC, Op.getValueType(), &Ops[0], Ops.size(), false,
1570 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
1571 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1572 // Any additional optimization in this function should be recorded
1573 // in the cost tables.
1574 EVT VT = Op.getValueType();
1576 SDValue In = Op.getOperand(0);
1577 EVT InVT = In.getValueType();
1579 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
1581 MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
1582 InVT.getVectorNumElements());
1583 In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
1584 return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0));
1587 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
1589 Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1590 EVT CastVT = VT.changeVectorElementTypeToInteger();
1591 In = DAG.getNode(CastOpc, dl, CastVT, In);
1592 return DAG.getNode(Op.getOpcode(), dl, VT, In);
1598 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
1599 SelectionDAG &DAG) const {
1600 if (Op.getValueType().isVector())
1601 return LowerVectorINT_TO_FP(Op, DAG);
1603 // i128 conversions are libcalls.
1604 if (Op.getOperand(0).getValueType() == MVT::i128)
1607 // Other conversions are legal, unless it's to the completely software-based
1609 if (Op.getValueType() != MVT::f128)
1613 if (Op.getOpcode() == ISD::SINT_TO_FP)
1614 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
1616 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
1618 return LowerF128Call(Op, DAG, LC);
1621 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
1622 SelectionDAG &DAG) const {
1623 // For iOS, we want to call an alternative entry point: __sincos_stret,
1624 // which returns the values in two S / D registers.
1626 SDValue Arg = Op.getOperand(0);
1627 EVT ArgVT = Arg.getValueType();
1628 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
1635 Entry.isSExt = false;
1636 Entry.isZExt = false;
1637 Args.push_back(Entry);
1639 const char *LibcallName =
1640 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
1641 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
1643 StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
1644 TargetLowering::CallLoweringInfo CLI(DAG);
1645 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
1646 .setCallee(CallingConv::Fast, RetTy, Callee, std::move(Args), 0);
1648 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1649 return CallResult.first;
1652 static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
1653 if (Op.getValueType() != MVT::f16)
1656 assert(Op.getOperand(0).getValueType() == MVT::i16);
1659 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
1660 Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
1662 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
1663 DAG.getTargetConstant(AArch64::hsub, MVT::i32)),
1667 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
1668 if (OrigVT.getSizeInBits() >= 64)
1671 assert(OrigVT.isSimple() && "Expecting a simple value type");
1673 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
1674 switch (OrigSimpleTy) {
1675 default: llvm_unreachable("Unexpected Vector Type");
1684 static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
1687 unsigned ExtOpcode) {
1688 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
1689 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
1690 // 64-bits we need to insert a new extension so that it will be 64-bits.
1691 assert(ExtTy.is128BitVector() && "Unexpected extension size");
1692 if (OrigTy.getSizeInBits() >= 64)
1695 // Must extend size to at least 64 bits to be used as an operand for VMULL.
1696 EVT NewVT = getExtensionTo64Bits(OrigTy);
1698 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
1701 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
1703 EVT VT = N->getValueType(0);
1705 if (N->getOpcode() != ISD::BUILD_VECTOR)
1708 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1709 SDNode *Elt = N->getOperand(i).getNode();
1710 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
1711 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1712 unsigned HalfSize = EltSize / 2;
1714 if (!isIntN(HalfSize, C->getSExtValue()))
1717 if (!isUIntN(HalfSize, C->getZExtValue()))
1728 static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
1729 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
1730 return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
1731 N->getOperand(0)->getValueType(0),
1735 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
1736 EVT VT = N->getValueType(0);
1737 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
1738 unsigned NumElts = VT.getVectorNumElements();
1739 MVT TruncVT = MVT::getIntegerVT(EltSize);
1740 SmallVector<SDValue, 8> Ops;
1741 for (unsigned i = 0; i != NumElts; ++i) {
1742 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
1743 const APInt &CInt = C->getAPIntValue();
1744 // Element types smaller than 32 bits are not legal, so use i32 elements.
1745 // The values are implicitly truncated so sext vs. zext doesn't matter.
1746 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), MVT::i32));
1748 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
1749 MVT::getVectorVT(TruncVT, NumElts), Ops);
1752 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
1753 if (N->getOpcode() == ISD::SIGN_EXTEND)
1755 if (isExtendedBUILD_VECTOR(N, DAG, true))
1760 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
1761 if (N->getOpcode() == ISD::ZERO_EXTEND)
1763 if (isExtendedBUILD_VECTOR(N, DAG, false))
1768 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
1769 unsigned Opcode = N->getOpcode();
1770 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
1771 SDNode *N0 = N->getOperand(0).getNode();
1772 SDNode *N1 = N->getOperand(1).getNode();
1773 return N0->hasOneUse() && N1->hasOneUse() &&
1774 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
1779 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
1780 unsigned Opcode = N->getOpcode();
1781 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
1782 SDNode *N0 = N->getOperand(0).getNode();
1783 SDNode *N1 = N->getOperand(1).getNode();
1784 return N0->hasOneUse() && N1->hasOneUse() &&
1785 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
1790 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
1791 // Multiplications are only custom-lowered for 128-bit vectors so that
1792 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
1793 EVT VT = Op.getValueType();
1794 assert(VT.is128BitVector() && VT.isInteger() &&
1795 "unexpected type for custom-lowering ISD::MUL");
1796 SDNode *N0 = Op.getOperand(0).getNode();
1797 SDNode *N1 = Op.getOperand(1).getNode();
1798 unsigned NewOpc = 0;
1800 bool isN0SExt = isSignExtended(N0, DAG);
1801 bool isN1SExt = isSignExtended(N1, DAG);
1802 if (isN0SExt && isN1SExt)
1803 NewOpc = AArch64ISD::SMULL;
1805 bool isN0ZExt = isZeroExtended(N0, DAG);
1806 bool isN1ZExt = isZeroExtended(N1, DAG);
1807 if (isN0ZExt && isN1ZExt)
1808 NewOpc = AArch64ISD::UMULL;
1809 else if (isN1SExt || isN1ZExt) {
1810 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
1811 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
1812 if (isN1SExt && isAddSubSExt(N0, DAG)) {
1813 NewOpc = AArch64ISD::SMULL;
1815 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
1816 NewOpc = AArch64ISD::UMULL;
1818 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
1820 NewOpc = AArch64ISD::UMULL;
1826 if (VT == MVT::v2i64)
1827 // Fall through to expand this. It is not legal.
1830 // Other vector multiplications are legal.
1835 // Legalize to a S/UMULL instruction
1838 SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
1840 Op0 = skipExtensionForVectorMULL(N0, DAG);
1841 assert(Op0.getValueType().is64BitVector() &&
1842 Op1.getValueType().is64BitVector() &&
1843 "unexpected types for extended operands to VMULL");
1844 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
1846 // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
1847 // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
1848 // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
1849 SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
1850 SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
1851 EVT Op1VT = Op1.getValueType();
1852 return DAG.getNode(N0->getOpcode(), DL, VT,
1853 DAG.getNode(NewOpc, DL, VT,
1854 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
1855 DAG.getNode(NewOpc, DL, VT,
1856 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
1859 SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
1860 SelectionDAG &DAG) const {
1861 switch (Op.getOpcode()) {
1863 llvm_unreachable("unimplemented operand");
1866 return LowerBITCAST(Op, DAG);
1867 case ISD::GlobalAddress:
1868 return LowerGlobalAddress(Op, DAG);
1869 case ISD::GlobalTLSAddress:
1870 return LowerGlobalTLSAddress(Op, DAG);
1872 return LowerSETCC(Op, DAG);
1874 return LowerBR_CC(Op, DAG);
1876 return LowerSELECT(Op, DAG);
1877 case ISD::SELECT_CC:
1878 return LowerSELECT_CC(Op, DAG);
1879 case ISD::JumpTable:
1880 return LowerJumpTable(Op, DAG);
1881 case ISD::ConstantPool:
1882 return LowerConstantPool(Op, DAG);
1883 case ISD::BlockAddress:
1884 return LowerBlockAddress(Op, DAG);
1886 return LowerVASTART(Op, DAG);
1888 return LowerVACOPY(Op, DAG);
1890 return LowerVAARG(Op, DAG);
1895 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
1902 return LowerXALUO(Op, DAG);
1904 return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
1906 return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
1908 return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
1910 return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
1912 return LowerFP_ROUND(Op, DAG);
1913 case ISD::FP_EXTEND:
1914 return LowerFP_EXTEND(Op, DAG);
1915 case ISD::FRAMEADDR:
1916 return LowerFRAMEADDR(Op, DAG);
1917 case ISD::RETURNADDR:
1918 return LowerRETURNADDR(Op, DAG);
1919 case ISD::INSERT_VECTOR_ELT:
1920 return LowerINSERT_VECTOR_ELT(Op, DAG);
1921 case ISD::EXTRACT_VECTOR_ELT:
1922 return LowerEXTRACT_VECTOR_ELT(Op, DAG);
1923 case ISD::BUILD_VECTOR:
1924 return LowerBUILD_VECTOR(Op, DAG);
1925 case ISD::VECTOR_SHUFFLE:
1926 return LowerVECTOR_SHUFFLE(Op, DAG);
1927 case ISD::EXTRACT_SUBVECTOR:
1928 return LowerEXTRACT_SUBVECTOR(Op, DAG);
1932 return LowerVectorSRA_SRL_SHL(Op, DAG);
1933 case ISD::SHL_PARTS:
1934 return LowerShiftLeftParts(Op, DAG);
1935 case ISD::SRL_PARTS:
1936 case ISD::SRA_PARTS:
1937 return LowerShiftRightParts(Op, DAG);
1939 return LowerCTPOP(Op, DAG);
1940 case ISD::FCOPYSIGN:
1941 return LowerFCOPYSIGN(Op, DAG);
1943 return LowerVectorAND(Op, DAG);
1945 return LowerVectorOR(Op, DAG);
1947 return LowerXOR(Op, DAG);
1949 return LowerPREFETCH(Op, DAG);
1950 case ISD::SINT_TO_FP:
1951 case ISD::UINT_TO_FP:
1952 return LowerINT_TO_FP(Op, DAG);
1953 case ISD::FP_TO_SINT:
1954 case ISD::FP_TO_UINT:
1955 return LowerFP_TO_INT(Op, DAG);
1957 return LowerFSINCOS(Op, DAG);
1959 return LowerMUL(Op, DAG);
1963 /// getFunctionAlignment - Return the Log2 alignment of this function.
1964 unsigned AArch64TargetLowering::getFunctionAlignment(const Function *F) const {
1968 //===----------------------------------------------------------------------===//
1969 // Calling Convention Implementation
1970 //===----------------------------------------------------------------------===//
1972 #include "AArch64GenCallingConv.inc"
1974 /// Selects the correct CCAssignFn for a given CallingConvention value.
1975 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
1976 bool IsVarArg) const {
1979 llvm_unreachable("Unsupported calling convention.");
1980 case CallingConv::WebKit_JS:
1981 return CC_AArch64_WebKit_JS;
1982 case CallingConv::GHC:
1983 return CC_AArch64_GHC;
1984 case CallingConv::C:
1985 case CallingConv::Fast:
1986 if (!Subtarget->isTargetDarwin())
1987 return CC_AArch64_AAPCS;
1988 return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
1992 SDValue AArch64TargetLowering::LowerFormalArguments(
1993 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
1994 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
1995 SmallVectorImpl<SDValue> &InVals) const {
1996 MachineFunction &MF = DAG.getMachineFunction();
1997 MachineFrameInfo *MFI = MF.getFrameInfo();
1999 // Assign locations to all of the incoming arguments.
2000 SmallVector<CCValAssign, 16> ArgLocs;
2001 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2004 // At this point, Ins[].VT may already be promoted to i32. To correctly
2005 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2006 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2007 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
2008 // we use a special version of AnalyzeFormalArguments to pass in ValVT and
2010 unsigned NumArgs = Ins.size();
2011 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2012 unsigned CurArgIdx = 0;
2013 for (unsigned i = 0; i != NumArgs; ++i) {
2014 MVT ValVT = Ins[i].VT;
2015 if (Ins[i].isOrigArg()) {
2016 std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
2017 CurArgIdx = Ins[i].getOrigArgIndex();
2019 // Get type of the original argument.
2020 EVT ActualVT = getValueType(CurOrigArg->getType(), /*AllowUnknown*/ true);
2021 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
2022 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2023 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2025 else if (ActualMVT == MVT::i16)
2028 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2030 AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
2031 assert(!Res && "Call operand has unhandled type");
2034 assert(ArgLocs.size() == Ins.size());
2035 SmallVector<SDValue, 16> ArgValues;
2036 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2037 CCValAssign &VA = ArgLocs[i];
2039 if (Ins[i].Flags.isByVal()) {
2040 // Byval is used for HFAs in the PCS, but the system should work in a
2041 // non-compliant manner for larger structs.
2042 EVT PtrTy = getPointerTy();
2043 int Size = Ins[i].Flags.getByValSize();
2044 unsigned NumRegs = (Size + 7) / 8;
2046 // FIXME: This works on big-endian for composite byvals, which are the common
2047 // case. It should also work for fundamental types too.
2049 MFI->CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
2050 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrTy);
2051 InVals.push_back(FrameIdxN);
2056 if (VA.isRegLoc()) {
2057 // Arguments stored in registers.
2058 EVT RegVT = VA.getLocVT();
2061 const TargetRegisterClass *RC;
2063 if (RegVT == MVT::i32)
2064 RC = &AArch64::GPR32RegClass;
2065 else if (RegVT == MVT::i64)
2066 RC = &AArch64::GPR64RegClass;
2067 else if (RegVT == MVT::f16)
2068 RC = &AArch64::FPR16RegClass;
2069 else if (RegVT == MVT::f32)
2070 RC = &AArch64::FPR32RegClass;
2071 else if (RegVT == MVT::f64 || RegVT.is64BitVector())
2072 RC = &AArch64::FPR64RegClass;
2073 else if (RegVT == MVT::f128 || RegVT.is128BitVector())
2074 RC = &AArch64::FPR128RegClass;
2076 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2078 // Transform the arguments in physical registers into virtual ones.
2079 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2080 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2082 // If this is an 8, 16 or 32-bit value, it is really passed promoted
2083 // to 64 bits. Insert an assert[sz]ext to capture this, then
2084 // truncate to the right size.
2085 switch (VA.getLocInfo()) {
2087 llvm_unreachable("Unknown loc info!");
2088 case CCValAssign::Full:
2090 case CCValAssign::BCvt:
2091 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
2093 case CCValAssign::AExt:
2094 case CCValAssign::SExt:
2095 case CCValAssign::ZExt:
2096 // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
2097 // nodes after our lowering.
2098 assert(RegVT == Ins[i].VT && "incorrect register location selected");
2102 InVals.push_back(ArgValue);
2104 } else { // VA.isRegLoc()
2105 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
2106 unsigned ArgOffset = VA.getLocMemOffset();
2107 unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
2109 uint32_t BEAlign = 0;
2110 if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
2111 !Ins[i].Flags.isInConsecutiveRegs())
2112 BEAlign = 8 - ArgSize;
2114 int FI = MFI->CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
2116 // Create load nodes to retrieve arguments from the stack.
2117 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2120 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
2121 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
2122 MVT MemVT = VA.getValVT();
2124 switch (VA.getLocInfo()) {
2127 case CCValAssign::BCvt:
2128 MemVT = VA.getLocVT();
2130 case CCValAssign::SExt:
2131 ExtType = ISD::SEXTLOAD;
2133 case CCValAssign::ZExt:
2134 ExtType = ISD::ZEXTLOAD;
2136 case CCValAssign::AExt:
2137 ExtType = ISD::EXTLOAD;
2141 ArgValue = DAG.getExtLoad(ExtType, DL, VA.getLocVT(), Chain, FIN,
2142 MachinePointerInfo::getFixedStack(FI),
2143 MemVT, false, false, false, 0);
2145 InVals.push_back(ArgValue);
2151 if (!Subtarget->isTargetDarwin()) {
2152 // The AAPCS variadic function ABI is identical to the non-variadic
2153 // one. As a result there may be more arguments in registers and we should
2154 // save them for future reference.
2155 saveVarArgRegisters(CCInfo, DAG, DL, Chain);
2158 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
2159 // This will point to the next argument passed via stack.
2160 unsigned StackOffset = CCInfo.getNextStackOffset();
2161 // We currently pass all varargs at 8-byte alignment.
2162 StackOffset = ((StackOffset + 7) & ~7);
2163 AFI->setVarArgsStackIndex(MFI->CreateFixedObject(4, StackOffset, true));
2166 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2167 unsigned StackArgSize = CCInfo.getNextStackOffset();
2168 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2169 if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
2170 // This is a non-standard ABI so by fiat I say we're allowed to make full
2171 // use of the stack area to be popped, which must be aligned to 16 bytes in
2173 StackArgSize = RoundUpToAlignment(StackArgSize, 16);
2175 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
2176 // a multiple of 16.
2177 FuncInfo->setArgumentStackToRestore(StackArgSize);
2179 // This realignment carries over to the available bytes below. Our own
2180 // callers will guarantee the space is free by giving an aligned value to
2183 // Even if we're not expected to free up the space, it's useful to know how
2184 // much is there while considering tail calls (because we can reuse it).
2185 FuncInfo->setBytesInStackArgArea(StackArgSize);
2190 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
2191 SelectionDAG &DAG, SDLoc DL,
2192 SDValue &Chain) const {
2193 MachineFunction &MF = DAG.getMachineFunction();
2194 MachineFrameInfo *MFI = MF.getFrameInfo();
2195 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2197 SmallVector<SDValue, 8> MemOps;
2199 static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
2200 AArch64::X3, AArch64::X4, AArch64::X5,
2201 AArch64::X6, AArch64::X7 };
2202 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
2203 unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
2205 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
2207 if (GPRSaveSize != 0) {
2208 GPRIdx = MFI->CreateStackObject(GPRSaveSize, 8, false);
2210 SDValue FIN = DAG.getFrameIndex(GPRIdx, getPointerTy());
2212 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
2213 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
2214 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
2216 DAG.getStore(Val.getValue(1), DL, Val, FIN,
2217 MachinePointerInfo::getStack(i * 8), false, false, 0);
2218 MemOps.push_back(Store);
2219 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), FIN,
2220 DAG.getConstant(8, getPointerTy()));
2223 FuncInfo->setVarArgsGPRIndex(GPRIdx);
2224 FuncInfo->setVarArgsGPRSize(GPRSaveSize);
2226 if (Subtarget->hasFPARMv8()) {
2227 static const MCPhysReg FPRArgRegs[] = {
2228 AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
2229 AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
2230 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
2231 unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
2233 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
2235 if (FPRSaveSize != 0) {
2236 FPRIdx = MFI->CreateStackObject(FPRSaveSize, 16, false);
2238 SDValue FIN = DAG.getFrameIndex(FPRIdx, getPointerTy());
2240 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
2241 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
2242 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
2245 DAG.getStore(Val.getValue(1), DL, Val, FIN,
2246 MachinePointerInfo::getStack(i * 16), false, false, 0);
2247 MemOps.push_back(Store);
2248 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), FIN,
2249 DAG.getConstant(16, getPointerTy()));
2252 FuncInfo->setVarArgsFPRIndex(FPRIdx);
2253 FuncInfo->setVarArgsFPRSize(FPRSaveSize);
2256 if (!MemOps.empty()) {
2257 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
2261 /// LowerCallResult - Lower the result values of a call into the
2262 /// appropriate copies out of appropriate physical registers.
2263 SDValue AArch64TargetLowering::LowerCallResult(
2264 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
2265 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2266 SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
2267 SDValue ThisVal) const {
2268 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
2269 ? RetCC_AArch64_WebKit_JS
2270 : RetCC_AArch64_AAPCS;
2271 // Assign locations to each value returned by this call.
2272 SmallVector<CCValAssign, 16> RVLocs;
2273 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2275 CCInfo.AnalyzeCallResult(Ins, RetCC);
2277 // Copy all of the result registers out of their specified physreg.
2278 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2279 CCValAssign VA = RVLocs[i];
2281 // Pass 'this' value directly from the argument to return value, to avoid
2282 // reg unit interference
2283 if (i == 0 && isThisReturn) {
2284 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
2285 "unexpected return calling convention register assignment");
2286 InVals.push_back(ThisVal);
2291 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2292 Chain = Val.getValue(1);
2293 InFlag = Val.getValue(2);
2295 switch (VA.getLocInfo()) {
2297 llvm_unreachable("Unknown loc info!");
2298 case CCValAssign::Full:
2300 case CCValAssign::BCvt:
2301 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2305 InVals.push_back(Val);
2311 bool AArch64TargetLowering::isEligibleForTailCallOptimization(
2312 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
2313 bool isCalleeStructRet, bool isCallerStructRet,
2314 const SmallVectorImpl<ISD::OutputArg> &Outs,
2315 const SmallVectorImpl<SDValue> &OutVals,
2316 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2317 // For CallingConv::C this function knows whether the ABI needs
2318 // changing. That's not true for other conventions so they will have to opt in
2320 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
2323 const MachineFunction &MF = DAG.getMachineFunction();
2324 const Function *CallerF = MF.getFunction();
2325 CallingConv::ID CallerCC = CallerF->getCallingConv();
2326 bool CCMatch = CallerCC == CalleeCC;
2328 // Byval parameters hand the function a pointer directly into the stack area
2329 // we want to reuse during a tail call. Working around this *is* possible (see
2330 // X86) but less efficient and uglier in LowerCall.
2331 for (Function::const_arg_iterator i = CallerF->arg_begin(),
2332 e = CallerF->arg_end();
2334 if (i->hasByValAttr())
2337 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2338 if (IsTailCallConvention(CalleeCC) && CCMatch)
2343 // Externally-defined functions with weak linkage should not be
2344 // tail-called on AArch64 when the OS does not support dynamic
2345 // pre-emption of symbols, as the AAELF spec requires normal calls
2346 // to undefined weak functions to be replaced with a NOP or jump to the
2347 // next instruction. The behaviour of branch instructions in this
2348 // situation (as used for tail calls) is implementation-defined, so we
2349 // cannot rely on the linker replacing the tail call with a return.
2350 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2351 const GlobalValue *GV = G->getGlobal();
2352 const Triple TT(getTargetMachine().getTargetTriple());
2353 if (GV->hasExternalWeakLinkage() &&
2354 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2358 // Now we search for cases where we can use a tail call without changing the
2359 // ABI. Sibcall is used in some places (particularly gcc) to refer to this
2362 // I want anyone implementing a new calling convention to think long and hard
2363 // about this assert.
2364 assert((!isVarArg || CalleeCC == CallingConv::C) &&
2365 "Unexpected variadic calling convention");
2367 if (isVarArg && !Outs.empty()) {
2368 // At least two cases here: if caller is fastcc then we can't have any
2369 // memory arguments (we'd be expected to clean up the stack afterwards). If
2370 // caller is C then we could potentially use its argument area.
2372 // FIXME: for now we take the most conservative of these in both cases:
2373 // disallow all variadic memory operands.
2374 SmallVector<CCValAssign, 16> ArgLocs;
2375 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2378 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
2379 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2380 if (!ArgLocs[i].isRegLoc())
2384 // If the calling conventions do not match, then we'd better make sure the
2385 // results are returned in the same way as what the caller expects.
2387 SmallVector<CCValAssign, 16> RVLocs1;
2388 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2390 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForCall(CalleeCC, isVarArg));
2392 SmallVector<CCValAssign, 16> RVLocs2;
2393 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2395 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForCall(CallerCC, isVarArg));
2397 if (RVLocs1.size() != RVLocs2.size())
2399 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2400 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2402 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2404 if (RVLocs1[i].isRegLoc()) {
2405 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2408 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2414 // Nothing more to check if the callee is taking no arguments
2418 SmallVector<CCValAssign, 16> ArgLocs;
2419 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2422 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2424 const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2426 // If the stack arguments for this call would fit into our own save area then
2427 // the call can be made tail.
2428 return CCInfo.getNextStackOffset() <= FuncInfo->getBytesInStackArgArea();
2431 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
2433 MachineFrameInfo *MFI,
2434 int ClobberedFI) const {
2435 SmallVector<SDValue, 8> ArgChains;
2436 int64_t FirstByte = MFI->getObjectOffset(ClobberedFI);
2437 int64_t LastByte = FirstByte + MFI->getObjectSize(ClobberedFI) - 1;
2439 // Include the original chain at the beginning of the list. When this is
2440 // used by target LowerCall hooks, this helps legalize find the
2441 // CALLSEQ_BEGIN node.
2442 ArgChains.push_back(Chain);
2444 // Add a chain value for each stack argument corresponding
2445 for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
2446 UE = DAG.getEntryNode().getNode()->use_end();
2448 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
2449 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
2450 if (FI->getIndex() < 0) {
2451 int64_t InFirstByte = MFI->getObjectOffset(FI->getIndex());
2452 int64_t InLastByte = InFirstByte;
2453 InLastByte += MFI->getObjectSize(FI->getIndex()) - 1;
2455 if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
2456 (FirstByte <= InFirstByte && InFirstByte <= LastByte))
2457 ArgChains.push_back(SDValue(L, 1));
2460 // Build a tokenfactor for all the chains.
2461 return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
2464 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
2465 bool TailCallOpt) const {
2466 return CallCC == CallingConv::Fast && TailCallOpt;
2469 bool AArch64TargetLowering::IsTailCallConvention(CallingConv::ID CallCC) const {
2470 return CallCC == CallingConv::Fast;
2473 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
2474 /// and add input and output parameter nodes.
2476 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
2477 SmallVectorImpl<SDValue> &InVals) const {
2478 SelectionDAG &DAG = CLI.DAG;
2480 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2481 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2482 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2483 SDValue Chain = CLI.Chain;
2484 SDValue Callee = CLI.Callee;
2485 bool &IsTailCall = CLI.IsTailCall;
2486 CallingConv::ID CallConv = CLI.CallConv;
2487 bool IsVarArg = CLI.IsVarArg;
2489 MachineFunction &MF = DAG.getMachineFunction();
2490 bool IsStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
2491 bool IsThisReturn = false;
2493 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2494 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2495 bool IsSibCall = false;
2498 // Check if it's really possible to do a tail call.
2499 IsTailCall = isEligibleForTailCallOptimization(
2500 Callee, CallConv, IsVarArg, IsStructRet,
2501 MF.getFunction()->hasStructRetAttr(), Outs, OutVals, Ins, DAG);
2502 if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
2503 report_fatal_error("failed to perform tail call elimination on a call "
2504 "site marked musttail");
2506 // A sibling call is one where we're under the usual C ABI and not planning
2507 // to change that but can still do a tail call:
2508 if (!TailCallOpt && IsTailCall)
2515 // Analyze operands of the call, assigning locations to each operand.
2516 SmallVector<CCValAssign, 16> ArgLocs;
2517 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
2521 // Handle fixed and variable vector arguments differently.
2522 // Variable vector arguments always go into memory.
2523 unsigned NumArgs = Outs.size();
2525 for (unsigned i = 0; i != NumArgs; ++i) {
2526 MVT ArgVT = Outs[i].VT;
2527 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2528 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
2529 /*IsVarArg=*/ !Outs[i].IsFixed);
2530 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
2531 assert(!Res && "Call operand has unhandled type");
2535 // At this point, Outs[].VT may already be promoted to i32. To correctly
2536 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2537 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2538 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
2539 // we use a special version of AnalyzeCallOperands to pass in ValVT and
2541 unsigned NumArgs = Outs.size();
2542 for (unsigned i = 0; i != NumArgs; ++i) {
2543 MVT ValVT = Outs[i].VT;
2544 // Get type of the original argument.
2545 EVT ActualVT = getValueType(CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
2546 /*AllowUnknown*/ true);
2547 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
2548 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2549 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2550 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2552 else if (ActualMVT == MVT::i16)
2555 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2556 bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
2557 assert(!Res && "Call operand has unhandled type");
2562 // Get a count of how many bytes are to be pushed on the stack.
2563 unsigned NumBytes = CCInfo.getNextStackOffset();
2566 // Since we're not changing the ABI to make this a tail call, the memory
2567 // operands are already available in the caller's incoming argument space.
2571 // FPDiff is the byte offset of the call's argument area from the callee's.
2572 // Stores to callee stack arguments will be placed in FixedStackSlots offset
2573 // by this amount for a tail call. In a sibling call it must be 0 because the
2574 // caller will deallocate the entire stack and the callee still expects its
2575 // arguments to begin at SP+0. Completely unused for non-tail calls.
2578 if (IsTailCall && !IsSibCall) {
2579 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
2581 // Since callee will pop argument stack as a tail call, we must keep the
2582 // popped size 16-byte aligned.
2583 NumBytes = RoundUpToAlignment(NumBytes, 16);
2585 // FPDiff will be negative if this tail call requires more space than we
2586 // would automatically have in our incoming argument space. Positive if we
2587 // can actually shrink the stack.
2588 FPDiff = NumReusableBytes - NumBytes;
2590 // The stack pointer must be 16-byte aligned at all times it's used for a
2591 // memory operation, which in practice means at *all* times and in
2592 // particular across call boundaries. Therefore our own arguments started at
2593 // a 16-byte aligned SP and the delta applied for the tail call should
2594 // satisfy the same constraint.
2595 assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
2598 // Adjust the stack pointer for the new arguments...
2599 // These operations are automatically eliminated by the prolog/epilog pass
2602 DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true), DL);
2604 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP, getPointerTy());
2606 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2607 SmallVector<SDValue, 8> MemOpChains;
2609 // Walk the register/memloc assignments, inserting copies/loads.
2610 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
2611 ++i, ++realArgIdx) {
2612 CCValAssign &VA = ArgLocs[i];
2613 SDValue Arg = OutVals[realArgIdx];
2614 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2616 // Promote the value if needed.
2617 switch (VA.getLocInfo()) {
2619 llvm_unreachable("Unknown loc info!");
2620 case CCValAssign::Full:
2622 case CCValAssign::SExt:
2623 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2625 case CCValAssign::ZExt:
2626 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2628 case CCValAssign::AExt:
2629 if (Outs[realArgIdx].ArgVT == MVT::i1) {
2630 // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
2631 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
2632 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
2634 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2636 case CCValAssign::BCvt:
2637 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2639 case CCValAssign::FPExt:
2640 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
2644 if (VA.isRegLoc()) {
2645 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i64) {
2646 assert(VA.getLocVT() == MVT::i64 &&
2647 "unexpected calling convention register assignment");
2648 assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
2649 "unexpected use of 'returned'");
2650 IsThisReturn = true;
2652 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2654 assert(VA.isMemLoc());
2657 MachinePointerInfo DstInfo;
2659 // FIXME: This works on big-endian for composite byvals, which are the
2660 // common case. It should also work for fundamental types too.
2661 uint32_t BEAlign = 0;
2662 unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
2663 : VA.getValVT().getSizeInBits();
2664 OpSize = (OpSize + 7) / 8;
2665 if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
2666 !Flags.isInConsecutiveRegs()) {
2668 BEAlign = 8 - OpSize;
2670 unsigned LocMemOffset = VA.getLocMemOffset();
2671 int32_t Offset = LocMemOffset + BEAlign;
2672 SDValue PtrOff = DAG.getIntPtrConstant(Offset);
2673 PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr, PtrOff);
2676 Offset = Offset + FPDiff;
2677 int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2679 DstAddr = DAG.getFrameIndex(FI, getPointerTy());
2680 DstInfo = MachinePointerInfo::getFixedStack(FI);
2682 // Make sure any stack arguments overlapping with where we're storing
2683 // are loaded before this eventual operation. Otherwise they'll be
2685 Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
2687 SDValue PtrOff = DAG.getIntPtrConstant(Offset);
2689 DstAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr, PtrOff);
2690 DstInfo = MachinePointerInfo::getStack(LocMemOffset);
2693 if (Outs[i].Flags.isByVal()) {
2695 DAG.getConstant(Outs[i].Flags.getByValSize(), MVT::i64);
2696 SDValue Cpy = DAG.getMemcpy(
2697 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
2699 /*AlwaysInline = */ false, DstInfo, MachinePointerInfo());
2701 MemOpChains.push_back(Cpy);
2703 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
2704 // promoted to a legal register type i32, we should truncate Arg back to
2706 if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
2707 VA.getValVT() == MVT::i16)
2708 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
2711 DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, false, false, 0);
2712 MemOpChains.push_back(Store);
2717 if (!MemOpChains.empty())
2718 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2720 // Build a sequence of copy-to-reg nodes chained together with token chain
2721 // and flag operands which copy the outgoing args into the appropriate regs.
2723 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2724 Chain = DAG.getCopyToReg(Chain, DL, RegsToPass[i].first,
2725 RegsToPass[i].second, InFlag);
2726 InFlag = Chain.getValue(1);
2729 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2730 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2731 // node so that legalize doesn't hack it.
2732 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
2733 Subtarget->isTargetMachO()) {
2734 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2735 const GlobalValue *GV = G->getGlobal();
2736 bool InternalLinkage = GV->hasInternalLinkage();
2737 if (InternalLinkage)
2738 Callee = DAG.getTargetGlobalAddress(GV, DL, getPointerTy(), 0, 0);
2740 Callee = DAG.getTargetGlobalAddress(GV, DL, getPointerTy(), 0,
2742 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, getPointerTy(), Callee);
2744 } else if (ExternalSymbolSDNode *S =
2745 dyn_cast<ExternalSymbolSDNode>(Callee)) {
2746 const char *Sym = S->getSymbol();
2748 DAG.getTargetExternalSymbol(Sym, getPointerTy(), AArch64II::MO_GOT);
2749 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, getPointerTy(), Callee);
2751 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2752 const GlobalValue *GV = G->getGlobal();
2753 Callee = DAG.getTargetGlobalAddress(GV, DL, getPointerTy(), 0, 0);
2754 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2755 const char *Sym = S->getSymbol();
2756 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), 0);
2759 // We don't usually want to end the call-sequence here because we would tidy
2760 // the frame up *after* the call, however in the ABI-changing tail-call case
2761 // we've carefully laid out the parameters so that when sp is reset they'll be
2762 // in the correct location.
2763 if (IsTailCall && !IsSibCall) {
2764 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2765 DAG.getIntPtrConstant(0, true), InFlag, DL);
2766 InFlag = Chain.getValue(1);
2769 std::vector<SDValue> Ops;
2770 Ops.push_back(Chain);
2771 Ops.push_back(Callee);
2774 // Each tail call may have to adjust the stack by a different amount, so
2775 // this information must travel along with the operation for eventual
2776 // consumption by emitEpilogue.
2777 Ops.push_back(DAG.getTargetConstant(FPDiff, MVT::i32));
2780 // Add argument registers to the end of the list so that they are known live
2782 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2783 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2784 RegsToPass[i].second.getValueType()));
2786 // Add a register mask operand representing the call-preserved registers.
2787 const uint32_t *Mask;
2788 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
2790 // For 'this' returns, use the X0-preserving mask if applicable
2791 Mask = TRI->getThisReturnPreservedMask(CallConv);
2793 IsThisReturn = false;
2794 Mask = TRI->getCallPreservedMask(CallConv);
2797 Mask = TRI->getCallPreservedMask(CallConv);
2799 assert(Mask && "Missing call preserved mask for calling convention");
2800 Ops.push_back(DAG.getRegisterMask(Mask));
2802 if (InFlag.getNode())
2803 Ops.push_back(InFlag);
2805 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2807 // If we're doing a tall call, use a TC_RETURN here rather than an
2808 // actual call instruction.
2810 return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
2812 // Returns a chain and a flag for retval copy to use.
2813 Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
2814 InFlag = Chain.getValue(1);
2816 uint64_t CalleePopBytes = DoesCalleeRestoreStack(CallConv, TailCallOpt)
2817 ? RoundUpToAlignment(NumBytes, 16)
2820 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2821 DAG.getIntPtrConstant(CalleePopBytes, true),
2824 InFlag = Chain.getValue(1);
2826 // Handle result values, copying them out of physregs into vregs that we
2828 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
2829 InVals, IsThisReturn,
2830 IsThisReturn ? OutVals[0] : SDValue());
2833 bool AArch64TargetLowering::CanLowerReturn(
2834 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
2835 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
2836 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
2837 ? RetCC_AArch64_WebKit_JS
2838 : RetCC_AArch64_AAPCS;
2839 SmallVector<CCValAssign, 16> RVLocs;
2840 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2841 return CCInfo.CheckReturn(Outs, RetCC);
2845 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2847 const SmallVectorImpl<ISD::OutputArg> &Outs,
2848 const SmallVectorImpl<SDValue> &OutVals,
2849 SDLoc DL, SelectionDAG &DAG) const {
2850 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
2851 ? RetCC_AArch64_WebKit_JS
2852 : RetCC_AArch64_AAPCS;
2853 SmallVector<CCValAssign, 16> RVLocs;
2854 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2856 CCInfo.AnalyzeReturn(Outs, RetCC);
2858 // Copy the result values into the output registers.
2860 SmallVector<SDValue, 4> RetOps(1, Chain);
2861 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
2862 ++i, ++realRVLocIdx) {
2863 CCValAssign &VA = RVLocs[i];
2864 assert(VA.isRegLoc() && "Can only return in registers!");
2865 SDValue Arg = OutVals[realRVLocIdx];
2867 switch (VA.getLocInfo()) {
2869 llvm_unreachable("Unknown loc info!");
2870 case CCValAssign::Full:
2871 if (Outs[i].ArgVT == MVT::i1) {
2872 // AAPCS requires i1 to be zero-extended to i8 by the producer of the
2873 // value. This is strictly redundant on Darwin (which uses "zeroext
2874 // i1"), but will be optimised out before ISel.
2875 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
2876 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2879 case CCValAssign::BCvt:
2880 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2884 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2885 Flag = Chain.getValue(1);
2886 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2889 RetOps[0] = Chain; // Update chain.
2891 // Add the flag if we have it.
2893 RetOps.push_back(Flag);
2895 return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
2898 //===----------------------------------------------------------------------===//
2899 // Other Lowering Code
2900 //===----------------------------------------------------------------------===//
2902 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
2903 SelectionDAG &DAG) const {
2904 EVT PtrVT = getPointerTy();
2906 const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
2907 const GlobalValue *GV = GN->getGlobal();
2908 unsigned char OpFlags =
2909 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
2911 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
2912 "unexpected offset in global node");
2914 // This also catched the large code model case for Darwin.
2915 if ((OpFlags & AArch64II::MO_GOT) != 0) {
2916 SDValue GotAddr = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
2917 // FIXME: Once remat is capable of dealing with instructions with register
2918 // operands, expand this into two nodes instead of using a wrapper node.
2919 return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
2922 if ((OpFlags & AArch64II::MO_CONSTPOOL) != 0) {
2923 assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
2924 "use of MO_CONSTPOOL only supported on small model");
2925 SDValue Hi = DAG.getTargetConstantPool(GV, PtrVT, 0, 0, AArch64II::MO_PAGE);
2926 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
2927 unsigned char LoFlags = AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
2928 SDValue Lo = DAG.getTargetConstantPool(GV, PtrVT, 0, 0, LoFlags);
2929 SDValue PoolAddr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
2930 SDValue GlobalAddr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), PoolAddr,
2931 MachinePointerInfo::getConstantPool(),
2932 /*isVolatile=*/ false,
2933 /*isNonTemporal=*/ true,
2934 /*isInvariant=*/ true, 8);
2935 if (GN->getOffset() != 0)
2936 return DAG.getNode(ISD::ADD, DL, PtrVT, GlobalAddr,
2937 DAG.getConstant(GN->getOffset(), PtrVT));
2941 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2942 const unsigned char MO_NC = AArch64II::MO_NC;
2944 AArch64ISD::WrapperLarge, DL, PtrVT,
2945 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G3),
2946 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
2947 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
2948 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
2950 // Use ADRP/ADD or ADRP/LDR for everything else: the small model on ELF and
2951 // the only correct model on Darwin.
2952 SDValue Hi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2953 OpFlags | AArch64II::MO_PAGE);
2954 unsigned char LoFlags = OpFlags | AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
2955 SDValue Lo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, LoFlags);
2957 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
2958 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
2962 /// \brief Convert a TLS address reference into the correct sequence of loads
2963 /// and calls to compute the variable's address (for Darwin, currently) and
2964 /// return an SDValue containing the final node.
2966 /// Darwin only has one TLS scheme which must be capable of dealing with the
2967 /// fully general situation, in the worst case. This means:
2968 /// + "extern __thread" declaration.
2969 /// + Defined in a possibly unknown dynamic library.
2971 /// The general system is that each __thread variable has a [3 x i64] descriptor
2972 /// which contains information used by the runtime to calculate the address. The
2973 /// only part of this the compiler needs to know about is the first xword, which
2974 /// contains a function pointer that must be called with the address of the
2975 /// entire descriptor in "x0".
2977 /// Since this descriptor may be in a different unit, in general even the
2978 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
2980 /// adrp x0, _var@TLVPPAGE
2981 /// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor
2982 /// ldr x1, [x0] ; x1 contains 1st entry of descriptor,
2983 /// ; the function pointer
2984 /// blr x1 ; Uses descriptor address in x0
2985 /// ; Address of _var is now in x0.
2987 /// If the address of _var's descriptor *is* known to the linker, then it can
2988 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
2989 /// a slight efficiency gain.
2991 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
2992 SelectionDAG &DAG) const {
2993 assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
2996 MVT PtrVT = getPointerTy();
2997 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3000 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3001 SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
3003 // The first entry in the descriptor is a function pointer that we must call
3004 // to obtain the address of the variable.
3005 SDValue Chain = DAG.getEntryNode();
3006 SDValue FuncTLVGet =
3007 DAG.getLoad(MVT::i64, DL, Chain, DescAddr, MachinePointerInfo::getGOT(),
3008 false, true, true, 8);
3009 Chain = FuncTLVGet.getValue(1);
3011 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3012 MFI->setAdjustsStack(true);
3014 // TLS calls preserve all registers except those that absolutely must be
3015 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
3017 const uint32_t *Mask =
3018 Subtarget->getRegisterInfo()->getTLSCallPreservedMask();
3020 // Finally, we can make the call. This is just a degenerate version of a
3021 // normal AArch64 call node: x0 takes the address of the descriptor, and
3022 // returns the address of the variable in this thread.
3023 Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
3025 DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3026 Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
3027 DAG.getRegisterMask(Mask), Chain.getValue(1));
3028 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
3031 /// When accessing thread-local variables under either the general-dynamic or
3032 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
3033 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
3034 /// is a function pointer to carry out the resolution.
3036 /// The sequence is:
3037 /// adrp x0, :tlsdesc:var
3038 /// ldr x1, [x0, #:tlsdesc_lo12:var]
3039 /// add x0, x0, #:tlsdesc_lo12:var
3040 /// .tlsdesccall var
3042 /// (TPIDR_EL0 offset now in x0)
3044 /// The above sequence must be produced unscheduled, to enable the linker to
3045 /// optimize/relax this sequence.
3046 /// Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
3047 /// above sequence, and expanded really late in the compilation flow, to ensure
3048 /// the sequence is produced as per above.
3049 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr, SDLoc DL,
3050 SelectionDAG &DAG) const {
3051 EVT PtrVT = getPointerTy();
3053 SDValue Chain = DAG.getEntryNode();
3054 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3056 SmallVector<SDValue, 2> Ops;
3057 Ops.push_back(Chain);
3058 Ops.push_back(SymAddr);
3060 Chain = DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, Ops);
3061 SDValue Glue = Chain.getValue(1);
3063 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
3067 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
3068 SelectionDAG &DAG) const {
3069 assert(Subtarget->isTargetELF() && "This function expects an ELF target");
3070 assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
3071 "ELF TLS only supported in small memory model");
3072 // Different choices can be made for the maximum size of the TLS area for a
3073 // module. For the small address model, the default TLS size is 16MiB and the
3074 // maximum TLS size is 4GiB.
3075 // FIXME: add -mtls-size command line option and make it control the 16MiB
3076 // vs. 4GiB code sequence generation.
3077 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3079 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
3080 if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
3081 if (Model == TLSModel::LocalDynamic)
3082 Model = TLSModel::GeneralDynamic;
3086 EVT PtrVT = getPointerTy();
3088 const GlobalValue *GV = GA->getGlobal();
3090 SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
3092 if (Model == TLSModel::LocalExec) {
3093 SDValue HiVar = DAG.getTargetGlobalAddress(
3094 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
3095 SDValue LoVar = DAG.getTargetGlobalAddress(
3097 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3099 SDValue TPWithOff_lo =
3100 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
3101 HiVar, DAG.getTargetConstant(0, MVT::i32)),
3104 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
3105 LoVar, DAG.getTargetConstant(0, MVT::i32)),
3108 } else if (Model == TLSModel::InitialExec) {
3109 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3110 TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
3111 } else if (Model == TLSModel::LocalDynamic) {
3112 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
3113 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
3114 // the beginning of the module's TLS region, followed by a DTPREL offset
3117 // These accesses will need deduplicating if there's more than one.
3118 AArch64FunctionInfo *MFI =
3119 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
3120 MFI->incNumLocalDynamicTLSAccesses();
3122 // The call needs a relocation too for linker relaxation. It doesn't make
3123 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3125 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
3128 // Now we can calculate the offset from TPIDR_EL0 to this module's
3129 // thread-local area.
3130 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
3132 // Now use :dtprel_whatever: operations to calculate this variable's offset
3133 // in its thread-storage area.
3134 SDValue HiVar = DAG.getTargetGlobalAddress(
3135 GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
3136 SDValue LoVar = DAG.getTargetGlobalAddress(
3137 GV, DL, MVT::i64, 0,
3138 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3140 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
3141 DAG.getTargetConstant(0, MVT::i32)),
3143 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
3144 DAG.getTargetConstant(0, MVT::i32)),
3146 } else if (Model == TLSModel::GeneralDynamic) {
3147 // The call needs a relocation too for linker relaxation. It doesn't make
3148 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3151 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3153 // Finally we can make a call to calculate the offset from tpidr_el0.
3154 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
3156 llvm_unreachable("Unsupported ELF TLS access model");
3158 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
3161 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
3162 SelectionDAG &DAG) const {
3163 if (Subtarget->isTargetDarwin())
3164 return LowerDarwinGlobalTLSAddress(Op, DAG);
3165 else if (Subtarget->isTargetELF())
3166 return LowerELFGlobalTLSAddress(Op, DAG);
3168 llvm_unreachable("Unexpected platform trying to use TLS");
3170 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3171 SDValue Chain = Op.getOperand(0);
3172 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3173 SDValue LHS = Op.getOperand(2);
3174 SDValue RHS = Op.getOperand(3);
3175 SDValue Dest = Op.getOperand(4);
3178 // Handle f128 first, since lowering it will result in comparing the return
3179 // value of a libcall against zero, which is just what the rest of LowerBR_CC
3180 // is expecting to deal with.
3181 if (LHS.getValueType() == MVT::f128) {
3182 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3184 // If softenSetCCOperands returned a scalar, we need to compare the result
3185 // against zero to select between true and false values.
3186 if (!RHS.getNode()) {
3187 RHS = DAG.getConstant(0, LHS.getValueType());
3192 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
3194 unsigned Opc = LHS.getOpcode();
3195 if (LHS.getResNo() == 1 && isa<ConstantSDNode>(RHS) &&
3196 cast<ConstantSDNode>(RHS)->isOne() &&
3197 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3198 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
3199 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
3200 "Unexpected condition code.");
3201 // Only lower legal XALUO ops.
3202 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
3205 // The actual operation with overflow check.
3206 AArch64CC::CondCode OFCC;
3207 SDValue Value, Overflow;
3208 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
3210 if (CC == ISD::SETNE)
3211 OFCC = getInvertedCondCode(OFCC);
3212 SDValue CCVal = DAG.getConstant(OFCC, MVT::i32);
3214 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3218 if (LHS.getValueType().isInteger()) {
3219 assert((LHS.getValueType() == RHS.getValueType()) &&
3220 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3222 // If the RHS of the comparison is zero, we can potentially fold this
3223 // to a specialized branch.
3224 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
3225 if (RHSC && RHSC->getZExtValue() == 0) {
3226 if (CC == ISD::SETEQ) {
3227 // See if we can use a TBZ to fold in an AND as well.
3228 // TBZ has a smaller branch displacement than CBZ. If the offset is
3229 // out of bounds, a late MI-layer pass rewrites branches.
3230 // 403.gcc is an example that hits this case.
3231 if (LHS.getOpcode() == ISD::AND &&
3232 isa<ConstantSDNode>(LHS.getOperand(1)) &&
3233 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3234 SDValue Test = LHS.getOperand(0);
3235 uint64_t Mask = LHS.getConstantOperandVal(1);
3236 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
3237 DAG.getConstant(Log2_64(Mask), MVT::i64), Dest);
3240 return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
3241 } else if (CC == ISD::SETNE) {
3242 // See if we can use a TBZ to fold in an AND as well.
3243 // TBZ has a smaller branch displacement than CBZ. If the offset is
3244 // out of bounds, a late MI-layer pass rewrites branches.
3245 // 403.gcc is an example that hits this case.
3246 if (LHS.getOpcode() == ISD::AND &&
3247 isa<ConstantSDNode>(LHS.getOperand(1)) &&
3248 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3249 SDValue Test = LHS.getOperand(0);
3250 uint64_t Mask = LHS.getConstantOperandVal(1);
3251 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
3252 DAG.getConstant(Log2_64(Mask), MVT::i64), Dest);
3255 return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
3256 } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
3257 // Don't combine AND since emitComparison converts the AND to an ANDS
3258 // (a.k.a. TST) and the test in the test bit and branch instruction
3259 // becomes redundant. This would also increase register pressure.
3260 uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
3261 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
3262 DAG.getConstant(Mask, MVT::i64), Dest);
3265 if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
3266 LHS.getOpcode() != ISD::AND) {
3267 // Don't combine AND since emitComparison converts the AND to an ANDS
3268 // (a.k.a. TST) and the test in the test bit and branch instruction
3269 // becomes redundant. This would also increase register pressure.
3270 uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
3271 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
3272 DAG.getConstant(Mask, MVT::i64), Dest);
3276 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3277 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3281 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3283 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
3284 // clean. Some of them require two branches to implement.
3285 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3286 AArch64CC::CondCode CC1, CC2;
3287 changeFPCCToAArch64CC(CC, CC1, CC2);
3288 SDValue CC1Val = DAG.getConstant(CC1, MVT::i32);
3290 DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
3291 if (CC2 != AArch64CC::AL) {
3292 SDValue CC2Val = DAG.getConstant(CC2, MVT::i32);
3293 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
3300 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
3301 SelectionDAG &DAG) const {
3302 EVT VT = Op.getValueType();
3305 SDValue In1 = Op.getOperand(0);
3306 SDValue In2 = Op.getOperand(1);
3307 EVT SrcVT = In2.getValueType();
3309 if (SrcVT == MVT::f32 && VT == MVT::f64)
3310 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
3311 else if (SrcVT == MVT::f64 && VT == MVT::f32)
3312 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0));
3314 // FIXME: Src type is different, bail out for now. Can VT really be a
3322 SDValue VecVal1, VecVal2;
3323 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
3326 EltMask = 0x80000000ULL;
3328 if (!VT.isVector()) {
3329 VecVal1 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3330 DAG.getUNDEF(VecVT), In1);
3331 VecVal2 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3332 DAG.getUNDEF(VecVT), In2);
3334 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3335 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3337 } else if (VT == MVT::f64 || VT == MVT::v2f64) {
3341 // We want to materialize a mask with the the high bit set, but the AdvSIMD
3342 // immediate moves cannot materialize that in a single instruction for
3343 // 64-bit elements. Instead, materialize zero and then negate it.
3346 if (!VT.isVector()) {
3347 VecVal1 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3348 DAG.getUNDEF(VecVT), In1);
3349 VecVal2 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3350 DAG.getUNDEF(VecVT), In2);
3352 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3353 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3356 llvm_unreachable("Invalid type for copysign!");
3359 SDValue BuildVec = DAG.getConstant(EltMask, VecVT);
3361 // If we couldn't materialize the mask above, then the mask vector will be
3362 // the zero vector, and we need to negate it here.
3363 if (VT == MVT::f64 || VT == MVT::v2f64) {
3364 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
3365 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
3366 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
3370 DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
3373 return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
3374 else if (VT == MVT::f64)
3375 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
3377 return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
3380 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
3381 if (DAG.getMachineFunction().getFunction()->hasFnAttribute(
3382 Attribute::NoImplicitFloat))
3385 if (!Subtarget->hasNEON())
3388 // While there is no integer popcount instruction, it can
3389 // be more efficiently lowered to the following sequence that uses
3390 // AdvSIMD registers/instructions as long as the copies to/from
3391 // the AdvSIMD registers are cheap.
3392 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd
3393 // CNT V0.8B, V0.8B // 8xbyte pop-counts
3394 // ADDV B0, V0.8B // sum 8xbyte pop-counts
3395 // UMOV X0, V0.B[0] // copy byte result back to integer reg
3396 SDValue Val = Op.getOperand(0);
3398 EVT VT = Op.getValueType();
3401 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
3402 Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
3404 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
3405 SDValue UaddLV = DAG.getNode(
3406 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
3407 DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, MVT::i32), CtPop);
3410 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
3414 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3416 if (Op.getValueType().isVector())
3417 return LowerVSETCC(Op, DAG);
3419 SDValue LHS = Op.getOperand(0);
3420 SDValue RHS = Op.getOperand(1);
3421 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3424 // We chose ZeroOrOneBooleanContents, so use zero and one.
3425 EVT VT = Op.getValueType();
3426 SDValue TVal = DAG.getConstant(1, VT);
3427 SDValue FVal = DAG.getConstant(0, VT);
3429 // Handle f128 first, since one possible outcome is a normal integer
3430 // comparison which gets picked up by the next if statement.
3431 if (LHS.getValueType() == MVT::f128) {
3432 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3434 // If softenSetCCOperands returned a scalar, use it.
3435 if (!RHS.getNode()) {
3436 assert(LHS.getValueType() == Op.getValueType() &&
3437 "Unexpected setcc expansion!");
3442 if (LHS.getValueType().isInteger()) {
3445 getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
3447 // Note that we inverted the condition above, so we reverse the order of
3448 // the true and false operands here. This will allow the setcc to be
3449 // matched to a single CSINC instruction.
3450 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
3453 // Now we know we're dealing with FP values.
3454 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3456 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
3457 // and do the comparison.
3458 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3460 AArch64CC::CondCode CC1, CC2;
3461 changeFPCCToAArch64CC(CC, CC1, CC2);
3462 if (CC2 == AArch64CC::AL) {
3463 changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
3464 SDValue CC1Val = DAG.getConstant(CC1, MVT::i32);
3466 // Note that we inverted the condition above, so we reverse the order of
3467 // the true and false operands here. This will allow the setcc to be
3468 // matched to a single CSINC instruction.
3469 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
3471 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
3472 // totally clean. Some of them require two CSELs to implement. As is in
3473 // this case, we emit the first CSEL and then emit a second using the output
3474 // of the first as the RHS. We're effectively OR'ing the two CC's together.
3476 // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
3477 SDValue CC1Val = DAG.getConstant(CC1, MVT::i32);
3479 DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3481 SDValue CC2Val = DAG.getConstant(CC2, MVT::i32);
3482 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3486 /// A SELECT_CC operation is really some kind of max or min if both values being
3487 /// compared are, in some sense, equal to the results in either case. However,
3488 /// it is permissible to compare f32 values and produce directly extended f64
3491 /// Extending the comparison operands would also be allowed, but is less likely
3492 /// to happen in practice since their use is right here. Note that truncate
3493 /// operations would *not* be semantically equivalent.
3494 static bool selectCCOpsAreFMaxCompatible(SDValue Cmp, SDValue Result) {
3498 ConstantFPSDNode *CCmp = dyn_cast<ConstantFPSDNode>(Cmp);
3499 ConstantFPSDNode *CResult = dyn_cast<ConstantFPSDNode>(Result);
3500 if (CCmp && CResult && Cmp.getValueType() == MVT::f32 &&
3501 Result.getValueType() == MVT::f64) {
3503 APFloat CmpVal = CCmp->getValueAPF();
3504 CmpVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &Lossy);
3505 return CResult->getValueAPF().bitwiseIsEqual(CmpVal);
3508 return Result->getOpcode() == ISD::FP_EXTEND && Result->getOperand(0) == Cmp;
3511 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
3512 SelectionDAG &DAG) const {
3513 SDValue CC = Op->getOperand(0);
3514 SDValue TVal = Op->getOperand(1);
3515 SDValue FVal = Op->getOperand(2);
3518 unsigned Opc = CC.getOpcode();
3519 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
3521 if (CC.getResNo() == 1 &&
3522 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3523 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
3524 // Only lower legal XALUO ops.
3525 if (!DAG.getTargetLoweringInfo().isTypeLegal(CC->getValueType(0)))
3528 AArch64CC::CondCode OFCC;
3529 SDValue Value, Overflow;
3530 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CC.getValue(0), DAG);
3531 SDValue CCVal = DAG.getConstant(OFCC, MVT::i32);
3533 return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
3537 if (CC.getOpcode() == ISD::SETCC)
3538 return DAG.getSelectCC(DL, CC.getOperand(0), CC.getOperand(1), TVal, FVal,
3539 cast<CondCodeSDNode>(CC.getOperand(2))->get());
3541 return DAG.getSelectCC(DL, CC, DAG.getConstant(0, CC.getValueType()), TVal,
3545 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
3546 SelectionDAG &DAG) const {
3547 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3548 SDValue LHS = Op.getOperand(0);
3549 SDValue RHS = Op.getOperand(1);
3550 SDValue TVal = Op.getOperand(2);
3551 SDValue FVal = Op.getOperand(3);
3554 // Handle f128 first, because it will result in a comparison of some RTLIB
3555 // call result against zero.
3556 if (LHS.getValueType() == MVT::f128) {
3557 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3559 // If softenSetCCOperands returned a scalar, we need to compare the result
3560 // against zero to select between true and false values.
3561 if (!RHS.getNode()) {
3562 RHS = DAG.getConstant(0, LHS.getValueType());
3567 // Handle integers first.
3568 if (LHS.getValueType().isInteger()) {
3569 assert((LHS.getValueType() == RHS.getValueType()) &&
3570 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3572 unsigned Opcode = AArch64ISD::CSEL;
3574 // If both the TVal and the FVal are constants, see if we can swap them in
3575 // order to for a CSINV or CSINC out of them.
3576 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
3577 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
3579 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
3580 std::swap(TVal, FVal);
3581 std::swap(CTVal, CFVal);
3582 CC = ISD::getSetCCInverse(CC, true);
3583 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
3584 std::swap(TVal, FVal);
3585 std::swap(CTVal, CFVal);
3586 CC = ISD::getSetCCInverse(CC, true);
3587 } else if (TVal.getOpcode() == ISD::XOR) {
3588 // If TVal is a NOT we want to swap TVal and FVal so that we can match
3589 // with a CSINV rather than a CSEL.
3590 ConstantSDNode *CVal = dyn_cast<ConstantSDNode>(TVal.getOperand(1));
3592 if (CVal && CVal->isAllOnesValue()) {
3593 std::swap(TVal, FVal);
3594 std::swap(CTVal, CFVal);
3595 CC = ISD::getSetCCInverse(CC, true);
3597 } else if (TVal.getOpcode() == ISD::SUB) {
3598 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
3599 // that we can match with a CSNEG rather than a CSEL.
3600 ConstantSDNode *CVal = dyn_cast<ConstantSDNode>(TVal.getOperand(0));
3602 if (CVal && CVal->isNullValue()) {
3603 std::swap(TVal, FVal);
3604 std::swap(CTVal, CFVal);
3605 CC = ISD::getSetCCInverse(CC, true);
3607 } else if (CTVal && CFVal) {
3608 const int64_t TrueVal = CTVal->getSExtValue();
3609 const int64_t FalseVal = CFVal->getSExtValue();
3612 // If both TVal and FVal are constants, see if FVal is the
3613 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
3614 // instead of a CSEL in that case.
3615 if (TrueVal == ~FalseVal) {
3616 Opcode = AArch64ISD::CSINV;
3617 } else if (TrueVal == -FalseVal) {
3618 Opcode = AArch64ISD::CSNEG;
3619 } else if (TVal.getValueType() == MVT::i32) {
3620 // If our operands are only 32-bit wide, make sure we use 32-bit
3621 // arithmetic for the check whether we can use CSINC. This ensures that
3622 // the addition in the check will wrap around properly in case there is
3623 // an overflow (which would not be the case if we do the check with
3624 // 64-bit arithmetic).
3625 const uint32_t TrueVal32 = CTVal->getZExtValue();
3626 const uint32_t FalseVal32 = CFVal->getZExtValue();
3628 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
3629 Opcode = AArch64ISD::CSINC;
3631 if (TrueVal32 > FalseVal32) {
3635 // 64-bit check whether we can use CSINC.
3636 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
3637 Opcode = AArch64ISD::CSINC;
3639 if (TrueVal > FalseVal) {
3644 // Swap TVal and FVal if necessary.
3646 std::swap(TVal, FVal);
3647 std::swap(CTVal, CFVal);
3648 CC = ISD::getSetCCInverse(CC, true);
3651 if (Opcode != AArch64ISD::CSEL) {
3652 // Drop FVal since we can get its value by simply inverting/negating
3659 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3661 EVT VT = Op.getValueType();
3662 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
3665 // Now we know we're dealing with FP values.
3666 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3667 assert(LHS.getValueType() == RHS.getValueType());
3668 EVT VT = Op.getValueType();
3670 // Try to match this select into a max/min operation, which have dedicated
3671 // opcode in the instruction set.
3672 // FIXME: This is not correct in the presence of NaNs, so we only enable this
3674 if (getTargetMachine().Options.NoNaNsFPMath) {
3675 SDValue MinMaxLHS = TVal, MinMaxRHS = FVal;
3676 if (selectCCOpsAreFMaxCompatible(LHS, MinMaxRHS) &&
3677 selectCCOpsAreFMaxCompatible(RHS, MinMaxLHS)) {
3678 CC = ISD::getSetCCSwappedOperands(CC);
3679 std::swap(MinMaxLHS, MinMaxRHS);
3682 if (selectCCOpsAreFMaxCompatible(LHS, MinMaxLHS) &&
3683 selectCCOpsAreFMaxCompatible(RHS, MinMaxRHS)) {
3693 return DAG.getNode(AArch64ISD::FMAX, dl, VT, MinMaxLHS, MinMaxRHS);
3701 return DAG.getNode(AArch64ISD::FMIN, dl, VT, MinMaxLHS, MinMaxRHS);
3707 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
3708 // and do the comparison.
3709 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3711 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
3712 // clean. Some of them require two CSELs to implement.
3713 AArch64CC::CondCode CC1, CC2;
3714 changeFPCCToAArch64CC(CC, CC1, CC2);
3715 SDValue CC1Val = DAG.getConstant(CC1, MVT::i32);
3716 SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3718 // If we need a second CSEL, emit it, using the output of the first as the
3719 // RHS. We're effectively OR'ing the two CC's together.
3720 if (CC2 != AArch64CC::AL) {
3721 SDValue CC2Val = DAG.getConstant(CC2, MVT::i32);
3722 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3725 // Otherwise, return the output of the first CSEL.
3729 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
3730 SelectionDAG &DAG) const {
3731 // Jump table entries as PC relative offsets. No additional tweaking
3732 // is necessary here. Just get the address of the jump table.
3733 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
3734 EVT PtrVT = getPointerTy();
3737 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3738 !Subtarget->isTargetMachO()) {
3739 const unsigned char MO_NC = AArch64II::MO_NC;
3741 AArch64ISD::WrapperLarge, DL, PtrVT,
3742 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G3),
3743 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G2 | MO_NC),
3744 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G1 | MO_NC),
3745 DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
3746 AArch64II::MO_G0 | MO_NC));
3750 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_PAGE);
3751 SDValue Lo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
3752 AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3753 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3754 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3757 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
3758 SelectionDAG &DAG) const {
3759 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3760 EVT PtrVT = getPointerTy();
3763 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
3764 // Use the GOT for the large code model on iOS.
3765 if (Subtarget->isTargetMachO()) {
3766 SDValue GotAddr = DAG.getTargetConstantPool(
3767 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
3769 return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
3772 const unsigned char MO_NC = AArch64II::MO_NC;
3774 AArch64ISD::WrapperLarge, DL, PtrVT,
3775 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3776 CP->getOffset(), AArch64II::MO_G3),
3777 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3778 CP->getOffset(), AArch64II::MO_G2 | MO_NC),
3779 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3780 CP->getOffset(), AArch64II::MO_G1 | MO_NC),
3781 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3782 CP->getOffset(), AArch64II::MO_G0 | MO_NC));
3784 // Use ADRP/ADD or ADRP/LDR for everything else: the small memory model on
3785 // ELF, the only valid one on Darwin.
3787 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3788 CP->getOffset(), AArch64II::MO_PAGE);
3789 SDValue Lo = DAG.getTargetConstantPool(
3790 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
3791 AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3793 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3794 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3798 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
3799 SelectionDAG &DAG) const {
3800 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
3801 EVT PtrVT = getPointerTy();
3803 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3804 !Subtarget->isTargetMachO()) {
3805 const unsigned char MO_NC = AArch64II::MO_NC;
3807 AArch64ISD::WrapperLarge, DL, PtrVT,
3808 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G3),
3809 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
3810 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
3811 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
3813 SDValue Hi = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGE);
3814 SDValue Lo = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGEOFF |
3816 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3817 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3821 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
3822 SelectionDAG &DAG) const {
3823 AArch64FunctionInfo *FuncInfo =
3824 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
3828 DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), getPointerTy());
3829 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3830 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
3831 MachinePointerInfo(SV), false, false, 0);
3834 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
3835 SelectionDAG &DAG) const {
3836 // The layout of the va_list struct is specified in the AArch64 Procedure Call
3837 // Standard, section B.3.
3838 MachineFunction &MF = DAG.getMachineFunction();
3839 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3842 SDValue Chain = Op.getOperand(0);
3843 SDValue VAList = Op.getOperand(1);
3844 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3845 SmallVector<SDValue, 4> MemOps;
3847 // void *__stack at offset 0
3849 DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), getPointerTy());
3850 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
3851 MachinePointerInfo(SV), false, false, 8));
3853 // void *__gr_top at offset 8
3854 int GPRSize = FuncInfo->getVarArgsGPRSize();
3856 SDValue GRTop, GRTopAddr;
3858 GRTopAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3859 DAG.getConstant(8, getPointerTy()));
3861 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), getPointerTy());
3862 GRTop = DAG.getNode(ISD::ADD, DL, getPointerTy(), GRTop,
3863 DAG.getConstant(GPRSize, getPointerTy()));
3865 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
3866 MachinePointerInfo(SV, 8), false, false, 8));
3869 // void *__vr_top at offset 16
3870 int FPRSize = FuncInfo->getVarArgsFPRSize();
3872 SDValue VRTop, VRTopAddr;
3873 VRTopAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3874 DAG.getConstant(16, getPointerTy()));
3876 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), getPointerTy());
3877 VRTop = DAG.getNode(ISD::ADD, DL, getPointerTy(), VRTop,
3878 DAG.getConstant(FPRSize, getPointerTy()));
3880 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
3881 MachinePointerInfo(SV, 16), false, false, 8));
3884 // int __gr_offs at offset 24
3885 SDValue GROffsAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3886 DAG.getConstant(24, getPointerTy()));
3887 MemOps.push_back(DAG.getStore(Chain, DL, DAG.getConstant(-GPRSize, MVT::i32),
3888 GROffsAddr, MachinePointerInfo(SV, 24), false,
3891 // int __vr_offs at offset 28
3892 SDValue VROffsAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3893 DAG.getConstant(28, getPointerTy()));
3894 MemOps.push_back(DAG.getStore(Chain, DL, DAG.getConstant(-FPRSize, MVT::i32),
3895 VROffsAddr, MachinePointerInfo(SV, 28), false,
3898 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
3901 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
3902 SelectionDAG &DAG) const {
3903 return Subtarget->isTargetDarwin() ? LowerDarwin_VASTART(Op, DAG)
3904 : LowerAAPCS_VASTART(Op, DAG);
3907 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
3908 SelectionDAG &DAG) const {
3909 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
3911 unsigned VaListSize = Subtarget->isTargetDarwin() ? 8 : 32;
3912 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
3913 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
3915 return DAG.getMemcpy(Op.getOperand(0), SDLoc(Op), Op.getOperand(1),
3916 Op.getOperand(2), DAG.getConstant(VaListSize, MVT::i32),
3917 8, false, false, MachinePointerInfo(DestSV),
3918 MachinePointerInfo(SrcSV));
3921 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
3922 assert(Subtarget->isTargetDarwin() &&
3923 "automatic va_arg instruction only works on Darwin");
3925 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3926 EVT VT = Op.getValueType();
3928 SDValue Chain = Op.getOperand(0);
3929 SDValue Addr = Op.getOperand(1);
3930 unsigned Align = Op.getConstantOperandVal(3);
3932 SDValue VAList = DAG.getLoad(getPointerTy(), DL, Chain, Addr,
3933 MachinePointerInfo(V), false, false, false, 0);
3934 Chain = VAList.getValue(1);
3937 assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
3938 VAList = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3939 DAG.getConstant(Align - 1, getPointerTy()));
3940 VAList = DAG.getNode(ISD::AND, DL, getPointerTy(), VAList,
3941 DAG.getConstant(-(int64_t)Align, getPointerTy()));
3944 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
3945 uint64_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
3947 // Scalar integer and FP values smaller than 64 bits are implicitly extended
3948 // up to 64 bits. At the very least, we have to increase the striding of the
3949 // vaargs list to match this, and for FP values we need to introduce
3950 // FP_ROUND nodes as well.
3951 if (VT.isInteger() && !VT.isVector())
3953 bool NeedFPTrunc = false;
3954 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
3959 // Increment the pointer, VAList, to the next vaarg
3960 SDValue VANext = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3961 DAG.getConstant(ArgSize, getPointerTy()));
3962 // Store the incremented VAList to the legalized pointer
3963 SDValue APStore = DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V),
3966 // Load the actual argument out of the pointer VAList
3968 // Load the value as an f64.
3969 SDValue WideFP = DAG.getLoad(MVT::f64, DL, APStore, VAList,
3970 MachinePointerInfo(), false, false, false, 0);
3971 // Round the value down to an f32.
3972 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
3973 DAG.getIntPtrConstant(1));
3974 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
3975 // Merge the rounded value with the chain output of the load.
3976 return DAG.getMergeValues(Ops, DL);
3979 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo(), false,
3983 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
3984 SelectionDAG &DAG) const {
3985 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3986 MFI->setFrameAddressIsTaken(true);
3988 EVT VT = Op.getValueType();
3990 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3992 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
3994 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
3995 MachinePointerInfo(), false, false, false, 0);
3999 // FIXME? Maybe this could be a TableGen attribute on some registers and
4000 // this table could be generated automatically from RegInfo.
4001 unsigned AArch64TargetLowering::getRegisterByName(const char* RegName,
4003 unsigned Reg = StringSwitch<unsigned>(RegName)
4004 .Case("sp", AArch64::SP)
4008 report_fatal_error("Invalid register name global variable");
4011 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
4012 SelectionDAG &DAG) const {
4013 MachineFunction &MF = DAG.getMachineFunction();
4014 MachineFrameInfo *MFI = MF.getFrameInfo();
4015 MFI->setReturnAddressIsTaken(true);
4017 EVT VT = Op.getValueType();
4019 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4021 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4022 SDValue Offset = DAG.getConstant(8, getPointerTy());
4023 return DAG.getLoad(VT, DL, DAG.getEntryNode(),
4024 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
4025 MachinePointerInfo(), false, false, false, 0);
4028 // Return LR, which contains the return address. Mark it an implicit live-in.
4029 unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
4030 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4033 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4034 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
4035 SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
4036 SelectionDAG &DAG) const {
4037 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4038 EVT VT = Op.getValueType();
4039 unsigned VTBits = VT.getSizeInBits();
4041 SDValue ShOpLo = Op.getOperand(0);
4042 SDValue ShOpHi = Op.getOperand(1);
4043 SDValue ShAmt = Op.getOperand(2);
4045 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4047 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4049 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
4050 DAG.getConstant(VTBits, MVT::i64), ShAmt);
4051 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4052 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
4053 DAG.getConstant(VTBits, MVT::i64));
4054 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4056 SDValue Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, MVT::i64),
4057 ISD::SETGE, dl, DAG);
4058 SDValue CCVal = DAG.getConstant(AArch64CC::GE, MVT::i32);
4060 SDValue FalseValLo = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4061 SDValue TrueValLo = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4063 DAG.getNode(AArch64ISD::CSEL, dl, VT, TrueValLo, FalseValLo, CCVal, Cmp);
4065 // AArch64 shifts larger than the register width are wrapped rather than
4066 // clamped, so we can't just emit "hi >> x".
4067 SDValue FalseValHi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4068 SDValue TrueValHi = Opc == ISD::SRA
4069 ? DAG.getNode(Opc, dl, VT, ShOpHi,
4070 DAG.getConstant(VTBits - 1, MVT::i64))
4071 : DAG.getConstant(0, VT);
4073 DAG.getNode(AArch64ISD::CSEL, dl, VT, TrueValHi, FalseValHi, CCVal, Cmp);
4075 SDValue Ops[2] = { Lo, Hi };
4076 return DAG.getMergeValues(Ops, dl);
4079 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4080 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
4081 SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
4082 SelectionDAG &DAG) const {
4083 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4084 EVT VT = Op.getValueType();
4085 unsigned VTBits = VT.getSizeInBits();
4087 SDValue ShOpLo = Op.getOperand(0);
4088 SDValue ShOpHi = Op.getOperand(1);
4089 SDValue ShAmt = Op.getOperand(2);
4092 assert(Op.getOpcode() == ISD::SHL_PARTS);
4093 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
4094 DAG.getConstant(VTBits, MVT::i64), ShAmt);
4095 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4096 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
4097 DAG.getConstant(VTBits, MVT::i64));
4098 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4099 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4101 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4103 SDValue Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, MVT::i64),
4104 ISD::SETGE, dl, DAG);
4105 SDValue CCVal = DAG.getConstant(AArch64CC::GE, MVT::i32);
4107 DAG.getNode(AArch64ISD::CSEL, dl, VT, Tmp3, FalseVal, CCVal, Cmp);
4109 // AArch64 shifts of larger than register sizes are wrapped rather than
4110 // clamped, so we can't just emit "lo << a" if a is too big.
4111 SDValue TrueValLo = DAG.getConstant(0, VT);
4112 SDValue FalseValLo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4114 DAG.getNode(AArch64ISD::CSEL, dl, VT, TrueValLo, FalseValLo, CCVal, Cmp);
4116 SDValue Ops[2] = { Lo, Hi };
4117 return DAG.getMergeValues(Ops, dl);
4120 bool AArch64TargetLowering::isOffsetFoldingLegal(
4121 const GlobalAddressSDNode *GA) const {
4122 // The AArch64 target doesn't support folding offsets into global addresses.
4126 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4127 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
4128 // FIXME: We should be able to handle f128 as well with a clever lowering.
4129 if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32))
4133 return AArch64_AM::getFP64Imm(Imm) != -1;
4134 else if (VT == MVT::f32)
4135 return AArch64_AM::getFP32Imm(Imm) != -1;
4139 //===----------------------------------------------------------------------===//
4140 // AArch64 Optimization Hooks
4141 //===----------------------------------------------------------------------===//
4143 //===----------------------------------------------------------------------===//
4144 // AArch64 Inline Assembly Support
4145 //===----------------------------------------------------------------------===//
4147 // Table of Constraints
4148 // TODO: This is the current set of constraints supported by ARM for the
4149 // compiler, not all of them may make sense, e.g. S may be difficult to support.
4151 // r - A general register
4152 // w - An FP/SIMD register of some size in the range v0-v31
4153 // x - An FP/SIMD register of some size in the range v0-v15
4154 // I - Constant that can be used with an ADD instruction
4155 // J - Constant that can be used with a SUB instruction
4156 // K - Constant that can be used with a 32-bit logical instruction
4157 // L - Constant that can be used with a 64-bit logical instruction
4158 // M - Constant that can be used as a 32-bit MOV immediate
4159 // N - Constant that can be used as a 64-bit MOV immediate
4160 // Q - A memory reference with base register and no offset
4161 // S - A symbolic address
4162 // Y - Floating point constant zero
4163 // Z - Integer constant zero
4165 // Note that general register operands will be output using their 64-bit x
4166 // register name, whatever the size of the variable, unless the asm operand
4167 // is prefixed by the %w modifier. Floating-point and SIMD register operands
4168 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
4171 /// getConstraintType - Given a constraint letter, return the type of
4172 /// constraint it is for this target.
4173 AArch64TargetLowering::ConstraintType
4174 AArch64TargetLowering::getConstraintType(const std::string &Constraint) const {
4175 if (Constraint.size() == 1) {
4176 switch (Constraint[0]) {
4183 return C_RegisterClass;
4184 // An address with a single base register. Due to the way we
4185 // currently handle addresses it is the same as 'r'.
4190 return TargetLowering::getConstraintType(Constraint);
4193 /// Examine constraint type and operand type and determine a weight value.
4194 /// This object must already have been set up with the operand type
4195 /// and the current alternative constraint selected.
4196 TargetLowering::ConstraintWeight
4197 AArch64TargetLowering::getSingleConstraintMatchWeight(
4198 AsmOperandInfo &info, const char *constraint) const {
4199 ConstraintWeight weight = CW_Invalid;
4200 Value *CallOperandVal = info.CallOperandVal;
4201 // If we don't have a value, we can't do a match,
4202 // but allow it at the lowest weight.
4203 if (!CallOperandVal)
4205 Type *type = CallOperandVal->getType();
4206 // Look at the constraint type.
4207 switch (*constraint) {
4209 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
4213 if (type->isFloatingPointTy() || type->isVectorTy())
4214 weight = CW_Register;
4217 weight = CW_Constant;
4223 std::pair<unsigned, const TargetRegisterClass *>
4224 AArch64TargetLowering::getRegForInlineAsmConstraint(
4225 const TargetRegisterInfo *TRI, const std::string &Constraint,
4227 if (Constraint.size() == 1) {
4228 switch (Constraint[0]) {
4230 if (VT.getSizeInBits() == 64)
4231 return std::make_pair(0U, &AArch64::GPR64commonRegClass);
4232 return std::make_pair(0U, &AArch64::GPR32commonRegClass);
4235 return std::make_pair(0U, &AArch64::FPR32RegClass);
4236 if (VT.getSizeInBits() == 64)
4237 return std::make_pair(0U, &AArch64::FPR64RegClass);
4238 if (VT.getSizeInBits() == 128)
4239 return std::make_pair(0U, &AArch64::FPR128RegClass);
4241 // The instructions that this constraint is designed for can
4242 // only take 128-bit registers so just use that regclass.
4244 if (VT.getSizeInBits() == 128)
4245 return std::make_pair(0U, &AArch64::FPR128_loRegClass);
4249 if (StringRef("{cc}").equals_lower(Constraint))
4250 return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
4252 // Use the default implementation in TargetLowering to convert the register
4253 // constraint into a member of a register class.
4254 std::pair<unsigned, const TargetRegisterClass *> Res;
4255 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
4257 // Not found as a standard register?
4259 unsigned Size = Constraint.size();
4260 if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
4261 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
4262 const std::string Reg =
4263 std::string(&Constraint[2], &Constraint[Size - 1]);
4264 int RegNo = atoi(Reg.c_str());
4265 if (RegNo >= 0 && RegNo <= 31) {
4266 // v0 - v31 are aliases of q0 - q31.
4267 // By default we'll emit v0-v31 for this unless there's a modifier where
4268 // we'll emit the correct register as well.
4269 Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
4270 Res.second = &AArch64::FPR128RegClass;
4278 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
4279 /// vector. If it is invalid, don't add anything to Ops.
4280 void AArch64TargetLowering::LowerAsmOperandForConstraint(
4281 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
4282 SelectionDAG &DAG) const {
4285 // Currently only support length 1 constraints.
4286 if (Constraint.length() != 1)
4289 char ConstraintLetter = Constraint[0];
4290 switch (ConstraintLetter) {
4294 // This set of constraints deal with valid constants for various instructions.
4295 // Validate and return a target constant for them if we can.
4297 // 'z' maps to xzr or wzr so it needs an input of 0.
4298 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4299 if (!C || C->getZExtValue() != 0)
4302 if (Op.getValueType() == MVT::i64)
4303 Result = DAG.getRegister(AArch64::XZR, MVT::i64);
4305 Result = DAG.getRegister(AArch64::WZR, MVT::i32);
4315 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4319 // Grab the value and do some validation.
4320 uint64_t CVal = C->getZExtValue();
4321 switch (ConstraintLetter) {
4322 // The I constraint applies only to simple ADD or SUB immediate operands:
4323 // i.e. 0 to 4095 with optional shift by 12
4324 // The J constraint applies only to ADD or SUB immediates that would be
4325 // valid when negated, i.e. if [an add pattern] were to be output as a SUB
4326 // instruction [or vice versa], in other words -1 to -4095 with optional
4327 // left shift by 12.
4329 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
4333 uint64_t NVal = -C->getSExtValue();
4334 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
4335 CVal = C->getSExtValue();
4340 // The K and L constraints apply *only* to logical immediates, including
4341 // what used to be the MOVI alias for ORR (though the MOVI alias has now
4342 // been removed and MOV should be used). So these constraints have to
4343 // distinguish between bit patterns that are valid 32-bit or 64-bit
4344 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
4345 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
4348 if (AArch64_AM::isLogicalImmediate(CVal, 32))
4352 if (AArch64_AM::isLogicalImmediate(CVal, 64))
4355 // The M and N constraints are a superset of K and L respectively, for use
4356 // with the MOV (immediate) alias. As well as the logical immediates they
4357 // also match 32 or 64-bit immediates that can be loaded either using a
4358 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
4359 // (M) or 64-bit 0x1234000000000000 (N) etc.
4360 // As a note some of this code is liberally stolen from the asm parser.
4362 if (!isUInt<32>(CVal))
4364 if (AArch64_AM::isLogicalImmediate(CVal, 32))
4366 if ((CVal & 0xFFFF) == CVal)
4368 if ((CVal & 0xFFFF0000ULL) == CVal)
4370 uint64_t NCVal = ~(uint32_t)CVal;
4371 if ((NCVal & 0xFFFFULL) == NCVal)
4373 if ((NCVal & 0xFFFF0000ULL) == NCVal)
4378 if (AArch64_AM::isLogicalImmediate(CVal, 64))
4380 if ((CVal & 0xFFFFULL) == CVal)
4382 if ((CVal & 0xFFFF0000ULL) == CVal)
4384 if ((CVal & 0xFFFF00000000ULL) == CVal)
4386 if ((CVal & 0xFFFF000000000000ULL) == CVal)
4388 uint64_t NCVal = ~CVal;
4389 if ((NCVal & 0xFFFFULL) == NCVal)
4391 if ((NCVal & 0xFFFF0000ULL) == NCVal)
4393 if ((NCVal & 0xFFFF00000000ULL) == NCVal)
4395 if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
4403 // All assembler immediates are 64-bit integers.
4404 Result = DAG.getTargetConstant(CVal, MVT::i64);
4408 if (Result.getNode()) {
4409 Ops.push_back(Result);
4413 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
4416 //===----------------------------------------------------------------------===//
4417 // AArch64 Advanced SIMD Support
4418 //===----------------------------------------------------------------------===//
4420 /// WidenVector - Given a value in the V64 register class, produce the
4421 /// equivalent value in the V128 register class.
4422 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
4423 EVT VT = V64Reg.getValueType();
4424 unsigned NarrowSize = VT.getVectorNumElements();
4425 MVT EltTy = VT.getVectorElementType().getSimpleVT();
4426 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
4429 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
4430 V64Reg, DAG.getConstant(0, MVT::i32));
4433 /// getExtFactor - Determine the adjustment factor for the position when
4434 /// generating an "extract from vector registers" instruction.
4435 static unsigned getExtFactor(SDValue &V) {
4436 EVT EltType = V.getValueType().getVectorElementType();
4437 return EltType.getSizeInBits() / 8;
4440 /// NarrowVector - Given a value in the V128 register class, produce the
4441 /// equivalent value in the V64 register class.
4442 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
4443 EVT VT = V128Reg.getValueType();
4444 unsigned WideSize = VT.getVectorNumElements();
4445 MVT EltTy = VT.getVectorElementType().getSimpleVT();
4446 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
4449 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
4452 // Gather data to see if the operation can be modelled as a
4453 // shuffle in combination with VEXTs.
4454 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
4455 SelectionDAG &DAG) const {
4456 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
4458 EVT VT = Op.getValueType();
4459 unsigned NumElts = VT.getVectorNumElements();
4461 struct ShuffleSourceInfo {
4466 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
4467 // be compatible with the shuffle we intend to construct. As a result
4468 // ShuffleVec will be some sliding window into the original Vec.
4471 // Code should guarantee that element i in Vec starts at element "WindowBase
4472 // + i * WindowScale in ShuffleVec".
4476 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
4477 ShuffleSourceInfo(SDValue Vec)
4478 : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
4482 // First gather all vectors used as an immediate source for this BUILD_VECTOR
4484 SmallVector<ShuffleSourceInfo, 2> Sources;
4485 for (unsigned i = 0; i < NumElts; ++i) {
4486 SDValue V = Op.getOperand(i);
4487 if (V.getOpcode() == ISD::UNDEF)
4489 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4490 // A shuffle can only come from building a vector from various
4491 // elements of other vectors.
4495 // Add this element source to the list if it's not already there.
4496 SDValue SourceVec = V.getOperand(0);
4497 auto Source = std::find(Sources.begin(), Sources.end(), SourceVec);
4498 if (Source == Sources.end())
4499 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
4501 // Update the minimum and maximum lane number seen.
4502 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4503 Source->MinElt = std::min(Source->MinElt, EltNo);
4504 Source->MaxElt = std::max(Source->MaxElt, EltNo);
4507 // Currently only do something sane when at most two source vectors
4509 if (Sources.size() > 2)
4512 // Find out the smallest element size among result and two sources, and use
4513 // it as element size to build the shuffle_vector.
4514 EVT SmallestEltTy = VT.getVectorElementType();
4515 for (auto &Source : Sources) {
4516 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
4517 if (SrcEltTy.bitsLT(SmallestEltTy)) {
4518 SmallestEltTy = SrcEltTy;
4521 unsigned ResMultiplier =
4522 VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
4523 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
4524 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
4526 // If the source vector is too wide or too narrow, we may nevertheless be able
4527 // to construct a compatible shuffle either by concatenating it with UNDEF or
4528 // extracting a suitable range of elements.
4529 for (auto &Src : Sources) {
4530 EVT SrcVT = Src.ShuffleVec.getValueType();
4532 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
4535 // This stage of the search produces a source with the same element type as
4536 // the original, but with a total width matching the BUILD_VECTOR output.
4537 EVT EltVT = SrcVT.getVectorElementType();
4538 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
4539 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
4541 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
4542 assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
4543 // We can pad out the smaller vector for free, so if it's part of a
4546 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
4547 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
4551 assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
4553 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
4554 // Span too large for a VEXT to cope
4558 if (Src.MinElt >= NumSrcElts) {
4559 // The extraction can just take the second half
4561 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4562 DAG.getConstant(NumSrcElts, MVT::i64));
4563 Src.WindowBase = -NumSrcElts;
4564 } else if (Src.MaxElt < NumSrcElts) {
4565 // The extraction can just take the first half
4567 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4568 DAG.getConstant(0, MVT::i64));
4570 // An actual VEXT is needed
4572 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4573 DAG.getConstant(0, MVT::i64));
4575 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4576 DAG.getConstant(NumSrcElts, MVT::i64));
4577 unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
4579 Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
4580 VEXTSrc2, DAG.getConstant(Imm, MVT::i32));
4581 Src.WindowBase = -Src.MinElt;
4585 // Another possible incompatibility occurs from the vector element types. We
4586 // can fix this by bitcasting the source vectors to the same type we intend
4588 for (auto &Src : Sources) {
4589 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
4590 if (SrcEltTy == SmallestEltTy)
4592 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
4593 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
4594 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
4595 Src.WindowBase *= Src.WindowScale;
4598 // Final sanity check before we try to actually produce a shuffle.
4600 for (auto Src : Sources)
4601 assert(Src.ShuffleVec.getValueType() == ShuffleVT);
4604 // The stars all align, our next step is to produce the mask for the shuffle.
4605 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
4606 int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
4607 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
4608 SDValue Entry = Op.getOperand(i);
4609 if (Entry.getOpcode() == ISD::UNDEF)
4612 auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0));
4613 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
4615 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
4616 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
4618 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
4619 int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
4620 VT.getVectorElementType().getSizeInBits());
4621 int LanesDefined = BitsDefined / BitsPerShuffleLane;
4623 // This source is expected to fill ResMultiplier lanes of the final shuffle,
4624 // starting at the appropriate offset.
4625 int *LaneMask = &Mask[i * ResMultiplier];
4627 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
4628 ExtractBase += NumElts * (Src - Sources.begin());
4629 for (int j = 0; j < LanesDefined; ++j)
4630 LaneMask[j] = ExtractBase + j;
4633 // Final check before we try to produce nonsense...
4634 if (!isShuffleMaskLegal(Mask, ShuffleVT))
4637 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
4638 for (unsigned i = 0; i < Sources.size(); ++i)
4639 ShuffleOps[i] = Sources[i].ShuffleVec;
4641 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
4642 ShuffleOps[1], &Mask[0]);
4643 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
4646 // check if an EXT instruction can handle the shuffle mask when the
4647 // vector sources of the shuffle are the same.
4648 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4649 unsigned NumElts = VT.getVectorNumElements();
4651 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4657 // If this is a VEXT shuffle, the immediate value is the index of the first
4658 // element. The other shuffle indices must be the successive elements after
4660 unsigned ExpectedElt = Imm;
4661 for (unsigned i = 1; i < NumElts; ++i) {
4662 // Increment the expected index. If it wraps around, just follow it
4663 // back to index zero and keep going.
4665 if (ExpectedElt == NumElts)
4669 continue; // ignore UNDEF indices
4670 if (ExpectedElt != static_cast<unsigned>(M[i]))
4677 // check if an EXT instruction can handle the shuffle mask when the
4678 // vector sources of the shuffle are different.
4679 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
4681 // Look for the first non-undef element.
4682 const int *FirstRealElt = std::find_if(M.begin(), M.end(),
4683 [](int Elt) {return Elt >= 0;});
4685 // Benefit form APInt to handle overflow when calculating expected element.
4686 unsigned NumElts = VT.getVectorNumElements();
4687 unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
4688 APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
4689 // The following shuffle indices must be the successive elements after the
4690 // first real element.
4691 const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
4692 [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
4693 if (FirstWrongElt != M.end())
4696 // The index of an EXT is the first element if it is not UNDEF.
4697 // Watch out for the beginning UNDEFs. The EXT index should be the expected
4698 // value of the first element. E.g.
4699 // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
4700 // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
4701 // ExpectedElt is the last mask index plus 1.
4702 Imm = ExpectedElt.getZExtValue();
4704 // There are two difference cases requiring to reverse input vectors.
4705 // For example, for vector <4 x i32> we have the following cases,
4706 // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
4707 // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
4708 // For both cases, we finally use mask <5, 6, 7, 0>, which requires
4709 // to reverse two input vectors.
4718 /// isREVMask - Check if a vector shuffle corresponds to a REV
4719 /// instruction with the specified blocksize. (The order of the elements
4720 /// within each block of the vector is reversed.)
4721 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4722 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
4723 "Only possible block sizes for REV are: 16, 32, 64");
4725 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4729 unsigned NumElts = VT.getVectorNumElements();
4730 unsigned BlockElts = M[0] + 1;
4731 // If the first shuffle index is UNDEF, be optimistic.
4733 BlockElts = BlockSize / EltSz;
4735 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4738 for (unsigned i = 0; i < NumElts; ++i) {
4740 continue; // ignore UNDEF indices
4741 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
4748 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4749 unsigned NumElts = VT.getVectorNumElements();
4750 WhichResult = (M[0] == 0 ? 0 : 1);
4751 unsigned Idx = WhichResult * NumElts / 2;
4752 for (unsigned i = 0; i != NumElts; i += 2) {
4753 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
4754 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
4762 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4763 unsigned NumElts = VT.getVectorNumElements();
4764 WhichResult = (M[0] == 0 ? 0 : 1);
4765 for (unsigned i = 0; i != NumElts; ++i) {
4767 continue; // ignore UNDEF indices
4768 if ((unsigned)M[i] != 2 * i + WhichResult)
4775 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4776 unsigned NumElts = VT.getVectorNumElements();
4777 WhichResult = (M[0] == 0 ? 0 : 1);
4778 for (unsigned i = 0; i < NumElts; i += 2) {
4779 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
4780 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
4786 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
4787 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4788 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4789 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4790 unsigned NumElts = VT.getVectorNumElements();
4791 WhichResult = (M[0] == 0 ? 0 : 1);
4792 unsigned Idx = WhichResult * NumElts / 2;
4793 for (unsigned i = 0; i != NumElts; i += 2) {
4794 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
4795 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
4803 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
4804 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4805 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4806 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4807 unsigned Half = VT.getVectorNumElements() / 2;
4808 WhichResult = (M[0] == 0 ? 0 : 1);
4809 for (unsigned j = 0; j != 2; ++j) {
4810 unsigned Idx = WhichResult;
4811 for (unsigned i = 0; i != Half; ++i) {
4812 int MIdx = M[i + j * Half];
4813 if (MIdx >= 0 && (unsigned)MIdx != Idx)
4822 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
4823 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4824 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4825 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4826 unsigned NumElts = VT.getVectorNumElements();
4827 WhichResult = (M[0] == 0 ? 0 : 1);
4828 for (unsigned i = 0; i < NumElts; i += 2) {
4829 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
4830 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
4836 static bool isINSMask(ArrayRef<int> M, int NumInputElements,
4837 bool &DstIsLeft, int &Anomaly) {
4838 if (M.size() != static_cast<size_t>(NumInputElements))
4841 int NumLHSMatch = 0, NumRHSMatch = 0;
4842 int LastLHSMismatch = -1, LastRHSMismatch = -1;
4844 for (int i = 0; i < NumInputElements; ++i) {
4854 LastLHSMismatch = i;
4856 if (M[i] == i + NumInputElements)
4859 LastRHSMismatch = i;
4862 if (NumLHSMatch == NumInputElements - 1) {
4864 Anomaly = LastLHSMismatch;
4866 } else if (NumRHSMatch == NumInputElements - 1) {
4868 Anomaly = LastRHSMismatch;
4875 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
4876 if (VT.getSizeInBits() != 128)
4879 unsigned NumElts = VT.getVectorNumElements();
4881 for (int I = 0, E = NumElts / 2; I != E; I++) {
4886 int Offset = NumElts / 2;
4887 for (int I = NumElts / 2, E = NumElts; I != E; I++) {
4888 if (Mask[I] != I + SplitLHS * Offset)
4895 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
4897 EVT VT = Op.getValueType();
4898 SDValue V0 = Op.getOperand(0);
4899 SDValue V1 = Op.getOperand(1);
4900 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
4902 if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
4903 VT.getVectorElementType() != V1.getValueType().getVectorElementType())
4906 bool SplitV0 = V0.getValueType().getSizeInBits() == 128;
4908 if (!isConcatMask(Mask, VT, SplitV0))
4911 EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
4912 VT.getVectorNumElements() / 2);
4914 V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
4915 DAG.getConstant(0, MVT::i64));
4917 if (V1.getValueType().getSizeInBits() == 128) {
4918 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
4919 DAG.getConstant(0, MVT::i64));
4921 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
4924 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
4925 /// the specified operations to build the shuffle.
4926 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
4927 SDValue RHS, SelectionDAG &DAG,
4929 unsigned OpNum = (PFEntry >> 26) & 0x0F;
4930 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
4931 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
4934 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
4943 OP_VUZPL, // VUZP, left result
4944 OP_VUZPR, // VUZP, right result
4945 OP_VZIPL, // VZIP, left result
4946 OP_VZIPR, // VZIP, right result
4947 OP_VTRNL, // VTRN, left result
4948 OP_VTRNR // VTRN, right result
4951 if (OpNum == OP_COPY) {
4952 if (LHSID == (1 * 9 + 2) * 9 + 3)
4954 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
4958 SDValue OpLHS, OpRHS;
4959 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
4960 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
4961 EVT VT = OpLHS.getValueType();
4965 llvm_unreachable("Unknown shuffle opcode!");
4967 // VREV divides the vector in half and swaps within the half.
4968 if (VT.getVectorElementType() == MVT::i32 ||
4969 VT.getVectorElementType() == MVT::f32)
4970 return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
4971 // vrev <4 x i16> -> REV32
4972 if (VT.getVectorElementType() == MVT::i16 ||
4973 VT.getVectorElementType() == MVT::f16)
4974 return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
4975 // vrev <4 x i8> -> REV16
4976 assert(VT.getVectorElementType() == MVT::i8);
4977 return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
4982 EVT EltTy = VT.getVectorElementType();
4984 if (EltTy == MVT::i8)
4985 Opcode = AArch64ISD::DUPLANE8;
4986 else if (EltTy == MVT::i16)
4987 Opcode = AArch64ISD::DUPLANE16;
4988 else if (EltTy == MVT::i32 || EltTy == MVT::f32)
4989 Opcode = AArch64ISD::DUPLANE32;
4990 else if (EltTy == MVT::i64 || EltTy == MVT::f64)
4991 Opcode = AArch64ISD::DUPLANE64;
4993 llvm_unreachable("Invalid vector element type?");
4995 if (VT.getSizeInBits() == 64)
4996 OpLHS = WidenVector(OpLHS, DAG);
4997 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, MVT::i64);
4998 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
5003 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
5004 return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
5005 DAG.getConstant(Imm, MVT::i32));
5008 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
5011 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
5014 return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
5017 return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
5020 return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
5023 return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
5028 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
5029 SelectionDAG &DAG) {
5030 // Check to see if we can use the TBL instruction.
5031 SDValue V1 = Op.getOperand(0);
5032 SDValue V2 = Op.getOperand(1);
5035 EVT EltVT = Op.getValueType().getVectorElementType();
5036 unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
5038 SmallVector<SDValue, 8> TBLMask;
5039 for (int Val : ShuffleMask) {
5040 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
5041 unsigned Offset = Byte + Val * BytesPerElt;
5042 TBLMask.push_back(DAG.getConstant(Offset, MVT::i32));
5046 MVT IndexVT = MVT::v8i8;
5047 unsigned IndexLen = 8;
5048 if (Op.getValueType().getSizeInBits() == 128) {
5049 IndexVT = MVT::v16i8;
5053 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
5054 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
5057 if (V2.getNode()->getOpcode() == ISD::UNDEF) {
5059 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
5060 Shuffle = DAG.getNode(
5061 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5062 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, MVT::i32), V1Cst,
5063 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5064 makeArrayRef(TBLMask.data(), IndexLen)));
5066 if (IndexLen == 8) {
5067 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
5068 Shuffle = DAG.getNode(
5069 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5070 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, MVT::i32), V1Cst,
5071 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5072 makeArrayRef(TBLMask.data(), IndexLen)));
5074 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
5075 // cannot currently represent the register constraints on the input
5077 // Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
5078 // DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5079 // &TBLMask[0], IndexLen));
5080 Shuffle = DAG.getNode(
5081 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5082 DAG.getConstant(Intrinsic::aarch64_neon_tbl2, MVT::i32), V1Cst, V2Cst,
5083 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5084 makeArrayRef(TBLMask.data(), IndexLen)));
5087 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
5090 static unsigned getDUPLANEOp(EVT EltType) {
5091 if (EltType == MVT::i8)
5092 return AArch64ISD::DUPLANE8;
5093 if (EltType == MVT::i16 || EltType == MVT::f16)
5094 return AArch64ISD::DUPLANE16;
5095 if (EltType == MVT::i32 || EltType == MVT::f32)
5096 return AArch64ISD::DUPLANE32;
5097 if (EltType == MVT::i64 || EltType == MVT::f64)
5098 return AArch64ISD::DUPLANE64;
5100 llvm_unreachable("Invalid vector element type?");
5103 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5104 SelectionDAG &DAG) const {
5106 EVT VT = Op.getValueType();
5108 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5110 // Convert shuffles that are directly supported on NEON to target-specific
5111 // DAG nodes, instead of keeping them as shuffles and matching them again
5112 // during code selection. This is more efficient and avoids the possibility
5113 // of inconsistencies between legalization and selection.
5114 ArrayRef<int> ShuffleMask = SVN->getMask();
5116 SDValue V1 = Op.getOperand(0);
5117 SDValue V2 = Op.getOperand(1);
5119 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0],
5120 V1.getValueType().getSimpleVT())) {
5121 int Lane = SVN->getSplatIndex();
5122 // If this is undef splat, generate it via "just" vdup, if possible.
5126 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
5127 return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
5129 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
5130 // constant. If so, we can just reference the lane's definition directly.
5131 if (V1.getOpcode() == ISD::BUILD_VECTOR &&
5132 !isa<ConstantSDNode>(V1.getOperand(Lane)))
5133 return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
5135 // Otherwise, duplicate from the lane of the input vector.
5136 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
5138 // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
5139 // to make a vector of the same size as this SHUFFLE. We can ignore the
5140 // extract entirely, and canonicalise the concat using WidenVector.
5141 if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
5142 Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
5143 V1 = V1.getOperand(0);
5144 } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
5145 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
5146 Lane -= Idx * VT.getVectorNumElements() / 2;
5147 V1 = WidenVector(V1.getOperand(Idx), DAG);
5148 } else if (VT.getSizeInBits() == 64)
5149 V1 = WidenVector(V1, DAG);
5151 return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, MVT::i64));
5154 if (isREVMask(ShuffleMask, VT, 64))
5155 return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
5156 if (isREVMask(ShuffleMask, VT, 32))
5157 return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
5158 if (isREVMask(ShuffleMask, VT, 16))
5159 return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
5161 bool ReverseEXT = false;
5163 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
5166 Imm *= getExtFactor(V1);
5167 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
5168 DAG.getConstant(Imm, MVT::i32));
5169 } else if (V2->getOpcode() == ISD::UNDEF &&
5170 isSingletonEXTMask(ShuffleMask, VT, Imm)) {
5171 Imm *= getExtFactor(V1);
5172 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
5173 DAG.getConstant(Imm, MVT::i32));
5176 unsigned WhichResult;
5177 if (isZIPMask(ShuffleMask, VT, WhichResult)) {
5178 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5179 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5181 if (isUZPMask(ShuffleMask, VT, WhichResult)) {
5182 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5183 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5185 if (isTRNMask(ShuffleMask, VT, WhichResult)) {
5186 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5187 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5190 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5191 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5192 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5194 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5195 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5196 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5198 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5199 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5200 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5203 SDValue Concat = tryFormConcatFromShuffle(Op, DAG);
5204 if (Concat.getNode())
5209 int NumInputElements = V1.getValueType().getVectorNumElements();
5210 if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
5211 SDValue DstVec = DstIsLeft ? V1 : V2;
5212 SDValue DstLaneV = DAG.getConstant(Anomaly, MVT::i64);
5214 SDValue SrcVec = V1;
5215 int SrcLane = ShuffleMask[Anomaly];
5216 if (SrcLane >= NumInputElements) {
5218 SrcLane -= VT.getVectorNumElements();
5220 SDValue SrcLaneV = DAG.getConstant(SrcLane, MVT::i64);
5222 EVT ScalarVT = VT.getVectorElementType();
5224 if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
5225 ScalarVT = MVT::i32;
5228 ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5229 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
5233 // If the shuffle is not directly supported and it has 4 elements, use
5234 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5235 unsigned NumElts = VT.getVectorNumElements();
5237 unsigned PFIndexes[4];
5238 for (unsigned i = 0; i != 4; ++i) {
5239 if (ShuffleMask[i] < 0)
5242 PFIndexes[i] = ShuffleMask[i];
5245 // Compute the index in the perfect shuffle table.
5246 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
5247 PFIndexes[2] * 9 + PFIndexes[3];
5248 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5249 unsigned Cost = (PFEntry >> 30);
5252 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5255 return GenerateTBL(Op, ShuffleMask, DAG);
5258 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
5260 EVT VT = BVN->getValueType(0);
5261 APInt SplatBits, SplatUndef;
5262 unsigned SplatBitSize;
5264 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5265 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
5267 for (unsigned i = 0; i < NumSplats; ++i) {
5268 CnstBits <<= SplatBitSize;
5269 UndefBits <<= SplatBitSize;
5270 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
5271 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
5280 SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op,
5281 SelectionDAG &DAG) const {
5282 BuildVectorSDNode *BVN =
5283 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5284 SDValue LHS = Op.getOperand(0);
5286 EVT VT = Op.getValueType();
5291 APInt CnstBits(VT.getSizeInBits(), 0);
5292 APInt UndefBits(VT.getSizeInBits(), 0);
5293 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5294 // We only have BIC vector immediate instruction, which is and-not.
5295 CnstBits = ~CnstBits;
5297 // We make use of a little bit of goto ickiness in order to avoid having to
5298 // duplicate the immediate matching logic for the undef toggled case.
5299 bool SecondTry = false;
5302 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5303 CnstBits = CnstBits.zextOrTrunc(64);
5304 uint64_t CnstVal = CnstBits.getZExtValue();
5306 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5307 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5308 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5309 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5310 DAG.getConstant(CnstVal, MVT::i32),
5311 DAG.getConstant(0, MVT::i32));
5312 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5315 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5316 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5317 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5318 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5319 DAG.getConstant(CnstVal, MVT::i32),
5320 DAG.getConstant(8, MVT::i32));
5321 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5324 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5325 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5326 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5327 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5328 DAG.getConstant(CnstVal, MVT::i32),
5329 DAG.getConstant(16, MVT::i32));
5330 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5333 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5334 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5335 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5336 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5337 DAG.getConstant(CnstVal, MVT::i32),
5338 DAG.getConstant(24, MVT::i32));
5339 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5342 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5343 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5344 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5345 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5346 DAG.getConstant(CnstVal, MVT::i32),
5347 DAG.getConstant(0, MVT::i32));
5348 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5351 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5352 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5353 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5354 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5355 DAG.getConstant(CnstVal, MVT::i32),
5356 DAG.getConstant(8, MVT::i32));
5357 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5364 CnstBits = ~UndefBits;
5368 // We can always fall back to a non-immediate AND.
5373 // Specialized code to quickly find if PotentialBVec is a BuildVector that
5374 // consists of only the same constant int value, returned in reference arg
5376 static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
5377 uint64_t &ConstVal) {
5378 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
5381 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
5384 EVT VT = Bvec->getValueType(0);
5385 unsigned NumElts = VT.getVectorNumElements();
5386 for (unsigned i = 1; i < NumElts; ++i)
5387 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
5389 ConstVal = FirstElt->getZExtValue();
5393 static unsigned getIntrinsicID(const SDNode *N) {
5394 unsigned Opcode = N->getOpcode();
5397 return Intrinsic::not_intrinsic;
5398 case ISD::INTRINSIC_WO_CHAIN: {
5399 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
5400 if (IID < Intrinsic::num_intrinsics)
5402 return Intrinsic::not_intrinsic;
5407 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
5408 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
5409 // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
5410 // Also, logical shift right -> sri, with the same structure.
5411 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
5412 EVT VT = N->getValueType(0);
5419 // Is the first op an AND?
5420 const SDValue And = N->getOperand(0);
5421 if (And.getOpcode() != ISD::AND)
5424 // Is the second op an shl or lshr?
5425 SDValue Shift = N->getOperand(1);
5426 // This will have been turned into: AArch64ISD::VSHL vector, #shift
5427 // or AArch64ISD::VLSHR vector, #shift
5428 unsigned ShiftOpc = Shift.getOpcode();
5429 if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
5431 bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
5433 // Is the shift amount constant?
5434 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
5438 // Is the and mask vector all constant?
5440 if (!isAllConstantBuildVector(And.getOperand(1), C1))
5443 // Is C1 == ~C2, taking into account how much one can shift elements of a
5445 uint64_t C2 = C2node->getZExtValue();
5446 unsigned ElemSizeInBits = VT.getVectorElementType().getSizeInBits();
5447 if (C2 > ElemSizeInBits)
5449 unsigned ElemMask = (1 << ElemSizeInBits) - 1;
5450 if ((C1 & ElemMask) != (~C2 & ElemMask))
5453 SDValue X = And.getOperand(0);
5454 SDValue Y = Shift.getOperand(0);
5457 IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
5459 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
5460 DAG.getConstant(Intrin, MVT::i32), X, Y, Shift.getOperand(1));
5462 DEBUG(dbgs() << "aarch64-lower: transformed: \n");
5463 DEBUG(N->dump(&DAG));
5464 DEBUG(dbgs() << "into: \n");
5465 DEBUG(ResultSLI->dump(&DAG));
5471 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
5472 SelectionDAG &DAG) const {
5473 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
5474 if (EnableAArch64SlrGeneration) {
5475 SDValue Res = tryLowerToSLI(Op.getNode(), DAG);
5480 BuildVectorSDNode *BVN =
5481 dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
5482 SDValue LHS = Op.getOperand(1);
5484 EVT VT = Op.getValueType();
5486 // OR commutes, so try swapping the operands.
5488 LHS = Op.getOperand(0);
5489 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5494 APInt CnstBits(VT.getSizeInBits(), 0);
5495 APInt UndefBits(VT.getSizeInBits(), 0);
5496 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5497 // We make use of a little bit of goto ickiness in order to avoid having to
5498 // duplicate the immediate matching logic for the undef toggled case.
5499 bool SecondTry = false;
5502 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5503 CnstBits = CnstBits.zextOrTrunc(64);
5504 uint64_t CnstVal = CnstBits.getZExtValue();
5506 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5507 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5508 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5509 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5510 DAG.getConstant(CnstVal, MVT::i32),
5511 DAG.getConstant(0, MVT::i32));
5512 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5515 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5516 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5517 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5518 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5519 DAG.getConstant(CnstVal, MVT::i32),
5520 DAG.getConstant(8, MVT::i32));
5521 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5524 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5525 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5526 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5527 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5528 DAG.getConstant(CnstVal, MVT::i32),
5529 DAG.getConstant(16, MVT::i32));
5530 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5533 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5534 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5535 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5536 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5537 DAG.getConstant(CnstVal, MVT::i32),
5538 DAG.getConstant(24, MVT::i32));
5539 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5542 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5543 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5544 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5545 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5546 DAG.getConstant(CnstVal, MVT::i32),
5547 DAG.getConstant(0, MVT::i32));
5548 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5551 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5552 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5553 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5554 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5555 DAG.getConstant(CnstVal, MVT::i32),
5556 DAG.getConstant(8, MVT::i32));
5557 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5564 CnstBits = UndefBits;
5568 // We can always fall back to a non-immediate OR.
5573 // Normalize the operands of BUILD_VECTOR. The value of constant operands will
5574 // be truncated to fit element width.
5575 static SDValue NormalizeBuildVector(SDValue Op,
5576 SelectionDAG &DAG) {
5577 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
5579 EVT VT = Op.getValueType();
5580 EVT EltTy= VT.getVectorElementType();
5582 if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
5585 SmallVector<SDValue, 16> Ops;
5586 for (unsigned I = 0, E = VT.getVectorNumElements(); I != E; ++I) {
5587 SDValue Lane = Op.getOperand(I);
5588 if (Lane.getOpcode() == ISD::Constant) {
5589 APInt LowBits(EltTy.getSizeInBits(),
5590 cast<ConstantSDNode>(Lane)->getZExtValue());
5591 Lane = DAG.getConstant(LowBits.getZExtValue(), MVT::i32);
5593 Ops.push_back(Lane);
5595 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5598 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
5599 SelectionDAG &DAG) const {
5601 EVT VT = Op.getValueType();
5602 Op = NormalizeBuildVector(Op, DAG);
5603 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5605 APInt CnstBits(VT.getSizeInBits(), 0);
5606 APInt UndefBits(VT.getSizeInBits(), 0);
5607 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5608 // We make use of a little bit of goto ickiness in order to avoid having to
5609 // duplicate the immediate matching logic for the undef toggled case.
5610 bool SecondTry = false;
5613 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5614 CnstBits = CnstBits.zextOrTrunc(64);
5615 uint64_t CnstVal = CnstBits.getZExtValue();
5617 // Certain magic vector constants (used to express things like NOT
5618 // and NEG) are passed through unmodified. This allows codegen patterns
5619 // for these operations to match. Special-purpose patterns will lower
5620 // these immediates to MOVIs if it proves necessary.
5621 if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL))
5624 // The many faces of MOVI...
5625 if (AArch64_AM::isAdvSIMDModImmType10(CnstVal)) {
5626 CnstVal = AArch64_AM::encodeAdvSIMDModImmType10(CnstVal);
5627 if (VT.getSizeInBits() == 128) {
5628 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::v2i64,
5629 DAG.getConstant(CnstVal, MVT::i32));
5630 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5633 // Support the V64 version via subregister insertion.
5634 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::f64,
5635 DAG.getConstant(CnstVal, MVT::i32));
5636 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5639 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5640 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5641 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5642 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5643 DAG.getConstant(CnstVal, MVT::i32),
5644 DAG.getConstant(0, MVT::i32));
5645 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5648 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5649 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5650 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5651 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5652 DAG.getConstant(CnstVal, MVT::i32),
5653 DAG.getConstant(8, MVT::i32));
5654 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5657 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5658 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5659 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5660 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5661 DAG.getConstant(CnstVal, MVT::i32),
5662 DAG.getConstant(16, MVT::i32));
5663 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5666 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5667 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5668 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5669 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5670 DAG.getConstant(CnstVal, MVT::i32),
5671 DAG.getConstant(24, MVT::i32));
5672 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5675 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5676 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5677 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5678 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5679 DAG.getConstant(CnstVal, MVT::i32),
5680 DAG.getConstant(0, MVT::i32));
5681 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5684 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5685 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5686 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5687 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5688 DAG.getConstant(CnstVal, MVT::i32),
5689 DAG.getConstant(8, MVT::i32));
5690 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5693 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
5694 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
5695 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5696 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
5697 DAG.getConstant(CnstVal, MVT::i32),
5698 DAG.getConstant(264, MVT::i32));
5699 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5702 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
5703 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
5704 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5705 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
5706 DAG.getConstant(CnstVal, MVT::i32),
5707 DAG.getConstant(272, MVT::i32));
5708 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5711 if (AArch64_AM::isAdvSIMDModImmType9(CnstVal)) {
5712 CnstVal = AArch64_AM::encodeAdvSIMDModImmType9(CnstVal);
5713 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
5714 SDValue Mov = DAG.getNode(AArch64ISD::MOVI, dl, MovTy,
5715 DAG.getConstant(CnstVal, MVT::i32));
5716 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5719 // The few faces of FMOV...
5720 if (AArch64_AM::isAdvSIMDModImmType11(CnstVal)) {
5721 CnstVal = AArch64_AM::encodeAdvSIMDModImmType11(CnstVal);
5722 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32;
5723 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MovTy,
5724 DAG.getConstant(CnstVal, MVT::i32));
5725 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5728 if (AArch64_AM::isAdvSIMDModImmType12(CnstVal) &&
5729 VT.getSizeInBits() == 128) {
5730 CnstVal = AArch64_AM::encodeAdvSIMDModImmType12(CnstVal);
5731 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MVT::v2f64,
5732 DAG.getConstant(CnstVal, MVT::i32));
5733 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5736 // The many faces of MVNI...
5738 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5739 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5740 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5741 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
5742 DAG.getConstant(CnstVal, MVT::i32),
5743 DAG.getConstant(0, MVT::i32));
5744 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5747 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5748 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5749 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5750 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
5751 DAG.getConstant(CnstVal, MVT::i32),
5752 DAG.getConstant(8, MVT::i32));
5753 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5756 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5757 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5758 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5759 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
5760 DAG.getConstant(CnstVal, MVT::i32),
5761 DAG.getConstant(16, MVT::i32));
5762 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5765 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5766 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5767 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5768 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
5769 DAG.getConstant(CnstVal, MVT::i32),
5770 DAG.getConstant(24, MVT::i32));
5771 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5774 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5775 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5776 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5777 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
5778 DAG.getConstant(CnstVal, MVT::i32),
5779 DAG.getConstant(0, MVT::i32));
5780 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5783 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5784 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5785 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5786 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
5787 DAG.getConstant(CnstVal, MVT::i32),
5788 DAG.getConstant(8, MVT::i32));
5789 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5792 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
5793 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
5794 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5795 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
5796 DAG.getConstant(CnstVal, MVT::i32),
5797 DAG.getConstant(264, MVT::i32));
5798 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5801 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
5802 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
5803 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5804 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
5805 DAG.getConstant(CnstVal, MVT::i32),
5806 DAG.getConstant(272, MVT::i32));
5807 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5814 CnstBits = UndefBits;
5819 // Scan through the operands to find some interesting properties we can
5821 // 1) If only one value is used, we can use a DUP, or
5822 // 2) if only the low element is not undef, we can just insert that, or
5823 // 3) if only one constant value is used (w/ some non-constant lanes),
5824 // we can splat the constant value into the whole vector then fill
5825 // in the non-constant lanes.
5826 // 4) FIXME: If different constant values are used, but we can intelligently
5827 // select the values we'll be overwriting for the non-constant
5828 // lanes such that we can directly materialize the vector
5829 // some other way (MOVI, e.g.), we can be sneaky.
5830 unsigned NumElts = VT.getVectorNumElements();
5831 bool isOnlyLowElement = true;
5832 bool usesOnlyOneValue = true;
5833 bool usesOnlyOneConstantValue = true;
5834 bool isConstant = true;
5835 unsigned NumConstantLanes = 0;
5837 SDValue ConstantValue;
5838 for (unsigned i = 0; i < NumElts; ++i) {
5839 SDValue V = Op.getOperand(i);
5840 if (V.getOpcode() == ISD::UNDEF)
5843 isOnlyLowElement = false;
5844 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5847 if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
5849 if (!ConstantValue.getNode())
5851 else if (ConstantValue != V)
5852 usesOnlyOneConstantValue = false;
5855 if (!Value.getNode())
5857 else if (V != Value)
5858 usesOnlyOneValue = false;
5861 if (!Value.getNode())
5862 return DAG.getUNDEF(VT);
5864 if (isOnlyLowElement)
5865 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5867 // Use DUP for non-constant splats. For f32 constant splats, reduce to
5868 // i32 and try again.
5869 if (usesOnlyOneValue) {
5871 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5872 Value.getValueType() != VT)
5873 return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
5875 // This is actually a DUPLANExx operation, which keeps everything vectory.
5877 // DUPLANE works on 128-bit vectors, widen it if necessary.
5878 SDValue Lane = Value.getOperand(1);
5879 Value = Value.getOperand(0);
5880 if (Value.getValueType().getSizeInBits() == 64)
5881 Value = WidenVector(Value, DAG);
5883 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
5884 return DAG.getNode(Opcode, dl, VT, Value, Lane);
5887 if (VT.getVectorElementType().isFloatingPoint()) {
5888 SmallVector<SDValue, 8> Ops;
5890 (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
5891 for (unsigned i = 0; i < NumElts; ++i)
5892 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
5893 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
5894 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5895 Val = LowerBUILD_VECTOR(Val, DAG);
5897 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5901 // If there was only one constant value used and for more than one lane,
5902 // start by splatting that value, then replace the non-constant lanes. This
5903 // is better than the default, which will perform a separate initialization
5905 if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
5906 SDValue Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
5907 // Now insert the non-constant lanes.
5908 for (unsigned i = 0; i < NumElts; ++i) {
5909 SDValue V = Op.getOperand(i);
5910 SDValue LaneIdx = DAG.getConstant(i, MVT::i64);
5911 if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) {
5912 // Note that type legalization likely mucked about with the VT of the
5913 // source operand, so we may have to convert it here before inserting.
5914 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
5920 // If all elements are constants and the case above didn't get hit, fall back
5921 // to the default expansion, which will generate a load from the constant
5926 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5928 SDValue shuffle = ReconstructShuffle(Op, DAG);
5929 if (shuffle != SDValue())
5933 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5934 // know the default expansion would otherwise fall back on something even
5935 // worse. For a vector with one or two non-undef values, that's
5936 // scalar_to_vector for the elements followed by a shuffle (provided the
5937 // shuffle is valid for the target) and materialization element by element
5938 // on the stack followed by a load for everything else.
5939 if (!isConstant && !usesOnlyOneValue) {
5940 SDValue Vec = DAG.getUNDEF(VT);
5941 SDValue Op0 = Op.getOperand(0);
5942 unsigned ElemSize = VT.getVectorElementType().getSizeInBits();
5944 // For 32 and 64 bit types, use INSERT_SUBREG for lane zero to
5945 // a) Avoid a RMW dependency on the full vector register, and
5946 // b) Allow the register coalescer to fold away the copy if the
5947 // value is already in an S or D register.
5948 if (Op0.getOpcode() != ISD::UNDEF && (ElemSize == 32 || ElemSize == 64)) {
5949 unsigned SubIdx = ElemSize == 32 ? AArch64::ssub : AArch64::dsub;
5951 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl, VT, Vec, Op0,
5952 DAG.getTargetConstant(SubIdx, MVT::i32));
5953 Vec = SDValue(N, 0);
5956 for (; i < NumElts; ++i) {
5957 SDValue V = Op.getOperand(i);
5958 if (V.getOpcode() == ISD::UNDEF)
5960 SDValue LaneIdx = DAG.getConstant(i, MVT::i64);
5961 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5966 // Just use the default expansion. We failed to find a better alternative.
5970 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
5971 SelectionDAG &DAG) const {
5972 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
5974 // Check for non-constant or out of range lane.
5975 EVT VT = Op.getOperand(0).getValueType();
5976 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
5977 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
5981 // Insertion/extraction are legal for V128 types.
5982 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
5983 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
5987 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
5988 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
5991 // For V64 types, we perform insertion by expanding the value
5992 // to a V128 type and perform the insertion on that.
5994 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
5995 EVT WideTy = WideVec.getValueType();
5997 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
5998 Op.getOperand(1), Op.getOperand(2));
5999 // Re-narrow the resultant vector.
6000 return NarrowVector(Node, DAG);
6004 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6005 SelectionDAG &DAG) const {
6006 assert(Op.getOpcode() == ISD::EXTRACT_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(1));
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 extraction by expanding the value
6026 // to a V128 type and perform the extraction on that.
6028 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6029 EVT WideTy = WideVec.getValueType();
6031 EVT ExtrTy = WideTy.getVectorElementType();
6032 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
6035 // For extractions, we just return the result directly.
6036 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
6040 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
6041 SelectionDAG &DAG) const {
6042 EVT VT = Op.getOperand(0).getValueType();
6048 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6051 unsigned Val = Cst->getZExtValue();
6053 unsigned Size = Op.getValueType().getSizeInBits();
6057 return DAG.getTargetExtractSubreg(AArch64::bsub, dl, Op.getValueType(),
6060 return DAG.getTargetExtractSubreg(AArch64::hsub, dl, Op.getValueType(),
6063 return DAG.getTargetExtractSubreg(AArch64::ssub, dl, Op.getValueType(),
6066 return DAG.getTargetExtractSubreg(AArch64::dsub, dl, Op.getValueType(),
6069 llvm_unreachable("Unexpected vector type in extract_subvector!");
6072 // If this is extracting the upper 64-bits of a 128-bit vector, we match
6074 if (Size == 64 && Val * VT.getVectorElementType().getSizeInBits() == 64)
6080 bool AArch64TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
6082 if (VT.getVectorNumElements() == 4 &&
6083 (VT.is128BitVector() || VT.is64BitVector())) {
6084 unsigned PFIndexes[4];
6085 for (unsigned i = 0; i != 4; ++i) {
6089 PFIndexes[i] = M[i];
6092 // Compute the index in the perfect shuffle table.
6093 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6094 PFIndexes[2] * 9 + PFIndexes[3];
6095 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6096 unsigned Cost = (PFEntry >> 30);
6104 unsigned DummyUnsigned;
6106 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
6107 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
6108 isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
6109 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
6110 isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
6111 isZIPMask(M, VT, DummyUnsigned) ||
6112 isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
6113 isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
6114 isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
6115 isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
6116 isConcatMask(M, VT, VT.getSizeInBits() == 128));
6119 /// getVShiftImm - Check if this is a valid build_vector for the immediate
6120 /// operand of a vector shift operation, where all the elements of the
6121 /// build_vector must have the same constant integer value.
6122 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
6123 // Ignore bit_converts.
6124 while (Op.getOpcode() == ISD::BITCAST)
6125 Op = Op.getOperand(0);
6126 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6127 APInt SplatBits, SplatUndef;
6128 unsigned SplatBitSize;
6130 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
6131 HasAnyUndefs, ElementBits) ||
6132 SplatBitSize > ElementBits)
6134 Cnt = SplatBits.getSExtValue();
6138 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
6139 /// operand of a vector shift left operation. That value must be in the range:
6140 /// 0 <= Value < ElementBits for a left shift; or
6141 /// 0 <= Value <= ElementBits for a long left shift.
6142 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
6143 assert(VT.isVector() && "vector shift count is not a vector type");
6144 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
6145 if (!getVShiftImm(Op, ElementBits, Cnt))
6147 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
6150 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
6151 /// operand of a vector shift right operation. For a shift opcode, the value
6152 /// is positive, but for an intrinsic the value count must be negative. The
6153 /// absolute value must be in the range:
6154 /// 1 <= |Value| <= ElementBits for a right shift; or
6155 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
6156 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
6158 assert(VT.isVector() && "vector shift count is not a vector type");
6159 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
6160 if (!getVShiftImm(Op, ElementBits, Cnt))
6164 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
6167 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
6168 SelectionDAG &DAG) const {
6169 EVT VT = Op.getValueType();
6173 if (!Op.getOperand(1).getValueType().isVector())
6175 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6177 switch (Op.getOpcode()) {
6179 llvm_unreachable("unexpected shift opcode");
6182 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
6183 return DAG.getNode(AArch64ISD::VSHL, SDLoc(Op), VT, Op.getOperand(0),
6184 DAG.getConstant(Cnt, MVT::i32));
6185 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
6186 DAG.getConstant(Intrinsic::aarch64_neon_ushl, MVT::i32),
6187 Op.getOperand(0), Op.getOperand(1));
6190 // Right shift immediate
6191 if (isVShiftRImm(Op.getOperand(1), VT, false, false, Cnt) &&
6194 (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
6195 return DAG.getNode(Opc, SDLoc(Op), VT, Op.getOperand(0),
6196 DAG.getConstant(Cnt, MVT::i32));
6199 // Right shift register. Note, there is not a shift right register
6200 // instruction, but the shift left register instruction takes a signed
6201 // value, where negative numbers specify a right shift.
6202 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
6203 : Intrinsic::aarch64_neon_ushl;
6204 // negate the shift amount
6205 SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
6206 SDValue NegShiftLeft =
6207 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
6208 DAG.getConstant(Opc, MVT::i32), Op.getOperand(0), NegShift);
6209 return NegShiftLeft;
6215 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
6216 AArch64CC::CondCode CC, bool NoNans, EVT VT,
6217 SDLoc dl, SelectionDAG &DAG) {
6218 EVT SrcVT = LHS.getValueType();
6219 assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
6220 "function only supposed to emit natural comparisons");
6222 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
6223 APInt CnstBits(VT.getSizeInBits(), 0);
6224 APInt UndefBits(VT.getSizeInBits(), 0);
6225 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
6226 bool IsZero = IsCnst && (CnstBits == 0);
6228 if (SrcVT.getVectorElementType().isFloatingPoint()) {
6232 case AArch64CC::NE: {
6235 Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6237 Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6238 return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
6242 return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6243 return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6246 return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
6247 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
6250 return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
6251 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
6254 return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
6255 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
6259 // If we ignore NaNs then we can use to the MI implementation.
6263 return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
6264 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
6271 case AArch64CC::NE: {
6274 Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6276 Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6277 return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
6281 return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6282 return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6285 return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
6286 return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
6289 return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
6290 return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
6293 return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
6294 return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
6296 return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
6298 return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
6301 return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
6302 return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
6304 return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
6306 return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
6310 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
6311 SelectionDAG &DAG) const {
6312 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6313 SDValue LHS = Op.getOperand(0);
6314 SDValue RHS = Op.getOperand(1);
6315 EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
6318 if (LHS.getValueType().getVectorElementType().isInteger()) {
6319 assert(LHS.getValueType() == RHS.getValueType());
6320 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
6322 EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
6323 return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
6326 assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
6327 LHS.getValueType().getVectorElementType() == MVT::f64);
6329 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
6330 // clean. Some of them require two branches to implement.
6331 AArch64CC::CondCode CC1, CC2;
6333 changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
6335 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
6337 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
6341 if (CC2 != AArch64CC::AL) {
6343 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
6344 if (!Cmp2.getNode())
6347 Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
6350 Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
6353 return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
6358 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
6359 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
6360 /// specified in the intrinsic calls.
6361 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
6363 unsigned Intrinsic) const {
6364 switch (Intrinsic) {
6365 case Intrinsic::aarch64_neon_ld2:
6366 case Intrinsic::aarch64_neon_ld3:
6367 case Intrinsic::aarch64_neon_ld4:
6368 case Intrinsic::aarch64_neon_ld1x2:
6369 case Intrinsic::aarch64_neon_ld1x3:
6370 case Intrinsic::aarch64_neon_ld1x4:
6371 case Intrinsic::aarch64_neon_ld2lane:
6372 case Intrinsic::aarch64_neon_ld3lane:
6373 case Intrinsic::aarch64_neon_ld4lane:
6374 case Intrinsic::aarch64_neon_ld2r:
6375 case Intrinsic::aarch64_neon_ld3r:
6376 case Intrinsic::aarch64_neon_ld4r: {
6377 Info.opc = ISD::INTRINSIC_W_CHAIN;
6378 // Conservatively set memVT to the entire set of vectors loaded.
6379 uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
6380 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6381 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6384 Info.vol = false; // volatile loads with NEON intrinsics not supported
6385 Info.readMem = true;
6386 Info.writeMem = false;
6389 case Intrinsic::aarch64_neon_st2:
6390 case Intrinsic::aarch64_neon_st3:
6391 case Intrinsic::aarch64_neon_st4:
6392 case Intrinsic::aarch64_neon_st1x2:
6393 case Intrinsic::aarch64_neon_st1x3:
6394 case Intrinsic::aarch64_neon_st1x4:
6395 case Intrinsic::aarch64_neon_st2lane:
6396 case Intrinsic::aarch64_neon_st3lane:
6397 case Intrinsic::aarch64_neon_st4lane: {
6398 Info.opc = ISD::INTRINSIC_VOID;
6399 // Conservatively set memVT to the entire set of vectors stored.
6400 unsigned NumElts = 0;
6401 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
6402 Type *ArgTy = I.getArgOperand(ArgI)->getType();
6403 if (!ArgTy->isVectorTy())
6405 NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
6407 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6408 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6411 Info.vol = false; // volatile stores with NEON intrinsics not supported
6412 Info.readMem = false;
6413 Info.writeMem = true;
6416 case Intrinsic::aarch64_ldaxr:
6417 case Intrinsic::aarch64_ldxr: {
6418 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
6419 Info.opc = ISD::INTRINSIC_W_CHAIN;
6420 Info.memVT = MVT::getVT(PtrTy->getElementType());
6421 Info.ptrVal = I.getArgOperand(0);
6423 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
6425 Info.readMem = true;
6426 Info.writeMem = false;
6429 case Intrinsic::aarch64_stlxr:
6430 case Intrinsic::aarch64_stxr: {
6431 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
6432 Info.opc = ISD::INTRINSIC_W_CHAIN;
6433 Info.memVT = MVT::getVT(PtrTy->getElementType());
6434 Info.ptrVal = I.getArgOperand(1);
6436 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
6438 Info.readMem = false;
6439 Info.writeMem = true;
6442 case Intrinsic::aarch64_ldaxp:
6443 case Intrinsic::aarch64_ldxp: {
6444 Info.opc = ISD::INTRINSIC_W_CHAIN;
6445 Info.memVT = MVT::i128;
6446 Info.ptrVal = I.getArgOperand(0);
6450 Info.readMem = true;
6451 Info.writeMem = false;
6454 case Intrinsic::aarch64_stlxp:
6455 case Intrinsic::aarch64_stxp: {
6456 Info.opc = ISD::INTRINSIC_W_CHAIN;
6457 Info.memVT = MVT::i128;
6458 Info.ptrVal = I.getArgOperand(2);
6462 Info.readMem = false;
6463 Info.writeMem = true;
6473 // Truncations from 64-bit GPR to 32-bit GPR is free.
6474 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
6475 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6477 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6478 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6479 return NumBits1 > NumBits2;
6481 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
6482 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
6484 unsigned NumBits1 = VT1.getSizeInBits();
6485 unsigned NumBits2 = VT2.getSizeInBits();
6486 return NumBits1 > NumBits2;
6489 /// Check if it is profitable to hoist instruction in then/else to if.
6490 /// Not profitable if I and it's user can form a FMA instruction
6491 /// because we prefer FMSUB/FMADD.
6492 bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
6493 if (I->getOpcode() != Instruction::FMul)
6496 if (I->getNumUses() != 1)
6499 Instruction *User = I->user_back();
6502 !(User->getOpcode() == Instruction::FSub ||
6503 User->getOpcode() == Instruction::FAdd))
6506 const TargetOptions &Options = getTargetMachine().Options;
6507 EVT VT = getValueType(User->getOperand(0)->getType());
6509 if (isFMAFasterThanFMulAndFAdd(VT) &&
6510 isOperationLegalOrCustom(ISD::FMA, VT) &&
6511 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath))
6517 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
6519 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
6520 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6522 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6523 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6524 return NumBits1 == 32 && NumBits2 == 64;
6526 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
6527 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
6529 unsigned NumBits1 = VT1.getSizeInBits();
6530 unsigned NumBits2 = VT2.getSizeInBits();
6531 return NumBits1 == 32 && NumBits2 == 64;
6534 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
6535 EVT VT1 = Val.getValueType();
6536 if (isZExtFree(VT1, VT2)) {
6540 if (Val.getOpcode() != ISD::LOAD)
6543 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
6544 return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
6545 VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
6546 VT1.getSizeInBits() <= 32);
6549 bool AArch64TargetLowering::hasPairedLoad(Type *LoadedType,
6550 unsigned &RequiredAligment) const {
6551 if (!LoadedType->isIntegerTy() && !LoadedType->isFloatTy())
6553 // Cyclone supports unaligned accesses.
6554 RequiredAligment = 0;
6555 unsigned NumBits = LoadedType->getPrimitiveSizeInBits();
6556 return NumBits == 32 || NumBits == 64;
6559 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
6560 unsigned &RequiredAligment) const {
6561 if (!LoadedType.isSimple() ||
6562 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
6564 // Cyclone supports unaligned accesses.
6565 RequiredAligment = 0;
6566 unsigned NumBits = LoadedType.getSizeInBits();
6567 return NumBits == 32 || NumBits == 64;
6570 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
6571 unsigned AlignCheck) {
6572 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
6573 (DstAlign == 0 || DstAlign % AlignCheck == 0));
6576 EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
6577 unsigned SrcAlign, bool IsMemset,
6580 MachineFunction &MF) const {
6581 // Don't use AdvSIMD to implement 16-byte memset. It would have taken one
6582 // instruction to materialize the v2i64 zero and one store (with restrictive
6583 // addressing mode). Just do two i64 store of zero-registers.
6585 const Function *F = MF.getFunction();
6586 if (Subtarget->hasFPARMv8() && !IsMemset && Size >= 16 &&
6587 !F->hasFnAttribute(Attribute::NoImplicitFloat) &&
6588 (memOpAlign(SrcAlign, DstAlign, 16) ||
6589 (allowsMisalignedMemoryAccesses(MVT::f128, 0, 1, &Fast) && Fast)))
6592 return Size >= 8 ? MVT::i64 : MVT::i32;
6595 // 12-bit optionally shifted immediates are legal for adds.
6596 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
6597 if ((Immed >> 12) == 0 || ((Immed & 0xfff) == 0 && Immed >> 24 == 0))
6602 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
6603 // immediates is the same as for an add or a sub.
6604 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
6607 return isLegalAddImmediate(Immed);
6610 /// isLegalAddressingMode - Return true if the addressing mode represented
6611 /// by AM is legal for this target, for a load/store of the specified type.
6612 bool AArch64TargetLowering::isLegalAddressingMode(const AddrMode &AM,
6614 // AArch64 has five basic addressing modes:
6616 // reg + 9-bit signed offset
6617 // reg + SIZE_IN_BYTES * 12-bit unsigned offset
6619 // reg + SIZE_IN_BYTES * reg
6621 // No global is ever allowed as a base.
6625 // No reg+reg+imm addressing.
6626 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
6629 // check reg + imm case:
6630 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
6631 uint64_t NumBytes = 0;
6632 if (Ty->isSized()) {
6633 uint64_t NumBits = getDataLayout()->getTypeSizeInBits(Ty);
6634 NumBytes = NumBits / 8;
6635 if (!isPowerOf2_64(NumBits))
6640 int64_t Offset = AM.BaseOffs;
6642 // 9-bit signed offset
6643 if (Offset >= -(1LL << 9) && Offset <= (1LL << 9) - 1)
6646 // 12-bit unsigned offset
6647 unsigned shift = Log2_64(NumBytes);
6648 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
6649 // Must be a multiple of NumBytes (NumBytes is a power of 2)
6650 (Offset >> shift) << shift == Offset)
6655 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
6657 if (!AM.Scale || AM.Scale == 1 ||
6658 (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes))
6663 int AArch64TargetLowering::getScalingFactorCost(const AddrMode &AM,
6665 // Scaling factors are not free at all.
6666 // Operands | Rt Latency
6667 // -------------------------------------------
6669 // -------------------------------------------
6670 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5
6671 // Rt, [Xn, Wm, <extend> #imm] |
6672 if (isLegalAddressingMode(AM, Ty))
6673 // Scale represents reg2 * scale, thus account for 1 if
6674 // it is not equal to 0 or 1.
6675 return AM.Scale != 0 && AM.Scale != 1;
6679 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
6680 VT = VT.getScalarType();
6685 switch (VT.getSimpleVT().SimpleTy) {
6697 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
6698 // LR is a callee-save register, but we must treat it as clobbered by any call
6699 // site. Hence we include LR in the scratch registers, which are in turn added
6700 // as implicit-defs for stackmaps and patchpoints.
6701 static const MCPhysReg ScratchRegs[] = {
6702 AArch64::X16, AArch64::X17, AArch64::LR, 0
6708 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N) const {
6709 EVT VT = N->getValueType(0);
6710 // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
6711 // it with shift to let it be lowered to UBFX.
6712 if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
6713 isa<ConstantSDNode>(N->getOperand(1))) {
6714 uint64_t TruncMask = N->getConstantOperandVal(1);
6715 if (isMask_64(TruncMask) &&
6716 N->getOperand(0).getOpcode() == ISD::SRL &&
6717 isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
6723 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
6725 assert(Ty->isIntegerTy());
6727 unsigned BitSize = Ty->getPrimitiveSizeInBits();
6731 int64_t Val = Imm.getSExtValue();
6732 if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
6735 if ((int64_t)Val < 0)
6738 Val &= (1LL << 32) - 1;
6740 unsigned LZ = countLeadingZeros((uint64_t)Val);
6741 unsigned Shift = (63 - LZ) / 16;
6742 // MOVZ is free so return true for one or fewer MOVK.
6743 return (Shift < 3) ? true : false;
6746 // Generate SUBS and CSEL for integer abs.
6747 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
6748 EVT VT = N->getValueType(0);
6750 SDValue N0 = N->getOperand(0);
6751 SDValue N1 = N->getOperand(1);
6754 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
6755 // and change it to SUB and CSEL.
6756 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
6757 N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
6758 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
6759 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
6760 if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
6761 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, VT),
6763 // Generate SUBS & CSEL.
6765 DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
6766 N0.getOperand(0), DAG.getConstant(0, VT));
6767 return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
6768 DAG.getConstant(AArch64CC::PL, MVT::i32),
6769 SDValue(Cmp.getNode(), 1));
6774 // performXorCombine - Attempts to handle integer ABS.
6775 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
6776 TargetLowering::DAGCombinerInfo &DCI,
6777 const AArch64Subtarget *Subtarget) {
6778 if (DCI.isBeforeLegalizeOps())
6781 return performIntegerAbsCombine(N, DAG);
6785 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
6787 std::vector<SDNode *> *Created) const {
6788 // fold (sdiv X, pow2)
6789 EVT VT = N->getValueType(0);
6790 if ((VT != MVT::i32 && VT != MVT::i64) ||
6791 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
6795 SDValue N0 = N->getOperand(0);
6796 unsigned Lg2 = Divisor.countTrailingZeros();
6797 SDValue Zero = DAG.getConstant(0, VT);
6798 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, VT);
6800 // Add (N0 < 0) ? Pow2 - 1 : 0;
6802 SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
6803 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
6804 SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
6807 Created->push_back(Cmp.getNode());
6808 Created->push_back(Add.getNode());
6809 Created->push_back(CSel.getNode());
6814 DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, MVT::i64));
6816 // If we're dividing by a positive value, we're done. Otherwise, we must
6817 // negate the result.
6818 if (Divisor.isNonNegative())
6822 Created->push_back(SRA.getNode());
6823 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, VT), SRA);
6826 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
6827 TargetLowering::DAGCombinerInfo &DCI,
6828 const AArch64Subtarget *Subtarget) {
6829 if (DCI.isBeforeLegalizeOps())
6832 // Multiplication of a power of two plus/minus one can be done more
6833 // cheaply as as shift+add/sub. For now, this is true unilaterally. If
6834 // future CPUs have a cheaper MADD instruction, this may need to be
6835 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
6836 // 64-bit is 5 cycles, so this is always a win.
6837 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
6838 APInt Value = C->getAPIntValue();
6839 EVT VT = N->getValueType(0);
6840 if (Value.isNonNegative()) {
6841 // (mul x, 2^N + 1) => (add (shl x, N), x)
6842 APInt VM1 = Value - 1;
6843 if (VM1.isPowerOf2()) {
6844 SDValue ShiftedVal =
6845 DAG.getNode(ISD::SHL, SDLoc(N), VT, N->getOperand(0),
6846 DAG.getConstant(VM1.logBase2(), MVT::i64));
6847 return DAG.getNode(ISD::ADD, SDLoc(N), VT, ShiftedVal,
6850 // (mul x, 2^N - 1) => (sub (shl x, N), x)
6851 APInt VP1 = Value + 1;
6852 if (VP1.isPowerOf2()) {
6853 SDValue ShiftedVal =
6854 DAG.getNode(ISD::SHL, SDLoc(N), VT, N->getOperand(0),
6855 DAG.getConstant(VP1.logBase2(), MVT::i64));
6856 return DAG.getNode(ISD::SUB, SDLoc(N), VT, ShiftedVal,
6860 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
6861 APInt VNP1 = -Value + 1;
6862 if (VNP1.isPowerOf2()) {
6863 SDValue ShiftedVal =
6864 DAG.getNode(ISD::SHL, SDLoc(N), VT, N->getOperand(0),
6865 DAG.getConstant(VNP1.logBase2(), MVT::i64));
6866 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N->getOperand(0),
6869 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
6870 APInt VNM1 = -Value - 1;
6871 if (VNM1.isPowerOf2()) {
6872 SDValue ShiftedVal =
6873 DAG.getNode(ISD::SHL, SDLoc(N), VT, N->getOperand(0),
6874 DAG.getConstant(VNM1.logBase2(), MVT::i64));
6876 DAG.getNode(ISD::ADD, SDLoc(N), VT, ShiftedVal, N->getOperand(0));
6877 return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), Add);
6884 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
6885 SelectionDAG &DAG) {
6886 // Take advantage of vector comparisons producing 0 or -1 in each lane to
6887 // optimize away operation when it's from a constant.
6889 // The general transformation is:
6890 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
6891 // AND(VECTOR_CMP(x,y), constant2)
6892 // constant2 = UNARYOP(constant)
6894 // Early exit if this isn't a vector operation, the operand of the
6895 // unary operation isn't a bitwise AND, or if the sizes of the operations
6897 EVT VT = N->getValueType(0);
6898 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
6899 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
6900 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
6903 // Now check that the other operand of the AND is a constant. We could
6904 // make the transformation for non-constant splats as well, but it's unclear
6905 // that would be a benefit as it would not eliminate any operations, just
6906 // perform one more step in scalar code before moving to the vector unit.
6907 if (BuildVectorSDNode *BV =
6908 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
6909 // Bail out if the vector isn't a constant.
6910 if (!BV->isConstant())
6913 // Everything checks out. Build up the new and improved node.
6915 EVT IntVT = BV->getValueType(0);
6916 // Create a new constant of the appropriate type for the transformed
6918 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
6919 // The AND node needs bitcasts to/from an integer vector type around it.
6920 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
6921 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
6922 N->getOperand(0)->getOperand(0), MaskConst);
6923 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
6930 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
6931 const AArch64Subtarget *Subtarget) {
6932 // First try to optimize away the conversion when it's conditionally from
6933 // a constant. Vectors only.
6934 SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
6935 if (Res != SDValue())
6938 EVT VT = N->getValueType(0);
6939 if (VT != MVT::f32 && VT != MVT::f64)
6942 // Only optimize when the source and destination types have the same width.
6943 if (VT.getSizeInBits() != N->getOperand(0).getValueType().getSizeInBits())
6946 // If the result of an integer load is only used by an integer-to-float
6947 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
6948 // This eliminates an "integer-to-vector-move UOP and improve throughput.
6949 SDValue N0 = N->getOperand(0);
6950 if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6951 // Do not change the width of a volatile load.
6952 !cast<LoadSDNode>(N0)->isVolatile()) {
6953 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6954 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
6955 LN0->getPointerInfo(), LN0->isVolatile(),
6956 LN0->isNonTemporal(), LN0->isInvariant(),
6957 LN0->getAlignment());
6959 // Make sure successors of the original load stay after it by updating them
6960 // to use the new Chain.
6961 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
6964 (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
6965 return DAG.getNode(Opcode, SDLoc(N), VT, Load);
6971 /// An EXTR instruction is made up of two shifts, ORed together. This helper
6972 /// searches for and classifies those shifts.
6973 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
6975 if (N.getOpcode() == ISD::SHL)
6977 else if (N.getOpcode() == ISD::SRL)
6982 if (!isa<ConstantSDNode>(N.getOperand(1)))
6985 ShiftAmount = N->getConstantOperandVal(1);
6986 Src = N->getOperand(0);
6990 /// EXTR instruction extracts a contiguous chunk of bits from two existing
6991 /// registers viewed as a high/low pair. This function looks for the pattern:
6992 /// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an
6993 /// EXTR. Can't quite be done in TableGen because the two immediates aren't
6995 static SDValue tryCombineToEXTR(SDNode *N,
6996 TargetLowering::DAGCombinerInfo &DCI) {
6997 SelectionDAG &DAG = DCI.DAG;
6999 EVT VT = N->getValueType(0);
7001 assert(N->getOpcode() == ISD::OR && "Unexpected root");
7003 if (VT != MVT::i32 && VT != MVT::i64)
7007 uint32_t ShiftLHS = 0;
7009 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
7013 uint32_t ShiftRHS = 0;
7015 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
7018 // If they're both trying to come from the high part of the register, they're
7019 // not really an EXTR.
7020 if (LHSFromHi == RHSFromHi)
7023 if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
7027 std::swap(LHS, RHS);
7028 std::swap(ShiftLHS, ShiftRHS);
7031 return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
7032 DAG.getConstant(ShiftRHS, MVT::i64));
7035 static SDValue tryCombineToBSL(SDNode *N,
7036 TargetLowering::DAGCombinerInfo &DCI) {
7037 EVT VT = N->getValueType(0);
7038 SelectionDAG &DAG = DCI.DAG;
7044 SDValue N0 = N->getOperand(0);
7045 if (N0.getOpcode() != ISD::AND)
7048 SDValue N1 = N->getOperand(1);
7049 if (N1.getOpcode() != ISD::AND)
7052 // We only have to look for constant vectors here since the general, variable
7053 // case can be handled in TableGen.
7054 unsigned Bits = VT.getVectorElementType().getSizeInBits();
7055 uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
7056 for (int i = 1; i >= 0; --i)
7057 for (int j = 1; j >= 0; --j) {
7058 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
7059 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
7063 bool FoundMatch = true;
7064 for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
7065 ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
7066 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
7068 CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
7075 return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
7076 N0->getOperand(1 - i), N1->getOperand(1 - j));
7082 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
7083 const AArch64Subtarget *Subtarget) {
7084 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
7085 if (!EnableAArch64ExtrGeneration)
7087 SelectionDAG &DAG = DCI.DAG;
7088 EVT VT = N->getValueType(0);
7090 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7093 SDValue Res = tryCombineToEXTR(N, DCI);
7097 Res = tryCombineToBSL(N, DCI);
7104 static SDValue performBitcastCombine(SDNode *N,
7105 TargetLowering::DAGCombinerInfo &DCI,
7106 SelectionDAG &DAG) {
7107 // Wait 'til after everything is legalized to try this. That way we have
7108 // legal vector types and such.
7109 if (DCI.isBeforeLegalizeOps())
7112 // Remove extraneous bitcasts around an extract_subvector.
7114 // (v4i16 (bitconvert
7115 // (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
7117 // (extract_subvector ((v8i16 ...), (i64 4)))
7119 // Only interested in 64-bit vectors as the ultimate result.
7120 EVT VT = N->getValueType(0);
7123 if (VT.getSimpleVT().getSizeInBits() != 64)
7125 // Is the operand an extract_subvector starting at the beginning or halfway
7126 // point of the vector? A low half may also come through as an
7127 // EXTRACT_SUBREG, so look for that, too.
7128 SDValue Op0 = N->getOperand(0);
7129 if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
7130 !(Op0->isMachineOpcode() &&
7131 Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
7133 uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
7134 if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
7135 if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
7137 } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
7138 if (idx != AArch64::dsub)
7140 // The dsub reference is equivalent to a lane zero subvector reference.
7143 // Look through the bitcast of the input to the extract.
7144 if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
7146 SDValue Source = Op0->getOperand(0)->getOperand(0);
7147 // If the source type has twice the number of elements as our destination
7148 // type, we know this is an extract of the high or low half of the vector.
7149 EVT SVT = Source->getValueType(0);
7150 if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
7153 DEBUG(dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
7155 // Create the simplified form to just extract the low or high half of the
7156 // vector directly rather than bothering with the bitcasts.
7158 unsigned NumElements = VT.getVectorNumElements();
7160 SDValue HalfIdx = DAG.getConstant(NumElements, MVT::i64);
7161 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
7163 SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, MVT::i32);
7164 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
7170 static SDValue performConcatVectorsCombine(SDNode *N,
7171 TargetLowering::DAGCombinerInfo &DCI,
7172 SelectionDAG &DAG) {
7173 // Wait 'til after everything is legalized to try this. That way we have
7174 // legal vector types and such.
7175 if (DCI.isBeforeLegalizeOps())
7179 EVT VT = N->getValueType(0);
7181 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
7182 // splat. The indexed instructions are going to be expecting a DUPLANE64, so
7183 // canonicalise to that.
7184 if (N->getOperand(0) == N->getOperand(1) && VT.getVectorNumElements() == 2) {
7185 assert(VT.getVectorElementType().getSizeInBits() == 64);
7186 return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT,
7187 WidenVector(N->getOperand(0), DAG),
7188 DAG.getConstant(0, MVT::i64));
7191 // Canonicalise concat_vectors so that the right-hand vector has as few
7192 // bit-casts as possible before its real operation. The primary matching
7193 // destination for these operations will be the narrowing "2" instructions,
7194 // which depend on the operation being performed on this right-hand vector.
7196 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS))))
7198 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
7200 SDValue Op1 = N->getOperand(1);
7201 if (Op1->getOpcode() != ISD::BITCAST)
7203 SDValue RHS = Op1->getOperand(0);
7204 MVT RHSTy = RHS.getValueType().getSimpleVT();
7205 // If the RHS is not a vector, this is not the pattern we're looking for.
7206 if (!RHSTy.isVector())
7209 DEBUG(dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
7211 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
7212 RHSTy.getVectorNumElements() * 2);
7214 ISD::BITCAST, dl, VT,
7215 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
7216 DAG.getNode(ISD::BITCAST, dl, RHSTy, N->getOperand(0)), RHS));
7219 static SDValue tryCombineFixedPointConvert(SDNode *N,
7220 TargetLowering::DAGCombinerInfo &DCI,
7221 SelectionDAG &DAG) {
7222 // Wait 'til after everything is legalized to try this. That way we have
7223 // legal vector types and such.
7224 if (DCI.isBeforeLegalizeOps())
7226 // Transform a scalar conversion of a value from a lane extract into a
7227 // lane extract of a vector conversion. E.g., from foo1 to foo2:
7228 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
7229 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
7231 // The second form interacts better with instruction selection and the
7232 // register allocator to avoid cross-class register copies that aren't
7233 // coalescable due to a lane reference.
7235 // Check the operand and see if it originates from a lane extract.
7236 SDValue Op1 = N->getOperand(1);
7237 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7238 // Yep, no additional predication needed. Perform the transform.
7239 SDValue IID = N->getOperand(0);
7240 SDValue Shift = N->getOperand(2);
7241 SDValue Vec = Op1.getOperand(0);
7242 SDValue Lane = Op1.getOperand(1);
7243 EVT ResTy = N->getValueType(0);
7247 // The vector width should be 128 bits by the time we get here, even
7248 // if it started as 64 bits (the extract_vector handling will have
7250 assert(Vec.getValueType().getSizeInBits() == 128 &&
7251 "unexpected vector size on extract_vector_elt!");
7252 if (Vec.getValueType() == MVT::v4i32)
7253 VecResTy = MVT::v4f32;
7254 else if (Vec.getValueType() == MVT::v2i64)
7255 VecResTy = MVT::v2f64;
7257 llvm_unreachable("unexpected vector type!");
7260 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
7261 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
7266 // AArch64 high-vector "long" operations are formed by performing the non-high
7267 // version on an extract_subvector of each operand which gets the high half:
7269 // (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
7271 // However, there are cases which don't have an extract_high explicitly, but
7272 // have another operation that can be made compatible with one for free. For
7275 // (dupv64 scalar) --> (extract_high (dup128 scalar))
7277 // This routine does the actual conversion of such DUPs, once outer routines
7278 // have determined that everything else is in order.
7279 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
7280 // We can handle most types of duplicate, but the lane ones have an extra
7281 // operand saying *which* lane, so we need to know.
7283 switch (N.getOpcode()) {
7284 case AArch64ISD::DUP:
7287 case AArch64ISD::DUPLANE8:
7288 case AArch64ISD::DUPLANE16:
7289 case AArch64ISD::DUPLANE32:
7290 case AArch64ISD::DUPLANE64:
7297 MVT NarrowTy = N.getSimpleValueType();
7298 if (!NarrowTy.is64BitVector())
7301 MVT ElementTy = NarrowTy.getVectorElementType();
7302 unsigned NumElems = NarrowTy.getVectorNumElements();
7303 MVT NewDUPVT = MVT::getVectorVT(ElementTy, NumElems * 2);
7307 NewDUP = DAG.getNode(N.getOpcode(), SDLoc(N), NewDUPVT, N.getOperand(0),
7310 NewDUP = DAG.getNode(AArch64ISD::DUP, SDLoc(N), NewDUPVT, N.getOperand(0));
7312 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N.getNode()), NarrowTy,
7313 NewDUP, DAG.getConstant(NumElems, MVT::i64));
7316 static bool isEssentiallyExtractSubvector(SDValue N) {
7317 if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
7320 return N.getOpcode() == ISD::BITCAST &&
7321 N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
7324 /// \brief Helper structure to keep track of ISD::SET_CC operands.
7325 struct GenericSetCCInfo {
7326 const SDValue *Opnd0;
7327 const SDValue *Opnd1;
7331 /// \brief Helper structure to keep track of a SET_CC lowered into AArch64 code.
7332 struct AArch64SetCCInfo {
7334 AArch64CC::CondCode CC;
7337 /// \brief Helper structure to keep track of SetCC information.
7339 GenericSetCCInfo Generic;
7340 AArch64SetCCInfo AArch64;
7343 /// \brief Helper structure to be able to read SetCC information. If set to
7344 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
7345 /// GenericSetCCInfo.
7346 struct SetCCInfoAndKind {
7351 /// \brief Check whether or not \p Op is a SET_CC operation, either a generic or
7353 /// AArch64 lowered one.
7354 /// \p SetCCInfo is filled accordingly.
7355 /// \post SetCCInfo is meanginfull only when this function returns true.
7356 /// \return True when Op is a kind of SET_CC operation.
7357 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
7358 // If this is a setcc, this is straight forward.
7359 if (Op.getOpcode() == ISD::SETCC) {
7360 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
7361 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
7362 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7363 SetCCInfo.IsAArch64 = false;
7366 // Otherwise, check if this is a matching csel instruction.
7370 if (Op.getOpcode() != AArch64ISD::CSEL)
7372 // Set the information about the operands.
7373 // TODO: we want the operands of the Cmp not the csel
7374 SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
7375 SetCCInfo.IsAArch64 = true;
7376 SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
7377 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
7379 // Check that the operands matches the constraints:
7380 // (1) Both operands must be constants.
7381 // (2) One must be 1 and the other must be 0.
7382 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
7383 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7386 if (!TValue || !FValue)
7390 if (!TValue->isOne()) {
7391 // Update the comparison when we are interested in !cc.
7392 std::swap(TValue, FValue);
7393 SetCCInfo.Info.AArch64.CC =
7394 AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
7396 return TValue->isOne() && FValue->isNullValue();
7399 // Returns true if Op is setcc or zext of setcc.
7400 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
7401 if (isSetCC(Op, Info))
7403 return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
7404 isSetCC(Op->getOperand(0), Info));
7407 // The folding we want to perform is:
7408 // (add x, [zext] (setcc cc ...) )
7410 // (csel x, (add x, 1), !cc ...)
7412 // The latter will get matched to a CSINC instruction.
7413 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
7414 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
7415 SDValue LHS = Op->getOperand(0);
7416 SDValue RHS = Op->getOperand(1);
7417 SetCCInfoAndKind InfoAndKind;
7419 // If neither operand is a SET_CC, give up.
7420 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
7421 std::swap(LHS, RHS);
7422 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
7426 // FIXME: This could be generatized to work for FP comparisons.
7427 EVT CmpVT = InfoAndKind.IsAArch64
7428 ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
7429 : InfoAndKind.Info.Generic.Opnd0->getValueType();
7430 if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
7436 if (InfoAndKind.IsAArch64) {
7437 CCVal = DAG.getConstant(
7438 AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), MVT::i32);
7439 Cmp = *InfoAndKind.Info.AArch64.Cmp;
7441 Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
7442 *InfoAndKind.Info.Generic.Opnd1,
7443 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
7446 EVT VT = Op->getValueType(0);
7447 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, VT));
7448 return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
7451 // The basic add/sub long vector instructions have variants with "2" on the end
7452 // which act on the high-half of their inputs. They are normally matched by
7455 // (add (zeroext (extract_high LHS)),
7456 // (zeroext (extract_high RHS)))
7457 // -> uaddl2 vD, vN, vM
7459 // However, if one of the extracts is something like a duplicate, this
7460 // instruction can still be used profitably. This function puts the DAG into a
7461 // more appropriate form for those patterns to trigger.
7462 static SDValue performAddSubLongCombine(SDNode *N,
7463 TargetLowering::DAGCombinerInfo &DCI,
7464 SelectionDAG &DAG) {
7465 if (DCI.isBeforeLegalizeOps())
7468 MVT VT = N->getSimpleValueType(0);
7469 if (!VT.is128BitVector()) {
7470 if (N->getOpcode() == ISD::ADD)
7471 return performSetccAddFolding(N, DAG);
7475 // Make sure both branches are extended in the same way.
7476 SDValue LHS = N->getOperand(0);
7477 SDValue RHS = N->getOperand(1);
7478 if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
7479 LHS.getOpcode() != ISD::SIGN_EXTEND) ||
7480 LHS.getOpcode() != RHS.getOpcode())
7483 unsigned ExtType = LHS.getOpcode();
7485 // It's not worth doing if at least one of the inputs isn't already an
7486 // extract, but we don't know which it'll be so we have to try both.
7487 if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
7488 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
7492 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
7493 } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
7494 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
7498 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
7501 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
7504 // Massage DAGs which we can use the high-half "long" operations on into
7505 // something isel will recognize better. E.g.
7507 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
7508 // (aarch64_neon_umull (extract_high (v2i64 vec)))
7509 // (extract_high (v2i64 (dup128 scalar)))))
7511 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
7512 TargetLowering::DAGCombinerInfo &DCI,
7513 SelectionDAG &DAG) {
7514 if (DCI.isBeforeLegalizeOps())
7517 SDValue LHS = N->getOperand(1);
7518 SDValue RHS = N->getOperand(2);
7519 assert(LHS.getValueType().is64BitVector() &&
7520 RHS.getValueType().is64BitVector() &&
7521 "unexpected shape for long operation");
7523 // Either node could be a DUP, but it's not worth doing both of them (you'd
7524 // just as well use the non-high version) so look for a corresponding extract
7525 // operation on the other "wing".
7526 if (isEssentiallyExtractSubvector(LHS)) {
7527 RHS = tryExtendDUPToExtractHigh(RHS, DAG);
7530 } else if (isEssentiallyExtractSubvector(RHS)) {
7531 LHS = tryExtendDUPToExtractHigh(LHS, DAG);
7536 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
7537 N->getOperand(0), LHS, RHS);
7540 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
7541 MVT ElemTy = N->getSimpleValueType(0).getScalarType();
7542 unsigned ElemBits = ElemTy.getSizeInBits();
7544 int64_t ShiftAmount;
7545 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
7546 APInt SplatValue, SplatUndef;
7547 unsigned SplatBitSize;
7549 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
7550 HasAnyUndefs, ElemBits) ||
7551 SplatBitSize != ElemBits)
7554 ShiftAmount = SplatValue.getSExtValue();
7555 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
7556 ShiftAmount = CVN->getSExtValue();
7564 llvm_unreachable("Unknown shift intrinsic");
7565 case Intrinsic::aarch64_neon_sqshl:
7566 Opcode = AArch64ISD::SQSHL_I;
7567 IsRightShift = false;
7569 case Intrinsic::aarch64_neon_uqshl:
7570 Opcode = AArch64ISD::UQSHL_I;
7571 IsRightShift = false;
7573 case Intrinsic::aarch64_neon_srshl:
7574 Opcode = AArch64ISD::SRSHR_I;
7575 IsRightShift = true;
7577 case Intrinsic::aarch64_neon_urshl:
7578 Opcode = AArch64ISD::URSHR_I;
7579 IsRightShift = true;
7581 case Intrinsic::aarch64_neon_sqshlu:
7582 Opcode = AArch64ISD::SQSHLU_I;
7583 IsRightShift = false;
7587 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits)
7588 return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), N->getOperand(1),
7589 DAG.getConstant(-ShiftAmount, MVT::i32));
7590 else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits)
7591 return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), N->getOperand(1),
7592 DAG.getConstant(ShiftAmount, MVT::i32));
7597 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
7598 // the intrinsics must be legal and take an i32, this means there's almost
7599 // certainly going to be a zext in the DAG which we can eliminate.
7600 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
7601 SDValue AndN = N->getOperand(2);
7602 if (AndN.getOpcode() != ISD::AND)
7605 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
7606 if (!CMask || CMask->getZExtValue() != Mask)
7609 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
7610 N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
7613 static SDValue performIntrinsicCombine(SDNode *N,
7614 TargetLowering::DAGCombinerInfo &DCI,
7615 const AArch64Subtarget *Subtarget) {
7616 SelectionDAG &DAG = DCI.DAG;
7617 unsigned IID = getIntrinsicID(N);
7621 case Intrinsic::aarch64_neon_vcvtfxs2fp:
7622 case Intrinsic::aarch64_neon_vcvtfxu2fp:
7623 return tryCombineFixedPointConvert(N, DCI, DAG);
7625 case Intrinsic::aarch64_neon_fmax:
7626 return DAG.getNode(AArch64ISD::FMAX, SDLoc(N), N->getValueType(0),
7627 N->getOperand(1), N->getOperand(2));
7628 case Intrinsic::aarch64_neon_fmin:
7629 return DAG.getNode(AArch64ISD::FMIN, SDLoc(N), N->getValueType(0),
7630 N->getOperand(1), N->getOperand(2));
7631 case Intrinsic::aarch64_neon_smull:
7632 case Intrinsic::aarch64_neon_umull:
7633 case Intrinsic::aarch64_neon_pmull:
7634 case Intrinsic::aarch64_neon_sqdmull:
7635 return tryCombineLongOpWithDup(IID, N, DCI, DAG);
7636 case Intrinsic::aarch64_neon_sqshl:
7637 case Intrinsic::aarch64_neon_uqshl:
7638 case Intrinsic::aarch64_neon_sqshlu:
7639 case Intrinsic::aarch64_neon_srshl:
7640 case Intrinsic::aarch64_neon_urshl:
7641 return tryCombineShiftImm(IID, N, DAG);
7642 case Intrinsic::aarch64_crc32b:
7643 case Intrinsic::aarch64_crc32cb:
7644 return tryCombineCRC32(0xff, N, DAG);
7645 case Intrinsic::aarch64_crc32h:
7646 case Intrinsic::aarch64_crc32ch:
7647 return tryCombineCRC32(0xffff, N, DAG);
7652 static SDValue performExtendCombine(SDNode *N,
7653 TargetLowering::DAGCombinerInfo &DCI,
7654 SelectionDAG &DAG) {
7655 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
7656 // we can convert that DUP into another extract_high (of a bigger DUP), which
7657 // helps the backend to decide that an sabdl2 would be useful, saving a real
7658 // extract_high operation.
7659 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
7660 N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
7661 SDNode *ABDNode = N->getOperand(0).getNode();
7662 unsigned IID = getIntrinsicID(ABDNode);
7663 if (IID == Intrinsic::aarch64_neon_sabd ||
7664 IID == Intrinsic::aarch64_neon_uabd) {
7665 SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
7666 if (!NewABD.getNode())
7669 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
7674 // This is effectively a custom type legalization for AArch64.
7676 // Type legalization will split an extend of a small, legal, type to a larger
7677 // illegal type by first splitting the destination type, often creating
7678 // illegal source types, which then get legalized in isel-confusing ways,
7679 // leading to really terrible codegen. E.g.,
7680 // %result = v8i32 sext v8i8 %value
7682 // %losrc = extract_subreg %value, ...
7683 // %hisrc = extract_subreg %value, ...
7684 // %lo = v4i32 sext v4i8 %losrc
7685 // %hi = v4i32 sext v4i8 %hisrc
7686 // Things go rapidly downhill from there.
7688 // For AArch64, the [sz]ext vector instructions can only go up one element
7689 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
7690 // take two instructions.
7692 // This implies that the most efficient way to do the extend from v8i8
7693 // to two v4i32 values is to first extend the v8i8 to v8i16, then do
7694 // the normal splitting to happen for the v8i16->v8i32.
7696 // This is pre-legalization to catch some cases where the default
7697 // type legalization will create ill-tempered code.
7698 if (!DCI.isBeforeLegalizeOps())
7701 // We're only interested in cleaning things up for non-legal vector types
7702 // here. If both the source and destination are legal, things will just
7703 // work naturally without any fiddling.
7704 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7705 EVT ResVT = N->getValueType(0);
7706 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
7708 // If the vector type isn't a simple VT, it's beyond the scope of what
7709 // we're worried about here. Let legalization do its thing and hope for
7711 SDValue Src = N->getOperand(0);
7712 EVT SrcVT = Src->getValueType(0);
7713 if (!ResVT.isSimple() || !SrcVT.isSimple())
7716 // If the source VT is a 64-bit vector, we can play games and get the
7717 // better results we want.
7718 if (SrcVT.getSizeInBits() != 64)
7721 unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits();
7722 unsigned ElementCount = SrcVT.getVectorNumElements();
7723 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
7725 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
7727 // Now split the rest of the operation into two halves, each with a 64
7731 unsigned NumElements = ResVT.getVectorNumElements();
7732 assert(!(NumElements & 1) && "Splitting vector, but not in half!");
7733 LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
7734 ResVT.getVectorElementType(), NumElements / 2);
7736 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
7737 LoVT.getVectorNumElements());
7738 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
7739 DAG.getConstant(0, MVT::i64));
7740 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
7741 DAG.getConstant(InNVT.getVectorNumElements(), MVT::i64));
7742 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
7743 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
7745 // Now combine the parts back together so we still have a single result
7746 // like the combiner expects.
7747 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
7750 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
7751 /// value. The load store optimizer pass will merge them to store pair stores.
7752 /// This has better performance than a splat of the scalar followed by a split
7753 /// vector store. Even if the stores are not merged it is four stores vs a dup,
7754 /// followed by an ext.b and two stores.
7755 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode *St) {
7756 SDValue StVal = St->getValue();
7757 EVT VT = StVal.getValueType();
7759 // Don't replace floating point stores, they possibly won't be transformed to
7760 // stp because of the store pair suppress pass.
7761 if (VT.isFloatingPoint())
7764 // Check for insert vector elements.
7765 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
7768 // We can express a splat as store pair(s) for 2 or 4 elements.
7769 unsigned NumVecElts = VT.getVectorNumElements();
7770 if (NumVecElts != 4 && NumVecElts != 2)
7772 SDValue SplatVal = StVal.getOperand(1);
7773 unsigned RemainInsertElts = NumVecElts - 1;
7775 // Check that this is a splat.
7776 while (--RemainInsertElts) {
7777 SDValue NextInsertElt = StVal.getOperand(0);
7778 if (NextInsertElt.getOpcode() != ISD::INSERT_VECTOR_ELT)
7780 if (NextInsertElt.getOperand(1) != SplatVal)
7782 StVal = NextInsertElt;
7784 unsigned OrigAlignment = St->getAlignment();
7785 unsigned EltOffset = NumVecElts == 4 ? 4 : 8;
7786 unsigned Alignment = std::min(OrigAlignment, EltOffset);
7788 // Create scalar stores. This is at least as good as the code sequence for a
7789 // split unaligned store wich is a dup.s, ext.b, and two stores.
7790 // Most of the time the three stores should be replaced by store pair
7791 // instructions (stp).
7793 SDValue BasePtr = St->getBasePtr();
7795 DAG.getStore(St->getChain(), DL, SplatVal, BasePtr, St->getPointerInfo(),
7796 St->isVolatile(), St->isNonTemporal(), St->getAlignment());
7798 unsigned Offset = EltOffset;
7799 while (--NumVecElts) {
7800 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
7801 DAG.getConstant(Offset, MVT::i64));
7802 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
7803 St->getPointerInfo(), St->isVolatile(),
7804 St->isNonTemporal(), Alignment);
7805 Offset += EltOffset;
7810 static SDValue performSTORECombine(SDNode *N,
7811 TargetLowering::DAGCombinerInfo &DCI,
7813 const AArch64Subtarget *Subtarget) {
7814 if (!DCI.isBeforeLegalize())
7817 StoreSDNode *S = cast<StoreSDNode>(N);
7818 if (S->isVolatile())
7821 // Cyclone has bad performance on unaligned 16B stores when crossing line and
7822 // page boundaries. We want to split such stores.
7823 if (!Subtarget->isCyclone())
7826 // Don't split at Oz.
7827 MachineFunction &MF = DAG.getMachineFunction();
7828 bool IsMinSize = MF.getFunction()->hasFnAttribute(Attribute::MinSize);
7832 SDValue StVal = S->getValue();
7833 EVT VT = StVal.getValueType();
7835 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
7836 // those up regresses performance on micro-benchmarks and olden/bh.
7837 if (!VT.isVector() || VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
7840 // Split unaligned 16B stores. They are terrible for performance.
7841 // Don't split stores with alignment of 1 or 2. Code that uses clang vector
7842 // extensions can use this to mark that it does not want splitting to happen
7843 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
7844 // eliminating alignment hazards is only 1 in 8 for alignment of 2.
7845 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
7846 S->getAlignment() <= 2)
7849 // If we get a splat of a scalar convert this vector store to a store of
7850 // scalars. They will be merged into store pairs thereby removing two
7852 SDValue ReplacedSplat = replaceSplatVectorStore(DAG, S);
7853 if (ReplacedSplat != SDValue())
7854 return ReplacedSplat;
7857 unsigned NumElts = VT.getVectorNumElements() / 2;
7858 // Split VT into two.
7860 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
7861 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
7862 DAG.getConstant(0, MVT::i64));
7863 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
7864 DAG.getConstant(NumElts, MVT::i64));
7865 SDValue BasePtr = S->getBasePtr();
7867 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
7868 S->isVolatile(), S->isNonTemporal(), S->getAlignment());
7869 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
7870 DAG.getConstant(8, MVT::i64));
7871 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
7872 S->getPointerInfo(), S->isVolatile(), S->isNonTemporal(),
7876 /// Target-specific DAG combine function for post-increment LD1 (lane) and
7877 /// post-increment LD1R.
7878 static SDValue performPostLD1Combine(SDNode *N,
7879 TargetLowering::DAGCombinerInfo &DCI,
7881 if (DCI.isBeforeLegalizeOps())
7884 SelectionDAG &DAG = DCI.DAG;
7885 EVT VT = N->getValueType(0);
7887 unsigned LoadIdx = IsLaneOp ? 1 : 0;
7888 SDNode *LD = N->getOperand(LoadIdx).getNode();
7889 // If it is not LOAD, can not do such combine.
7890 if (LD->getOpcode() != ISD::LOAD)
7893 LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
7894 EVT MemVT = LoadSDN->getMemoryVT();
7895 // Check if memory operand is the same type as the vector element.
7896 if (MemVT != VT.getVectorElementType())
7899 // Check if there are other uses. If so, do not combine as it will introduce
7901 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
7903 if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
7909 SDValue Addr = LD->getOperand(1);
7910 SDValue Vector = N->getOperand(0);
7911 // Search for a use of the address operand that is an increment.
7912 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
7913 Addr.getNode()->use_end(); UI != UE; ++UI) {
7915 if (User->getOpcode() != ISD::ADD
7916 || UI.getUse().getResNo() != Addr.getResNo())
7919 // Check that the add is independent of the load. Otherwise, folding it
7920 // would create a cycle.
7921 if (User->isPredecessorOf(LD) || LD->isPredecessorOf(User))
7923 // Also check that add is not used in the vector operand. This would also
7925 if (User->isPredecessorOf(Vector.getNode()))
7928 // If the increment is a constant, it must match the memory ref size.
7929 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
7930 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
7931 uint32_t IncVal = CInc->getZExtValue();
7932 unsigned NumBytes = VT.getScalarSizeInBits() / 8;
7933 if (IncVal != NumBytes)
7935 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
7938 SmallVector<SDValue, 8> Ops;
7939 Ops.push_back(LD->getOperand(0)); // Chain
7941 Ops.push_back(Vector); // The vector to be inserted
7942 Ops.push_back(N->getOperand(2)); // The lane to be inserted in the vector
7944 Ops.push_back(Addr);
7947 EVT Tys[3] = { VT, MVT::i64, MVT::Other };
7948 SDVTList SDTys = DAG.getVTList(Tys);
7949 unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
7950 SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
7952 LoadSDN->getMemOperand());
7955 SmallVector<SDValue, 2> NewResults;
7956 NewResults.push_back(SDValue(LD, 0)); // The result of load
7957 NewResults.push_back(SDValue(UpdN.getNode(), 2)); // Chain
7958 DCI.CombineTo(LD, NewResults);
7959 DCI.CombineTo(N, SDValue(UpdN.getNode(), 0)); // Dup/Inserted Result
7960 DCI.CombineTo(User, SDValue(UpdN.getNode(), 1)); // Write back register
7967 /// Target-specific DAG combine function for NEON load/store intrinsics
7968 /// to merge base address updates.
7969 static SDValue performNEONPostLDSTCombine(SDNode *N,
7970 TargetLowering::DAGCombinerInfo &DCI,
7971 SelectionDAG &DAG) {
7972 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
7975 unsigned AddrOpIdx = N->getNumOperands() - 1;
7976 SDValue Addr = N->getOperand(AddrOpIdx);
7978 // Search for a use of the address operand that is an increment.
7979 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
7980 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
7982 if (User->getOpcode() != ISD::ADD ||
7983 UI.getUse().getResNo() != Addr.getResNo())
7986 // Check that the add is independent of the load/store. Otherwise, folding
7987 // it would create a cycle.
7988 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
7991 // Find the new opcode for the updating load/store.
7992 bool IsStore = false;
7993 bool IsLaneOp = false;
7994 bool IsDupOp = false;
7995 unsigned NewOpc = 0;
7996 unsigned NumVecs = 0;
7997 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
7999 default: llvm_unreachable("unexpected intrinsic for Neon base update");
8000 case Intrinsic::aarch64_neon_ld2: NewOpc = AArch64ISD::LD2post;
8002 case Intrinsic::aarch64_neon_ld3: NewOpc = AArch64ISD::LD3post;
8004 case Intrinsic::aarch64_neon_ld4: NewOpc = AArch64ISD::LD4post;
8006 case Intrinsic::aarch64_neon_st2: NewOpc = AArch64ISD::ST2post;
8007 NumVecs = 2; IsStore = true; break;
8008 case Intrinsic::aarch64_neon_st3: NewOpc = AArch64ISD::ST3post;
8009 NumVecs = 3; IsStore = true; break;
8010 case Intrinsic::aarch64_neon_st4: NewOpc = AArch64ISD::ST4post;
8011 NumVecs = 4; IsStore = true; break;
8012 case Intrinsic::aarch64_neon_ld1x2: NewOpc = AArch64ISD::LD1x2post;
8014 case Intrinsic::aarch64_neon_ld1x3: NewOpc = AArch64ISD::LD1x3post;
8016 case Intrinsic::aarch64_neon_ld1x4: NewOpc = AArch64ISD::LD1x4post;
8018 case Intrinsic::aarch64_neon_st1x2: NewOpc = AArch64ISD::ST1x2post;
8019 NumVecs = 2; IsStore = true; break;
8020 case Intrinsic::aarch64_neon_st1x3: NewOpc = AArch64ISD::ST1x3post;
8021 NumVecs = 3; IsStore = true; break;
8022 case Intrinsic::aarch64_neon_st1x4: NewOpc = AArch64ISD::ST1x4post;
8023 NumVecs = 4; IsStore = true; break;
8024 case Intrinsic::aarch64_neon_ld2r: NewOpc = AArch64ISD::LD2DUPpost;
8025 NumVecs = 2; IsDupOp = true; break;
8026 case Intrinsic::aarch64_neon_ld3r: NewOpc = AArch64ISD::LD3DUPpost;
8027 NumVecs = 3; IsDupOp = true; break;
8028 case Intrinsic::aarch64_neon_ld4r: NewOpc = AArch64ISD::LD4DUPpost;
8029 NumVecs = 4; IsDupOp = true; break;
8030 case Intrinsic::aarch64_neon_ld2lane: NewOpc = AArch64ISD::LD2LANEpost;
8031 NumVecs = 2; IsLaneOp = true; break;
8032 case Intrinsic::aarch64_neon_ld3lane: NewOpc = AArch64ISD::LD3LANEpost;
8033 NumVecs = 3; IsLaneOp = true; break;
8034 case Intrinsic::aarch64_neon_ld4lane: NewOpc = AArch64ISD::LD4LANEpost;
8035 NumVecs = 4; IsLaneOp = true; break;
8036 case Intrinsic::aarch64_neon_st2lane: NewOpc = AArch64ISD::ST2LANEpost;
8037 NumVecs = 2; IsStore = true; IsLaneOp = true; break;
8038 case Intrinsic::aarch64_neon_st3lane: NewOpc = AArch64ISD::ST3LANEpost;
8039 NumVecs = 3; IsStore = true; IsLaneOp = true; break;
8040 case Intrinsic::aarch64_neon_st4lane: NewOpc = AArch64ISD::ST4LANEpost;
8041 NumVecs = 4; IsStore = true; IsLaneOp = true; break;
8046 VecTy = N->getOperand(2).getValueType();
8048 VecTy = N->getValueType(0);
8050 // If the increment is a constant, it must match the memory ref size.
8051 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8052 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8053 uint32_t IncVal = CInc->getZExtValue();
8054 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8055 if (IsLaneOp || IsDupOp)
8056 NumBytes /= VecTy.getVectorNumElements();
8057 if (IncVal != NumBytes)
8059 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
8061 SmallVector<SDValue, 8> Ops;
8062 Ops.push_back(N->getOperand(0)); // Incoming chain
8063 // Load lane and store have vector list as input.
8064 if (IsLaneOp || IsStore)
8065 for (unsigned i = 2; i < AddrOpIdx; ++i)
8066 Ops.push_back(N->getOperand(i));
8067 Ops.push_back(Addr); // Base register
8072 unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
8074 for (n = 0; n < NumResultVecs; ++n)
8076 Tys[n++] = MVT::i64; // Type of write back register
8077 Tys[n] = MVT::Other; // Type of the chain
8078 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
8080 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8081 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
8082 MemInt->getMemoryVT(),
8083 MemInt->getMemOperand());
8086 std::vector<SDValue> NewResults;
8087 for (unsigned i = 0; i < NumResultVecs; ++i) {
8088 NewResults.push_back(SDValue(UpdN.getNode(), i));
8090 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
8091 DCI.CombineTo(N, NewResults);
8092 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8099 // Checks to see if the value is the prescribed width and returns information
8100 // about its extension mode.
8102 bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
8103 ExtType = ISD::NON_EXTLOAD;
8104 switch(V.getNode()->getOpcode()) {
8108 LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
8109 if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
8110 || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
8111 ExtType = LoadNode->getExtensionType();
8116 case ISD::AssertSext: {
8117 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
8118 if ((TypeNode->getVT() == MVT::i8 && width == 8)
8119 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
8120 ExtType = ISD::SEXTLOAD;
8125 case ISD::AssertZext: {
8126 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
8127 if ((TypeNode->getVT() == MVT::i8 && width == 8)
8128 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
8129 ExtType = ISD::ZEXTLOAD;
8135 case ISD::TargetConstant: {
8136 if (std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
8146 // This function does a whole lot of voodoo to determine if the tests are
8147 // equivalent without and with a mask. Essentially what happens is that given a
8150 // +-------------+ +-------------+ +-------------+ +-------------+
8151 // | Input | | AddConstant | | CompConstant| | CC |
8152 // +-------------+ +-------------+ +-------------+ +-------------+
8154 // V V | +----------+
8155 // +-------------+ +----+ | |
8156 // | ADD | |0xff| | |
8157 // +-------------+ +----+ | |
8160 // +-------------+ | |
8162 // +-------------+ | |
8171 // The AND node may be safely removed for some combinations of inputs. In
8172 // particular we need to take into account the extension type of the Input,
8173 // the exact values of AddConstant, CompConstant, and CC, along with the nominal
8174 // width of the input (this can work for any width inputs, the above graph is
8175 // specific to 8 bits.
8177 // The specific equations were worked out by generating output tables for each
8178 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
8179 // problem was simplified by working with 4 bit inputs, which means we only
8180 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
8181 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
8182 // patterns present in both extensions (0,7). For every distinct set of
8183 // AddConstant and CompConstants bit patterns we can consider the masked and
8184 // unmasked versions to be equivalent if the result of this function is true for
8185 // all 16 distinct bit patterns of for the current extension type of Input (w0).
8188 // and w10, w8, #0x0f
8190 // cset w9, AArch64CC
8192 // cset w11, AArch64CC
8197 // Since the above function shows when the outputs are equivalent it defines
8198 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
8199 // would be expensive to run during compiles. The equations below were written
8200 // in a test harness that confirmed they gave equivalent outputs to the above
8201 // for all inputs function, so they can be used determine if the removal is
8204 // isEquivalentMaskless() is the code for testing if the AND can be removed
8205 // factored out of the DAG recognition as the DAG can take several forms.
8208 bool isEquivalentMaskless(unsigned CC, unsigned width,
8209 ISD::LoadExtType ExtType, signed AddConstant,
8210 signed CompConstant) {
8211 // By being careful about our equations and only writing the in term
8212 // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
8213 // make them generally applicable to all bit widths.
8214 signed MaxUInt = (1 << width);
8216 // For the purposes of these comparisons sign extending the type is
8217 // equivalent to zero extending the add and displacing it by half the integer
8218 // width. Provided we are careful and make sure our equations are valid over
8219 // the whole range we can just adjust the input and avoid writing equations
8220 // for sign extended inputs.
8221 if (ExtType == ISD::SEXTLOAD)
8222 AddConstant -= (1 << (width-1));
8226 case AArch64CC::GT: {
8227 if ((AddConstant == 0) ||
8228 (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
8229 (AddConstant >= 0 && CompConstant < 0) ||
8230 (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
8234 case AArch64CC::GE: {
8235 if ((AddConstant == 0) ||
8236 (AddConstant >= 0 && CompConstant <= 0) ||
8237 (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
8241 case AArch64CC::LS: {
8242 if ((AddConstant >= 0 && CompConstant < 0) ||
8243 (AddConstant <= 0 && CompConstant >= -1 &&
8244 CompConstant < AddConstant + MaxUInt))
8248 case AArch64CC::MI: {
8249 if ((AddConstant == 0) ||
8250 (AddConstant > 0 && CompConstant <= 0) ||
8251 (AddConstant < 0 && CompConstant <= AddConstant))
8255 case AArch64CC::HS: {
8256 if ((AddConstant >= 0 && CompConstant <= 0) ||
8257 (AddConstant <= 0 && CompConstant >= 0 &&
8258 CompConstant <= AddConstant + MaxUInt))
8262 case AArch64CC::NE: {
8263 if ((AddConstant > 0 && CompConstant < 0) ||
8264 (AddConstant < 0 && CompConstant >= 0 &&
8265 CompConstant < AddConstant + MaxUInt) ||
8266 (AddConstant >= 0 && CompConstant >= 0 &&
8267 CompConstant >= AddConstant) ||
8268 (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
8277 case AArch64CC::Invalid:
8285 SDValue performCONDCombine(SDNode *N,
8286 TargetLowering::DAGCombinerInfo &DCI,
8287 SelectionDAG &DAG, unsigned CCIndex,
8288 unsigned CmpIndex) {
8289 unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
8290 SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
8291 unsigned CondOpcode = SubsNode->getOpcode();
8293 if (CondOpcode != AArch64ISD::SUBS)
8296 // There is a SUBS feeding this condition. Is it fed by a mask we can
8299 SDNode *AndNode = SubsNode->getOperand(0).getNode();
8300 unsigned MaskBits = 0;
8302 if (AndNode->getOpcode() != ISD::AND)
8305 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
8306 uint32_t CNV = CN->getZExtValue();
8309 else if (CNV == 65535)
8316 SDValue AddValue = AndNode->getOperand(0);
8318 if (AddValue.getOpcode() != ISD::ADD)
8321 // The basic dag structure is correct, grab the inputs and validate them.
8323 SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
8324 SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
8325 SDValue SubsInputValue = SubsNode->getOperand(1);
8327 // The mask is present and the provenance of all the values is a smaller type,
8328 // lets see if the mask is superfluous.
8330 if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
8331 !isa<ConstantSDNode>(SubsInputValue.getNode()))
8334 ISD::LoadExtType ExtType;
8336 if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
8337 !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
8338 !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
8341 if(!isEquivalentMaskless(CC, MaskBits, ExtType,
8342 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
8343 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
8346 // The AND is not necessary, remove it.
8348 SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
8349 SubsNode->getValueType(1));
8350 SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
8352 SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
8353 DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
8355 return SDValue(N, 0);
8358 // Optimize compare with zero and branch.
8359 static SDValue performBRCONDCombine(SDNode *N,
8360 TargetLowering::DAGCombinerInfo &DCI,
8361 SelectionDAG &DAG) {
8362 SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3);
8365 SDValue Chain = N->getOperand(0);
8366 SDValue Dest = N->getOperand(1);
8367 SDValue CCVal = N->getOperand(2);
8368 SDValue Cmp = N->getOperand(3);
8370 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
8371 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
8372 if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
8375 unsigned CmpOpc = Cmp.getOpcode();
8376 if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
8379 // Only attempt folding if there is only one use of the flag and no use of the
8381 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
8384 SDValue LHS = Cmp.getOperand(0);
8385 SDValue RHS = Cmp.getOperand(1);
8387 assert(LHS.getValueType() == RHS.getValueType() &&
8388 "Expected the value type to be the same for both operands!");
8389 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
8392 if (isa<ConstantSDNode>(LHS) && cast<ConstantSDNode>(LHS)->isNullValue())
8393 std::swap(LHS, RHS);
8395 if (!isa<ConstantSDNode>(RHS) || !cast<ConstantSDNode>(RHS)->isNullValue())
8398 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
8399 LHS.getOpcode() == ISD::SRL)
8402 // Fold the compare into the branch instruction.
8404 if (CC == AArch64CC::EQ)
8405 BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
8407 BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
8409 // Do not add new nodes to DAG combiner worklist.
8410 DCI.CombineTo(N, BR, false);
8415 // vselect (v1i1 setcc) ->
8416 // vselect (v1iXX setcc) (XX is the size of the compared operand type)
8417 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
8418 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
8420 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
8421 SDValue N0 = N->getOperand(0);
8422 EVT CCVT = N0.getValueType();
8424 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
8425 CCVT.getVectorElementType() != MVT::i1)
8428 EVT ResVT = N->getValueType(0);
8429 EVT CmpVT = N0.getOperand(0).getValueType();
8430 // Only combine when the result type is of the same size as the compared
8432 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
8435 SDValue IfTrue = N->getOperand(1);
8436 SDValue IfFalse = N->getOperand(2);
8438 DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
8439 N0.getOperand(0), N0.getOperand(1),
8440 cast<CondCodeSDNode>(N0.getOperand(2))->get());
8441 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
8445 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
8446 /// the compare-mask instructions rather than going via NZCV, even if LHS and
8447 /// RHS are really scalar. This replaces any scalar setcc in the above pattern
8448 /// with a vector one followed by a DUP shuffle on the result.
8449 static SDValue performSelectCombine(SDNode *N, SelectionDAG &DAG) {
8450 SDValue N0 = N->getOperand(0);
8451 EVT ResVT = N->getValueType(0);
8453 if (N0.getOpcode() != ISD::SETCC || N0.getValueType() != MVT::i1)
8456 // If NumMaskElts == 0, the comparison is larger than select result. The
8457 // largest real NEON comparison is 64-bits per lane, which means the result is
8458 // at most 32-bits and an illegal vector. Just bail out for now.
8459 EVT SrcVT = N0.getOperand(0).getValueType();
8461 // Don't try to do this optimization when the setcc itself has i1 operands.
8462 // There are no legal vectors of i1, so this would be pointless.
8463 if (SrcVT == MVT::i1)
8466 int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
8467 if (!ResVT.isVector() || NumMaskElts == 0)
8470 SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
8471 EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
8473 // First perform a vector comparison, where lane 0 is the one we're interested
8477 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
8479 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
8480 SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
8482 // Now duplicate the comparison mask we want across all other lanes.
8483 SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
8484 SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask.data());
8485 Mask = DAG.getNode(ISD::BITCAST, DL,
8486 ResVT.changeVectorElementTypeToInteger(), Mask);
8488 return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
8491 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
8492 DAGCombinerInfo &DCI) const {
8493 SelectionDAG &DAG = DCI.DAG;
8494 switch (N->getOpcode()) {
8499 return performAddSubLongCombine(N, DCI, DAG);
8501 return performXorCombine(N, DAG, DCI, Subtarget);
8503 return performMulCombine(N, DAG, DCI, Subtarget);
8504 case ISD::SINT_TO_FP:
8505 case ISD::UINT_TO_FP:
8506 return performIntToFpCombine(N, DAG, Subtarget);
8508 return performORCombine(N, DCI, Subtarget);
8509 case ISD::INTRINSIC_WO_CHAIN:
8510 return performIntrinsicCombine(N, DCI, Subtarget);
8511 case ISD::ANY_EXTEND:
8512 case ISD::ZERO_EXTEND:
8513 case ISD::SIGN_EXTEND:
8514 return performExtendCombine(N, DCI, DAG);
8516 return performBitcastCombine(N, DCI, DAG);
8517 case ISD::CONCAT_VECTORS:
8518 return performConcatVectorsCombine(N, DCI, DAG);
8520 return performSelectCombine(N, DAG);
8522 return performVSelectCombine(N, DCI.DAG);
8524 return performSTORECombine(N, DCI, DAG, Subtarget);
8525 case AArch64ISD::BRCOND:
8526 return performBRCONDCombine(N, DCI, DAG);
8527 case AArch64ISD::CSEL:
8528 return performCONDCombine(N, DCI, DAG, 2, 3);
8529 case AArch64ISD::DUP:
8530 return performPostLD1Combine(N, DCI, false);
8531 case ISD::INSERT_VECTOR_ELT:
8532 return performPostLD1Combine(N, DCI, true);
8533 case ISD::INTRINSIC_VOID:
8534 case ISD::INTRINSIC_W_CHAIN:
8535 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
8536 case Intrinsic::aarch64_neon_ld2:
8537 case Intrinsic::aarch64_neon_ld3:
8538 case Intrinsic::aarch64_neon_ld4:
8539 case Intrinsic::aarch64_neon_ld1x2:
8540 case Intrinsic::aarch64_neon_ld1x3:
8541 case Intrinsic::aarch64_neon_ld1x4:
8542 case Intrinsic::aarch64_neon_ld2lane:
8543 case Intrinsic::aarch64_neon_ld3lane:
8544 case Intrinsic::aarch64_neon_ld4lane:
8545 case Intrinsic::aarch64_neon_ld2r:
8546 case Intrinsic::aarch64_neon_ld3r:
8547 case Intrinsic::aarch64_neon_ld4r:
8548 case Intrinsic::aarch64_neon_st2:
8549 case Intrinsic::aarch64_neon_st3:
8550 case Intrinsic::aarch64_neon_st4:
8551 case Intrinsic::aarch64_neon_st1x2:
8552 case Intrinsic::aarch64_neon_st1x3:
8553 case Intrinsic::aarch64_neon_st1x4:
8554 case Intrinsic::aarch64_neon_st2lane:
8555 case Intrinsic::aarch64_neon_st3lane:
8556 case Intrinsic::aarch64_neon_st4lane:
8557 return performNEONPostLDSTCombine(N, DCI, DAG);
8565 // Check if the return value is used as only a return value, as otherwise
8566 // we can't perform a tail-call. In particular, we need to check for
8567 // target ISD nodes that are returns and any other "odd" constructs
8568 // that the generic analysis code won't necessarily catch.
8569 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
8570 SDValue &Chain) const {
8571 if (N->getNumValues() != 1)
8573 if (!N->hasNUsesOfValue(1, 0))
8576 SDValue TCChain = Chain;
8577 SDNode *Copy = *N->use_begin();
8578 if (Copy->getOpcode() == ISD::CopyToReg) {
8579 // If the copy has a glue operand, we conservatively assume it isn't safe to
8580 // perform a tail call.
8581 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
8584 TCChain = Copy->getOperand(0);
8585 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
8588 bool HasRet = false;
8589 for (SDNode *Node : Copy->uses()) {
8590 if (Node->getOpcode() != AArch64ISD::RET_FLAG)
8602 // Return whether the an instruction can potentially be optimized to a tail
8603 // call. This will cause the optimizers to attempt to move, or duplicate,
8604 // return instructions to help enable tail call optimizations for this
8606 bool AArch64TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
8607 if (!CI->isTailCall())
8613 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
8615 ISD::MemIndexedMode &AM,
8617 SelectionDAG &DAG) const {
8618 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
8621 Base = Op->getOperand(0);
8622 // All of the indexed addressing mode instructions take a signed
8623 // 9 bit immediate offset.
8624 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
8625 int64_t RHSC = (int64_t)RHS->getZExtValue();
8626 if (RHSC >= 256 || RHSC <= -256)
8628 IsInc = (Op->getOpcode() == ISD::ADD);
8629 Offset = Op->getOperand(1);
8635 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
8637 ISD::MemIndexedMode &AM,
8638 SelectionDAG &DAG) const {
8641 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8642 VT = LD->getMemoryVT();
8643 Ptr = LD->getBasePtr();
8644 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
8645 VT = ST->getMemoryVT();
8646 Ptr = ST->getBasePtr();
8651 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
8653 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
8657 bool AArch64TargetLowering::getPostIndexedAddressParts(
8658 SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
8659 ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
8662 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8663 VT = LD->getMemoryVT();
8664 Ptr = LD->getBasePtr();
8665 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
8666 VT = ST->getMemoryVT();
8667 Ptr = ST->getBasePtr();
8672 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
8674 // Post-indexing updates the base, so it's not a valid transform
8675 // if that's not the same as the load's pointer.
8678 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
8682 static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
8683 SelectionDAG &DAG) {
8685 SDValue Op = N->getOperand(0);
8687 if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
8691 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
8692 DAG.getUNDEF(MVT::i32), Op,
8693 DAG.getTargetConstant(AArch64::hsub, MVT::i32)),
8695 Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
8696 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
8699 void AArch64TargetLowering::ReplaceNodeResults(
8700 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
8701 switch (N->getOpcode()) {
8703 llvm_unreachable("Don't know how to custom expand this");
8705 ReplaceBITCASTResults(N, Results, DAG);
8707 case ISD::FP_TO_UINT:
8708 case ISD::FP_TO_SINT:
8709 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
8710 // Let normal code take care of it by not adding anything to Results.
8715 bool AArch64TargetLowering::useLoadStackGuardNode() const {
8719 bool AArch64TargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
8720 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8721 // reciprocal if there are three or more FDIVs.
8722 return NumUsers > 2;
8725 TargetLoweringBase::LegalizeTypeAction
8726 AArch64TargetLowering::getPreferredVectorAction(EVT VT) const {
8727 MVT SVT = VT.getSimpleVT();
8728 // During type legalization, we prefer to widen v1i8, v1i16, v1i32 to v8i8,
8729 // v4i16, v2i32 instead of to promote.
8730 if (SVT == MVT::v1i8 || SVT == MVT::v1i16 || SVT == MVT::v1i32
8731 || SVT == MVT::v1f32)
8732 return TypeWidenVector;
8734 return TargetLoweringBase::getPreferredVectorAction(VT);
8737 // Loads and stores less than 128-bits are already atomic; ones above that
8738 // are doomed anyway, so defer to the default libcall and blame the OS when
8740 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
8741 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
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::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
8749 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
8753 // For the real atomic operations, we have ldxr/stxr up to 128 bits,
8754 TargetLoweringBase::AtomicRMWExpansionKind
8755 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
8756 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
8757 return Size <= 128 ? AtomicRMWExpansionKind::LLSC
8758 : AtomicRMWExpansionKind::None;
8761 bool AArch64TargetLowering::hasLoadLinkedStoreConditional() const {
8765 Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
8766 AtomicOrdering Ord) const {
8767 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
8768 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
8769 bool IsAcquire = isAtLeastAcquire(Ord);
8771 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
8772 // intrinsic must return {i64, i64} and we have to recombine them into a
8773 // single i128 here.
8774 if (ValTy->getPrimitiveSizeInBits() == 128) {
8776 IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
8777 Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int);
8779 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
8780 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
8782 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
8783 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
8784 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
8785 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
8786 return Builder.CreateOr(
8787 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
8790 Type *Tys[] = { Addr->getType() };
8792 IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
8793 Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int, Tys);
8795 return Builder.CreateTruncOrBitCast(
8796 Builder.CreateCall(Ldxr, Addr),
8797 cast<PointerType>(Addr->getType())->getElementType());
8800 Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
8801 Value *Val, Value *Addr,
8802 AtomicOrdering Ord) const {
8803 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
8804 bool IsRelease = isAtLeastRelease(Ord);
8806 // Since the intrinsics must have legal type, the i128 intrinsics take two
8807 // parameters: "i64, i64". We must marshal Val into the appropriate form
8809 if (Val->getType()->getPrimitiveSizeInBits() == 128) {
8811 IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
8812 Function *Stxr = Intrinsic::getDeclaration(M, Int);
8813 Type *Int64Ty = Type::getInt64Ty(M->getContext());
8815 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
8816 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
8817 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
8818 return Builder.CreateCall3(Stxr, Lo, Hi, Addr);
8822 IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
8823 Type *Tys[] = { Addr->getType() };
8824 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
8826 return Builder.CreateCall2(
8827 Stxr, Builder.CreateZExtOrBitCast(
8828 Val, Stxr->getFunctionType()->getParamType(0)),
8832 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
8833 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
8834 return Ty->isArrayTy();