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 a storage-only type, always promote it to f32.
285 setOperationAction(ISD::SETCC, MVT::f16, Promote);
286 setOperationAction(ISD::BR_CC, MVT::f16, Promote);
287 setOperationAction(ISD::SELECT_CC, MVT::f16, Promote);
288 setOperationAction(ISD::SELECT, MVT::f16, Promote);
289 setOperationAction(ISD::FADD, MVT::f16, Promote);
290 setOperationAction(ISD::FSUB, MVT::f16, Promote);
291 setOperationAction(ISD::FMUL, MVT::f16, Promote);
292 setOperationAction(ISD::FDIV, MVT::f16, Promote);
293 setOperationAction(ISD::FREM, MVT::f16, Promote);
294 setOperationAction(ISD::FMA, MVT::f16, Promote);
295 setOperationAction(ISD::FNEG, MVT::f16, Promote);
296 setOperationAction(ISD::FABS, MVT::f16, Promote);
297 setOperationAction(ISD::FCEIL, MVT::f16, Promote);
298 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote);
299 setOperationAction(ISD::FCOS, MVT::f16, Promote);
300 setOperationAction(ISD::FFLOOR, MVT::f16, Promote);
301 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote);
302 setOperationAction(ISD::FPOW, MVT::f16, Promote);
303 setOperationAction(ISD::FPOWI, MVT::f16, Promote);
304 setOperationAction(ISD::FRINT, MVT::f16, Promote);
305 setOperationAction(ISD::FSIN, MVT::f16, Promote);
306 setOperationAction(ISD::FSINCOS, MVT::f16, Promote);
307 setOperationAction(ISD::FSQRT, MVT::f16, Promote);
308 setOperationAction(ISD::FEXP, MVT::f16, Promote);
309 setOperationAction(ISD::FEXP2, MVT::f16, Promote);
310 setOperationAction(ISD::FLOG, MVT::f16, Promote);
311 setOperationAction(ISD::FLOG2, MVT::f16, Promote);
312 setOperationAction(ISD::FLOG10, MVT::f16, Promote);
313 setOperationAction(ISD::FROUND, MVT::f16, Promote);
314 setOperationAction(ISD::FTRUNC, MVT::f16, Promote);
315 setOperationAction(ISD::FMINNUM, MVT::f16, Promote);
316 setOperationAction(ISD::FMAXNUM, MVT::f16, Promote);
318 // v4f16 is also a storage-only type, so promote it to v4f32 when that is
320 setOperationAction(ISD::FADD, MVT::v4f16, Promote);
321 setOperationAction(ISD::FSUB, MVT::v4f16, Promote);
322 setOperationAction(ISD::FMUL, MVT::v4f16, Promote);
323 setOperationAction(ISD::FDIV, MVT::v4f16, Promote);
324 setOperationAction(ISD::FP_EXTEND, MVT::v4f16, Promote);
325 setOperationAction(ISD::FP_ROUND, MVT::v4f16, Promote);
326 AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32);
327 AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32);
328 AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32);
329 AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32);
330 AddPromotedToType(ISD::FP_EXTEND, MVT::v4f16, MVT::v4f32);
331 AddPromotedToType(ISD::FP_ROUND, MVT::v4f16, MVT::v4f32);
333 // Expand all other v4f16 operations.
334 // FIXME: We could generate better code by promoting some operations to
336 setOperationAction(ISD::FABS, MVT::v4f16, Expand);
337 setOperationAction(ISD::FCEIL, MVT::v4f16, Expand);
338 setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand);
339 setOperationAction(ISD::FCOS, MVT::v4f16, Expand);
340 setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand);
341 setOperationAction(ISD::FMA, MVT::v4f16, Expand);
342 setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand);
343 setOperationAction(ISD::FNEG, MVT::v4f16, Expand);
344 setOperationAction(ISD::FPOW, MVT::v4f16, Expand);
345 setOperationAction(ISD::FPOWI, MVT::v4f16, Expand);
346 setOperationAction(ISD::FREM, MVT::v4f16, Expand);
347 setOperationAction(ISD::FROUND, MVT::v4f16, Expand);
348 setOperationAction(ISD::FRINT, MVT::v4f16, Expand);
349 setOperationAction(ISD::FSIN, MVT::v4f16, Expand);
350 setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand);
351 setOperationAction(ISD::FSQRT, MVT::v4f16, Expand);
352 setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand);
353 setOperationAction(ISD::SETCC, MVT::v4f16, Expand);
354 setOperationAction(ISD::BR_CC, MVT::v4f16, Expand);
355 setOperationAction(ISD::SELECT, MVT::v4f16, Expand);
356 setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand);
357 setOperationAction(ISD::FEXP, MVT::v4f16, Expand);
358 setOperationAction(ISD::FEXP2, MVT::v4f16, Expand);
359 setOperationAction(ISD::FLOG, MVT::v4f16, Expand);
360 setOperationAction(ISD::FLOG2, MVT::v4f16, Expand);
361 setOperationAction(ISD::FLOG10, MVT::v4f16, Expand);
364 // v8f16 is also a storage-only type, so expand it.
365 setOperationAction(ISD::FABS, MVT::v8f16, Expand);
366 setOperationAction(ISD::FADD, MVT::v8f16, Expand);
367 setOperationAction(ISD::FCEIL, MVT::v8f16, Expand);
368 setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand);
369 setOperationAction(ISD::FCOS, MVT::v8f16, Expand);
370 setOperationAction(ISD::FDIV, MVT::v8f16, Expand);
371 setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand);
372 setOperationAction(ISD::FMA, MVT::v8f16, Expand);
373 setOperationAction(ISD::FMUL, MVT::v8f16, Expand);
374 setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand);
375 setOperationAction(ISD::FNEG, MVT::v8f16, Expand);
376 setOperationAction(ISD::FPOW, MVT::v8f16, Expand);
377 setOperationAction(ISD::FPOWI, MVT::v8f16, Expand);
378 setOperationAction(ISD::FREM, MVT::v8f16, Expand);
379 setOperationAction(ISD::FROUND, MVT::v8f16, Expand);
380 setOperationAction(ISD::FRINT, MVT::v8f16, Expand);
381 setOperationAction(ISD::FSIN, MVT::v8f16, Expand);
382 setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
383 setOperationAction(ISD::FSQRT, MVT::v8f16, Expand);
384 setOperationAction(ISD::FSUB, MVT::v8f16, Expand);
385 setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand);
386 setOperationAction(ISD::SETCC, MVT::v8f16, Expand);
387 setOperationAction(ISD::BR_CC, MVT::v8f16, Expand);
388 setOperationAction(ISD::SELECT, MVT::v8f16, Expand);
389 setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand);
390 setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand);
391 setOperationAction(ISD::FEXP, MVT::v8f16, Expand);
392 setOperationAction(ISD::FEXP2, MVT::v8f16, Expand);
393 setOperationAction(ISD::FLOG, MVT::v8f16, Expand);
394 setOperationAction(ISD::FLOG2, MVT::v8f16, Expand);
395 setOperationAction(ISD::FLOG10, MVT::v8f16, Expand);
397 // AArch64 has implementations of a lot of rounding-like FP operations.
398 for (MVT Ty : {MVT::f32, MVT::f64}) {
399 setOperationAction(ISD::FFLOOR, Ty, Legal);
400 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
401 setOperationAction(ISD::FCEIL, Ty, Legal);
402 setOperationAction(ISD::FRINT, Ty, Legal);
403 setOperationAction(ISD::FTRUNC, Ty, Legal);
404 setOperationAction(ISD::FROUND, Ty, Legal);
407 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
409 if (Subtarget->isTargetMachO()) {
410 // For iOS, we don't want to the normal expansion of a libcall to
411 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
413 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
414 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
416 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
417 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
420 // Make floating-point constants legal for the large code model, so they don't
421 // become loads from the constant pool.
422 if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
423 setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
424 setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
427 // AArch64 does not have floating-point extending loads, i1 sign-extending
428 // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
429 for (MVT VT : MVT::fp_valuetypes()) {
430 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
431 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
432 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
433 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
435 for (MVT VT : MVT::integer_valuetypes())
436 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
438 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
439 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
440 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
441 setTruncStoreAction(MVT::f128, MVT::f80, Expand);
442 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
443 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
444 setTruncStoreAction(MVT::f128, MVT::f16, Expand);
446 setOperationAction(ISD::BITCAST, MVT::i16, Custom);
447 setOperationAction(ISD::BITCAST, MVT::f16, Custom);
449 // Indexed loads and stores are supported.
450 for (unsigned im = (unsigned)ISD::PRE_INC;
451 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
452 setIndexedLoadAction(im, MVT::i8, Legal);
453 setIndexedLoadAction(im, MVT::i16, Legal);
454 setIndexedLoadAction(im, MVT::i32, Legal);
455 setIndexedLoadAction(im, MVT::i64, Legal);
456 setIndexedLoadAction(im, MVT::f64, Legal);
457 setIndexedLoadAction(im, MVT::f32, Legal);
458 setIndexedStoreAction(im, MVT::i8, Legal);
459 setIndexedStoreAction(im, MVT::i16, Legal);
460 setIndexedStoreAction(im, MVT::i32, Legal);
461 setIndexedStoreAction(im, MVT::i64, Legal);
462 setIndexedStoreAction(im, MVT::f64, Legal);
463 setIndexedStoreAction(im, MVT::f32, Legal);
467 setOperationAction(ISD::TRAP, MVT::Other, Legal);
469 // We combine OR nodes for bitfield operations.
470 setTargetDAGCombine(ISD::OR);
472 // Vector add and sub nodes may conceal a high-half opportunity.
473 // Also, try to fold ADD into CSINC/CSINV..
474 setTargetDAGCombine(ISD::ADD);
475 setTargetDAGCombine(ISD::SUB);
477 setTargetDAGCombine(ISD::XOR);
478 setTargetDAGCombine(ISD::SINT_TO_FP);
479 setTargetDAGCombine(ISD::UINT_TO_FP);
481 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
483 setTargetDAGCombine(ISD::ANY_EXTEND);
484 setTargetDAGCombine(ISD::ZERO_EXTEND);
485 setTargetDAGCombine(ISD::SIGN_EXTEND);
486 setTargetDAGCombine(ISD::BITCAST);
487 setTargetDAGCombine(ISD::CONCAT_VECTORS);
488 setTargetDAGCombine(ISD::STORE);
490 setTargetDAGCombine(ISD::MUL);
492 setTargetDAGCombine(ISD::SELECT);
493 setTargetDAGCombine(ISD::VSELECT);
495 setTargetDAGCombine(ISD::INTRINSIC_VOID);
496 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
497 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
499 MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 8;
500 MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 4;
501 MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = 4;
503 setStackPointerRegisterToSaveRestore(AArch64::SP);
505 setSchedulingPreference(Sched::Hybrid);
508 MaskAndBranchFoldingIsLegal = true;
509 EnableExtLdPromotion = true;
511 setMinFunctionAlignment(2);
513 RequireStrictAlign = (Align == StrictAlign);
515 setHasExtractBitsInsn(true);
517 if (Subtarget->hasNEON()) {
518 // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
519 // silliness like this:
520 setOperationAction(ISD::FABS, MVT::v1f64, Expand);
521 setOperationAction(ISD::FADD, MVT::v1f64, Expand);
522 setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
523 setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
524 setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
525 setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
526 setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
527 setOperationAction(ISD::FMA, MVT::v1f64, Expand);
528 setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
529 setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
530 setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
531 setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
532 setOperationAction(ISD::FREM, MVT::v1f64, Expand);
533 setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
534 setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
535 setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
536 setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
537 setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
538 setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
539 setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
540 setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
541 setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
542 setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
543 setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
544 setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
546 setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
547 setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
548 setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
549 setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
550 setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
552 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
554 // AArch64 doesn't have a direct vector ->f32 conversion instructions for
555 // elements smaller than i32, so promote the input to i32 first.
556 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Promote);
557 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Promote);
558 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Promote);
559 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Promote);
560 // i8 and i16 vector elements also need promotion to i32 for v8i8 or v8i16
561 // -> v8f16 conversions.
562 setOperationAction(ISD::SINT_TO_FP, MVT::v8i8, Promote);
563 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Promote);
564 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
565 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Promote);
566 // Similarly, there is no direct i32 -> f64 vector conversion instruction.
567 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
568 setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
569 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
570 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
571 // Or, direct i32 -> f16 vector conversion. Set it so custom, so the
572 // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
573 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
574 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
576 // AArch64 doesn't have MUL.2d:
577 setOperationAction(ISD::MUL, MVT::v2i64, Expand);
578 // Custom handling for some quad-vector types to detect MULL.
579 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
580 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
581 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
583 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
584 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
585 // Likewise, narrowing and extending vector loads/stores aren't handled
587 for (MVT VT : MVT::vector_valuetypes()) {
588 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
590 setOperationAction(ISD::MULHS, VT, Expand);
591 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
592 setOperationAction(ISD::MULHU, VT, Expand);
593 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
595 setOperationAction(ISD::BSWAP, VT, Expand);
597 for (MVT InnerVT : MVT::vector_valuetypes()) {
598 setTruncStoreAction(VT, InnerVT, Expand);
599 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
600 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
601 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
605 // AArch64 has implementations of a lot of rounding-like FP operations.
606 for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
607 setOperationAction(ISD::FFLOOR, Ty, Legal);
608 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
609 setOperationAction(ISD::FCEIL, Ty, Legal);
610 setOperationAction(ISD::FRINT, Ty, Legal);
611 setOperationAction(ISD::FTRUNC, Ty, Legal);
612 setOperationAction(ISD::FROUND, Ty, Legal);
616 // Prefer likely predicted branches to selects on out-of-order cores.
617 if (Subtarget->isCortexA57())
618 PredictableSelectIsExpensive = true;
621 void AArch64TargetLowering::addTypeForNEON(EVT VT, EVT PromotedBitwiseVT) {
622 if (VT == MVT::v2f32 || VT == MVT::v4f16) {
623 setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
624 AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i32);
626 setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
627 AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i32);
628 } else if (VT == MVT::v2f64 || VT == MVT::v4f32 || VT == MVT::v8f16) {
629 setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
630 AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i64);
632 setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
633 AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i64);
636 // Mark vector float intrinsics as expand.
637 if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
638 setOperationAction(ISD::FSIN, VT.getSimpleVT(), Expand);
639 setOperationAction(ISD::FCOS, VT.getSimpleVT(), Expand);
640 setOperationAction(ISD::FPOWI, VT.getSimpleVT(), Expand);
641 setOperationAction(ISD::FPOW, VT.getSimpleVT(), Expand);
642 setOperationAction(ISD::FLOG, VT.getSimpleVT(), Expand);
643 setOperationAction(ISD::FLOG2, VT.getSimpleVT(), Expand);
644 setOperationAction(ISD::FLOG10, VT.getSimpleVT(), Expand);
645 setOperationAction(ISD::FEXP, VT.getSimpleVT(), Expand);
646 setOperationAction(ISD::FEXP2, VT.getSimpleVT(), Expand);
649 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT.getSimpleVT(), Custom);
650 setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getSimpleVT(), Custom);
651 setOperationAction(ISD::BUILD_VECTOR, VT.getSimpleVT(), Custom);
652 setOperationAction(ISD::VECTOR_SHUFFLE, VT.getSimpleVT(), Custom);
653 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT.getSimpleVT(), Custom);
654 setOperationAction(ISD::SRA, VT.getSimpleVT(), Custom);
655 setOperationAction(ISD::SRL, VT.getSimpleVT(), Custom);
656 setOperationAction(ISD::SHL, VT.getSimpleVT(), Custom);
657 setOperationAction(ISD::AND, VT.getSimpleVT(), Custom);
658 setOperationAction(ISD::OR, VT.getSimpleVT(), Custom);
659 setOperationAction(ISD::SETCC, VT.getSimpleVT(), Custom);
660 setOperationAction(ISD::CONCAT_VECTORS, VT.getSimpleVT(), Legal);
662 setOperationAction(ISD::SELECT, VT.getSimpleVT(), Expand);
663 setOperationAction(ISD::SELECT_CC, VT.getSimpleVT(), Expand);
664 setOperationAction(ISD::VSELECT, VT.getSimpleVT(), Expand);
665 for (MVT InnerVT : MVT::all_valuetypes())
666 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT.getSimpleVT(), Expand);
668 // CNT supports only B element sizes.
669 if (VT != MVT::v8i8 && VT != MVT::v16i8)
670 setOperationAction(ISD::CTPOP, VT.getSimpleVT(), Expand);
672 setOperationAction(ISD::UDIV, VT.getSimpleVT(), Expand);
673 setOperationAction(ISD::SDIV, VT.getSimpleVT(), Expand);
674 setOperationAction(ISD::UREM, VT.getSimpleVT(), Expand);
675 setOperationAction(ISD::SREM, VT.getSimpleVT(), Expand);
676 setOperationAction(ISD::FREM, VT.getSimpleVT(), Expand);
678 setOperationAction(ISD::FP_TO_SINT, VT.getSimpleVT(), Custom);
679 setOperationAction(ISD::FP_TO_UINT, VT.getSimpleVT(), Custom);
681 if (Subtarget->isLittleEndian()) {
682 for (unsigned im = (unsigned)ISD::PRE_INC;
683 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
684 setIndexedLoadAction(im, VT.getSimpleVT(), Legal);
685 setIndexedStoreAction(im, VT.getSimpleVT(), Legal);
690 void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
691 addRegisterClass(VT, &AArch64::FPR64RegClass);
692 addTypeForNEON(VT, MVT::v2i32);
695 void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
696 addRegisterClass(VT, &AArch64::FPR128RegClass);
697 addTypeForNEON(VT, MVT::v4i32);
700 EVT AArch64TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
703 return VT.changeVectorElementTypeToInteger();
706 /// computeKnownBitsForTargetNode - Determine which of the bits specified in
707 /// Mask are known to be either zero or one and return them in the
708 /// KnownZero/KnownOne bitsets.
709 void AArch64TargetLowering::computeKnownBitsForTargetNode(
710 const SDValue Op, APInt &KnownZero, APInt &KnownOne,
711 const SelectionDAG &DAG, unsigned Depth) const {
712 switch (Op.getOpcode()) {
715 case AArch64ISD::CSEL: {
716 APInt KnownZero2, KnownOne2;
717 DAG.computeKnownBits(Op->getOperand(0), KnownZero, KnownOne, Depth + 1);
718 DAG.computeKnownBits(Op->getOperand(1), KnownZero2, KnownOne2, Depth + 1);
719 KnownZero &= KnownZero2;
720 KnownOne &= KnownOne2;
723 case ISD::INTRINSIC_W_CHAIN: {
724 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
725 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
728 case Intrinsic::aarch64_ldaxr:
729 case Intrinsic::aarch64_ldxr: {
730 unsigned BitWidth = KnownOne.getBitWidth();
731 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
732 unsigned MemBits = VT.getScalarType().getSizeInBits();
733 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
739 case ISD::INTRINSIC_WO_CHAIN:
740 case ISD::INTRINSIC_VOID: {
741 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
745 case Intrinsic::aarch64_neon_umaxv:
746 case Intrinsic::aarch64_neon_uminv: {
747 // Figure out the datatype of the vector operand. The UMINV instruction
748 // will zero extend the result, so we can mark as known zero all the
749 // bits larger than the element datatype. 32-bit or larget doesn't need
750 // this as those are legal types and will be handled by isel directly.
751 MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
752 unsigned BitWidth = KnownZero.getBitWidth();
753 if (VT == MVT::v8i8 || VT == MVT::v16i8) {
754 assert(BitWidth >= 8 && "Unexpected width!");
755 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
757 } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
758 assert(BitWidth >= 16 && "Unexpected width!");
759 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
769 MVT AArch64TargetLowering::getScalarShiftAmountTy(EVT LHSTy) const {
774 AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
775 const TargetLibraryInfo *libInfo) const {
776 return AArch64::createFastISel(funcInfo, libInfo);
779 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
780 switch ((AArch64ISD::NodeType)Opcode) {
781 case AArch64ISD::FIRST_NUMBER: break;
782 case AArch64ISD::CALL: return "AArch64ISD::CALL";
783 case AArch64ISD::ADRP: return "AArch64ISD::ADRP";
784 case AArch64ISD::ADDlow: return "AArch64ISD::ADDlow";
785 case AArch64ISD::LOADgot: return "AArch64ISD::LOADgot";
786 case AArch64ISD::RET_FLAG: return "AArch64ISD::RET_FLAG";
787 case AArch64ISD::BRCOND: return "AArch64ISD::BRCOND";
788 case AArch64ISD::CSEL: return "AArch64ISD::CSEL";
789 case AArch64ISD::FCSEL: return "AArch64ISD::FCSEL";
790 case AArch64ISD::CSINV: return "AArch64ISD::CSINV";
791 case AArch64ISD::CSNEG: return "AArch64ISD::CSNEG";
792 case AArch64ISD::CSINC: return "AArch64ISD::CSINC";
793 case AArch64ISD::THREAD_POINTER: return "AArch64ISD::THREAD_POINTER";
794 case AArch64ISD::TLSDESC_CALLSEQ: return "AArch64ISD::TLSDESC_CALLSEQ";
795 case AArch64ISD::ADC: return "AArch64ISD::ADC";
796 case AArch64ISD::SBC: return "AArch64ISD::SBC";
797 case AArch64ISD::ADDS: return "AArch64ISD::ADDS";
798 case AArch64ISD::SUBS: return "AArch64ISD::SUBS";
799 case AArch64ISD::ADCS: return "AArch64ISD::ADCS";
800 case AArch64ISD::SBCS: return "AArch64ISD::SBCS";
801 case AArch64ISD::ANDS: return "AArch64ISD::ANDS";
802 case AArch64ISD::FCMP: return "AArch64ISD::FCMP";
803 case AArch64ISD::FMIN: return "AArch64ISD::FMIN";
804 case AArch64ISD::FMAX: return "AArch64ISD::FMAX";
805 case AArch64ISD::DUP: return "AArch64ISD::DUP";
806 case AArch64ISD::DUPLANE8: return "AArch64ISD::DUPLANE8";
807 case AArch64ISD::DUPLANE16: return "AArch64ISD::DUPLANE16";
808 case AArch64ISD::DUPLANE32: return "AArch64ISD::DUPLANE32";
809 case AArch64ISD::DUPLANE64: return "AArch64ISD::DUPLANE64";
810 case AArch64ISD::MOVI: return "AArch64ISD::MOVI";
811 case AArch64ISD::MOVIshift: return "AArch64ISD::MOVIshift";
812 case AArch64ISD::MOVIedit: return "AArch64ISD::MOVIedit";
813 case AArch64ISD::MOVImsl: return "AArch64ISD::MOVImsl";
814 case AArch64ISD::FMOV: return "AArch64ISD::FMOV";
815 case AArch64ISD::MVNIshift: return "AArch64ISD::MVNIshift";
816 case AArch64ISD::MVNImsl: return "AArch64ISD::MVNImsl";
817 case AArch64ISD::BICi: return "AArch64ISD::BICi";
818 case AArch64ISD::ORRi: return "AArch64ISD::ORRi";
819 case AArch64ISD::BSL: return "AArch64ISD::BSL";
820 case AArch64ISD::NEG: return "AArch64ISD::NEG";
821 case AArch64ISD::EXTR: return "AArch64ISD::EXTR";
822 case AArch64ISD::ZIP1: return "AArch64ISD::ZIP1";
823 case AArch64ISD::ZIP2: return "AArch64ISD::ZIP2";
824 case AArch64ISD::UZP1: return "AArch64ISD::UZP1";
825 case AArch64ISD::UZP2: return "AArch64ISD::UZP2";
826 case AArch64ISD::TRN1: return "AArch64ISD::TRN1";
827 case AArch64ISD::TRN2: return "AArch64ISD::TRN2";
828 case AArch64ISD::REV16: return "AArch64ISD::REV16";
829 case AArch64ISD::REV32: return "AArch64ISD::REV32";
830 case AArch64ISD::REV64: return "AArch64ISD::REV64";
831 case AArch64ISD::EXT: return "AArch64ISD::EXT";
832 case AArch64ISD::VSHL: return "AArch64ISD::VSHL";
833 case AArch64ISD::VLSHR: return "AArch64ISD::VLSHR";
834 case AArch64ISD::VASHR: return "AArch64ISD::VASHR";
835 case AArch64ISD::CMEQ: return "AArch64ISD::CMEQ";
836 case AArch64ISD::CMGE: return "AArch64ISD::CMGE";
837 case AArch64ISD::CMGT: return "AArch64ISD::CMGT";
838 case AArch64ISD::CMHI: return "AArch64ISD::CMHI";
839 case AArch64ISD::CMHS: return "AArch64ISD::CMHS";
840 case AArch64ISD::FCMEQ: return "AArch64ISD::FCMEQ";
841 case AArch64ISD::FCMGE: return "AArch64ISD::FCMGE";
842 case AArch64ISD::FCMGT: return "AArch64ISD::FCMGT";
843 case AArch64ISD::CMEQz: return "AArch64ISD::CMEQz";
844 case AArch64ISD::CMGEz: return "AArch64ISD::CMGEz";
845 case AArch64ISD::CMGTz: return "AArch64ISD::CMGTz";
846 case AArch64ISD::CMLEz: return "AArch64ISD::CMLEz";
847 case AArch64ISD::CMLTz: return "AArch64ISD::CMLTz";
848 case AArch64ISD::FCMEQz: return "AArch64ISD::FCMEQz";
849 case AArch64ISD::FCMGEz: return "AArch64ISD::FCMGEz";
850 case AArch64ISD::FCMGTz: return "AArch64ISD::FCMGTz";
851 case AArch64ISD::FCMLEz: return "AArch64ISD::FCMLEz";
852 case AArch64ISD::FCMLTz: return "AArch64ISD::FCMLTz";
853 case AArch64ISD::SADDV: return "AArch64ISD::SADDV";
854 case AArch64ISD::UADDV: return "AArch64ISD::UADDV";
855 case AArch64ISD::SMINV: return "AArch64ISD::SMINV";
856 case AArch64ISD::UMINV: return "AArch64ISD::UMINV";
857 case AArch64ISD::SMAXV: return "AArch64ISD::SMAXV";
858 case AArch64ISD::UMAXV: return "AArch64ISD::UMAXV";
859 case AArch64ISD::NOT: return "AArch64ISD::NOT";
860 case AArch64ISD::BIT: return "AArch64ISD::BIT";
861 case AArch64ISD::CBZ: return "AArch64ISD::CBZ";
862 case AArch64ISD::CBNZ: return "AArch64ISD::CBNZ";
863 case AArch64ISD::TBZ: return "AArch64ISD::TBZ";
864 case AArch64ISD::TBNZ: return "AArch64ISD::TBNZ";
865 case AArch64ISD::TC_RETURN: return "AArch64ISD::TC_RETURN";
866 case AArch64ISD::PREFETCH: return "AArch64ISD::PREFETCH";
867 case AArch64ISD::SITOF: return "AArch64ISD::SITOF";
868 case AArch64ISD::UITOF: return "AArch64ISD::UITOF";
869 case AArch64ISD::NVCAST: return "AArch64ISD::NVCAST";
870 case AArch64ISD::SQSHL_I: return "AArch64ISD::SQSHL_I";
871 case AArch64ISD::UQSHL_I: return "AArch64ISD::UQSHL_I";
872 case AArch64ISD::SRSHR_I: return "AArch64ISD::SRSHR_I";
873 case AArch64ISD::URSHR_I: return "AArch64ISD::URSHR_I";
874 case AArch64ISD::SQSHLU_I: return "AArch64ISD::SQSHLU_I";
875 case AArch64ISD::WrapperLarge: return "AArch64ISD::WrapperLarge";
876 case AArch64ISD::LD2post: return "AArch64ISD::LD2post";
877 case AArch64ISD::LD3post: return "AArch64ISD::LD3post";
878 case AArch64ISD::LD4post: return "AArch64ISD::LD4post";
879 case AArch64ISD::ST2post: return "AArch64ISD::ST2post";
880 case AArch64ISD::ST3post: return "AArch64ISD::ST3post";
881 case AArch64ISD::ST4post: return "AArch64ISD::ST4post";
882 case AArch64ISD::LD1x2post: return "AArch64ISD::LD1x2post";
883 case AArch64ISD::LD1x3post: return "AArch64ISD::LD1x3post";
884 case AArch64ISD::LD1x4post: return "AArch64ISD::LD1x4post";
885 case AArch64ISD::ST1x2post: return "AArch64ISD::ST1x2post";
886 case AArch64ISD::ST1x3post: return "AArch64ISD::ST1x3post";
887 case AArch64ISD::ST1x4post: return "AArch64ISD::ST1x4post";
888 case AArch64ISD::LD1DUPpost: return "AArch64ISD::LD1DUPpost";
889 case AArch64ISD::LD2DUPpost: return "AArch64ISD::LD2DUPpost";
890 case AArch64ISD::LD3DUPpost: return "AArch64ISD::LD3DUPpost";
891 case AArch64ISD::LD4DUPpost: return "AArch64ISD::LD4DUPpost";
892 case AArch64ISD::LD1LANEpost: return "AArch64ISD::LD1LANEpost";
893 case AArch64ISD::LD2LANEpost: return "AArch64ISD::LD2LANEpost";
894 case AArch64ISD::LD3LANEpost: return "AArch64ISD::LD3LANEpost";
895 case AArch64ISD::LD4LANEpost: return "AArch64ISD::LD4LANEpost";
896 case AArch64ISD::ST2LANEpost: return "AArch64ISD::ST2LANEpost";
897 case AArch64ISD::ST3LANEpost: return "AArch64ISD::ST3LANEpost";
898 case AArch64ISD::ST4LANEpost: return "AArch64ISD::ST4LANEpost";
899 case AArch64ISD::SMULL: return "AArch64ISD::SMULL";
900 case AArch64ISD::UMULL: return "AArch64ISD::UMULL";
906 AArch64TargetLowering::EmitF128CSEL(MachineInstr *MI,
907 MachineBasicBlock *MBB) const {
908 // We materialise the F128CSEL pseudo-instruction as some control flow and a
912 // [... previous instrs leading to comparison ...]
918 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
920 MachineFunction *MF = MBB->getParent();
921 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
922 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
923 DebugLoc DL = MI->getDebugLoc();
924 MachineFunction::iterator It = MBB;
927 unsigned DestReg = MI->getOperand(0).getReg();
928 unsigned IfTrueReg = MI->getOperand(1).getReg();
929 unsigned IfFalseReg = MI->getOperand(2).getReg();
930 unsigned CondCode = MI->getOperand(3).getImm();
931 bool NZCVKilled = MI->getOperand(4).isKill();
933 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
934 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
935 MF->insert(It, TrueBB);
936 MF->insert(It, EndBB);
938 // Transfer rest of current basic-block to EndBB
939 EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
941 EndBB->transferSuccessorsAndUpdatePHIs(MBB);
943 BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
944 BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
945 MBB->addSuccessor(TrueBB);
946 MBB->addSuccessor(EndBB);
948 // TrueBB falls through to the end.
949 TrueBB->addSuccessor(EndBB);
952 TrueBB->addLiveIn(AArch64::NZCV);
953 EndBB->addLiveIn(AArch64::NZCV);
956 BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
962 MI->eraseFromParent();
967 AArch64TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
968 MachineBasicBlock *BB) const {
969 switch (MI->getOpcode()) {
974 llvm_unreachable("Unexpected instruction for custom inserter!");
976 case AArch64::F128CSEL:
977 return EmitF128CSEL(MI, BB);
979 case TargetOpcode::STACKMAP:
980 case TargetOpcode::PATCHPOINT:
981 return emitPatchPoint(MI, BB);
985 //===----------------------------------------------------------------------===//
986 // AArch64 Lowering private implementation.
987 //===----------------------------------------------------------------------===//
989 //===----------------------------------------------------------------------===//
991 //===----------------------------------------------------------------------===//
993 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
995 static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
998 llvm_unreachable("Unknown condition code!");
1000 return AArch64CC::NE;
1002 return AArch64CC::EQ;
1004 return AArch64CC::GT;
1006 return AArch64CC::GE;
1008 return AArch64CC::LT;
1010 return AArch64CC::LE;
1012 return AArch64CC::HI;
1014 return AArch64CC::HS;
1016 return AArch64CC::LO;
1018 return AArch64CC::LS;
1022 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1023 static void changeFPCCToAArch64CC(ISD::CondCode CC,
1024 AArch64CC::CondCode &CondCode,
1025 AArch64CC::CondCode &CondCode2) {
1026 CondCode2 = AArch64CC::AL;
1029 llvm_unreachable("Unknown FP condition!");
1032 CondCode = AArch64CC::EQ;
1036 CondCode = AArch64CC::GT;
1040 CondCode = AArch64CC::GE;
1043 CondCode = AArch64CC::MI;
1046 CondCode = AArch64CC::LS;
1049 CondCode = AArch64CC::MI;
1050 CondCode2 = AArch64CC::GT;
1053 CondCode = AArch64CC::VC;
1056 CondCode = AArch64CC::VS;
1059 CondCode = AArch64CC::EQ;
1060 CondCode2 = AArch64CC::VS;
1063 CondCode = AArch64CC::HI;
1066 CondCode = AArch64CC::PL;
1070 CondCode = AArch64CC::LT;
1074 CondCode = AArch64CC::LE;
1078 CondCode = AArch64CC::NE;
1083 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1084 /// CC usable with the vector instructions. Fewer operations are available
1085 /// without a real NZCV register, so we have to use less efficient combinations
1086 /// to get the same effect.
1087 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1088 AArch64CC::CondCode &CondCode,
1089 AArch64CC::CondCode &CondCode2,
1094 // Mostly the scalar mappings work fine.
1095 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1098 Invert = true; // Fallthrough
1100 CondCode = AArch64CC::MI;
1101 CondCode2 = AArch64CC::GE;
1108 // All of the compare-mask comparisons are ordered, but we can switch
1109 // between the two by a double inversion. E.g. ULE == !OGT.
1111 changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1116 static bool isLegalArithImmed(uint64_t C) {
1117 // Matches AArch64DAGToDAGISel::SelectArithImmed().
1118 return (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1121 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1122 SDLoc dl, SelectionDAG &DAG) {
1123 EVT VT = LHS.getValueType();
1125 if (VT.isFloatingPoint())
1126 return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
1128 // The CMP instruction is just an alias for SUBS, and representing it as
1129 // SUBS means that it's possible to get CSE with subtract operations.
1130 // A later phase can perform the optimization of setting the destination
1131 // register to WZR/XZR if it ends up being unused.
1132 unsigned Opcode = AArch64ISD::SUBS;
1134 if (RHS.getOpcode() == ISD::SUB && isa<ConstantSDNode>(RHS.getOperand(0)) &&
1135 cast<ConstantSDNode>(RHS.getOperand(0))->getZExtValue() == 0 &&
1136 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1137 // We'd like to combine a (CMP op1, (sub 0, op2) into a CMN instruction on
1138 // the grounds that "op1 - (-op2) == op1 + op2". However, the C and V flags
1139 // can be set differently by this operation. It comes down to whether
1140 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1141 // everything is fine. If not then the optimization is wrong. Thus general
1142 // comparisons are only valid if op2 != 0.
1144 // So, finally, the only LLVM-native comparisons that don't mention C and V
1145 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1146 // the absence of information about op2.
1147 Opcode = AArch64ISD::ADDS;
1148 RHS = RHS.getOperand(1);
1149 } else if (LHS.getOpcode() == ISD::AND && isa<ConstantSDNode>(RHS) &&
1150 cast<ConstantSDNode>(RHS)->getZExtValue() == 0 &&
1151 !isUnsignedIntSetCC(CC)) {
1152 // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1153 // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1154 // of the signed comparisons.
1155 Opcode = AArch64ISD::ANDS;
1156 RHS = LHS.getOperand(1);
1157 LHS = LHS.getOperand(0);
1160 return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS)
1164 static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1165 SDValue &AArch64cc, SelectionDAG &DAG, SDLoc dl) {
1167 AArch64CC::CondCode AArch64CC;
1168 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1169 EVT VT = RHS.getValueType();
1170 uint64_t C = RHSC->getZExtValue();
1171 if (!isLegalArithImmed(C)) {
1172 // Constant does not fit, try adjusting it by one?
1178 if ((VT == MVT::i32 && C != 0x80000000 &&
1179 isLegalArithImmed((uint32_t)(C - 1))) ||
1180 (VT == MVT::i64 && C != 0x80000000ULL &&
1181 isLegalArithImmed(C - 1ULL))) {
1182 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1183 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1184 RHS = DAG.getConstant(C, dl, VT);
1189 if ((VT == MVT::i32 && C != 0 &&
1190 isLegalArithImmed((uint32_t)(C - 1))) ||
1191 (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1192 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1193 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1194 RHS = DAG.getConstant(C, dl, VT);
1199 if ((VT == MVT::i32 && C != INT32_MAX &&
1200 isLegalArithImmed((uint32_t)(C + 1))) ||
1201 (VT == MVT::i64 && C != INT64_MAX &&
1202 isLegalArithImmed(C + 1ULL))) {
1203 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1204 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1205 RHS = DAG.getConstant(C, dl, VT);
1210 if ((VT == MVT::i32 && C != UINT32_MAX &&
1211 isLegalArithImmed((uint32_t)(C + 1))) ||
1212 (VT == MVT::i64 && C != UINT64_MAX &&
1213 isLegalArithImmed(C + 1ULL))) {
1214 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1215 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1216 RHS = DAG.getConstant(C, dl, VT);
1222 // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
1223 // For the i8 operand, the largest immediate is 255, so this can be easily
1224 // encoded in the compare instruction. For the i16 operand, however, the
1225 // largest immediate cannot be encoded in the compare.
1226 // Therefore, use a sign extending load and cmn to avoid materializing the -1
1227 // constant. For example,
1229 // ldrh w0, [x0, #0]
1232 // ldrsh w0, [x0, #0]
1234 // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
1235 // if and only if (sext LHS) == (sext RHS). The checks are in place to ensure
1236 // both the LHS and RHS are truely zero extended and to make sure the
1237 // transformation is profitable.
1238 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
1239 if ((cast<ConstantSDNode>(RHS)->getZExtValue() >> 16 == 0) &&
1240 isa<LoadSDNode>(LHS)) {
1241 if (cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
1242 cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
1243 LHS.getNode()->hasNUsesOfValue(1, 0)) {
1244 int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
1245 if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
1247 DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
1248 DAG.getValueType(MVT::i16));
1249 Cmp = emitComparison(SExt,
1250 DAG.getConstant(ValueofRHS, dl,
1251 RHS.getValueType()),
1253 AArch64CC = changeIntCCToAArch64CC(CC);
1254 AArch64cc = DAG.getConstant(AArch64CC, dl, MVT::i32);
1260 Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
1261 AArch64CC = changeIntCCToAArch64CC(CC);
1262 AArch64cc = DAG.getConstant(AArch64CC, dl, MVT::i32);
1266 static std::pair<SDValue, SDValue>
1267 getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
1268 assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
1269 "Unsupported value type");
1270 SDValue Value, Overflow;
1272 SDValue LHS = Op.getOperand(0);
1273 SDValue RHS = Op.getOperand(1);
1275 switch (Op.getOpcode()) {
1277 llvm_unreachable("Unknown overflow instruction!");
1279 Opc = AArch64ISD::ADDS;
1283 Opc = AArch64ISD::ADDS;
1287 Opc = AArch64ISD::SUBS;
1291 Opc = AArch64ISD::SUBS;
1294 // Multiply needs a little bit extra work.
1298 bool IsSigned = Op.getOpcode() == ISD::SMULO;
1299 if (Op.getValueType() == MVT::i32) {
1300 unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1301 // For a 32 bit multiply with overflow check we want the instruction
1302 // selector to generate a widening multiply (SMADDL/UMADDL). For that we
1303 // need to generate the following pattern:
1304 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
1305 LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
1306 RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
1307 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1308 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
1309 DAG.getConstant(0, DL, MVT::i64));
1310 // On AArch64 the upper 32 bits are always zero extended for a 32 bit
1311 // operation. We need to clear out the upper 32 bits, because we used a
1312 // widening multiply that wrote all 64 bits. In the end this should be a
1314 Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
1316 // The signed overflow check requires more than just a simple check for
1317 // any bit set in the upper 32 bits of the result. These bits could be
1318 // just the sign bits of a negative number. To perform the overflow
1319 // check we have to arithmetic shift right the 32nd bit of the result by
1320 // 31 bits. Then we compare the result to the upper 32 bits.
1321 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
1322 DAG.getConstant(32, DL, MVT::i64));
1323 UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
1324 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
1325 DAG.getConstant(31, DL, MVT::i64));
1326 // It is important that LowerBits is last, otherwise the arithmetic
1327 // shift will not be folded into the compare (SUBS).
1328 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
1329 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1332 // The overflow check for unsigned multiply is easy. We only need to
1333 // check if any of the upper 32 bits are set. This can be done with a
1334 // CMP (shifted register). For that we need to generate the following
1336 // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
1337 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
1338 DAG.getConstant(32, DL, MVT::i64));
1339 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1341 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1342 DAG.getConstant(0, DL, MVT::i64),
1343 UpperBits).getValue(1);
1347 assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
1348 // For the 64 bit multiply
1349 Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1351 SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
1352 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
1353 DAG.getConstant(63, DL, MVT::i64));
1354 // It is important that LowerBits is last, otherwise the arithmetic
1355 // shift will not be folded into the compare (SUBS).
1356 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1357 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1360 SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
1361 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1363 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1364 DAG.getConstant(0, DL, MVT::i64),
1365 UpperBits).getValue(1);
1372 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
1374 // Emit the AArch64 operation with overflow check.
1375 Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
1376 Overflow = Value.getValue(1);
1378 return std::make_pair(Value, Overflow);
1381 SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
1382 RTLIB::Libcall Call) const {
1383 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
1384 return makeLibCall(DAG, Call, MVT::f128, &Ops[0], Ops.size(), false,
1388 static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
1389 SDValue Sel = Op.getOperand(0);
1390 SDValue Other = Op.getOperand(1);
1392 // If neither operand is a SELECT_CC, give up.
1393 if (Sel.getOpcode() != ISD::SELECT_CC)
1394 std::swap(Sel, Other);
1395 if (Sel.getOpcode() != ISD::SELECT_CC)
1398 // The folding we want to perform is:
1399 // (xor x, (select_cc a, b, cc, 0, -1) )
1401 // (csel x, (xor x, -1), cc ...)
1403 // The latter will get matched to a CSINV instruction.
1405 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
1406 SDValue LHS = Sel.getOperand(0);
1407 SDValue RHS = Sel.getOperand(1);
1408 SDValue TVal = Sel.getOperand(2);
1409 SDValue FVal = Sel.getOperand(3);
1412 // FIXME: This could be generalized to non-integer comparisons.
1413 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
1416 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
1417 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
1419 // The the values aren't constants, this isn't the pattern we're looking for.
1420 if (!CFVal || !CTVal)
1423 // We can commute the SELECT_CC by inverting the condition. This
1424 // might be needed to make this fit into a CSINV pattern.
1425 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
1426 std::swap(TVal, FVal);
1427 std::swap(CTVal, CFVal);
1428 CC = ISD::getSetCCInverse(CC, true);
1431 // If the constants line up, perform the transform!
1432 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
1434 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
1437 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
1438 DAG.getConstant(-1ULL, dl, Other.getValueType()));
1440 return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
1447 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
1448 EVT VT = Op.getValueType();
1450 // Let legalize expand this if it isn't a legal type yet.
1451 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
1454 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
1457 bool ExtraOp = false;
1458 switch (Op.getOpcode()) {
1460 llvm_unreachable("Invalid code");
1462 Opc = AArch64ISD::ADDS;
1465 Opc = AArch64ISD::SUBS;
1468 Opc = AArch64ISD::ADCS;
1472 Opc = AArch64ISD::SBCS;
1478 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
1479 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
1483 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
1484 // Let legalize expand this if it isn't a legal type yet.
1485 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
1489 AArch64CC::CondCode CC;
1490 // The actual operation that sets the overflow or carry flag.
1491 SDValue Value, Overflow;
1492 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
1494 // We use 0 and 1 as false and true values.
1495 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
1496 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
1498 // We use an inverted condition, because the conditional select is inverted
1499 // too. This will allow it to be selected to a single instruction:
1500 // CSINC Wd, WZR, WZR, invert(cond).
1501 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
1502 Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
1505 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
1506 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
1509 // Prefetch operands are:
1510 // 1: Address to prefetch
1512 // 3: int locality (0 = no locality ... 3 = extreme locality)
1513 // 4: bool isDataCache
1514 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
1516 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
1517 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
1518 unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
1520 bool IsStream = !Locality;
1521 // When the locality number is set
1523 // The front-end should have filtered out the out-of-range values
1524 assert(Locality <= 3 && "Prefetch locality out-of-range");
1525 // The locality degree is the opposite of the cache speed.
1526 // Put the number the other way around.
1527 // The encoding starts at 0 for level 1
1528 Locality = 3 - Locality;
1531 // built the mask value encoding the expected behavior.
1532 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit
1533 (!IsData << 3) | // IsDataCache bit
1534 (Locality << 1) | // Cache level bits
1535 (unsigned)IsStream; // Stream bit
1536 return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
1537 DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
1540 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
1541 SelectionDAG &DAG) const {
1542 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
1545 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
1547 return LowerF128Call(Op, DAG, LC);
1550 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
1551 SelectionDAG &DAG) const {
1552 if (Op.getOperand(0).getValueType() != MVT::f128) {
1553 // It's legal except when f128 is involved
1558 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
1560 // FP_ROUND node has a second operand indicating whether it is known to be
1561 // precise. That doesn't take part in the LibCall so we can't directly use
1563 SDValue SrcVal = Op.getOperand(0);
1564 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
1565 /*isSigned*/ false, SDLoc(Op)).first;
1568 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
1569 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1570 // Any additional optimization in this function should be recorded
1571 // in the cost tables.
1572 EVT InVT = Op.getOperand(0).getValueType();
1573 EVT VT = Op.getValueType();
1575 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
1578 DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
1580 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
1583 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
1586 MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
1587 VT.getVectorNumElements());
1588 SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
1589 return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
1592 // Type changing conversions are illegal.
1596 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
1597 SelectionDAG &DAG) const {
1598 if (Op.getOperand(0).getValueType().isVector())
1599 return LowerVectorFP_TO_INT(Op, DAG);
1601 // f16 conversions are promoted to f32.
1602 if (Op.getOperand(0).getValueType() == MVT::f16) {
1605 Op.getOpcode(), dl, Op.getValueType(),
1606 DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
1609 if (Op.getOperand(0).getValueType() != MVT::f128) {
1610 // It's legal except when f128 is involved
1615 if (Op.getOpcode() == ISD::FP_TO_SINT)
1616 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
1618 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
1620 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
1621 return makeLibCall(DAG, LC, Op.getValueType(), &Ops[0], Ops.size(), false,
1625 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
1626 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1627 // Any additional optimization in this function should be recorded
1628 // in the cost tables.
1629 EVT VT = Op.getValueType();
1631 SDValue In = Op.getOperand(0);
1632 EVT InVT = In.getValueType();
1634 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
1636 MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
1637 InVT.getVectorNumElements());
1638 In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
1639 return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
1642 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
1644 Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1645 EVT CastVT = VT.changeVectorElementTypeToInteger();
1646 In = DAG.getNode(CastOpc, dl, CastVT, In);
1647 return DAG.getNode(Op.getOpcode(), dl, VT, In);
1653 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
1654 SelectionDAG &DAG) const {
1655 if (Op.getValueType().isVector())
1656 return LowerVectorINT_TO_FP(Op, DAG);
1658 // f16 conversions are promoted to f32.
1659 if (Op.getValueType() == MVT::f16) {
1662 ISD::FP_ROUND, dl, MVT::f16,
1663 DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
1664 DAG.getIntPtrConstant(0, dl));
1667 // i128 conversions are libcalls.
1668 if (Op.getOperand(0).getValueType() == MVT::i128)
1671 // Other conversions are legal, unless it's to the completely software-based
1673 if (Op.getValueType() != MVT::f128)
1677 if (Op.getOpcode() == ISD::SINT_TO_FP)
1678 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
1680 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
1682 return LowerF128Call(Op, DAG, LC);
1685 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
1686 SelectionDAG &DAG) const {
1687 // For iOS, we want to call an alternative entry point: __sincos_stret,
1688 // which returns the values in two S / D registers.
1690 SDValue Arg = Op.getOperand(0);
1691 EVT ArgVT = Arg.getValueType();
1692 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
1699 Entry.isSExt = false;
1700 Entry.isZExt = false;
1701 Args.push_back(Entry);
1703 const char *LibcallName =
1704 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
1705 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
1707 StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
1708 TargetLowering::CallLoweringInfo CLI(DAG);
1709 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
1710 .setCallee(CallingConv::Fast, RetTy, Callee, std::move(Args), 0);
1712 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1713 return CallResult.first;
1716 static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
1717 if (Op.getValueType() != MVT::f16)
1720 assert(Op.getOperand(0).getValueType() == MVT::i16);
1723 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
1724 Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
1726 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
1727 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
1731 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
1732 if (OrigVT.getSizeInBits() >= 64)
1735 assert(OrigVT.isSimple() && "Expecting a simple value type");
1737 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
1738 switch (OrigSimpleTy) {
1739 default: llvm_unreachable("Unexpected Vector Type");
1748 static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
1751 unsigned ExtOpcode) {
1752 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
1753 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
1754 // 64-bits we need to insert a new extension so that it will be 64-bits.
1755 assert(ExtTy.is128BitVector() && "Unexpected extension size");
1756 if (OrigTy.getSizeInBits() >= 64)
1759 // Must extend size to at least 64 bits to be used as an operand for VMULL.
1760 EVT NewVT = getExtensionTo64Bits(OrigTy);
1762 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
1765 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
1767 EVT VT = N->getValueType(0);
1769 if (N->getOpcode() != ISD::BUILD_VECTOR)
1772 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1773 SDNode *Elt = N->getOperand(i).getNode();
1774 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
1775 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1776 unsigned HalfSize = EltSize / 2;
1778 if (!isIntN(HalfSize, C->getSExtValue()))
1781 if (!isUIntN(HalfSize, C->getZExtValue()))
1792 static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
1793 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
1794 return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
1795 N->getOperand(0)->getValueType(0),
1799 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
1800 EVT VT = N->getValueType(0);
1802 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
1803 unsigned NumElts = VT.getVectorNumElements();
1804 MVT TruncVT = MVT::getIntegerVT(EltSize);
1805 SmallVector<SDValue, 8> Ops;
1806 for (unsigned i = 0; i != NumElts; ++i) {
1807 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
1808 const APInt &CInt = C->getAPIntValue();
1809 // Element types smaller than 32 bits are not legal, so use i32 elements.
1810 // The values are implicitly truncated so sext vs. zext doesn't matter.
1811 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
1813 return DAG.getNode(ISD::BUILD_VECTOR, dl,
1814 MVT::getVectorVT(TruncVT, NumElts), Ops);
1817 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
1818 if (N->getOpcode() == ISD::SIGN_EXTEND)
1820 if (isExtendedBUILD_VECTOR(N, DAG, true))
1825 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
1826 if (N->getOpcode() == ISD::ZERO_EXTEND)
1828 if (isExtendedBUILD_VECTOR(N, DAG, false))
1833 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
1834 unsigned Opcode = N->getOpcode();
1835 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
1836 SDNode *N0 = N->getOperand(0).getNode();
1837 SDNode *N1 = N->getOperand(1).getNode();
1838 return N0->hasOneUse() && N1->hasOneUse() &&
1839 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
1844 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
1845 unsigned Opcode = N->getOpcode();
1846 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
1847 SDNode *N0 = N->getOperand(0).getNode();
1848 SDNode *N1 = N->getOperand(1).getNode();
1849 return N0->hasOneUse() && N1->hasOneUse() &&
1850 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
1855 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
1856 // Multiplications are only custom-lowered for 128-bit vectors so that
1857 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
1858 EVT VT = Op.getValueType();
1859 assert(VT.is128BitVector() && VT.isInteger() &&
1860 "unexpected type for custom-lowering ISD::MUL");
1861 SDNode *N0 = Op.getOperand(0).getNode();
1862 SDNode *N1 = Op.getOperand(1).getNode();
1863 unsigned NewOpc = 0;
1865 bool isN0SExt = isSignExtended(N0, DAG);
1866 bool isN1SExt = isSignExtended(N1, DAG);
1867 if (isN0SExt && isN1SExt)
1868 NewOpc = AArch64ISD::SMULL;
1870 bool isN0ZExt = isZeroExtended(N0, DAG);
1871 bool isN1ZExt = isZeroExtended(N1, DAG);
1872 if (isN0ZExt && isN1ZExt)
1873 NewOpc = AArch64ISD::UMULL;
1874 else if (isN1SExt || isN1ZExt) {
1875 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
1876 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
1877 if (isN1SExt && isAddSubSExt(N0, DAG)) {
1878 NewOpc = AArch64ISD::SMULL;
1880 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
1881 NewOpc = AArch64ISD::UMULL;
1883 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
1885 NewOpc = AArch64ISD::UMULL;
1891 if (VT == MVT::v2i64)
1892 // Fall through to expand this. It is not legal.
1895 // Other vector multiplications are legal.
1900 // Legalize to a S/UMULL instruction
1903 SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
1905 Op0 = skipExtensionForVectorMULL(N0, DAG);
1906 assert(Op0.getValueType().is64BitVector() &&
1907 Op1.getValueType().is64BitVector() &&
1908 "unexpected types for extended operands to VMULL");
1909 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
1911 // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
1912 // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
1913 // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
1914 SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
1915 SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
1916 EVT Op1VT = Op1.getValueType();
1917 return DAG.getNode(N0->getOpcode(), DL, VT,
1918 DAG.getNode(NewOpc, DL, VT,
1919 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
1920 DAG.getNode(NewOpc, DL, VT,
1921 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
1924 SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
1925 SelectionDAG &DAG) const {
1926 switch (Op.getOpcode()) {
1928 llvm_unreachable("unimplemented operand");
1931 return LowerBITCAST(Op, DAG);
1932 case ISD::GlobalAddress:
1933 return LowerGlobalAddress(Op, DAG);
1934 case ISD::GlobalTLSAddress:
1935 return LowerGlobalTLSAddress(Op, DAG);
1937 return LowerSETCC(Op, DAG);
1939 return LowerBR_CC(Op, DAG);
1941 return LowerSELECT(Op, DAG);
1942 case ISD::SELECT_CC:
1943 return LowerSELECT_CC(Op, DAG);
1944 case ISD::JumpTable:
1945 return LowerJumpTable(Op, DAG);
1946 case ISD::ConstantPool:
1947 return LowerConstantPool(Op, DAG);
1948 case ISD::BlockAddress:
1949 return LowerBlockAddress(Op, DAG);
1951 return LowerVASTART(Op, DAG);
1953 return LowerVACOPY(Op, DAG);
1955 return LowerVAARG(Op, DAG);
1960 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
1967 return LowerXALUO(Op, DAG);
1969 return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
1971 return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
1973 return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
1975 return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
1977 return LowerFP_ROUND(Op, DAG);
1978 case ISD::FP_EXTEND:
1979 return LowerFP_EXTEND(Op, DAG);
1980 case ISD::FRAMEADDR:
1981 return LowerFRAMEADDR(Op, DAG);
1982 case ISD::RETURNADDR:
1983 return LowerRETURNADDR(Op, DAG);
1984 case ISD::INSERT_VECTOR_ELT:
1985 return LowerINSERT_VECTOR_ELT(Op, DAG);
1986 case ISD::EXTRACT_VECTOR_ELT:
1987 return LowerEXTRACT_VECTOR_ELT(Op, DAG);
1988 case ISD::BUILD_VECTOR:
1989 return LowerBUILD_VECTOR(Op, DAG);
1990 case ISD::VECTOR_SHUFFLE:
1991 return LowerVECTOR_SHUFFLE(Op, DAG);
1992 case ISD::EXTRACT_SUBVECTOR:
1993 return LowerEXTRACT_SUBVECTOR(Op, DAG);
1997 return LowerVectorSRA_SRL_SHL(Op, DAG);
1998 case ISD::SHL_PARTS:
1999 return LowerShiftLeftParts(Op, DAG);
2000 case ISD::SRL_PARTS:
2001 case ISD::SRA_PARTS:
2002 return LowerShiftRightParts(Op, DAG);
2004 return LowerCTPOP(Op, DAG);
2005 case ISD::FCOPYSIGN:
2006 return LowerFCOPYSIGN(Op, DAG);
2008 return LowerVectorAND(Op, DAG);
2010 return LowerVectorOR(Op, DAG);
2012 return LowerXOR(Op, DAG);
2014 return LowerPREFETCH(Op, DAG);
2015 case ISD::SINT_TO_FP:
2016 case ISD::UINT_TO_FP:
2017 return LowerINT_TO_FP(Op, DAG);
2018 case ISD::FP_TO_SINT:
2019 case ISD::FP_TO_UINT:
2020 return LowerFP_TO_INT(Op, DAG);
2022 return LowerFSINCOS(Op, DAG);
2024 return LowerMUL(Op, DAG);
2028 /// getFunctionAlignment - Return the Log2 alignment of this function.
2029 unsigned AArch64TargetLowering::getFunctionAlignment(const Function *F) const {
2033 //===----------------------------------------------------------------------===//
2034 // Calling Convention Implementation
2035 //===----------------------------------------------------------------------===//
2037 #include "AArch64GenCallingConv.inc"
2039 /// Selects the correct CCAssignFn for a given CallingConvention value.
2040 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2041 bool IsVarArg) const {
2044 llvm_unreachable("Unsupported calling convention.");
2045 case CallingConv::WebKit_JS:
2046 return CC_AArch64_WebKit_JS;
2047 case CallingConv::GHC:
2048 return CC_AArch64_GHC;
2049 case CallingConv::C:
2050 case CallingConv::Fast:
2051 if (!Subtarget->isTargetDarwin())
2052 return CC_AArch64_AAPCS;
2053 return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
2057 SDValue AArch64TargetLowering::LowerFormalArguments(
2058 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2059 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2060 SmallVectorImpl<SDValue> &InVals) const {
2061 MachineFunction &MF = DAG.getMachineFunction();
2062 MachineFrameInfo *MFI = MF.getFrameInfo();
2064 // Assign locations to all of the incoming arguments.
2065 SmallVector<CCValAssign, 16> ArgLocs;
2066 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2069 // At this point, Ins[].VT may already be promoted to i32. To correctly
2070 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2071 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2072 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
2073 // we use a special version of AnalyzeFormalArguments to pass in ValVT and
2075 unsigned NumArgs = Ins.size();
2076 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2077 unsigned CurArgIdx = 0;
2078 for (unsigned i = 0; i != NumArgs; ++i) {
2079 MVT ValVT = Ins[i].VT;
2080 if (Ins[i].isOrigArg()) {
2081 std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
2082 CurArgIdx = Ins[i].getOrigArgIndex();
2084 // Get type of the original argument.
2085 EVT ActualVT = getValueType(CurOrigArg->getType(), /*AllowUnknown*/ true);
2086 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
2087 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2088 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2090 else if (ActualMVT == MVT::i16)
2093 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2095 AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
2096 assert(!Res && "Call operand has unhandled type");
2099 assert(ArgLocs.size() == Ins.size());
2100 SmallVector<SDValue, 16> ArgValues;
2101 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2102 CCValAssign &VA = ArgLocs[i];
2104 if (Ins[i].Flags.isByVal()) {
2105 // Byval is used for HFAs in the PCS, but the system should work in a
2106 // non-compliant manner for larger structs.
2107 EVT PtrTy = getPointerTy();
2108 int Size = Ins[i].Flags.getByValSize();
2109 unsigned NumRegs = (Size + 7) / 8;
2111 // FIXME: This works on big-endian for composite byvals, which are the common
2112 // case. It should also work for fundamental types too.
2114 MFI->CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
2115 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrTy);
2116 InVals.push_back(FrameIdxN);
2121 if (VA.isRegLoc()) {
2122 // Arguments stored in registers.
2123 EVT RegVT = VA.getLocVT();
2126 const TargetRegisterClass *RC;
2128 if (RegVT == MVT::i32)
2129 RC = &AArch64::GPR32RegClass;
2130 else if (RegVT == MVT::i64)
2131 RC = &AArch64::GPR64RegClass;
2132 else if (RegVT == MVT::f16)
2133 RC = &AArch64::FPR16RegClass;
2134 else if (RegVT == MVT::f32)
2135 RC = &AArch64::FPR32RegClass;
2136 else if (RegVT == MVT::f64 || RegVT.is64BitVector())
2137 RC = &AArch64::FPR64RegClass;
2138 else if (RegVT == MVT::f128 || RegVT.is128BitVector())
2139 RC = &AArch64::FPR128RegClass;
2141 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2143 // Transform the arguments in physical registers into virtual ones.
2144 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2145 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2147 // If this is an 8, 16 or 32-bit value, it is really passed promoted
2148 // to 64 bits. Insert an assert[sz]ext to capture this, then
2149 // truncate to the right size.
2150 switch (VA.getLocInfo()) {
2152 llvm_unreachable("Unknown loc info!");
2153 case CCValAssign::Full:
2155 case CCValAssign::BCvt:
2156 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
2158 case CCValAssign::AExt:
2159 case CCValAssign::SExt:
2160 case CCValAssign::ZExt:
2161 // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
2162 // nodes after our lowering.
2163 assert(RegVT == Ins[i].VT && "incorrect register location selected");
2167 InVals.push_back(ArgValue);
2169 } else { // VA.isRegLoc()
2170 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
2171 unsigned ArgOffset = VA.getLocMemOffset();
2172 unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
2174 uint32_t BEAlign = 0;
2175 if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
2176 !Ins[i].Flags.isInConsecutiveRegs())
2177 BEAlign = 8 - ArgSize;
2179 int FI = MFI->CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
2181 // Create load nodes to retrieve arguments from the stack.
2182 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2185 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
2186 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
2187 MVT MemVT = VA.getValVT();
2189 switch (VA.getLocInfo()) {
2192 case CCValAssign::BCvt:
2193 MemVT = VA.getLocVT();
2195 case CCValAssign::SExt:
2196 ExtType = ISD::SEXTLOAD;
2198 case CCValAssign::ZExt:
2199 ExtType = ISD::ZEXTLOAD;
2201 case CCValAssign::AExt:
2202 ExtType = ISD::EXTLOAD;
2206 ArgValue = DAG.getExtLoad(ExtType, DL, VA.getLocVT(), Chain, FIN,
2207 MachinePointerInfo::getFixedStack(FI),
2208 MemVT, false, false, false, 0);
2210 InVals.push_back(ArgValue);
2216 if (!Subtarget->isTargetDarwin()) {
2217 // The AAPCS variadic function ABI is identical to the non-variadic
2218 // one. As a result there may be more arguments in registers and we should
2219 // save them for future reference.
2220 saveVarArgRegisters(CCInfo, DAG, DL, Chain);
2223 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
2224 // This will point to the next argument passed via stack.
2225 unsigned StackOffset = CCInfo.getNextStackOffset();
2226 // We currently pass all varargs at 8-byte alignment.
2227 StackOffset = ((StackOffset + 7) & ~7);
2228 AFI->setVarArgsStackIndex(MFI->CreateFixedObject(4, StackOffset, true));
2231 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2232 unsigned StackArgSize = CCInfo.getNextStackOffset();
2233 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2234 if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
2235 // This is a non-standard ABI so by fiat I say we're allowed to make full
2236 // use of the stack area to be popped, which must be aligned to 16 bytes in
2238 StackArgSize = RoundUpToAlignment(StackArgSize, 16);
2240 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
2241 // a multiple of 16.
2242 FuncInfo->setArgumentStackToRestore(StackArgSize);
2244 // This realignment carries over to the available bytes below. Our own
2245 // callers will guarantee the space is free by giving an aligned value to
2248 // Even if we're not expected to free up the space, it's useful to know how
2249 // much is there while considering tail calls (because we can reuse it).
2250 FuncInfo->setBytesInStackArgArea(StackArgSize);
2255 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
2256 SelectionDAG &DAG, SDLoc DL,
2257 SDValue &Chain) const {
2258 MachineFunction &MF = DAG.getMachineFunction();
2259 MachineFrameInfo *MFI = MF.getFrameInfo();
2260 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2262 SmallVector<SDValue, 8> MemOps;
2264 static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
2265 AArch64::X3, AArch64::X4, AArch64::X5,
2266 AArch64::X6, AArch64::X7 };
2267 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
2268 unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
2270 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
2272 if (GPRSaveSize != 0) {
2273 GPRIdx = MFI->CreateStackObject(GPRSaveSize, 8, false);
2275 SDValue FIN = DAG.getFrameIndex(GPRIdx, getPointerTy());
2277 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
2278 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
2279 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
2281 DAG.getStore(Val.getValue(1), DL, Val, FIN,
2282 MachinePointerInfo::getStack(i * 8), false, false, 0);
2283 MemOps.push_back(Store);
2284 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), FIN,
2285 DAG.getConstant(8, DL, getPointerTy()));
2288 FuncInfo->setVarArgsGPRIndex(GPRIdx);
2289 FuncInfo->setVarArgsGPRSize(GPRSaveSize);
2291 if (Subtarget->hasFPARMv8()) {
2292 static const MCPhysReg FPRArgRegs[] = {
2293 AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
2294 AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
2295 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
2296 unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
2298 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
2300 if (FPRSaveSize != 0) {
2301 FPRIdx = MFI->CreateStackObject(FPRSaveSize, 16, false);
2303 SDValue FIN = DAG.getFrameIndex(FPRIdx, getPointerTy());
2305 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
2306 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
2307 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
2310 DAG.getStore(Val.getValue(1), DL, Val, FIN,
2311 MachinePointerInfo::getStack(i * 16), false, false, 0);
2312 MemOps.push_back(Store);
2313 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), FIN,
2314 DAG.getConstant(16, DL, getPointerTy()));
2317 FuncInfo->setVarArgsFPRIndex(FPRIdx);
2318 FuncInfo->setVarArgsFPRSize(FPRSaveSize);
2321 if (!MemOps.empty()) {
2322 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
2326 /// LowerCallResult - Lower the result values of a call into the
2327 /// appropriate copies out of appropriate physical registers.
2328 SDValue AArch64TargetLowering::LowerCallResult(
2329 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
2330 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2331 SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
2332 SDValue ThisVal) const {
2333 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
2334 ? RetCC_AArch64_WebKit_JS
2335 : RetCC_AArch64_AAPCS;
2336 // Assign locations to each value returned by this call.
2337 SmallVector<CCValAssign, 16> RVLocs;
2338 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2340 CCInfo.AnalyzeCallResult(Ins, RetCC);
2342 // Copy all of the result registers out of their specified physreg.
2343 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2344 CCValAssign VA = RVLocs[i];
2346 // Pass 'this' value directly from the argument to return value, to avoid
2347 // reg unit interference
2348 if (i == 0 && isThisReturn) {
2349 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
2350 "unexpected return calling convention register assignment");
2351 InVals.push_back(ThisVal);
2356 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2357 Chain = Val.getValue(1);
2358 InFlag = Val.getValue(2);
2360 switch (VA.getLocInfo()) {
2362 llvm_unreachable("Unknown loc info!");
2363 case CCValAssign::Full:
2365 case CCValAssign::BCvt:
2366 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2370 InVals.push_back(Val);
2376 bool AArch64TargetLowering::isEligibleForTailCallOptimization(
2377 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
2378 bool isCalleeStructRet, bool isCallerStructRet,
2379 const SmallVectorImpl<ISD::OutputArg> &Outs,
2380 const SmallVectorImpl<SDValue> &OutVals,
2381 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2382 // For CallingConv::C this function knows whether the ABI needs
2383 // changing. That's not true for other conventions so they will have to opt in
2385 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
2388 const MachineFunction &MF = DAG.getMachineFunction();
2389 const Function *CallerF = MF.getFunction();
2390 CallingConv::ID CallerCC = CallerF->getCallingConv();
2391 bool CCMatch = CallerCC == CalleeCC;
2393 // Byval parameters hand the function a pointer directly into the stack area
2394 // we want to reuse during a tail call. Working around this *is* possible (see
2395 // X86) but less efficient and uglier in LowerCall.
2396 for (Function::const_arg_iterator i = CallerF->arg_begin(),
2397 e = CallerF->arg_end();
2399 if (i->hasByValAttr())
2402 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2403 if (IsTailCallConvention(CalleeCC) && CCMatch)
2408 // Externally-defined functions with weak linkage should not be
2409 // tail-called on AArch64 when the OS does not support dynamic
2410 // pre-emption of symbols, as the AAELF spec requires normal calls
2411 // to undefined weak functions to be replaced with a NOP or jump to the
2412 // next instruction. The behaviour of branch instructions in this
2413 // situation (as used for tail calls) is implementation-defined, so we
2414 // cannot rely on the linker replacing the tail call with a return.
2415 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2416 const GlobalValue *GV = G->getGlobal();
2417 const Triple TT(getTargetMachine().getTargetTriple());
2418 if (GV->hasExternalWeakLinkage() &&
2419 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2423 // Now we search for cases where we can use a tail call without changing the
2424 // ABI. Sibcall is used in some places (particularly gcc) to refer to this
2427 // I want anyone implementing a new calling convention to think long and hard
2428 // about this assert.
2429 assert((!isVarArg || CalleeCC == CallingConv::C) &&
2430 "Unexpected variadic calling convention");
2432 if (isVarArg && !Outs.empty()) {
2433 // At least two cases here: if caller is fastcc then we can't have any
2434 // memory arguments (we'd be expected to clean up the stack afterwards). If
2435 // caller is C then we could potentially use its argument area.
2437 // FIXME: for now we take the most conservative of these in both cases:
2438 // disallow all variadic memory operands.
2439 SmallVector<CCValAssign, 16> ArgLocs;
2440 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2443 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
2444 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2445 if (!ArgLocs[i].isRegLoc())
2449 // If the calling conventions do not match, then we'd better make sure the
2450 // results are returned in the same way as what the caller expects.
2452 SmallVector<CCValAssign, 16> RVLocs1;
2453 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2455 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForCall(CalleeCC, isVarArg));
2457 SmallVector<CCValAssign, 16> RVLocs2;
2458 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2460 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForCall(CallerCC, isVarArg));
2462 if (RVLocs1.size() != RVLocs2.size())
2464 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2465 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2467 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2469 if (RVLocs1[i].isRegLoc()) {
2470 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2473 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2479 // Nothing more to check if the callee is taking no arguments
2483 SmallVector<CCValAssign, 16> ArgLocs;
2484 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2487 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2489 const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2491 // If the stack arguments for this call would fit into our own save area then
2492 // the call can be made tail.
2493 return CCInfo.getNextStackOffset() <= FuncInfo->getBytesInStackArgArea();
2496 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
2498 MachineFrameInfo *MFI,
2499 int ClobberedFI) const {
2500 SmallVector<SDValue, 8> ArgChains;
2501 int64_t FirstByte = MFI->getObjectOffset(ClobberedFI);
2502 int64_t LastByte = FirstByte + MFI->getObjectSize(ClobberedFI) - 1;
2504 // Include the original chain at the beginning of the list. When this is
2505 // used by target LowerCall hooks, this helps legalize find the
2506 // CALLSEQ_BEGIN node.
2507 ArgChains.push_back(Chain);
2509 // Add a chain value for each stack argument corresponding
2510 for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
2511 UE = DAG.getEntryNode().getNode()->use_end();
2513 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
2514 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
2515 if (FI->getIndex() < 0) {
2516 int64_t InFirstByte = MFI->getObjectOffset(FI->getIndex());
2517 int64_t InLastByte = InFirstByte;
2518 InLastByte += MFI->getObjectSize(FI->getIndex()) - 1;
2520 if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
2521 (FirstByte <= InFirstByte && InFirstByte <= LastByte))
2522 ArgChains.push_back(SDValue(L, 1));
2525 // Build a tokenfactor for all the chains.
2526 return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
2529 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
2530 bool TailCallOpt) const {
2531 return CallCC == CallingConv::Fast && TailCallOpt;
2534 bool AArch64TargetLowering::IsTailCallConvention(CallingConv::ID CallCC) const {
2535 return CallCC == CallingConv::Fast;
2538 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
2539 /// and add input and output parameter nodes.
2541 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
2542 SmallVectorImpl<SDValue> &InVals) const {
2543 SelectionDAG &DAG = CLI.DAG;
2545 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2546 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2547 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2548 SDValue Chain = CLI.Chain;
2549 SDValue Callee = CLI.Callee;
2550 bool &IsTailCall = CLI.IsTailCall;
2551 CallingConv::ID CallConv = CLI.CallConv;
2552 bool IsVarArg = CLI.IsVarArg;
2554 MachineFunction &MF = DAG.getMachineFunction();
2555 bool IsStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
2556 bool IsThisReturn = false;
2558 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2559 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2560 bool IsSibCall = false;
2563 // Check if it's really possible to do a tail call.
2564 IsTailCall = isEligibleForTailCallOptimization(
2565 Callee, CallConv, IsVarArg, IsStructRet,
2566 MF.getFunction()->hasStructRetAttr(), Outs, OutVals, Ins, DAG);
2567 if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
2568 report_fatal_error("failed to perform tail call elimination on a call "
2569 "site marked musttail");
2571 // A sibling call is one where we're under the usual C ABI and not planning
2572 // to change that but can still do a tail call:
2573 if (!TailCallOpt && IsTailCall)
2580 // Analyze operands of the call, assigning locations to each operand.
2581 SmallVector<CCValAssign, 16> ArgLocs;
2582 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
2586 // Handle fixed and variable vector arguments differently.
2587 // Variable vector arguments always go into memory.
2588 unsigned NumArgs = Outs.size();
2590 for (unsigned i = 0; i != NumArgs; ++i) {
2591 MVT ArgVT = Outs[i].VT;
2592 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2593 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
2594 /*IsVarArg=*/ !Outs[i].IsFixed);
2595 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
2596 assert(!Res && "Call operand has unhandled type");
2600 // At this point, Outs[].VT may already be promoted to i32. To correctly
2601 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2602 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2603 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
2604 // we use a special version of AnalyzeCallOperands to pass in ValVT and
2606 unsigned NumArgs = Outs.size();
2607 for (unsigned i = 0; i != NumArgs; ++i) {
2608 MVT ValVT = Outs[i].VT;
2609 // Get type of the original argument.
2610 EVT ActualVT = getValueType(CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
2611 /*AllowUnknown*/ true);
2612 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
2613 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2614 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2615 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2617 else if (ActualMVT == MVT::i16)
2620 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2621 bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
2622 assert(!Res && "Call operand has unhandled type");
2627 // Get a count of how many bytes are to be pushed on the stack.
2628 unsigned NumBytes = CCInfo.getNextStackOffset();
2631 // Since we're not changing the ABI to make this a tail call, the memory
2632 // operands are already available in the caller's incoming argument space.
2636 // FPDiff is the byte offset of the call's argument area from the callee's.
2637 // Stores to callee stack arguments will be placed in FixedStackSlots offset
2638 // by this amount for a tail call. In a sibling call it must be 0 because the
2639 // caller will deallocate the entire stack and the callee still expects its
2640 // arguments to begin at SP+0. Completely unused for non-tail calls.
2643 if (IsTailCall && !IsSibCall) {
2644 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
2646 // Since callee will pop argument stack as a tail call, we must keep the
2647 // popped size 16-byte aligned.
2648 NumBytes = RoundUpToAlignment(NumBytes, 16);
2650 // FPDiff will be negative if this tail call requires more space than we
2651 // would automatically have in our incoming argument space. Positive if we
2652 // can actually shrink the stack.
2653 FPDiff = NumReusableBytes - NumBytes;
2655 // The stack pointer must be 16-byte aligned at all times it's used for a
2656 // memory operation, which in practice means at *all* times and in
2657 // particular across call boundaries. Therefore our own arguments started at
2658 // a 16-byte aligned SP and the delta applied for the tail call should
2659 // satisfy the same constraint.
2660 assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
2663 // Adjust the stack pointer for the new arguments...
2664 // These operations are automatically eliminated by the prolog/epilog pass
2666 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, DL,
2670 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP, getPointerTy());
2672 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2673 SmallVector<SDValue, 8> MemOpChains;
2675 // Walk the register/memloc assignments, inserting copies/loads.
2676 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
2677 ++i, ++realArgIdx) {
2678 CCValAssign &VA = ArgLocs[i];
2679 SDValue Arg = OutVals[realArgIdx];
2680 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2682 // Promote the value if needed.
2683 switch (VA.getLocInfo()) {
2685 llvm_unreachable("Unknown loc info!");
2686 case CCValAssign::Full:
2688 case CCValAssign::SExt:
2689 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2691 case CCValAssign::ZExt:
2692 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2694 case CCValAssign::AExt:
2695 if (Outs[realArgIdx].ArgVT == MVT::i1) {
2696 // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
2697 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
2698 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
2700 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2702 case CCValAssign::BCvt:
2703 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2705 case CCValAssign::FPExt:
2706 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
2710 if (VA.isRegLoc()) {
2711 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i64) {
2712 assert(VA.getLocVT() == MVT::i64 &&
2713 "unexpected calling convention register assignment");
2714 assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
2715 "unexpected use of 'returned'");
2716 IsThisReturn = true;
2718 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2720 assert(VA.isMemLoc());
2723 MachinePointerInfo DstInfo;
2725 // FIXME: This works on big-endian for composite byvals, which are the
2726 // common case. It should also work for fundamental types too.
2727 uint32_t BEAlign = 0;
2728 unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
2729 : VA.getValVT().getSizeInBits();
2730 OpSize = (OpSize + 7) / 8;
2731 if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
2732 !Flags.isInConsecutiveRegs()) {
2734 BEAlign = 8 - OpSize;
2736 unsigned LocMemOffset = VA.getLocMemOffset();
2737 int32_t Offset = LocMemOffset + BEAlign;
2738 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
2739 PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr, PtrOff);
2742 Offset = Offset + FPDiff;
2743 int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2745 DstAddr = DAG.getFrameIndex(FI, getPointerTy());
2746 DstInfo = MachinePointerInfo::getFixedStack(FI);
2748 // Make sure any stack arguments overlapping with where we're storing
2749 // are loaded before this eventual operation. Otherwise they'll be
2751 Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
2753 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
2755 DstAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr, PtrOff);
2756 DstInfo = MachinePointerInfo::getStack(LocMemOffset);
2759 if (Outs[i].Flags.isByVal()) {
2761 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
2762 SDValue Cpy = DAG.getMemcpy(
2763 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
2764 /*isVol = */ false, /*AlwaysInline = */ false,
2765 /*isTailCall = */ false,
2766 DstInfo, MachinePointerInfo());
2768 MemOpChains.push_back(Cpy);
2770 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
2771 // promoted to a legal register type i32, we should truncate Arg back to
2773 if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
2774 VA.getValVT() == MVT::i16)
2775 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
2778 DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, false, false, 0);
2779 MemOpChains.push_back(Store);
2784 if (!MemOpChains.empty())
2785 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2787 // Build a sequence of copy-to-reg nodes chained together with token chain
2788 // and flag operands which copy the outgoing args into the appropriate regs.
2790 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2791 Chain = DAG.getCopyToReg(Chain, DL, RegsToPass[i].first,
2792 RegsToPass[i].second, InFlag);
2793 InFlag = Chain.getValue(1);
2796 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2797 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2798 // node so that legalize doesn't hack it.
2799 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
2800 Subtarget->isTargetMachO()) {
2801 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2802 const GlobalValue *GV = G->getGlobal();
2803 bool InternalLinkage = GV->hasInternalLinkage();
2804 if (InternalLinkage)
2805 Callee = DAG.getTargetGlobalAddress(GV, DL, getPointerTy(), 0, 0);
2807 Callee = DAG.getTargetGlobalAddress(GV, DL, getPointerTy(), 0,
2809 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, getPointerTy(), Callee);
2811 } else if (ExternalSymbolSDNode *S =
2812 dyn_cast<ExternalSymbolSDNode>(Callee)) {
2813 const char *Sym = S->getSymbol();
2815 DAG.getTargetExternalSymbol(Sym, getPointerTy(), AArch64II::MO_GOT);
2816 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, getPointerTy(), Callee);
2818 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2819 const GlobalValue *GV = G->getGlobal();
2820 Callee = DAG.getTargetGlobalAddress(GV, DL, getPointerTy(), 0, 0);
2821 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2822 const char *Sym = S->getSymbol();
2823 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), 0);
2826 // We don't usually want to end the call-sequence here because we would tidy
2827 // the frame up *after* the call, however in the ABI-changing tail-call case
2828 // we've carefully laid out the parameters so that when sp is reset they'll be
2829 // in the correct location.
2830 if (IsTailCall && !IsSibCall) {
2831 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
2832 DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
2833 InFlag = Chain.getValue(1);
2836 std::vector<SDValue> Ops;
2837 Ops.push_back(Chain);
2838 Ops.push_back(Callee);
2841 // Each tail call may have to adjust the stack by a different amount, so
2842 // this information must travel along with the operation for eventual
2843 // consumption by emitEpilogue.
2844 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
2847 // Add argument registers to the end of the list so that they are known live
2849 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2850 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2851 RegsToPass[i].second.getValueType()));
2853 // Add a register mask operand representing the call-preserved registers.
2854 const uint32_t *Mask;
2855 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
2857 // For 'this' returns, use the X0-preserving mask if applicable
2858 Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
2860 IsThisReturn = false;
2861 Mask = TRI->getCallPreservedMask(MF, CallConv);
2864 Mask = TRI->getCallPreservedMask(MF, CallConv);
2866 assert(Mask && "Missing call preserved mask for calling convention");
2867 Ops.push_back(DAG.getRegisterMask(Mask));
2869 if (InFlag.getNode())
2870 Ops.push_back(InFlag);
2872 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2874 // If we're doing a tall call, use a TC_RETURN here rather than an
2875 // actual call instruction.
2877 MF.getFrameInfo()->setHasTailCall();
2878 return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
2881 // Returns a chain and a flag for retval copy to use.
2882 Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
2883 InFlag = Chain.getValue(1);
2885 uint64_t CalleePopBytes = DoesCalleeRestoreStack(CallConv, TailCallOpt)
2886 ? RoundUpToAlignment(NumBytes, 16)
2889 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
2890 DAG.getIntPtrConstant(CalleePopBytes, DL, true),
2893 InFlag = Chain.getValue(1);
2895 // Handle result values, copying them out of physregs into vregs that we
2897 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
2898 InVals, IsThisReturn,
2899 IsThisReturn ? OutVals[0] : SDValue());
2902 bool AArch64TargetLowering::CanLowerReturn(
2903 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
2904 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
2905 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
2906 ? RetCC_AArch64_WebKit_JS
2907 : RetCC_AArch64_AAPCS;
2908 SmallVector<CCValAssign, 16> RVLocs;
2909 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2910 return CCInfo.CheckReturn(Outs, RetCC);
2914 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2916 const SmallVectorImpl<ISD::OutputArg> &Outs,
2917 const SmallVectorImpl<SDValue> &OutVals,
2918 SDLoc DL, SelectionDAG &DAG) const {
2919 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
2920 ? RetCC_AArch64_WebKit_JS
2921 : RetCC_AArch64_AAPCS;
2922 SmallVector<CCValAssign, 16> RVLocs;
2923 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2925 CCInfo.AnalyzeReturn(Outs, RetCC);
2927 // Copy the result values into the output registers.
2929 SmallVector<SDValue, 4> RetOps(1, Chain);
2930 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
2931 ++i, ++realRVLocIdx) {
2932 CCValAssign &VA = RVLocs[i];
2933 assert(VA.isRegLoc() && "Can only return in registers!");
2934 SDValue Arg = OutVals[realRVLocIdx];
2936 switch (VA.getLocInfo()) {
2938 llvm_unreachable("Unknown loc info!");
2939 case CCValAssign::Full:
2940 if (Outs[i].ArgVT == MVT::i1) {
2941 // AAPCS requires i1 to be zero-extended to i8 by the producer of the
2942 // value. This is strictly redundant on Darwin (which uses "zeroext
2943 // i1"), but will be optimised out before ISel.
2944 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
2945 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2948 case CCValAssign::BCvt:
2949 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2953 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2954 Flag = Chain.getValue(1);
2955 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2958 RetOps[0] = Chain; // Update chain.
2960 // Add the flag if we have it.
2962 RetOps.push_back(Flag);
2964 return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
2967 //===----------------------------------------------------------------------===//
2968 // Other Lowering Code
2969 //===----------------------------------------------------------------------===//
2971 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
2972 SelectionDAG &DAG) const {
2973 EVT PtrVT = getPointerTy();
2975 const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
2976 const GlobalValue *GV = GN->getGlobal();
2977 unsigned char OpFlags =
2978 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
2980 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
2981 "unexpected offset in global node");
2983 // This also catched the large code model case for Darwin.
2984 if ((OpFlags & AArch64II::MO_GOT) != 0) {
2985 SDValue GotAddr = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
2986 // FIXME: Once remat is capable of dealing with instructions with register
2987 // operands, expand this into two nodes instead of using a wrapper node.
2988 return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
2991 if ((OpFlags & AArch64II::MO_CONSTPOOL) != 0) {
2992 assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
2993 "use of MO_CONSTPOOL only supported on small model");
2994 SDValue Hi = DAG.getTargetConstantPool(GV, PtrVT, 0, 0, AArch64II::MO_PAGE);
2995 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
2996 unsigned char LoFlags = AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
2997 SDValue Lo = DAG.getTargetConstantPool(GV, PtrVT, 0, 0, LoFlags);
2998 SDValue PoolAddr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
2999 SDValue GlobalAddr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), PoolAddr,
3000 MachinePointerInfo::getConstantPool(),
3001 /*isVolatile=*/ false,
3002 /*isNonTemporal=*/ true,
3003 /*isInvariant=*/ true, 8);
3004 if (GN->getOffset() != 0)
3005 return DAG.getNode(ISD::ADD, DL, PtrVT, GlobalAddr,
3006 DAG.getConstant(GN->getOffset(), DL, PtrVT));
3010 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
3011 const unsigned char MO_NC = AArch64II::MO_NC;
3013 AArch64ISD::WrapperLarge, DL, PtrVT,
3014 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G3),
3015 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
3016 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
3017 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
3019 // Use ADRP/ADD or ADRP/LDR for everything else: the small model on ELF and
3020 // the only correct model on Darwin.
3021 SDValue Hi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
3022 OpFlags | AArch64II::MO_PAGE);
3023 unsigned char LoFlags = OpFlags | AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
3024 SDValue Lo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, LoFlags);
3026 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3027 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3031 /// \brief Convert a TLS address reference into the correct sequence of loads
3032 /// and calls to compute the variable's address (for Darwin, currently) and
3033 /// return an SDValue containing the final node.
3035 /// Darwin only has one TLS scheme which must be capable of dealing with the
3036 /// fully general situation, in the worst case. This means:
3037 /// + "extern __thread" declaration.
3038 /// + Defined in a possibly unknown dynamic library.
3040 /// The general system is that each __thread variable has a [3 x i64] descriptor
3041 /// which contains information used by the runtime to calculate the address. The
3042 /// only part of this the compiler needs to know about is the first xword, which
3043 /// contains a function pointer that must be called with the address of the
3044 /// entire descriptor in "x0".
3046 /// Since this descriptor may be in a different unit, in general even the
3047 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
3049 /// adrp x0, _var@TLVPPAGE
3050 /// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor
3051 /// ldr x1, [x0] ; x1 contains 1st entry of descriptor,
3052 /// ; the function pointer
3053 /// blr x1 ; Uses descriptor address in x0
3054 /// ; Address of _var is now in x0.
3056 /// If the address of _var's descriptor *is* known to the linker, then it can
3057 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
3058 /// a slight efficiency gain.
3060 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
3061 SelectionDAG &DAG) const {
3062 assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
3065 MVT PtrVT = getPointerTy();
3066 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3069 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3070 SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
3072 // The first entry in the descriptor is a function pointer that we must call
3073 // to obtain the address of the variable.
3074 SDValue Chain = DAG.getEntryNode();
3075 SDValue FuncTLVGet =
3076 DAG.getLoad(MVT::i64, DL, Chain, DescAddr, MachinePointerInfo::getGOT(),
3077 false, true, true, 8);
3078 Chain = FuncTLVGet.getValue(1);
3080 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3081 MFI->setAdjustsStack(true);
3083 // TLS calls preserve all registers except those that absolutely must be
3084 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
3086 const uint32_t *Mask =
3087 Subtarget->getRegisterInfo()->getTLSCallPreservedMask();
3089 // Finally, we can make the call. This is just a degenerate version of a
3090 // normal AArch64 call node: x0 takes the address of the descriptor, and
3091 // returns the address of the variable in this thread.
3092 Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
3094 DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3095 Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
3096 DAG.getRegisterMask(Mask), Chain.getValue(1));
3097 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
3100 /// When accessing thread-local variables under either the general-dynamic or
3101 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
3102 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
3103 /// is a function pointer to carry out the resolution.
3105 /// The sequence is:
3106 /// adrp x0, :tlsdesc:var
3107 /// ldr x1, [x0, #:tlsdesc_lo12:var]
3108 /// add x0, x0, #:tlsdesc_lo12:var
3109 /// .tlsdesccall var
3111 /// (TPIDR_EL0 offset now in x0)
3113 /// The above sequence must be produced unscheduled, to enable the linker to
3114 /// optimize/relax this sequence.
3115 /// Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
3116 /// above sequence, and expanded really late in the compilation flow, to ensure
3117 /// the sequence is produced as per above.
3118 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr, SDLoc DL,
3119 SelectionDAG &DAG) const {
3120 EVT PtrVT = getPointerTy();
3122 SDValue Chain = DAG.getEntryNode();
3123 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3125 SmallVector<SDValue, 2> Ops;
3126 Ops.push_back(Chain);
3127 Ops.push_back(SymAddr);
3129 Chain = DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, Ops);
3130 SDValue Glue = Chain.getValue(1);
3132 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
3136 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
3137 SelectionDAG &DAG) const {
3138 assert(Subtarget->isTargetELF() && "This function expects an ELF target");
3139 assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
3140 "ELF TLS only supported in small memory model");
3141 // Different choices can be made for the maximum size of the TLS area for a
3142 // module. For the small address model, the default TLS size is 16MiB and the
3143 // maximum TLS size is 4GiB.
3144 // FIXME: add -mtls-size command line option and make it control the 16MiB
3145 // vs. 4GiB code sequence generation.
3146 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3148 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
3149 if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
3150 if (Model == TLSModel::LocalDynamic)
3151 Model = TLSModel::GeneralDynamic;
3155 EVT PtrVT = getPointerTy();
3157 const GlobalValue *GV = GA->getGlobal();
3159 SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
3161 if (Model == TLSModel::LocalExec) {
3162 SDValue HiVar = DAG.getTargetGlobalAddress(
3163 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
3164 SDValue LoVar = DAG.getTargetGlobalAddress(
3166 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3168 SDValue TPWithOff_lo =
3169 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
3171 DAG.getTargetConstant(0, DL, MVT::i32)),
3174 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
3176 DAG.getTargetConstant(0, DL, MVT::i32)),
3179 } else if (Model == TLSModel::InitialExec) {
3180 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3181 TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
3182 } else if (Model == TLSModel::LocalDynamic) {
3183 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
3184 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
3185 // the beginning of the module's TLS region, followed by a DTPREL offset
3188 // These accesses will need deduplicating if there's more than one.
3189 AArch64FunctionInfo *MFI =
3190 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
3191 MFI->incNumLocalDynamicTLSAccesses();
3193 // The call needs a relocation too for linker relaxation. It doesn't make
3194 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3196 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
3199 // Now we can calculate the offset from TPIDR_EL0 to this module's
3200 // thread-local area.
3201 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
3203 // Now use :dtprel_whatever: operations to calculate this variable's offset
3204 // in its thread-storage area.
3205 SDValue HiVar = DAG.getTargetGlobalAddress(
3206 GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
3207 SDValue LoVar = DAG.getTargetGlobalAddress(
3208 GV, DL, MVT::i64, 0,
3209 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3211 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
3212 DAG.getTargetConstant(0, DL, MVT::i32)),
3214 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
3215 DAG.getTargetConstant(0, DL, MVT::i32)),
3217 } else if (Model == TLSModel::GeneralDynamic) {
3218 // The call needs a relocation too for linker relaxation. It doesn't make
3219 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3222 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3224 // Finally we can make a call to calculate the offset from tpidr_el0.
3225 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
3227 llvm_unreachable("Unsupported ELF TLS access model");
3229 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
3232 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
3233 SelectionDAG &DAG) const {
3234 if (Subtarget->isTargetDarwin())
3235 return LowerDarwinGlobalTLSAddress(Op, DAG);
3236 else if (Subtarget->isTargetELF())
3237 return LowerELFGlobalTLSAddress(Op, DAG);
3239 llvm_unreachable("Unexpected platform trying to use TLS");
3241 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3242 SDValue Chain = Op.getOperand(0);
3243 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3244 SDValue LHS = Op.getOperand(2);
3245 SDValue RHS = Op.getOperand(3);
3246 SDValue Dest = Op.getOperand(4);
3249 // Handle f128 first, since lowering it will result in comparing the return
3250 // value of a libcall against zero, which is just what the rest of LowerBR_CC
3251 // is expecting to deal with.
3252 if (LHS.getValueType() == MVT::f128) {
3253 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3255 // If softenSetCCOperands returned a scalar, we need to compare the result
3256 // against zero to select between true and false values.
3257 if (!RHS.getNode()) {
3258 RHS = DAG.getConstant(0, dl, LHS.getValueType());
3263 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
3265 unsigned Opc = LHS.getOpcode();
3266 if (LHS.getResNo() == 1 && isa<ConstantSDNode>(RHS) &&
3267 cast<ConstantSDNode>(RHS)->isOne() &&
3268 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3269 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
3270 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
3271 "Unexpected condition code.");
3272 // Only lower legal XALUO ops.
3273 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
3276 // The actual operation with overflow check.
3277 AArch64CC::CondCode OFCC;
3278 SDValue Value, Overflow;
3279 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
3281 if (CC == ISD::SETNE)
3282 OFCC = getInvertedCondCode(OFCC);
3283 SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
3285 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3289 if (LHS.getValueType().isInteger()) {
3290 assert((LHS.getValueType() == RHS.getValueType()) &&
3291 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3293 // If the RHS of the comparison is zero, we can potentially fold this
3294 // to a specialized branch.
3295 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
3296 if (RHSC && RHSC->getZExtValue() == 0) {
3297 if (CC == ISD::SETEQ) {
3298 // See if we can use a TBZ to fold in an AND as well.
3299 // TBZ has a smaller branch displacement than CBZ. If the offset is
3300 // out of bounds, a late MI-layer pass rewrites branches.
3301 // 403.gcc is an example that hits this case.
3302 if (LHS.getOpcode() == ISD::AND &&
3303 isa<ConstantSDNode>(LHS.getOperand(1)) &&
3304 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3305 SDValue Test = LHS.getOperand(0);
3306 uint64_t Mask = LHS.getConstantOperandVal(1);
3307 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
3308 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3312 return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
3313 } else if (CC == ISD::SETNE) {
3314 // See if we can use a TBZ to fold in an AND as well.
3315 // TBZ has a smaller branch displacement than CBZ. If the offset is
3316 // out of bounds, a late MI-layer pass rewrites branches.
3317 // 403.gcc is an example that hits this case.
3318 if (LHS.getOpcode() == ISD::AND &&
3319 isa<ConstantSDNode>(LHS.getOperand(1)) &&
3320 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3321 SDValue Test = LHS.getOperand(0);
3322 uint64_t Mask = LHS.getConstantOperandVal(1);
3323 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
3324 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3328 return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
3329 } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
3330 // Don't combine AND since emitComparison converts the AND to an ANDS
3331 // (a.k.a. TST) and the test in the test bit and branch instruction
3332 // becomes redundant. This would also increase register pressure.
3333 uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
3334 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
3335 DAG.getConstant(Mask, dl, MVT::i64), Dest);
3338 if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
3339 LHS.getOpcode() != ISD::AND) {
3340 // Don't combine AND since emitComparison converts the AND to an ANDS
3341 // (a.k.a. TST) and the test in the test bit and branch instruction
3342 // becomes redundant. This would also increase register pressure.
3343 uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
3344 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
3345 DAG.getConstant(Mask, dl, MVT::i64), Dest);
3349 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3350 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3354 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3356 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
3357 // clean. Some of them require two branches to implement.
3358 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3359 AArch64CC::CondCode CC1, CC2;
3360 changeFPCCToAArch64CC(CC, CC1, CC2);
3361 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3363 DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
3364 if (CC2 != AArch64CC::AL) {
3365 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
3366 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
3373 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
3374 SelectionDAG &DAG) const {
3375 EVT VT = Op.getValueType();
3378 SDValue In1 = Op.getOperand(0);
3379 SDValue In2 = Op.getOperand(1);
3380 EVT SrcVT = In2.getValueType();
3382 if (SrcVT == MVT::f32 && VT == MVT::f64)
3383 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
3384 else if (SrcVT == MVT::f64 && VT == MVT::f32)
3385 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2,
3386 DAG.getIntPtrConstant(0, DL));
3388 // FIXME: Src type is different, bail out for now. Can VT really be a
3396 SDValue VecVal1, VecVal2;
3397 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
3400 EltMask = 0x80000000ULL;
3402 if (!VT.isVector()) {
3403 VecVal1 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3404 DAG.getUNDEF(VecVT), In1);
3405 VecVal2 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3406 DAG.getUNDEF(VecVT), In2);
3408 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3409 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3411 } else if (VT == MVT::f64 || VT == MVT::v2f64) {
3415 // We want to materialize a mask with the the high bit set, but the AdvSIMD
3416 // immediate moves cannot materialize that in a single instruction for
3417 // 64-bit elements. Instead, materialize zero and then negate it.
3420 if (!VT.isVector()) {
3421 VecVal1 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3422 DAG.getUNDEF(VecVT), In1);
3423 VecVal2 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3424 DAG.getUNDEF(VecVT), In2);
3426 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3427 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3430 llvm_unreachable("Invalid type for copysign!");
3433 SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
3435 // If we couldn't materialize the mask above, then the mask vector will be
3436 // the zero vector, and we need to negate it here.
3437 if (VT == MVT::f64 || VT == MVT::v2f64) {
3438 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
3439 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
3440 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
3444 DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
3447 return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
3448 else if (VT == MVT::f64)
3449 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
3451 return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
3454 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
3455 if (DAG.getMachineFunction().getFunction()->hasFnAttribute(
3456 Attribute::NoImplicitFloat))
3459 if (!Subtarget->hasNEON())
3462 // While there is no integer popcount instruction, it can
3463 // be more efficiently lowered to the following sequence that uses
3464 // AdvSIMD registers/instructions as long as the copies to/from
3465 // the AdvSIMD registers are cheap.
3466 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd
3467 // CNT V0.8B, V0.8B // 8xbyte pop-counts
3468 // ADDV B0, V0.8B // sum 8xbyte pop-counts
3469 // UMOV X0, V0.B[0] // copy byte result back to integer reg
3470 SDValue Val = Op.getOperand(0);
3472 EVT VT = Op.getValueType();
3475 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
3476 Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
3478 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
3479 SDValue UaddLV = DAG.getNode(
3480 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
3481 DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
3484 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
3488 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3490 if (Op.getValueType().isVector())
3491 return LowerVSETCC(Op, DAG);
3493 SDValue LHS = Op.getOperand(0);
3494 SDValue RHS = Op.getOperand(1);
3495 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3498 // We chose ZeroOrOneBooleanContents, so use zero and one.
3499 EVT VT = Op.getValueType();
3500 SDValue TVal = DAG.getConstant(1, dl, VT);
3501 SDValue FVal = DAG.getConstant(0, dl, VT);
3503 // Handle f128 first, since one possible outcome is a normal integer
3504 // comparison which gets picked up by the next if statement.
3505 if (LHS.getValueType() == MVT::f128) {
3506 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3508 // If softenSetCCOperands returned a scalar, use it.
3509 if (!RHS.getNode()) {
3510 assert(LHS.getValueType() == Op.getValueType() &&
3511 "Unexpected setcc expansion!");
3516 if (LHS.getValueType().isInteger()) {
3519 getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
3521 // Note that we inverted the condition above, so we reverse the order of
3522 // the true and false operands here. This will allow the setcc to be
3523 // matched to a single CSINC instruction.
3524 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
3527 // Now we know we're dealing with FP values.
3528 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3530 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
3531 // and do the comparison.
3532 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3534 AArch64CC::CondCode CC1, CC2;
3535 changeFPCCToAArch64CC(CC, CC1, CC2);
3536 if (CC2 == AArch64CC::AL) {
3537 changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
3538 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3540 // Note that we inverted the condition above, so we reverse the order of
3541 // the true and false operands here. This will allow the setcc to be
3542 // matched to a single CSINC instruction.
3543 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
3545 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
3546 // totally clean. Some of them require two CSELs to implement. As is in
3547 // this case, we emit the first CSEL and then emit a second using the output
3548 // of the first as the RHS. We're effectively OR'ing the two CC's together.
3550 // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
3551 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3553 DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3555 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
3556 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3560 /// A SELECT_CC operation is really some kind of max or min if both values being
3561 /// compared are, in some sense, equal to the results in either case. However,
3562 /// it is permissible to compare f32 values and produce directly extended f64
3565 /// Extending the comparison operands would also be allowed, but is less likely
3566 /// to happen in practice since their use is right here. Note that truncate
3567 /// operations would *not* be semantically equivalent.
3568 static bool selectCCOpsAreFMaxCompatible(SDValue Cmp, SDValue Result) {
3572 ConstantFPSDNode *CCmp = dyn_cast<ConstantFPSDNode>(Cmp);
3573 ConstantFPSDNode *CResult = dyn_cast<ConstantFPSDNode>(Result);
3574 if (CCmp && CResult && Cmp.getValueType() == MVT::f32 &&
3575 Result.getValueType() == MVT::f64) {
3577 APFloat CmpVal = CCmp->getValueAPF();
3578 CmpVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &Lossy);
3579 return CResult->getValueAPF().bitwiseIsEqual(CmpVal);
3582 return Result->getOpcode() == ISD::FP_EXTEND && Result->getOperand(0) == Cmp;
3585 SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
3586 SDValue RHS, SDValue TVal,
3587 SDValue FVal, SDLoc dl,
3588 SelectionDAG &DAG) const {
3589 // Handle f128 first, because it will result in a comparison of some RTLIB
3590 // call result against zero.
3591 if (LHS.getValueType() == MVT::f128) {
3592 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3594 // If softenSetCCOperands returned a scalar, we need to compare the result
3595 // against zero to select between true and false values.
3596 if (!RHS.getNode()) {
3597 RHS = DAG.getConstant(0, dl, LHS.getValueType());
3602 // Handle integers first.
3603 if (LHS.getValueType().isInteger()) {
3604 assert((LHS.getValueType() == RHS.getValueType()) &&
3605 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3607 unsigned Opcode = AArch64ISD::CSEL;
3609 // If both the TVal and the FVal are constants, see if we can swap them in
3610 // order to for a CSINV or CSINC out of them.
3611 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
3612 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
3614 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
3615 std::swap(TVal, FVal);
3616 std::swap(CTVal, CFVal);
3617 CC = ISD::getSetCCInverse(CC, true);
3618 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
3619 std::swap(TVal, FVal);
3620 std::swap(CTVal, CFVal);
3621 CC = ISD::getSetCCInverse(CC, true);
3622 } else if (TVal.getOpcode() == ISD::XOR) {
3623 // If TVal is a NOT we want to swap TVal and FVal so that we can match
3624 // with a CSINV rather than a CSEL.
3625 ConstantSDNode *CVal = dyn_cast<ConstantSDNode>(TVal.getOperand(1));
3627 if (CVal && CVal->isAllOnesValue()) {
3628 std::swap(TVal, FVal);
3629 std::swap(CTVal, CFVal);
3630 CC = ISD::getSetCCInverse(CC, true);
3632 } else if (TVal.getOpcode() == ISD::SUB) {
3633 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
3634 // that we can match with a CSNEG rather than a CSEL.
3635 ConstantSDNode *CVal = dyn_cast<ConstantSDNode>(TVal.getOperand(0));
3637 if (CVal && CVal->isNullValue()) {
3638 std::swap(TVal, FVal);
3639 std::swap(CTVal, CFVal);
3640 CC = ISD::getSetCCInverse(CC, true);
3642 } else if (CTVal && CFVal) {
3643 const int64_t TrueVal = CTVal->getSExtValue();
3644 const int64_t FalseVal = CFVal->getSExtValue();
3647 // If both TVal and FVal are constants, see if FVal is the
3648 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
3649 // instead of a CSEL in that case.
3650 if (TrueVal == ~FalseVal) {
3651 Opcode = AArch64ISD::CSINV;
3652 } else if (TrueVal == -FalseVal) {
3653 Opcode = AArch64ISD::CSNEG;
3654 } else if (TVal.getValueType() == MVT::i32) {
3655 // If our operands are only 32-bit wide, make sure we use 32-bit
3656 // arithmetic for the check whether we can use CSINC. This ensures that
3657 // the addition in the check will wrap around properly in case there is
3658 // an overflow (which would not be the case if we do the check with
3659 // 64-bit arithmetic).
3660 const uint32_t TrueVal32 = CTVal->getZExtValue();
3661 const uint32_t FalseVal32 = CFVal->getZExtValue();
3663 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
3664 Opcode = AArch64ISD::CSINC;
3666 if (TrueVal32 > FalseVal32) {
3670 // 64-bit check whether we can use CSINC.
3671 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
3672 Opcode = AArch64ISD::CSINC;
3674 if (TrueVal > FalseVal) {
3679 // Swap TVal and FVal if necessary.
3681 std::swap(TVal, FVal);
3682 std::swap(CTVal, CFVal);
3683 CC = ISD::getSetCCInverse(CC, true);
3686 if (Opcode != AArch64ISD::CSEL) {
3687 // Drop FVal since we can get its value by simply inverting/negating
3694 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3696 EVT VT = TVal.getValueType();
3697 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
3700 // Now we know we're dealing with FP values.
3701 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3702 assert(LHS.getValueType() == RHS.getValueType());
3703 EVT VT = TVal.getValueType();
3705 // Try to match this select into a max/min operation, which have dedicated
3706 // opcode in the instruction set.
3707 // FIXME: This is not correct in the presence of NaNs, so we only enable this
3709 if (getTargetMachine().Options.NoNaNsFPMath) {
3710 SDValue MinMaxLHS = TVal, MinMaxRHS = FVal;
3711 if (selectCCOpsAreFMaxCompatible(LHS, MinMaxRHS) &&
3712 selectCCOpsAreFMaxCompatible(RHS, MinMaxLHS)) {
3713 CC = ISD::getSetCCSwappedOperands(CC);
3714 std::swap(MinMaxLHS, MinMaxRHS);
3717 if (selectCCOpsAreFMaxCompatible(LHS, MinMaxLHS) &&
3718 selectCCOpsAreFMaxCompatible(RHS, MinMaxRHS)) {
3728 return DAG.getNode(AArch64ISD::FMAX, dl, VT, MinMaxLHS, MinMaxRHS);
3736 return DAG.getNode(AArch64ISD::FMIN, dl, VT, MinMaxLHS, MinMaxRHS);
3742 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
3743 // and do the comparison.
3744 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3746 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
3747 // clean. Some of them require two CSELs to implement.
3748 AArch64CC::CondCode CC1, CC2;
3749 changeFPCCToAArch64CC(CC, CC1, CC2);
3750 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3751 SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3753 // If we need a second CSEL, emit it, using the output of the first as the
3754 // RHS. We're effectively OR'ing the two CC's together.
3755 if (CC2 != AArch64CC::AL) {
3756 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
3757 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3760 // Otherwise, return the output of the first CSEL.
3764 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
3765 SelectionDAG &DAG) const {
3766 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3767 SDValue LHS = Op.getOperand(0);
3768 SDValue RHS = Op.getOperand(1);
3769 SDValue TVal = Op.getOperand(2);
3770 SDValue FVal = Op.getOperand(3);
3772 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
3775 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
3776 SelectionDAG &DAG) const {
3777 SDValue CCVal = Op->getOperand(0);
3778 SDValue TVal = Op->getOperand(1);
3779 SDValue FVal = Op->getOperand(2);
3782 unsigned Opc = CCVal.getOpcode();
3783 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
3785 if (CCVal.getResNo() == 1 &&
3786 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3787 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
3788 // Only lower legal XALUO ops.
3789 if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
3792 AArch64CC::CondCode OFCC;
3793 SDValue Value, Overflow;
3794 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
3795 SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
3797 return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
3801 // Lower it the same way as we would lower a SELECT_CC node.
3804 if (CCVal.getOpcode() == ISD::SETCC) {
3805 LHS = CCVal.getOperand(0);
3806 RHS = CCVal.getOperand(1);
3807 CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
3810 RHS = DAG.getConstant(0, DL, CCVal.getValueType());
3813 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
3816 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
3817 SelectionDAG &DAG) const {
3818 // Jump table entries as PC relative offsets. No additional tweaking
3819 // is necessary here. Just get the address of the jump table.
3820 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
3821 EVT PtrVT = getPointerTy();
3824 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3825 !Subtarget->isTargetMachO()) {
3826 const unsigned char MO_NC = AArch64II::MO_NC;
3828 AArch64ISD::WrapperLarge, DL, PtrVT,
3829 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G3),
3830 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G2 | MO_NC),
3831 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G1 | MO_NC),
3832 DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
3833 AArch64II::MO_G0 | MO_NC));
3837 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_PAGE);
3838 SDValue Lo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
3839 AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3840 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3841 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3844 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
3845 SelectionDAG &DAG) const {
3846 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3847 EVT PtrVT = getPointerTy();
3850 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
3851 // Use the GOT for the large code model on iOS.
3852 if (Subtarget->isTargetMachO()) {
3853 SDValue GotAddr = DAG.getTargetConstantPool(
3854 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
3856 return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
3859 const unsigned char MO_NC = AArch64II::MO_NC;
3861 AArch64ISD::WrapperLarge, DL, PtrVT,
3862 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3863 CP->getOffset(), AArch64II::MO_G3),
3864 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3865 CP->getOffset(), AArch64II::MO_G2 | MO_NC),
3866 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3867 CP->getOffset(), AArch64II::MO_G1 | MO_NC),
3868 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3869 CP->getOffset(), AArch64II::MO_G0 | MO_NC));
3871 // Use ADRP/ADD or ADRP/LDR for everything else: the small memory model on
3872 // ELF, the only valid one on Darwin.
3874 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3875 CP->getOffset(), AArch64II::MO_PAGE);
3876 SDValue Lo = DAG.getTargetConstantPool(
3877 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
3878 AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3880 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3881 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3885 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
3886 SelectionDAG &DAG) const {
3887 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
3888 EVT PtrVT = getPointerTy();
3890 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3891 !Subtarget->isTargetMachO()) {
3892 const unsigned char MO_NC = AArch64II::MO_NC;
3894 AArch64ISD::WrapperLarge, DL, PtrVT,
3895 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G3),
3896 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
3897 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
3898 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
3900 SDValue Hi = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGE);
3901 SDValue Lo = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGEOFF |
3903 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3904 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3908 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
3909 SelectionDAG &DAG) const {
3910 AArch64FunctionInfo *FuncInfo =
3911 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
3915 DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), getPointerTy());
3916 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3917 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
3918 MachinePointerInfo(SV), false, false, 0);
3921 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
3922 SelectionDAG &DAG) const {
3923 // The layout of the va_list struct is specified in the AArch64 Procedure Call
3924 // Standard, section B.3.
3925 MachineFunction &MF = DAG.getMachineFunction();
3926 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3929 SDValue Chain = Op.getOperand(0);
3930 SDValue VAList = Op.getOperand(1);
3931 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3932 SmallVector<SDValue, 4> MemOps;
3934 // void *__stack at offset 0
3936 DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), getPointerTy());
3937 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
3938 MachinePointerInfo(SV), false, false, 8));
3940 // void *__gr_top at offset 8
3941 int GPRSize = FuncInfo->getVarArgsGPRSize();
3943 SDValue GRTop, GRTopAddr;
3945 GRTopAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3946 DAG.getConstant(8, DL, getPointerTy()));
3948 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), getPointerTy());
3949 GRTop = DAG.getNode(ISD::ADD, DL, getPointerTy(), GRTop,
3950 DAG.getConstant(GPRSize, DL, getPointerTy()));
3952 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
3953 MachinePointerInfo(SV, 8), false, false, 8));
3956 // void *__vr_top at offset 16
3957 int FPRSize = FuncInfo->getVarArgsFPRSize();
3959 SDValue VRTop, VRTopAddr;
3960 VRTopAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3961 DAG.getConstant(16, DL, getPointerTy()));
3963 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), getPointerTy());
3964 VRTop = DAG.getNode(ISD::ADD, DL, getPointerTy(), VRTop,
3965 DAG.getConstant(FPRSize, DL, getPointerTy()));
3967 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
3968 MachinePointerInfo(SV, 16), false, false, 8));
3971 // int __gr_offs at offset 24
3972 SDValue GROffsAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3973 DAG.getConstant(24, DL, getPointerTy()));
3974 MemOps.push_back(DAG.getStore(Chain, DL,
3975 DAG.getConstant(-GPRSize, DL, MVT::i32),
3976 GROffsAddr, MachinePointerInfo(SV, 24), false,
3979 // int __vr_offs at offset 28
3980 SDValue VROffsAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3981 DAG.getConstant(28, DL, getPointerTy()));
3982 MemOps.push_back(DAG.getStore(Chain, DL,
3983 DAG.getConstant(-FPRSize, DL, MVT::i32),
3984 VROffsAddr, MachinePointerInfo(SV, 28), false,
3987 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
3990 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
3991 SelectionDAG &DAG) const {
3992 return Subtarget->isTargetDarwin() ? LowerDarwin_VASTART(Op, DAG)
3993 : LowerAAPCS_VASTART(Op, DAG);
3996 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
3997 SelectionDAG &DAG) const {
3998 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
4001 unsigned VaListSize = Subtarget->isTargetDarwin() ? 8 : 32;
4002 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4003 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4005 return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1),
4007 DAG.getConstant(VaListSize, DL, MVT::i32),
4008 8, false, false, false, MachinePointerInfo(DestSV),
4009 MachinePointerInfo(SrcSV));
4012 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
4013 assert(Subtarget->isTargetDarwin() &&
4014 "automatic va_arg instruction only works on Darwin");
4016 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4017 EVT VT = Op.getValueType();
4019 SDValue Chain = Op.getOperand(0);
4020 SDValue Addr = Op.getOperand(1);
4021 unsigned Align = Op.getConstantOperandVal(3);
4023 SDValue VAList = DAG.getLoad(getPointerTy(), DL, Chain, Addr,
4024 MachinePointerInfo(V), false, false, false, 0);
4025 Chain = VAList.getValue(1);
4028 assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
4029 VAList = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
4030 DAG.getConstant(Align - 1, DL, getPointerTy()));
4031 VAList = DAG.getNode(ISD::AND, DL, getPointerTy(), VAList,
4032 DAG.getConstant(-(int64_t)Align, DL, getPointerTy()));
4035 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
4036 uint64_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
4038 // Scalar integer and FP values smaller than 64 bits are implicitly extended
4039 // up to 64 bits. At the very least, we have to increase the striding of the
4040 // vaargs list to match this, and for FP values we need to introduce
4041 // FP_ROUND nodes as well.
4042 if (VT.isInteger() && !VT.isVector())
4044 bool NeedFPTrunc = false;
4045 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
4050 // Increment the pointer, VAList, to the next vaarg
4051 SDValue VANext = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
4052 DAG.getConstant(ArgSize, DL, getPointerTy()));
4053 // Store the incremented VAList to the legalized pointer
4054 SDValue APStore = DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V),
4057 // Load the actual argument out of the pointer VAList
4059 // Load the value as an f64.
4060 SDValue WideFP = DAG.getLoad(MVT::f64, DL, APStore, VAList,
4061 MachinePointerInfo(), false, false, false, 0);
4062 // Round the value down to an f32.
4063 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
4064 DAG.getIntPtrConstant(1, DL));
4065 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
4066 // Merge the rounded value with the chain output of the load.
4067 return DAG.getMergeValues(Ops, DL);
4070 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo(), false,
4074 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
4075 SelectionDAG &DAG) const {
4076 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4077 MFI->setFrameAddressIsTaken(true);
4079 EVT VT = Op.getValueType();
4081 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4083 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
4085 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
4086 MachinePointerInfo(), false, false, false, 0);
4090 // FIXME? Maybe this could be a TableGen attribute on some registers and
4091 // this table could be generated automatically from RegInfo.
4092 unsigned AArch64TargetLowering::getRegisterByName(const char* RegName,
4094 unsigned Reg = StringSwitch<unsigned>(RegName)
4095 .Case("sp", AArch64::SP)
4099 report_fatal_error("Invalid register name global variable");
4102 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
4103 SelectionDAG &DAG) const {
4104 MachineFunction &MF = DAG.getMachineFunction();
4105 MachineFrameInfo *MFI = MF.getFrameInfo();
4106 MFI->setReturnAddressIsTaken(true);
4108 EVT VT = Op.getValueType();
4110 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4112 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4113 SDValue Offset = DAG.getConstant(8, DL, getPointerTy());
4114 return DAG.getLoad(VT, DL, DAG.getEntryNode(),
4115 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
4116 MachinePointerInfo(), false, false, false, 0);
4119 // Return LR, which contains the return address. Mark it an implicit live-in.
4120 unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
4121 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4124 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4125 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
4126 SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
4127 SelectionDAG &DAG) const {
4128 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4129 EVT VT = Op.getValueType();
4130 unsigned VTBits = VT.getSizeInBits();
4132 SDValue ShOpLo = Op.getOperand(0);
4133 SDValue ShOpHi = Op.getOperand(1);
4134 SDValue ShAmt = Op.getOperand(2);
4136 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4138 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4140 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
4141 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
4142 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4143 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
4144 DAG.getConstant(VTBits, dl, MVT::i64));
4145 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4147 SDValue Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64),
4148 ISD::SETGE, dl, DAG);
4149 SDValue CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4151 SDValue FalseValLo = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4152 SDValue TrueValLo = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4154 DAG.getNode(AArch64ISD::CSEL, dl, VT, TrueValLo, FalseValLo, CCVal, Cmp);
4156 // AArch64 shifts larger than the register width are wrapped rather than
4157 // clamped, so we can't just emit "hi >> x".
4158 SDValue FalseValHi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4159 SDValue TrueValHi = Opc == ISD::SRA
4160 ? DAG.getNode(Opc, dl, VT, ShOpHi,
4161 DAG.getConstant(VTBits - 1, dl,
4163 : DAG.getConstant(0, dl, VT);
4165 DAG.getNode(AArch64ISD::CSEL, dl, VT, TrueValHi, FalseValHi, CCVal, Cmp);
4167 SDValue Ops[2] = { Lo, Hi };
4168 return DAG.getMergeValues(Ops, dl);
4171 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4172 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
4173 SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
4174 SelectionDAG &DAG) const {
4175 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4176 EVT VT = Op.getValueType();
4177 unsigned VTBits = VT.getSizeInBits();
4179 SDValue ShOpLo = Op.getOperand(0);
4180 SDValue ShOpHi = Op.getOperand(1);
4181 SDValue ShAmt = Op.getOperand(2);
4184 assert(Op.getOpcode() == ISD::SHL_PARTS);
4185 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
4186 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
4187 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4188 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
4189 DAG.getConstant(VTBits, dl, MVT::i64));
4190 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4191 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4193 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4195 SDValue Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64),
4196 ISD::SETGE, dl, DAG);
4197 SDValue CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4199 DAG.getNode(AArch64ISD::CSEL, dl, VT, Tmp3, FalseVal, CCVal, Cmp);
4201 // AArch64 shifts of larger than register sizes are wrapped rather than
4202 // clamped, so we can't just emit "lo << a" if a is too big.
4203 SDValue TrueValLo = DAG.getConstant(0, dl, VT);
4204 SDValue FalseValLo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4206 DAG.getNode(AArch64ISD::CSEL, dl, VT, TrueValLo, FalseValLo, CCVal, Cmp);
4208 SDValue Ops[2] = { Lo, Hi };
4209 return DAG.getMergeValues(Ops, dl);
4212 bool AArch64TargetLowering::isOffsetFoldingLegal(
4213 const GlobalAddressSDNode *GA) const {
4214 // The AArch64 target doesn't support folding offsets into global addresses.
4218 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4219 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
4220 // FIXME: We should be able to handle f128 as well with a clever lowering.
4221 if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32))
4225 return AArch64_AM::getFP64Imm(Imm) != -1;
4226 else if (VT == MVT::f32)
4227 return AArch64_AM::getFP32Imm(Imm) != -1;
4231 //===----------------------------------------------------------------------===//
4232 // AArch64 Optimization Hooks
4233 //===----------------------------------------------------------------------===//
4235 //===----------------------------------------------------------------------===//
4236 // AArch64 Inline Assembly Support
4237 //===----------------------------------------------------------------------===//
4239 // Table of Constraints
4240 // TODO: This is the current set of constraints supported by ARM for the
4241 // compiler, not all of them may make sense, e.g. S may be difficult to support.
4243 // r - A general register
4244 // w - An FP/SIMD register of some size in the range v0-v31
4245 // x - An FP/SIMD register of some size in the range v0-v15
4246 // I - Constant that can be used with an ADD instruction
4247 // J - Constant that can be used with a SUB instruction
4248 // K - Constant that can be used with a 32-bit logical instruction
4249 // L - Constant that can be used with a 64-bit logical instruction
4250 // M - Constant that can be used as a 32-bit MOV immediate
4251 // N - Constant that can be used as a 64-bit MOV immediate
4252 // Q - A memory reference with base register and no offset
4253 // S - A symbolic address
4254 // Y - Floating point constant zero
4255 // Z - Integer constant zero
4257 // Note that general register operands will be output using their 64-bit x
4258 // register name, whatever the size of the variable, unless the asm operand
4259 // is prefixed by the %w modifier. Floating-point and SIMD register operands
4260 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
4263 /// getConstraintType - Given a constraint letter, return the type of
4264 /// constraint it is for this target.
4265 AArch64TargetLowering::ConstraintType
4266 AArch64TargetLowering::getConstraintType(const std::string &Constraint) const {
4267 if (Constraint.size() == 1) {
4268 switch (Constraint[0]) {
4275 return C_RegisterClass;
4276 // An address with a single base register. Due to the way we
4277 // currently handle addresses it is the same as 'r'.
4282 return TargetLowering::getConstraintType(Constraint);
4285 /// Examine constraint type and operand type and determine a weight value.
4286 /// This object must already have been set up with the operand type
4287 /// and the current alternative constraint selected.
4288 TargetLowering::ConstraintWeight
4289 AArch64TargetLowering::getSingleConstraintMatchWeight(
4290 AsmOperandInfo &info, const char *constraint) const {
4291 ConstraintWeight weight = CW_Invalid;
4292 Value *CallOperandVal = info.CallOperandVal;
4293 // If we don't have a value, we can't do a match,
4294 // but allow it at the lowest weight.
4295 if (!CallOperandVal)
4297 Type *type = CallOperandVal->getType();
4298 // Look at the constraint type.
4299 switch (*constraint) {
4301 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
4305 if (type->isFloatingPointTy() || type->isVectorTy())
4306 weight = CW_Register;
4309 weight = CW_Constant;
4315 std::pair<unsigned, const TargetRegisterClass *>
4316 AArch64TargetLowering::getRegForInlineAsmConstraint(
4317 const TargetRegisterInfo *TRI, const std::string &Constraint,
4319 if (Constraint.size() == 1) {
4320 switch (Constraint[0]) {
4322 if (VT.getSizeInBits() == 64)
4323 return std::make_pair(0U, &AArch64::GPR64commonRegClass);
4324 return std::make_pair(0U, &AArch64::GPR32commonRegClass);
4327 return std::make_pair(0U, &AArch64::FPR32RegClass);
4328 if (VT.getSizeInBits() == 64)
4329 return std::make_pair(0U, &AArch64::FPR64RegClass);
4330 if (VT.getSizeInBits() == 128)
4331 return std::make_pair(0U, &AArch64::FPR128RegClass);
4333 // The instructions that this constraint is designed for can
4334 // only take 128-bit registers so just use that regclass.
4336 if (VT.getSizeInBits() == 128)
4337 return std::make_pair(0U, &AArch64::FPR128_loRegClass);
4341 if (StringRef("{cc}").equals_lower(Constraint))
4342 return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
4344 // Use the default implementation in TargetLowering to convert the register
4345 // constraint into a member of a register class.
4346 std::pair<unsigned, const TargetRegisterClass *> Res;
4347 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
4349 // Not found as a standard register?
4351 unsigned Size = Constraint.size();
4352 if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
4353 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
4354 const std::string Reg =
4355 std::string(&Constraint[2], &Constraint[Size - 1]);
4356 int RegNo = atoi(Reg.c_str());
4357 if (RegNo >= 0 && RegNo <= 31) {
4358 // v0 - v31 are aliases of q0 - q31.
4359 // By default we'll emit v0-v31 for this unless there's a modifier where
4360 // we'll emit the correct register as well.
4361 Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
4362 Res.second = &AArch64::FPR128RegClass;
4370 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
4371 /// vector. If it is invalid, don't add anything to Ops.
4372 void AArch64TargetLowering::LowerAsmOperandForConstraint(
4373 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
4374 SelectionDAG &DAG) const {
4377 // Currently only support length 1 constraints.
4378 if (Constraint.length() != 1)
4381 char ConstraintLetter = Constraint[0];
4382 switch (ConstraintLetter) {
4386 // This set of constraints deal with valid constants for various instructions.
4387 // Validate and return a target constant for them if we can.
4389 // 'z' maps to xzr or wzr so it needs an input of 0.
4390 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4391 if (!C || C->getZExtValue() != 0)
4394 if (Op.getValueType() == MVT::i64)
4395 Result = DAG.getRegister(AArch64::XZR, MVT::i64);
4397 Result = DAG.getRegister(AArch64::WZR, MVT::i32);
4407 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4411 // Grab the value and do some validation.
4412 uint64_t CVal = C->getZExtValue();
4413 switch (ConstraintLetter) {
4414 // The I constraint applies only to simple ADD or SUB immediate operands:
4415 // i.e. 0 to 4095 with optional shift by 12
4416 // The J constraint applies only to ADD or SUB immediates that would be
4417 // valid when negated, i.e. if [an add pattern] were to be output as a SUB
4418 // instruction [or vice versa], in other words -1 to -4095 with optional
4419 // left shift by 12.
4421 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
4425 uint64_t NVal = -C->getSExtValue();
4426 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
4427 CVal = C->getSExtValue();
4432 // The K and L constraints apply *only* to logical immediates, including
4433 // what used to be the MOVI alias for ORR (though the MOVI alias has now
4434 // been removed and MOV should be used). So these constraints have to
4435 // distinguish between bit patterns that are valid 32-bit or 64-bit
4436 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
4437 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
4440 if (AArch64_AM::isLogicalImmediate(CVal, 32))
4444 if (AArch64_AM::isLogicalImmediate(CVal, 64))
4447 // The M and N constraints are a superset of K and L respectively, for use
4448 // with the MOV (immediate) alias. As well as the logical immediates they
4449 // also match 32 or 64-bit immediates that can be loaded either using a
4450 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
4451 // (M) or 64-bit 0x1234000000000000 (N) etc.
4452 // As a note some of this code is liberally stolen from the asm parser.
4454 if (!isUInt<32>(CVal))
4456 if (AArch64_AM::isLogicalImmediate(CVal, 32))
4458 if ((CVal & 0xFFFF) == CVal)
4460 if ((CVal & 0xFFFF0000ULL) == CVal)
4462 uint64_t NCVal = ~(uint32_t)CVal;
4463 if ((NCVal & 0xFFFFULL) == NCVal)
4465 if ((NCVal & 0xFFFF0000ULL) == NCVal)
4470 if (AArch64_AM::isLogicalImmediate(CVal, 64))
4472 if ((CVal & 0xFFFFULL) == CVal)
4474 if ((CVal & 0xFFFF0000ULL) == CVal)
4476 if ((CVal & 0xFFFF00000000ULL) == CVal)
4478 if ((CVal & 0xFFFF000000000000ULL) == CVal)
4480 uint64_t NCVal = ~CVal;
4481 if ((NCVal & 0xFFFFULL) == NCVal)
4483 if ((NCVal & 0xFFFF0000ULL) == NCVal)
4485 if ((NCVal & 0xFFFF00000000ULL) == NCVal)
4487 if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
4495 // All assembler immediates are 64-bit integers.
4496 Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
4500 if (Result.getNode()) {
4501 Ops.push_back(Result);
4505 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
4508 //===----------------------------------------------------------------------===//
4509 // AArch64 Advanced SIMD Support
4510 //===----------------------------------------------------------------------===//
4512 /// WidenVector - Given a value in the V64 register class, produce the
4513 /// equivalent value in the V128 register class.
4514 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
4515 EVT VT = V64Reg.getValueType();
4516 unsigned NarrowSize = VT.getVectorNumElements();
4517 MVT EltTy = VT.getVectorElementType().getSimpleVT();
4518 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
4521 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
4522 V64Reg, DAG.getConstant(0, DL, MVT::i32));
4525 /// getExtFactor - Determine the adjustment factor for the position when
4526 /// generating an "extract from vector registers" instruction.
4527 static unsigned getExtFactor(SDValue &V) {
4528 EVT EltType = V.getValueType().getVectorElementType();
4529 return EltType.getSizeInBits() / 8;
4532 /// NarrowVector - Given a value in the V128 register class, produce the
4533 /// equivalent value in the V64 register class.
4534 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
4535 EVT VT = V128Reg.getValueType();
4536 unsigned WideSize = VT.getVectorNumElements();
4537 MVT EltTy = VT.getVectorElementType().getSimpleVT();
4538 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
4541 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
4544 // Gather data to see if the operation can be modelled as a
4545 // shuffle in combination with VEXTs.
4546 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
4547 SelectionDAG &DAG) const {
4548 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
4550 EVT VT = Op.getValueType();
4551 unsigned NumElts = VT.getVectorNumElements();
4553 struct ShuffleSourceInfo {
4558 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
4559 // be compatible with the shuffle we intend to construct. As a result
4560 // ShuffleVec will be some sliding window into the original Vec.
4563 // Code should guarantee that element i in Vec starts at element "WindowBase
4564 // + i * WindowScale in ShuffleVec".
4568 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
4569 ShuffleSourceInfo(SDValue Vec)
4570 : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
4574 // First gather all vectors used as an immediate source for this BUILD_VECTOR
4576 SmallVector<ShuffleSourceInfo, 2> Sources;
4577 for (unsigned i = 0; i < NumElts; ++i) {
4578 SDValue V = Op.getOperand(i);
4579 if (V.getOpcode() == ISD::UNDEF)
4581 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4582 // A shuffle can only come from building a vector from various
4583 // elements of other vectors.
4587 // Add this element source to the list if it's not already there.
4588 SDValue SourceVec = V.getOperand(0);
4589 auto Source = std::find(Sources.begin(), Sources.end(), SourceVec);
4590 if (Source == Sources.end())
4591 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
4593 // Update the minimum and maximum lane number seen.
4594 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4595 Source->MinElt = std::min(Source->MinElt, EltNo);
4596 Source->MaxElt = std::max(Source->MaxElt, EltNo);
4599 // Currently only do something sane when at most two source vectors
4601 if (Sources.size() > 2)
4604 // Find out the smallest element size among result and two sources, and use
4605 // it as element size to build the shuffle_vector.
4606 EVT SmallestEltTy = VT.getVectorElementType();
4607 for (auto &Source : Sources) {
4608 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
4609 if (SrcEltTy.bitsLT(SmallestEltTy)) {
4610 SmallestEltTy = SrcEltTy;
4613 unsigned ResMultiplier =
4614 VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
4615 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
4616 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
4618 // If the source vector is too wide or too narrow, we may nevertheless be able
4619 // to construct a compatible shuffle either by concatenating it with UNDEF or
4620 // extracting a suitable range of elements.
4621 for (auto &Src : Sources) {
4622 EVT SrcVT = Src.ShuffleVec.getValueType();
4624 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
4627 // This stage of the search produces a source with the same element type as
4628 // the original, but with a total width matching the BUILD_VECTOR output.
4629 EVT EltVT = SrcVT.getVectorElementType();
4630 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
4631 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
4633 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
4634 assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
4635 // We can pad out the smaller vector for free, so if it's part of a
4638 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
4639 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
4643 assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
4645 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
4646 // Span too large for a VEXT to cope
4650 if (Src.MinElt >= NumSrcElts) {
4651 // The extraction can just take the second half
4653 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4654 DAG.getConstant(NumSrcElts, dl, MVT::i64));
4655 Src.WindowBase = -NumSrcElts;
4656 } else if (Src.MaxElt < NumSrcElts) {
4657 // The extraction can just take the first half
4659 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4660 DAG.getConstant(0, dl, MVT::i64));
4662 // An actual VEXT is needed
4664 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4665 DAG.getConstant(0, dl, MVT::i64));
4667 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4668 DAG.getConstant(NumSrcElts, dl, MVT::i64));
4669 unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
4671 Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
4673 DAG.getConstant(Imm, dl, MVT::i32));
4674 Src.WindowBase = -Src.MinElt;
4678 // Another possible incompatibility occurs from the vector element types. We
4679 // can fix this by bitcasting the source vectors to the same type we intend
4681 for (auto &Src : Sources) {
4682 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
4683 if (SrcEltTy == SmallestEltTy)
4685 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
4686 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
4687 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
4688 Src.WindowBase *= Src.WindowScale;
4691 // Final sanity check before we try to actually produce a shuffle.
4693 for (auto Src : Sources)
4694 assert(Src.ShuffleVec.getValueType() == ShuffleVT);
4697 // The stars all align, our next step is to produce the mask for the shuffle.
4698 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
4699 int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
4700 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
4701 SDValue Entry = Op.getOperand(i);
4702 if (Entry.getOpcode() == ISD::UNDEF)
4705 auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0));
4706 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
4708 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
4709 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
4711 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
4712 int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
4713 VT.getVectorElementType().getSizeInBits());
4714 int LanesDefined = BitsDefined / BitsPerShuffleLane;
4716 // This source is expected to fill ResMultiplier lanes of the final shuffle,
4717 // starting at the appropriate offset.
4718 int *LaneMask = &Mask[i * ResMultiplier];
4720 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
4721 ExtractBase += NumElts * (Src - Sources.begin());
4722 for (int j = 0; j < LanesDefined; ++j)
4723 LaneMask[j] = ExtractBase + j;
4726 // Final check before we try to produce nonsense...
4727 if (!isShuffleMaskLegal(Mask, ShuffleVT))
4730 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
4731 for (unsigned i = 0; i < Sources.size(); ++i)
4732 ShuffleOps[i] = Sources[i].ShuffleVec;
4734 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
4735 ShuffleOps[1], &Mask[0]);
4736 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
4739 // check if an EXT instruction can handle the shuffle mask when the
4740 // vector sources of the shuffle are the same.
4741 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4742 unsigned NumElts = VT.getVectorNumElements();
4744 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4750 // If this is a VEXT shuffle, the immediate value is the index of the first
4751 // element. The other shuffle indices must be the successive elements after
4753 unsigned ExpectedElt = Imm;
4754 for (unsigned i = 1; i < NumElts; ++i) {
4755 // Increment the expected index. If it wraps around, just follow it
4756 // back to index zero and keep going.
4758 if (ExpectedElt == NumElts)
4762 continue; // ignore UNDEF indices
4763 if (ExpectedElt != static_cast<unsigned>(M[i]))
4770 // check if an EXT instruction can handle the shuffle mask when the
4771 // vector sources of the shuffle are different.
4772 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
4774 // Look for the first non-undef element.
4775 const int *FirstRealElt = std::find_if(M.begin(), M.end(),
4776 [](int Elt) {return Elt >= 0;});
4778 // Benefit form APInt to handle overflow when calculating expected element.
4779 unsigned NumElts = VT.getVectorNumElements();
4780 unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
4781 APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
4782 // The following shuffle indices must be the successive elements after the
4783 // first real element.
4784 const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
4785 [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
4786 if (FirstWrongElt != M.end())
4789 // The index of an EXT is the first element if it is not UNDEF.
4790 // Watch out for the beginning UNDEFs. The EXT index should be the expected
4791 // value of the first element. E.g.
4792 // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
4793 // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
4794 // ExpectedElt is the last mask index plus 1.
4795 Imm = ExpectedElt.getZExtValue();
4797 // There are two difference cases requiring to reverse input vectors.
4798 // For example, for vector <4 x i32> we have the following cases,
4799 // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
4800 // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
4801 // For both cases, we finally use mask <5, 6, 7, 0>, which requires
4802 // to reverse two input vectors.
4811 /// isREVMask - Check if a vector shuffle corresponds to a REV
4812 /// instruction with the specified blocksize. (The order of the elements
4813 /// within each block of the vector is reversed.)
4814 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4815 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
4816 "Only possible block sizes for REV are: 16, 32, 64");
4818 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4822 unsigned NumElts = VT.getVectorNumElements();
4823 unsigned BlockElts = M[0] + 1;
4824 // If the first shuffle index is UNDEF, be optimistic.
4826 BlockElts = BlockSize / EltSz;
4828 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4831 for (unsigned i = 0; i < NumElts; ++i) {
4833 continue; // ignore UNDEF indices
4834 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
4841 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4842 unsigned NumElts = VT.getVectorNumElements();
4843 WhichResult = (M[0] == 0 ? 0 : 1);
4844 unsigned Idx = WhichResult * NumElts / 2;
4845 for (unsigned i = 0; i != NumElts; i += 2) {
4846 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
4847 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
4855 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4856 unsigned NumElts = VT.getVectorNumElements();
4857 WhichResult = (M[0] == 0 ? 0 : 1);
4858 for (unsigned i = 0; i != NumElts; ++i) {
4860 continue; // ignore UNDEF indices
4861 if ((unsigned)M[i] != 2 * i + WhichResult)
4868 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4869 unsigned NumElts = VT.getVectorNumElements();
4870 WhichResult = (M[0] == 0 ? 0 : 1);
4871 for (unsigned i = 0; i < NumElts; i += 2) {
4872 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
4873 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
4879 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
4880 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4881 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4882 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4883 unsigned NumElts = VT.getVectorNumElements();
4884 WhichResult = (M[0] == 0 ? 0 : 1);
4885 unsigned Idx = WhichResult * NumElts / 2;
4886 for (unsigned i = 0; i != NumElts; i += 2) {
4887 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
4888 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
4896 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
4897 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4898 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4899 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4900 unsigned Half = VT.getVectorNumElements() / 2;
4901 WhichResult = (M[0] == 0 ? 0 : 1);
4902 for (unsigned j = 0; j != 2; ++j) {
4903 unsigned Idx = WhichResult;
4904 for (unsigned i = 0; i != Half; ++i) {
4905 int MIdx = M[i + j * Half];
4906 if (MIdx >= 0 && (unsigned)MIdx != Idx)
4915 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
4916 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4917 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4918 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4919 unsigned NumElts = VT.getVectorNumElements();
4920 WhichResult = (M[0] == 0 ? 0 : 1);
4921 for (unsigned i = 0; i < NumElts; i += 2) {
4922 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
4923 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
4929 static bool isINSMask(ArrayRef<int> M, int NumInputElements,
4930 bool &DstIsLeft, int &Anomaly) {
4931 if (M.size() != static_cast<size_t>(NumInputElements))
4934 int NumLHSMatch = 0, NumRHSMatch = 0;
4935 int LastLHSMismatch = -1, LastRHSMismatch = -1;
4937 for (int i = 0; i < NumInputElements; ++i) {
4947 LastLHSMismatch = i;
4949 if (M[i] == i + NumInputElements)
4952 LastRHSMismatch = i;
4955 if (NumLHSMatch == NumInputElements - 1) {
4957 Anomaly = LastLHSMismatch;
4959 } else if (NumRHSMatch == NumInputElements - 1) {
4961 Anomaly = LastRHSMismatch;
4968 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
4969 if (VT.getSizeInBits() != 128)
4972 unsigned NumElts = VT.getVectorNumElements();
4974 for (int I = 0, E = NumElts / 2; I != E; I++) {
4979 int Offset = NumElts / 2;
4980 for (int I = NumElts / 2, E = NumElts; I != E; I++) {
4981 if (Mask[I] != I + SplitLHS * Offset)
4988 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
4990 EVT VT = Op.getValueType();
4991 SDValue V0 = Op.getOperand(0);
4992 SDValue V1 = Op.getOperand(1);
4993 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
4995 if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
4996 VT.getVectorElementType() != V1.getValueType().getVectorElementType())
4999 bool SplitV0 = V0.getValueType().getSizeInBits() == 128;
5001 if (!isConcatMask(Mask, VT, SplitV0))
5004 EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
5005 VT.getVectorNumElements() / 2);
5007 V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
5008 DAG.getConstant(0, DL, MVT::i64));
5010 if (V1.getValueType().getSizeInBits() == 128) {
5011 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
5012 DAG.getConstant(0, DL, MVT::i64));
5014 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
5017 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5018 /// the specified operations to build the shuffle.
5019 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5020 SDValue RHS, SelectionDAG &DAG,
5022 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5023 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
5024 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
5027 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5036 OP_VUZPL, // VUZP, left result
5037 OP_VUZPR, // VUZP, right result
5038 OP_VZIPL, // VZIP, left result
5039 OP_VZIPR, // VZIP, right result
5040 OP_VTRNL, // VTRN, left result
5041 OP_VTRNR // VTRN, right result
5044 if (OpNum == OP_COPY) {
5045 if (LHSID == (1 * 9 + 2) * 9 + 3)
5047 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
5051 SDValue OpLHS, OpRHS;
5052 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5053 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5054 EVT VT = OpLHS.getValueType();
5058 llvm_unreachable("Unknown shuffle opcode!");
5060 // VREV divides the vector in half and swaps within the half.
5061 if (VT.getVectorElementType() == MVT::i32 ||
5062 VT.getVectorElementType() == MVT::f32)
5063 return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
5064 // vrev <4 x i16> -> REV32
5065 if (VT.getVectorElementType() == MVT::i16 ||
5066 VT.getVectorElementType() == MVT::f16)
5067 return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
5068 // vrev <4 x i8> -> REV16
5069 assert(VT.getVectorElementType() == MVT::i8);
5070 return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
5075 EVT EltTy = VT.getVectorElementType();
5077 if (EltTy == MVT::i8)
5078 Opcode = AArch64ISD::DUPLANE8;
5079 else if (EltTy == MVT::i16 || EltTy == MVT::f16)
5080 Opcode = AArch64ISD::DUPLANE16;
5081 else if (EltTy == MVT::i32 || EltTy == MVT::f32)
5082 Opcode = AArch64ISD::DUPLANE32;
5083 else if (EltTy == MVT::i64 || EltTy == MVT::f64)
5084 Opcode = AArch64ISD::DUPLANE64;
5086 llvm_unreachable("Invalid vector element type?");
5088 if (VT.getSizeInBits() == 64)
5089 OpLHS = WidenVector(OpLHS, DAG);
5090 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
5091 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
5096 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
5097 return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
5098 DAG.getConstant(Imm, dl, MVT::i32));
5101 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
5104 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
5107 return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
5110 return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
5113 return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
5116 return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
5121 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
5122 SelectionDAG &DAG) {
5123 // Check to see if we can use the TBL instruction.
5124 SDValue V1 = Op.getOperand(0);
5125 SDValue V2 = Op.getOperand(1);
5128 EVT EltVT = Op.getValueType().getVectorElementType();
5129 unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
5131 SmallVector<SDValue, 8> TBLMask;
5132 for (int Val : ShuffleMask) {
5133 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
5134 unsigned Offset = Byte + Val * BytesPerElt;
5135 TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
5139 MVT IndexVT = MVT::v8i8;
5140 unsigned IndexLen = 8;
5141 if (Op.getValueType().getSizeInBits() == 128) {
5142 IndexVT = MVT::v16i8;
5146 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
5147 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
5150 if (V2.getNode()->getOpcode() == ISD::UNDEF) {
5152 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
5153 Shuffle = DAG.getNode(
5154 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5155 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
5156 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5157 makeArrayRef(TBLMask.data(), IndexLen)));
5159 if (IndexLen == 8) {
5160 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
5161 Shuffle = DAG.getNode(
5162 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5163 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
5164 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5165 makeArrayRef(TBLMask.data(), IndexLen)));
5167 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
5168 // cannot currently represent the register constraints on the input
5170 // Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
5171 // DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5172 // &TBLMask[0], IndexLen));
5173 Shuffle = DAG.getNode(
5174 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5175 DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32),
5177 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5178 makeArrayRef(TBLMask.data(), IndexLen)));
5181 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
5184 static unsigned getDUPLANEOp(EVT EltType) {
5185 if (EltType == MVT::i8)
5186 return AArch64ISD::DUPLANE8;
5187 if (EltType == MVT::i16 || EltType == MVT::f16)
5188 return AArch64ISD::DUPLANE16;
5189 if (EltType == MVT::i32 || EltType == MVT::f32)
5190 return AArch64ISD::DUPLANE32;
5191 if (EltType == MVT::i64 || EltType == MVT::f64)
5192 return AArch64ISD::DUPLANE64;
5194 llvm_unreachable("Invalid vector element type?");
5197 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5198 SelectionDAG &DAG) const {
5200 EVT VT = Op.getValueType();
5202 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5204 // Convert shuffles that are directly supported on NEON to target-specific
5205 // DAG nodes, instead of keeping them as shuffles and matching them again
5206 // during code selection. This is more efficient and avoids the possibility
5207 // of inconsistencies between legalization and selection.
5208 ArrayRef<int> ShuffleMask = SVN->getMask();
5210 SDValue V1 = Op.getOperand(0);
5211 SDValue V2 = Op.getOperand(1);
5213 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0],
5214 V1.getValueType().getSimpleVT())) {
5215 int Lane = SVN->getSplatIndex();
5216 // If this is undef splat, generate it via "just" vdup, if possible.
5220 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
5221 return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
5223 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
5224 // constant. If so, we can just reference the lane's definition directly.
5225 if (V1.getOpcode() == ISD::BUILD_VECTOR &&
5226 !isa<ConstantSDNode>(V1.getOperand(Lane)))
5227 return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
5229 // Otherwise, duplicate from the lane of the input vector.
5230 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
5232 // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
5233 // to make a vector of the same size as this SHUFFLE. We can ignore the
5234 // extract entirely, and canonicalise the concat using WidenVector.
5235 if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
5236 Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
5237 V1 = V1.getOperand(0);
5238 } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
5239 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
5240 Lane -= Idx * VT.getVectorNumElements() / 2;
5241 V1 = WidenVector(V1.getOperand(Idx), DAG);
5242 } else if (VT.getSizeInBits() == 64)
5243 V1 = WidenVector(V1, DAG);
5245 return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
5248 if (isREVMask(ShuffleMask, VT, 64))
5249 return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
5250 if (isREVMask(ShuffleMask, VT, 32))
5251 return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
5252 if (isREVMask(ShuffleMask, VT, 16))
5253 return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
5255 bool ReverseEXT = false;
5257 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
5260 Imm *= getExtFactor(V1);
5261 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
5262 DAG.getConstant(Imm, dl, MVT::i32));
5263 } else if (V2->getOpcode() == ISD::UNDEF &&
5264 isSingletonEXTMask(ShuffleMask, VT, Imm)) {
5265 Imm *= getExtFactor(V1);
5266 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
5267 DAG.getConstant(Imm, dl, MVT::i32));
5270 unsigned WhichResult;
5271 if (isZIPMask(ShuffleMask, VT, WhichResult)) {
5272 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5273 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5275 if (isUZPMask(ShuffleMask, VT, WhichResult)) {
5276 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5277 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5279 if (isTRNMask(ShuffleMask, VT, WhichResult)) {
5280 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5281 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5284 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5285 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5286 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5288 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5289 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5290 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5292 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5293 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5294 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5297 SDValue Concat = tryFormConcatFromShuffle(Op, DAG);
5298 if (Concat.getNode())
5303 int NumInputElements = V1.getValueType().getVectorNumElements();
5304 if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
5305 SDValue DstVec = DstIsLeft ? V1 : V2;
5306 SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
5308 SDValue SrcVec = V1;
5309 int SrcLane = ShuffleMask[Anomaly];
5310 if (SrcLane >= NumInputElements) {
5312 SrcLane -= VT.getVectorNumElements();
5314 SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
5316 EVT ScalarVT = VT.getVectorElementType();
5318 if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
5319 ScalarVT = MVT::i32;
5322 ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5323 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
5327 // If the shuffle is not directly supported and it has 4 elements, use
5328 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5329 unsigned NumElts = VT.getVectorNumElements();
5331 unsigned PFIndexes[4];
5332 for (unsigned i = 0; i != 4; ++i) {
5333 if (ShuffleMask[i] < 0)
5336 PFIndexes[i] = ShuffleMask[i];
5339 // Compute the index in the perfect shuffle table.
5340 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
5341 PFIndexes[2] * 9 + PFIndexes[3];
5342 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5343 unsigned Cost = (PFEntry >> 30);
5346 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5349 return GenerateTBL(Op, ShuffleMask, DAG);
5352 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
5354 EVT VT = BVN->getValueType(0);
5355 APInt SplatBits, SplatUndef;
5356 unsigned SplatBitSize;
5358 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5359 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
5361 for (unsigned i = 0; i < NumSplats; ++i) {
5362 CnstBits <<= SplatBitSize;
5363 UndefBits <<= SplatBitSize;
5364 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
5365 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
5374 SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op,
5375 SelectionDAG &DAG) const {
5376 BuildVectorSDNode *BVN =
5377 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5378 SDValue LHS = Op.getOperand(0);
5380 EVT VT = Op.getValueType();
5385 APInt CnstBits(VT.getSizeInBits(), 0);
5386 APInt UndefBits(VT.getSizeInBits(), 0);
5387 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5388 // We only have BIC vector immediate instruction, which is and-not.
5389 CnstBits = ~CnstBits;
5391 // We make use of a little bit of goto ickiness in order to avoid having to
5392 // duplicate the immediate matching logic for the undef toggled case.
5393 bool SecondTry = false;
5396 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5397 CnstBits = CnstBits.zextOrTrunc(64);
5398 uint64_t CnstVal = CnstBits.getZExtValue();
5400 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5401 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5402 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5403 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5404 DAG.getConstant(CnstVal, dl, MVT::i32),
5405 DAG.getConstant(0, dl, MVT::i32));
5406 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5409 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5410 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5411 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5412 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5413 DAG.getConstant(CnstVal, dl, MVT::i32),
5414 DAG.getConstant(8, dl, MVT::i32));
5415 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5418 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5419 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5420 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5421 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5422 DAG.getConstant(CnstVal, dl, MVT::i32),
5423 DAG.getConstant(16, dl, MVT::i32));
5424 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5427 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5428 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5429 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5430 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5431 DAG.getConstant(CnstVal, dl, MVT::i32),
5432 DAG.getConstant(24, dl, MVT::i32));
5433 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5436 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5437 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5438 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5439 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5440 DAG.getConstant(CnstVal, dl, MVT::i32),
5441 DAG.getConstant(0, dl, MVT::i32));
5442 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5445 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5446 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5447 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5448 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5449 DAG.getConstant(CnstVal, dl, MVT::i32),
5450 DAG.getConstant(8, dl, MVT::i32));
5451 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5458 CnstBits = ~UndefBits;
5462 // We can always fall back to a non-immediate AND.
5467 // Specialized code to quickly find if PotentialBVec is a BuildVector that
5468 // consists of only the same constant int value, returned in reference arg
5470 static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
5471 uint64_t &ConstVal) {
5472 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
5475 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
5478 EVT VT = Bvec->getValueType(0);
5479 unsigned NumElts = VT.getVectorNumElements();
5480 for (unsigned i = 1; i < NumElts; ++i)
5481 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
5483 ConstVal = FirstElt->getZExtValue();
5487 static unsigned getIntrinsicID(const SDNode *N) {
5488 unsigned Opcode = N->getOpcode();
5491 return Intrinsic::not_intrinsic;
5492 case ISD::INTRINSIC_WO_CHAIN: {
5493 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
5494 if (IID < Intrinsic::num_intrinsics)
5496 return Intrinsic::not_intrinsic;
5501 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
5502 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
5503 // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
5504 // Also, logical shift right -> sri, with the same structure.
5505 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
5506 EVT VT = N->getValueType(0);
5513 // Is the first op an AND?
5514 const SDValue And = N->getOperand(0);
5515 if (And.getOpcode() != ISD::AND)
5518 // Is the second op an shl or lshr?
5519 SDValue Shift = N->getOperand(1);
5520 // This will have been turned into: AArch64ISD::VSHL vector, #shift
5521 // or AArch64ISD::VLSHR vector, #shift
5522 unsigned ShiftOpc = Shift.getOpcode();
5523 if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
5525 bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
5527 // Is the shift amount constant?
5528 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
5532 // Is the and mask vector all constant?
5534 if (!isAllConstantBuildVector(And.getOperand(1), C1))
5537 // Is C1 == ~C2, taking into account how much one can shift elements of a
5539 uint64_t C2 = C2node->getZExtValue();
5540 unsigned ElemSizeInBits = VT.getVectorElementType().getSizeInBits();
5541 if (C2 > ElemSizeInBits)
5543 unsigned ElemMask = (1 << ElemSizeInBits) - 1;
5544 if ((C1 & ElemMask) != (~C2 & ElemMask))
5547 SDValue X = And.getOperand(0);
5548 SDValue Y = Shift.getOperand(0);
5551 IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
5553 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
5554 DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
5555 Shift.getOperand(1));
5557 DEBUG(dbgs() << "aarch64-lower: transformed: \n");
5558 DEBUG(N->dump(&DAG));
5559 DEBUG(dbgs() << "into: \n");
5560 DEBUG(ResultSLI->dump(&DAG));
5566 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
5567 SelectionDAG &DAG) const {
5568 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
5569 if (EnableAArch64SlrGeneration) {
5570 SDValue Res = tryLowerToSLI(Op.getNode(), DAG);
5575 BuildVectorSDNode *BVN =
5576 dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
5577 SDValue LHS = Op.getOperand(1);
5579 EVT VT = Op.getValueType();
5581 // OR commutes, so try swapping the operands.
5583 LHS = Op.getOperand(0);
5584 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5589 APInt CnstBits(VT.getSizeInBits(), 0);
5590 APInt UndefBits(VT.getSizeInBits(), 0);
5591 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5592 // We make use of a little bit of goto ickiness in order to avoid having to
5593 // duplicate the immediate matching logic for the undef toggled case.
5594 bool SecondTry = false;
5597 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5598 CnstBits = CnstBits.zextOrTrunc(64);
5599 uint64_t CnstVal = CnstBits.getZExtValue();
5601 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5602 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5603 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5604 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5605 DAG.getConstant(CnstVal, dl, MVT::i32),
5606 DAG.getConstant(0, dl, MVT::i32));
5607 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5610 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5611 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5612 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5613 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5614 DAG.getConstant(CnstVal, dl, MVT::i32),
5615 DAG.getConstant(8, dl, MVT::i32));
5616 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5619 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5620 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5621 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5622 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5623 DAG.getConstant(CnstVal, dl, MVT::i32),
5624 DAG.getConstant(16, dl, MVT::i32));
5625 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5628 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5629 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5630 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5631 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5632 DAG.getConstant(CnstVal, dl, MVT::i32),
5633 DAG.getConstant(24, dl, MVT::i32));
5634 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5637 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5638 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5639 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5640 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5641 DAG.getConstant(CnstVal, dl, MVT::i32),
5642 DAG.getConstant(0, dl, MVT::i32));
5643 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5646 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5647 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5648 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5649 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5650 DAG.getConstant(CnstVal, dl, MVT::i32),
5651 DAG.getConstant(8, dl, MVT::i32));
5652 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5659 CnstBits = UndefBits;
5663 // We can always fall back to a non-immediate OR.
5668 // Normalize the operands of BUILD_VECTOR. The value of constant operands will
5669 // be truncated to fit element width.
5670 static SDValue NormalizeBuildVector(SDValue Op,
5671 SelectionDAG &DAG) {
5672 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
5674 EVT VT = Op.getValueType();
5675 EVT EltTy= VT.getVectorElementType();
5677 if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
5680 SmallVector<SDValue, 16> Ops;
5681 for (unsigned I = 0, E = VT.getVectorNumElements(); I != E; ++I) {
5682 SDValue Lane = Op.getOperand(I);
5683 if (Lane.getOpcode() == ISD::Constant) {
5684 APInt LowBits(EltTy.getSizeInBits(),
5685 cast<ConstantSDNode>(Lane)->getZExtValue());
5686 Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
5688 Ops.push_back(Lane);
5690 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5693 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
5694 SelectionDAG &DAG) const {
5696 EVT VT = Op.getValueType();
5697 Op = NormalizeBuildVector(Op, DAG);
5698 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5700 APInt CnstBits(VT.getSizeInBits(), 0);
5701 APInt UndefBits(VT.getSizeInBits(), 0);
5702 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5703 // We make use of a little bit of goto ickiness in order to avoid having to
5704 // duplicate the immediate matching logic for the undef toggled case.
5705 bool SecondTry = false;
5708 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5709 CnstBits = CnstBits.zextOrTrunc(64);
5710 uint64_t CnstVal = CnstBits.getZExtValue();
5712 // Certain magic vector constants (used to express things like NOT
5713 // and NEG) are passed through unmodified. This allows codegen patterns
5714 // for these operations to match. Special-purpose patterns will lower
5715 // these immediates to MOVIs if it proves necessary.
5716 if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL))
5719 // The many faces of MOVI...
5720 if (AArch64_AM::isAdvSIMDModImmType10(CnstVal)) {
5721 CnstVal = AArch64_AM::encodeAdvSIMDModImmType10(CnstVal);
5722 if (VT.getSizeInBits() == 128) {
5723 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::v2i64,
5724 DAG.getConstant(CnstVal, dl, MVT::i32));
5725 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5728 // Support the V64 version via subregister insertion.
5729 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::f64,
5730 DAG.getConstant(CnstVal, dl, MVT::i32));
5731 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5734 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5735 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5736 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5737 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5738 DAG.getConstant(CnstVal, dl, MVT::i32),
5739 DAG.getConstant(0, dl, MVT::i32));
5740 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5743 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5744 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5745 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5746 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5747 DAG.getConstant(CnstVal, dl, MVT::i32),
5748 DAG.getConstant(8, dl, MVT::i32));
5749 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5752 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5753 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5754 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5755 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5756 DAG.getConstant(CnstVal, dl, MVT::i32),
5757 DAG.getConstant(16, dl, MVT::i32));
5758 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5761 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5762 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5763 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5764 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5765 DAG.getConstant(CnstVal, dl, MVT::i32),
5766 DAG.getConstant(24, dl, MVT::i32));
5767 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5770 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5771 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5772 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5773 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5774 DAG.getConstant(CnstVal, dl, MVT::i32),
5775 DAG.getConstant(0, dl, MVT::i32));
5776 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5779 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5780 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5781 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5782 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
5783 DAG.getConstant(CnstVal, dl, MVT::i32),
5784 DAG.getConstant(8, dl, MVT::i32));
5785 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5788 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
5789 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
5790 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5791 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
5792 DAG.getConstant(CnstVal, dl, MVT::i32),
5793 DAG.getConstant(264, dl, MVT::i32));
5794 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5797 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
5798 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
5799 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5800 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
5801 DAG.getConstant(CnstVal, dl, MVT::i32),
5802 DAG.getConstant(272, dl, MVT::i32));
5803 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5806 if (AArch64_AM::isAdvSIMDModImmType9(CnstVal)) {
5807 CnstVal = AArch64_AM::encodeAdvSIMDModImmType9(CnstVal);
5808 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
5809 SDValue Mov = DAG.getNode(AArch64ISD::MOVI, dl, MovTy,
5810 DAG.getConstant(CnstVal, dl, MVT::i32));
5811 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5814 // The few faces of FMOV...
5815 if (AArch64_AM::isAdvSIMDModImmType11(CnstVal)) {
5816 CnstVal = AArch64_AM::encodeAdvSIMDModImmType11(CnstVal);
5817 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32;
5818 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MovTy,
5819 DAG.getConstant(CnstVal, dl, MVT::i32));
5820 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5823 if (AArch64_AM::isAdvSIMDModImmType12(CnstVal) &&
5824 VT.getSizeInBits() == 128) {
5825 CnstVal = AArch64_AM::encodeAdvSIMDModImmType12(CnstVal);
5826 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MVT::v2f64,
5827 DAG.getConstant(CnstVal, dl, MVT::i32));
5828 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5831 // The many faces of MVNI...
5833 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5834 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5835 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5836 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
5837 DAG.getConstant(CnstVal, dl, MVT::i32),
5838 DAG.getConstant(0, dl, MVT::i32));
5839 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5842 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5843 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5844 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5845 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
5846 DAG.getConstant(CnstVal, dl, MVT::i32),
5847 DAG.getConstant(8, dl, MVT::i32));
5848 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5851 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5852 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5853 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5854 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
5855 DAG.getConstant(CnstVal, dl, MVT::i32),
5856 DAG.getConstant(16, dl, MVT::i32));
5857 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5860 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5861 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5862 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5863 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
5864 DAG.getConstant(CnstVal, dl, MVT::i32),
5865 DAG.getConstant(24, dl, MVT::i32));
5866 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5869 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5870 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5871 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5872 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
5873 DAG.getConstant(CnstVal, dl, MVT::i32),
5874 DAG.getConstant(0, dl, MVT::i32));
5875 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5878 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5879 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5880 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5881 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
5882 DAG.getConstant(CnstVal, dl, MVT::i32),
5883 DAG.getConstant(8, dl, MVT::i32));
5884 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5887 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
5888 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
5889 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5890 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
5891 DAG.getConstant(CnstVal, dl, MVT::i32),
5892 DAG.getConstant(264, dl, MVT::i32));
5893 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5896 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
5897 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
5898 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5899 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
5900 DAG.getConstant(CnstVal, dl, MVT::i32),
5901 DAG.getConstant(272, dl, MVT::i32));
5902 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5909 CnstBits = UndefBits;
5914 // Scan through the operands to find some interesting properties we can
5916 // 1) If only one value is used, we can use a DUP, or
5917 // 2) if only the low element is not undef, we can just insert that, or
5918 // 3) if only one constant value is used (w/ some non-constant lanes),
5919 // we can splat the constant value into the whole vector then fill
5920 // in the non-constant lanes.
5921 // 4) FIXME: If different constant values are used, but we can intelligently
5922 // select the values we'll be overwriting for the non-constant
5923 // lanes such that we can directly materialize the vector
5924 // some other way (MOVI, e.g.), we can be sneaky.
5925 unsigned NumElts = VT.getVectorNumElements();
5926 bool isOnlyLowElement = true;
5927 bool usesOnlyOneValue = true;
5928 bool usesOnlyOneConstantValue = true;
5929 bool isConstant = true;
5930 unsigned NumConstantLanes = 0;
5932 SDValue ConstantValue;
5933 for (unsigned i = 0; i < NumElts; ++i) {
5934 SDValue V = Op.getOperand(i);
5935 if (V.getOpcode() == ISD::UNDEF)
5938 isOnlyLowElement = false;
5939 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5942 if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
5944 if (!ConstantValue.getNode())
5946 else if (ConstantValue != V)
5947 usesOnlyOneConstantValue = false;
5950 if (!Value.getNode())
5952 else if (V != Value)
5953 usesOnlyOneValue = false;
5956 if (!Value.getNode())
5957 return DAG.getUNDEF(VT);
5959 if (isOnlyLowElement)
5960 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5962 // Use DUP for non-constant splats. For f32 constant splats, reduce to
5963 // i32 and try again.
5964 if (usesOnlyOneValue) {
5966 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5967 Value.getValueType() != VT)
5968 return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
5970 // This is actually a DUPLANExx operation, which keeps everything vectory.
5972 // DUPLANE works on 128-bit vectors, widen it if necessary.
5973 SDValue Lane = Value.getOperand(1);
5974 Value = Value.getOperand(0);
5975 if (Value.getValueType().getSizeInBits() == 64)
5976 Value = WidenVector(Value, DAG);
5978 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
5979 return DAG.getNode(Opcode, dl, VT, Value, Lane);
5982 if (VT.getVectorElementType().isFloatingPoint()) {
5983 SmallVector<SDValue, 8> Ops;
5984 EVT EltTy = VT.getVectorElementType();
5985 assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
5986 "Unsupported floating-point vector type");
5987 MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
5988 for (unsigned i = 0; i < NumElts; ++i)
5989 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
5990 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
5991 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5992 Val = LowerBUILD_VECTOR(Val, DAG);
5994 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5998 // If there was only one constant value used and for more than one lane,
5999 // start by splatting that value, then replace the non-constant lanes. This
6000 // is better than the default, which will perform a separate initialization
6002 if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
6003 SDValue Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
6004 // Now insert the non-constant lanes.
6005 for (unsigned i = 0; i < NumElts; ++i) {
6006 SDValue V = Op.getOperand(i);
6007 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
6008 if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) {
6009 // Note that type legalization likely mucked about with the VT of the
6010 // source operand, so we may have to convert it here before inserting.
6011 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
6017 // If all elements are constants and the case above didn't get hit, fall back
6018 // to the default expansion, which will generate a load from the constant
6023 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6025 SDValue shuffle = ReconstructShuffle(Op, DAG);
6026 if (shuffle != SDValue())
6030 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6031 // know the default expansion would otherwise fall back on something even
6032 // worse. For a vector with one or two non-undef values, that's
6033 // scalar_to_vector for the elements followed by a shuffle (provided the
6034 // shuffle is valid for the target) and materialization element by element
6035 // on the stack followed by a load for everything else.
6036 if (!isConstant && !usesOnlyOneValue) {
6037 SDValue Vec = DAG.getUNDEF(VT);
6038 SDValue Op0 = Op.getOperand(0);
6039 unsigned ElemSize = VT.getVectorElementType().getSizeInBits();
6041 // For 32 and 64 bit types, use INSERT_SUBREG for lane zero to
6042 // a) Avoid a RMW dependency on the full vector register, and
6043 // b) Allow the register coalescer to fold away the copy if the
6044 // value is already in an S or D register.
6045 if (Op0.getOpcode() != ISD::UNDEF && (ElemSize == 32 || ElemSize == 64)) {
6046 unsigned SubIdx = ElemSize == 32 ? AArch64::ssub : AArch64::dsub;
6048 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl, VT, Vec, Op0,
6049 DAG.getTargetConstant(SubIdx, dl, MVT::i32));
6050 Vec = SDValue(N, 0);
6053 for (; i < NumElts; ++i) {
6054 SDValue V = Op.getOperand(i);
6055 if (V.getOpcode() == ISD::UNDEF)
6057 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
6058 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6063 // Just use the default expansion. We failed to find a better alternative.
6067 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
6068 SelectionDAG &DAG) const {
6069 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
6071 // Check for non-constant or out of range lane.
6072 EVT VT = Op.getOperand(0).getValueType();
6073 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
6074 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
6078 // Insertion/extraction are legal for V128 types.
6079 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
6080 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6084 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
6085 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
6088 // For V64 types, we perform insertion by expanding the value
6089 // to a V128 type and perform the insertion on that.
6091 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6092 EVT WideTy = WideVec.getValueType();
6094 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
6095 Op.getOperand(1), Op.getOperand(2));
6096 // Re-narrow the resultant vector.
6097 return NarrowVector(Node, DAG);
6101 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6102 SelectionDAG &DAG) const {
6103 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
6105 // Check for non-constant or out of range lane.
6106 EVT VT = Op.getOperand(0).getValueType();
6107 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6108 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
6112 // Insertion/extraction are legal for V128 types.
6113 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
6114 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6118 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
6119 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
6122 // For V64 types, we perform extraction by expanding the value
6123 // to a V128 type and perform the extraction on that.
6125 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6126 EVT WideTy = WideVec.getValueType();
6128 EVT ExtrTy = WideTy.getVectorElementType();
6129 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
6132 // For extractions, we just return the result directly.
6133 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
6137 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
6138 SelectionDAG &DAG) const {
6139 EVT VT = Op.getOperand(0).getValueType();
6145 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6148 unsigned Val = Cst->getZExtValue();
6150 unsigned Size = Op.getValueType().getSizeInBits();
6154 return DAG.getTargetExtractSubreg(AArch64::bsub, dl, Op.getValueType(),
6157 return DAG.getTargetExtractSubreg(AArch64::hsub, dl, Op.getValueType(),
6160 return DAG.getTargetExtractSubreg(AArch64::ssub, dl, Op.getValueType(),
6163 return DAG.getTargetExtractSubreg(AArch64::dsub, dl, Op.getValueType(),
6166 llvm_unreachable("Unexpected vector type in extract_subvector!");
6169 // If this is extracting the upper 64-bits of a 128-bit vector, we match
6171 if (Size == 64 && Val * VT.getVectorElementType().getSizeInBits() == 64)
6177 bool AArch64TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
6179 if (VT.getVectorNumElements() == 4 &&
6180 (VT.is128BitVector() || VT.is64BitVector())) {
6181 unsigned PFIndexes[4];
6182 for (unsigned i = 0; i != 4; ++i) {
6186 PFIndexes[i] = M[i];
6189 // Compute the index in the perfect shuffle table.
6190 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6191 PFIndexes[2] * 9 + PFIndexes[3];
6192 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6193 unsigned Cost = (PFEntry >> 30);
6201 unsigned DummyUnsigned;
6203 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
6204 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
6205 isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
6206 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
6207 isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
6208 isZIPMask(M, VT, DummyUnsigned) ||
6209 isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
6210 isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
6211 isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
6212 isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
6213 isConcatMask(M, VT, VT.getSizeInBits() == 128));
6216 /// getVShiftImm - Check if this is a valid build_vector for the immediate
6217 /// operand of a vector shift operation, where all the elements of the
6218 /// build_vector must have the same constant integer value.
6219 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
6220 // Ignore bit_converts.
6221 while (Op.getOpcode() == ISD::BITCAST)
6222 Op = Op.getOperand(0);
6223 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6224 APInt SplatBits, SplatUndef;
6225 unsigned SplatBitSize;
6227 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
6228 HasAnyUndefs, ElementBits) ||
6229 SplatBitSize > ElementBits)
6231 Cnt = SplatBits.getSExtValue();
6235 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
6236 /// operand of a vector shift left operation. That value must be in the range:
6237 /// 0 <= Value < ElementBits for a left shift; or
6238 /// 0 <= Value <= ElementBits for a long left shift.
6239 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
6240 assert(VT.isVector() && "vector shift count is not a vector type");
6241 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
6242 if (!getVShiftImm(Op, ElementBits, Cnt))
6244 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
6247 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
6248 /// operand of a vector shift right operation. For a shift opcode, the value
6249 /// is positive, but for an intrinsic the value count must be negative. The
6250 /// absolute value must be in the range:
6251 /// 1 <= |Value| <= ElementBits for a right shift; or
6252 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
6253 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
6255 assert(VT.isVector() && "vector shift count is not a vector type");
6256 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
6257 if (!getVShiftImm(Op, ElementBits, Cnt))
6261 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
6264 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
6265 SelectionDAG &DAG) const {
6266 EVT VT = Op.getValueType();
6270 if (!Op.getOperand(1).getValueType().isVector())
6272 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6274 switch (Op.getOpcode()) {
6276 llvm_unreachable("unexpected shift opcode");
6279 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
6280 return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
6281 DAG.getConstant(Cnt, DL, MVT::i32));
6282 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
6283 DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
6285 Op.getOperand(0), Op.getOperand(1));
6288 // Right shift immediate
6289 if (isVShiftRImm(Op.getOperand(1), VT, false, false, Cnt) &&
6292 (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
6293 return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
6294 DAG.getConstant(Cnt, DL, MVT::i32));
6297 // Right shift register. Note, there is not a shift right register
6298 // instruction, but the shift left register instruction takes a signed
6299 // value, where negative numbers specify a right shift.
6300 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
6301 : Intrinsic::aarch64_neon_ushl;
6302 // negate the shift amount
6303 SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
6304 SDValue NegShiftLeft =
6305 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
6306 DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
6308 return NegShiftLeft;
6314 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
6315 AArch64CC::CondCode CC, bool NoNans, EVT VT,
6316 SDLoc dl, SelectionDAG &DAG) {
6317 EVT SrcVT = LHS.getValueType();
6318 assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
6319 "function only supposed to emit natural comparisons");
6321 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
6322 APInt CnstBits(VT.getSizeInBits(), 0);
6323 APInt UndefBits(VT.getSizeInBits(), 0);
6324 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
6325 bool IsZero = IsCnst && (CnstBits == 0);
6327 if (SrcVT.getVectorElementType().isFloatingPoint()) {
6331 case AArch64CC::NE: {
6334 Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6336 Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6337 return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
6341 return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6342 return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6345 return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
6346 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
6349 return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
6350 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
6353 return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
6354 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
6358 // If we ignore NaNs then we can use to the MI implementation.
6362 return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
6363 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
6370 case AArch64CC::NE: {
6373 Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6375 Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6376 return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
6380 return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6381 return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6384 return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
6385 return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
6388 return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
6389 return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
6392 return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
6393 return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
6395 return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
6397 return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
6400 return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
6401 return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
6403 return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
6405 return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
6409 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
6410 SelectionDAG &DAG) const {
6411 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6412 SDValue LHS = Op.getOperand(0);
6413 SDValue RHS = Op.getOperand(1);
6414 EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
6417 if (LHS.getValueType().getVectorElementType().isInteger()) {
6418 assert(LHS.getValueType() == RHS.getValueType());
6419 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
6421 EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
6422 return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
6425 assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
6426 LHS.getValueType().getVectorElementType() == MVT::f64);
6428 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
6429 // clean. Some of them require two branches to implement.
6430 AArch64CC::CondCode CC1, CC2;
6432 changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
6434 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
6436 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
6440 if (CC2 != AArch64CC::AL) {
6442 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
6443 if (!Cmp2.getNode())
6446 Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
6449 Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
6452 return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
6457 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
6458 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
6459 /// specified in the intrinsic calls.
6460 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
6462 unsigned Intrinsic) const {
6463 switch (Intrinsic) {
6464 case Intrinsic::aarch64_neon_ld2:
6465 case Intrinsic::aarch64_neon_ld3:
6466 case Intrinsic::aarch64_neon_ld4:
6467 case Intrinsic::aarch64_neon_ld1x2:
6468 case Intrinsic::aarch64_neon_ld1x3:
6469 case Intrinsic::aarch64_neon_ld1x4:
6470 case Intrinsic::aarch64_neon_ld2lane:
6471 case Intrinsic::aarch64_neon_ld3lane:
6472 case Intrinsic::aarch64_neon_ld4lane:
6473 case Intrinsic::aarch64_neon_ld2r:
6474 case Intrinsic::aarch64_neon_ld3r:
6475 case Intrinsic::aarch64_neon_ld4r: {
6476 Info.opc = ISD::INTRINSIC_W_CHAIN;
6477 // Conservatively set memVT to the entire set of vectors loaded.
6478 uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
6479 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6480 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6483 Info.vol = false; // volatile loads with NEON intrinsics not supported
6484 Info.readMem = true;
6485 Info.writeMem = false;
6488 case Intrinsic::aarch64_neon_st2:
6489 case Intrinsic::aarch64_neon_st3:
6490 case Intrinsic::aarch64_neon_st4:
6491 case Intrinsic::aarch64_neon_st1x2:
6492 case Intrinsic::aarch64_neon_st1x3:
6493 case Intrinsic::aarch64_neon_st1x4:
6494 case Intrinsic::aarch64_neon_st2lane:
6495 case Intrinsic::aarch64_neon_st3lane:
6496 case Intrinsic::aarch64_neon_st4lane: {
6497 Info.opc = ISD::INTRINSIC_VOID;
6498 // Conservatively set memVT to the entire set of vectors stored.
6499 unsigned NumElts = 0;
6500 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
6501 Type *ArgTy = I.getArgOperand(ArgI)->getType();
6502 if (!ArgTy->isVectorTy())
6504 NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
6506 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6507 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6510 Info.vol = false; // volatile stores with NEON intrinsics not supported
6511 Info.readMem = false;
6512 Info.writeMem = true;
6515 case Intrinsic::aarch64_ldaxr:
6516 case Intrinsic::aarch64_ldxr: {
6517 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
6518 Info.opc = ISD::INTRINSIC_W_CHAIN;
6519 Info.memVT = MVT::getVT(PtrTy->getElementType());
6520 Info.ptrVal = I.getArgOperand(0);
6522 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
6524 Info.readMem = true;
6525 Info.writeMem = false;
6528 case Intrinsic::aarch64_stlxr:
6529 case Intrinsic::aarch64_stxr: {
6530 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
6531 Info.opc = ISD::INTRINSIC_W_CHAIN;
6532 Info.memVT = MVT::getVT(PtrTy->getElementType());
6533 Info.ptrVal = I.getArgOperand(1);
6535 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
6537 Info.readMem = false;
6538 Info.writeMem = true;
6541 case Intrinsic::aarch64_ldaxp:
6542 case Intrinsic::aarch64_ldxp: {
6543 Info.opc = ISD::INTRINSIC_W_CHAIN;
6544 Info.memVT = MVT::i128;
6545 Info.ptrVal = I.getArgOperand(0);
6549 Info.readMem = true;
6550 Info.writeMem = false;
6553 case Intrinsic::aarch64_stlxp:
6554 case Intrinsic::aarch64_stxp: {
6555 Info.opc = ISD::INTRINSIC_W_CHAIN;
6556 Info.memVT = MVT::i128;
6557 Info.ptrVal = I.getArgOperand(2);
6561 Info.readMem = false;
6562 Info.writeMem = true;
6572 // Truncations from 64-bit GPR to 32-bit GPR is free.
6573 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
6574 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6576 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6577 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6578 return NumBits1 > NumBits2;
6580 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
6581 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
6583 unsigned NumBits1 = VT1.getSizeInBits();
6584 unsigned NumBits2 = VT2.getSizeInBits();
6585 return NumBits1 > NumBits2;
6588 /// Check if it is profitable to hoist instruction in then/else to if.
6589 /// Not profitable if I and it's user can form a FMA instruction
6590 /// because we prefer FMSUB/FMADD.
6591 bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
6592 if (I->getOpcode() != Instruction::FMul)
6595 if (I->getNumUses() != 1)
6598 Instruction *User = I->user_back();
6601 !(User->getOpcode() == Instruction::FSub ||
6602 User->getOpcode() == Instruction::FAdd))
6605 const TargetOptions &Options = getTargetMachine().Options;
6606 EVT VT = getValueType(User->getOperand(0)->getType());
6608 if (isFMAFasterThanFMulAndFAdd(VT) &&
6609 isOperationLegalOrCustom(ISD::FMA, VT) &&
6610 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath))
6616 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
6618 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
6619 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6621 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6622 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6623 return NumBits1 == 32 && NumBits2 == 64;
6625 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
6626 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
6628 unsigned NumBits1 = VT1.getSizeInBits();
6629 unsigned NumBits2 = VT2.getSizeInBits();
6630 return NumBits1 == 32 && NumBits2 == 64;
6633 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
6634 EVT VT1 = Val.getValueType();
6635 if (isZExtFree(VT1, VT2)) {
6639 if (Val.getOpcode() != ISD::LOAD)
6642 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
6643 return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
6644 VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
6645 VT1.getSizeInBits() <= 32);
6648 bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
6649 if (isa<FPExtInst>(Ext))
6652 // Vector types are next free.
6653 if (Ext->getType()->isVectorTy())
6656 for (const Use &U : Ext->uses()) {
6657 // The extension is free if we can fold it with a left shift in an
6658 // addressing mode or an arithmetic operation: add, sub, and cmp.
6660 // Is there a shift?
6661 const Instruction *Instr = cast<Instruction>(U.getUser());
6663 // Is this a constant shift?
6664 switch (Instr->getOpcode()) {
6665 case Instruction::Shl:
6666 if (!isa<ConstantInt>(Instr->getOperand(1)))
6669 case Instruction::GetElementPtr: {
6670 gep_type_iterator GTI = gep_type_begin(Instr);
6671 std::advance(GTI, U.getOperandNo());
6673 // This extension will end up with a shift because of the scaling factor.
6674 // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
6675 // Get the shift amount based on the scaling factor:
6676 // log2(sizeof(IdxTy)) - log2(8).
6678 countTrailingZeros(getDataLayout()->getTypeStoreSizeInBits(IdxTy)) - 3;
6679 // Is the constant foldable in the shift of the addressing mode?
6680 // I.e., shift amount is between 1 and 4 inclusive.
6681 if (ShiftAmt == 0 || ShiftAmt > 4)
6685 case Instruction::Trunc:
6686 // Check if this is a noop.
6687 // trunc(sext ty1 to ty2) to ty1.
6688 if (Instr->getType() == Ext->getOperand(0)->getType())
6695 // At this point we can use the bfm family, so this extension is free
6701 bool AArch64TargetLowering::hasPairedLoad(Type *LoadedType,
6702 unsigned &RequiredAligment) const {
6703 if (!LoadedType->isIntegerTy() && !LoadedType->isFloatTy())
6705 // Cyclone supports unaligned accesses.
6706 RequiredAligment = 0;
6707 unsigned NumBits = LoadedType->getPrimitiveSizeInBits();
6708 return NumBits == 32 || NumBits == 64;
6711 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
6712 unsigned &RequiredAligment) const {
6713 if (!LoadedType.isSimple() ||
6714 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
6716 // Cyclone supports unaligned accesses.
6717 RequiredAligment = 0;
6718 unsigned NumBits = LoadedType.getSizeInBits();
6719 return NumBits == 32 || NumBits == 64;
6722 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
6723 unsigned AlignCheck) {
6724 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
6725 (DstAlign == 0 || DstAlign % AlignCheck == 0));
6728 EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
6729 unsigned SrcAlign, bool IsMemset,
6732 MachineFunction &MF) const {
6733 // Don't use AdvSIMD to implement 16-byte memset. It would have taken one
6734 // instruction to materialize the v2i64 zero and one store (with restrictive
6735 // addressing mode). Just do two i64 store of zero-registers.
6737 const Function *F = MF.getFunction();
6738 if (Subtarget->hasFPARMv8() && !IsMemset && Size >= 16 &&
6739 !F->hasFnAttribute(Attribute::NoImplicitFloat) &&
6740 (memOpAlign(SrcAlign, DstAlign, 16) ||
6741 (allowsMisalignedMemoryAccesses(MVT::f128, 0, 1, &Fast) && Fast)))
6745 (memOpAlign(SrcAlign, DstAlign, 8) ||
6746 (allowsMisalignedMemoryAccesses(MVT::i64, 0, 1, &Fast) && Fast)))
6750 (memOpAlign(SrcAlign, DstAlign, 4) ||
6751 (allowsMisalignedMemoryAccesses(MVT::i32, 0, 1, &Fast) && Fast)))
6757 // 12-bit optionally shifted immediates are legal for adds.
6758 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
6759 if ((Immed >> 12) == 0 || ((Immed & 0xfff) == 0 && Immed >> 24 == 0))
6764 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
6765 // immediates is the same as for an add or a sub.
6766 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
6769 return isLegalAddImmediate(Immed);
6772 /// isLegalAddressingMode - Return true if the addressing mode represented
6773 /// by AM is legal for this target, for a load/store of the specified type.
6774 bool AArch64TargetLowering::isLegalAddressingMode(const AddrMode &AM,
6776 // AArch64 has five basic addressing modes:
6778 // reg + 9-bit signed offset
6779 // reg + SIZE_IN_BYTES * 12-bit unsigned offset
6781 // reg + SIZE_IN_BYTES * reg
6783 // No global is ever allowed as a base.
6787 // No reg+reg+imm addressing.
6788 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
6791 // check reg + imm case:
6792 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
6793 uint64_t NumBytes = 0;
6794 if (Ty->isSized()) {
6795 uint64_t NumBits = getDataLayout()->getTypeSizeInBits(Ty);
6796 NumBytes = NumBits / 8;
6797 if (!isPowerOf2_64(NumBits))
6802 int64_t Offset = AM.BaseOffs;
6804 // 9-bit signed offset
6805 if (Offset >= -(1LL << 9) && Offset <= (1LL << 9) - 1)
6808 // 12-bit unsigned offset
6809 unsigned shift = Log2_64(NumBytes);
6810 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
6811 // Must be a multiple of NumBytes (NumBytes is a power of 2)
6812 (Offset >> shift) << shift == Offset)
6817 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
6819 if (!AM.Scale || AM.Scale == 1 ||
6820 (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes))
6825 int AArch64TargetLowering::getScalingFactorCost(const AddrMode &AM,
6827 // Scaling factors are not free at all.
6828 // Operands | Rt Latency
6829 // -------------------------------------------
6831 // -------------------------------------------
6832 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5
6833 // Rt, [Xn, Wm, <extend> #imm] |
6834 if (isLegalAddressingMode(AM, Ty))
6835 // Scale represents reg2 * scale, thus account for 1 if
6836 // it is not equal to 0 or 1.
6837 return AM.Scale != 0 && AM.Scale != 1;
6841 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
6842 VT = VT.getScalarType();
6847 switch (VT.getSimpleVT().SimpleTy) {
6859 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
6860 // LR is a callee-save register, but we must treat it as clobbered by any call
6861 // site. Hence we include LR in the scratch registers, which are in turn added
6862 // as implicit-defs for stackmaps and patchpoints.
6863 static const MCPhysReg ScratchRegs[] = {
6864 AArch64::X16, AArch64::X17, AArch64::LR, 0
6870 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N) const {
6871 EVT VT = N->getValueType(0);
6872 // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
6873 // it with shift to let it be lowered to UBFX.
6874 if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
6875 isa<ConstantSDNode>(N->getOperand(1))) {
6876 uint64_t TruncMask = N->getConstantOperandVal(1);
6877 if (isMask_64(TruncMask) &&
6878 N->getOperand(0).getOpcode() == ISD::SRL &&
6879 isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
6885 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
6887 assert(Ty->isIntegerTy());
6889 unsigned BitSize = Ty->getPrimitiveSizeInBits();
6893 int64_t Val = Imm.getSExtValue();
6894 if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
6897 if ((int64_t)Val < 0)
6900 Val &= (1LL << 32) - 1;
6902 unsigned LZ = countLeadingZeros((uint64_t)Val);
6903 unsigned Shift = (63 - LZ) / 16;
6904 // MOVZ is free so return true for one or fewer MOVK.
6908 // Generate SUBS and CSEL for integer abs.
6909 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
6910 EVT VT = N->getValueType(0);
6912 SDValue N0 = N->getOperand(0);
6913 SDValue N1 = N->getOperand(1);
6916 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
6917 // and change it to SUB and CSEL.
6918 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
6919 N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
6920 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
6921 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
6922 if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
6923 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
6925 // Generate SUBS & CSEL.
6927 DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
6928 N0.getOperand(0), DAG.getConstant(0, DL, VT));
6929 return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
6930 DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
6931 SDValue(Cmp.getNode(), 1));
6936 // performXorCombine - Attempts to handle integer ABS.
6937 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
6938 TargetLowering::DAGCombinerInfo &DCI,
6939 const AArch64Subtarget *Subtarget) {
6940 if (DCI.isBeforeLegalizeOps())
6943 return performIntegerAbsCombine(N, DAG);
6947 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
6949 std::vector<SDNode *> *Created) const {
6950 // fold (sdiv X, pow2)
6951 EVT VT = N->getValueType(0);
6952 if ((VT != MVT::i32 && VT != MVT::i64) ||
6953 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
6957 SDValue N0 = N->getOperand(0);
6958 unsigned Lg2 = Divisor.countTrailingZeros();
6959 SDValue Zero = DAG.getConstant(0, DL, VT);
6960 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
6962 // Add (N0 < 0) ? Pow2 - 1 : 0;
6964 SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
6965 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
6966 SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
6969 Created->push_back(Cmp.getNode());
6970 Created->push_back(Add.getNode());
6971 Created->push_back(CSel.getNode());
6976 DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
6978 // If we're dividing by a positive value, we're done. Otherwise, we must
6979 // negate the result.
6980 if (Divisor.isNonNegative())
6984 Created->push_back(SRA.getNode());
6985 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
6988 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
6989 TargetLowering::DAGCombinerInfo &DCI,
6990 const AArch64Subtarget *Subtarget) {
6991 if (DCI.isBeforeLegalizeOps())
6994 // Multiplication of a power of two plus/minus one can be done more
6995 // cheaply as as shift+add/sub. For now, this is true unilaterally. If
6996 // future CPUs have a cheaper MADD instruction, this may need to be
6997 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
6998 // 64-bit is 5 cycles, so this is always a win.
6999 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
7000 APInt Value = C->getAPIntValue();
7001 EVT VT = N->getValueType(0);
7003 if (Value.isNonNegative()) {
7004 // (mul x, 2^N + 1) => (add (shl x, N), x)
7005 APInt VM1 = Value - 1;
7006 if (VM1.isPowerOf2()) {
7007 SDValue ShiftedVal =
7008 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7009 DAG.getConstant(VM1.logBase2(), DL, MVT::i64));
7010 return DAG.getNode(ISD::ADD, DL, VT, ShiftedVal,
7013 // (mul x, 2^N - 1) => (sub (shl x, N), x)
7014 APInt VP1 = Value + 1;
7015 if (VP1.isPowerOf2()) {
7016 SDValue ShiftedVal =
7017 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7018 DAG.getConstant(VP1.logBase2(), DL, MVT::i64));
7019 return DAG.getNode(ISD::SUB, DL, VT, ShiftedVal,
7023 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7024 APInt VNP1 = -Value + 1;
7025 if (VNP1.isPowerOf2()) {
7026 SDValue ShiftedVal =
7027 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7028 DAG.getConstant(VNP1.logBase2(), DL, MVT::i64));
7029 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0),
7032 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7033 APInt VNM1 = -Value - 1;
7034 if (VNM1.isPowerOf2()) {
7035 SDValue ShiftedVal =
7036 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7037 DAG.getConstant(VNM1.logBase2(), DL, MVT::i64));
7039 DAG.getNode(ISD::ADD, DL, VT, ShiftedVal, N->getOperand(0));
7040 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Add);
7047 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
7048 SelectionDAG &DAG) {
7049 // Take advantage of vector comparisons producing 0 or -1 in each lane to
7050 // optimize away operation when it's from a constant.
7052 // The general transformation is:
7053 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
7054 // AND(VECTOR_CMP(x,y), constant2)
7055 // constant2 = UNARYOP(constant)
7057 // Early exit if this isn't a vector operation, the operand of the
7058 // unary operation isn't a bitwise AND, or if the sizes of the operations
7060 EVT VT = N->getValueType(0);
7061 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
7062 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
7063 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
7066 // Now check that the other operand of the AND is a constant. We could
7067 // make the transformation for non-constant splats as well, but it's unclear
7068 // that would be a benefit as it would not eliminate any operations, just
7069 // perform one more step in scalar code before moving to the vector unit.
7070 if (BuildVectorSDNode *BV =
7071 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
7072 // Bail out if the vector isn't a constant.
7073 if (!BV->isConstant())
7076 // Everything checks out. Build up the new and improved node.
7078 EVT IntVT = BV->getValueType(0);
7079 // Create a new constant of the appropriate type for the transformed
7081 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
7082 // The AND node needs bitcasts to/from an integer vector type around it.
7083 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
7084 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
7085 N->getOperand(0)->getOperand(0), MaskConst);
7086 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
7093 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
7094 const AArch64Subtarget *Subtarget) {
7095 // First try to optimize away the conversion when it's conditionally from
7096 // a constant. Vectors only.
7097 SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
7098 if (Res != SDValue())
7101 EVT VT = N->getValueType(0);
7102 if (VT != MVT::f32 && VT != MVT::f64)
7105 // Only optimize when the source and destination types have the same width.
7106 if (VT.getSizeInBits() != N->getOperand(0).getValueType().getSizeInBits())
7109 // If the result of an integer load is only used by an integer-to-float
7110 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
7111 // This eliminates an "integer-to-vector-move UOP and improve throughput.
7112 SDValue N0 = N->getOperand(0);
7113 if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7114 // Do not change the width of a volatile load.
7115 !cast<LoadSDNode>(N0)->isVolatile()) {
7116 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7117 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
7118 LN0->getPointerInfo(), LN0->isVolatile(),
7119 LN0->isNonTemporal(), LN0->isInvariant(),
7120 LN0->getAlignment());
7122 // Make sure successors of the original load stay after it by updating them
7123 // to use the new Chain.
7124 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
7127 (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
7128 return DAG.getNode(Opcode, SDLoc(N), VT, Load);
7134 /// An EXTR instruction is made up of two shifts, ORed together. This helper
7135 /// searches for and classifies those shifts.
7136 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
7138 if (N.getOpcode() == ISD::SHL)
7140 else if (N.getOpcode() == ISD::SRL)
7145 if (!isa<ConstantSDNode>(N.getOperand(1)))
7148 ShiftAmount = N->getConstantOperandVal(1);
7149 Src = N->getOperand(0);
7153 /// EXTR instruction extracts a contiguous chunk of bits from two existing
7154 /// registers viewed as a high/low pair. This function looks for the pattern:
7155 /// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an
7156 /// EXTR. Can't quite be done in TableGen because the two immediates aren't
7158 static SDValue tryCombineToEXTR(SDNode *N,
7159 TargetLowering::DAGCombinerInfo &DCI) {
7160 SelectionDAG &DAG = DCI.DAG;
7162 EVT VT = N->getValueType(0);
7164 assert(N->getOpcode() == ISD::OR && "Unexpected root");
7166 if (VT != MVT::i32 && VT != MVT::i64)
7170 uint32_t ShiftLHS = 0;
7172 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
7176 uint32_t ShiftRHS = 0;
7178 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
7181 // If they're both trying to come from the high part of the register, they're
7182 // not really an EXTR.
7183 if (LHSFromHi == RHSFromHi)
7186 if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
7190 std::swap(LHS, RHS);
7191 std::swap(ShiftLHS, ShiftRHS);
7194 return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
7195 DAG.getConstant(ShiftRHS, DL, MVT::i64));
7198 static SDValue tryCombineToBSL(SDNode *N,
7199 TargetLowering::DAGCombinerInfo &DCI) {
7200 EVT VT = N->getValueType(0);
7201 SelectionDAG &DAG = DCI.DAG;
7207 SDValue N0 = N->getOperand(0);
7208 if (N0.getOpcode() != ISD::AND)
7211 SDValue N1 = N->getOperand(1);
7212 if (N1.getOpcode() != ISD::AND)
7215 // We only have to look for constant vectors here since the general, variable
7216 // case can be handled in TableGen.
7217 unsigned Bits = VT.getVectorElementType().getSizeInBits();
7218 uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
7219 for (int i = 1; i >= 0; --i)
7220 for (int j = 1; j >= 0; --j) {
7221 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
7222 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
7226 bool FoundMatch = true;
7227 for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
7228 ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
7229 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
7231 CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
7238 return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
7239 N0->getOperand(1 - i), N1->getOperand(1 - j));
7245 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
7246 const AArch64Subtarget *Subtarget) {
7247 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
7248 if (!EnableAArch64ExtrGeneration)
7250 SelectionDAG &DAG = DCI.DAG;
7251 EVT VT = N->getValueType(0);
7253 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7256 SDValue Res = tryCombineToEXTR(N, DCI);
7260 Res = tryCombineToBSL(N, DCI);
7267 static SDValue performBitcastCombine(SDNode *N,
7268 TargetLowering::DAGCombinerInfo &DCI,
7269 SelectionDAG &DAG) {
7270 // Wait 'til after everything is legalized to try this. That way we have
7271 // legal vector types and such.
7272 if (DCI.isBeforeLegalizeOps())
7275 // Remove extraneous bitcasts around an extract_subvector.
7277 // (v4i16 (bitconvert
7278 // (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
7280 // (extract_subvector ((v8i16 ...), (i64 4)))
7282 // Only interested in 64-bit vectors as the ultimate result.
7283 EVT VT = N->getValueType(0);
7286 if (VT.getSimpleVT().getSizeInBits() != 64)
7288 // Is the operand an extract_subvector starting at the beginning or halfway
7289 // point of the vector? A low half may also come through as an
7290 // EXTRACT_SUBREG, so look for that, too.
7291 SDValue Op0 = N->getOperand(0);
7292 if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
7293 !(Op0->isMachineOpcode() &&
7294 Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
7296 uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
7297 if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
7298 if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
7300 } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
7301 if (idx != AArch64::dsub)
7303 // The dsub reference is equivalent to a lane zero subvector reference.
7306 // Look through the bitcast of the input to the extract.
7307 if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
7309 SDValue Source = Op0->getOperand(0)->getOperand(0);
7310 // If the source type has twice the number of elements as our destination
7311 // type, we know this is an extract of the high or low half of the vector.
7312 EVT SVT = Source->getValueType(0);
7313 if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
7316 DEBUG(dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
7318 // Create the simplified form to just extract the low or high half of the
7319 // vector directly rather than bothering with the bitcasts.
7321 unsigned NumElements = VT.getVectorNumElements();
7323 SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
7324 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
7326 SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
7327 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
7333 static SDValue performConcatVectorsCombine(SDNode *N,
7334 TargetLowering::DAGCombinerInfo &DCI,
7335 SelectionDAG &DAG) {
7337 EVT VT = N->getValueType(0);
7338 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
7340 // Optimize concat_vectors of truncated vectors, where the intermediate
7341 // type is illegal, to avoid said illegality, e.g.,
7342 // (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
7343 // (v2i16 (truncate (v2i64)))))
7345 // (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
7346 // (v4i32 (bitcast (v2i64))),
7348 // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
7349 // on both input and result type, so we might generate worse code.
7350 // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
7351 if (N->getNumOperands() == 2 &&
7352 N0->getOpcode() == ISD::TRUNCATE &&
7353 N1->getOpcode() == ISD::TRUNCATE) {
7354 SDValue N00 = N0->getOperand(0);
7355 SDValue N10 = N1->getOperand(0);
7356 EVT N00VT = N00.getValueType();
7358 if (N00VT == N10.getValueType() &&
7359 (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
7360 N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
7361 MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
7362 SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
7363 for (size_t i = 0; i < Mask.size(); ++i)
7365 return DAG.getNode(ISD::TRUNCATE, dl, VT,
7366 DAG.getVectorShuffle(
7368 DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
7369 DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
7373 // Wait 'til after everything is legalized to try this. That way we have
7374 // legal vector types and such.
7375 if (DCI.isBeforeLegalizeOps())
7378 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
7379 // splat. The indexed instructions are going to be expecting a DUPLANE64, so
7380 // canonicalise to that.
7381 if (N0 == N1 && VT.getVectorNumElements() == 2) {
7382 assert(VT.getVectorElementType().getSizeInBits() == 64);
7383 return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
7384 DAG.getConstant(0, dl, MVT::i64));
7387 // Canonicalise concat_vectors so that the right-hand vector has as few
7388 // bit-casts as possible before its real operation. The primary matching
7389 // destination for these operations will be the narrowing "2" instructions,
7390 // which depend on the operation being performed on this right-hand vector.
7392 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS))))
7394 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
7396 if (N1->getOpcode() != ISD::BITCAST)
7398 SDValue RHS = N1->getOperand(0);
7399 MVT RHSTy = RHS.getValueType().getSimpleVT();
7400 // If the RHS is not a vector, this is not the pattern we're looking for.
7401 if (!RHSTy.isVector())
7404 DEBUG(dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
7406 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
7407 RHSTy.getVectorNumElements() * 2);
7408 return DAG.getNode(ISD::BITCAST, dl, VT,
7409 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
7410 DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
7414 static SDValue tryCombineFixedPointConvert(SDNode *N,
7415 TargetLowering::DAGCombinerInfo &DCI,
7416 SelectionDAG &DAG) {
7417 // Wait 'til after everything is legalized to try this. That way we have
7418 // legal vector types and such.
7419 if (DCI.isBeforeLegalizeOps())
7421 // Transform a scalar conversion of a value from a lane extract into a
7422 // lane extract of a vector conversion. E.g., from foo1 to foo2:
7423 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
7424 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
7426 // The second form interacts better with instruction selection and the
7427 // register allocator to avoid cross-class register copies that aren't
7428 // coalescable due to a lane reference.
7430 // Check the operand and see if it originates from a lane extract.
7431 SDValue Op1 = N->getOperand(1);
7432 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7433 // Yep, no additional predication needed. Perform the transform.
7434 SDValue IID = N->getOperand(0);
7435 SDValue Shift = N->getOperand(2);
7436 SDValue Vec = Op1.getOperand(0);
7437 SDValue Lane = Op1.getOperand(1);
7438 EVT ResTy = N->getValueType(0);
7442 // The vector width should be 128 bits by the time we get here, even
7443 // if it started as 64 bits (the extract_vector handling will have
7445 assert(Vec.getValueType().getSizeInBits() == 128 &&
7446 "unexpected vector size on extract_vector_elt!");
7447 if (Vec.getValueType() == MVT::v4i32)
7448 VecResTy = MVT::v4f32;
7449 else if (Vec.getValueType() == MVT::v2i64)
7450 VecResTy = MVT::v2f64;
7452 llvm_unreachable("unexpected vector type!");
7455 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
7456 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
7461 // AArch64 high-vector "long" operations are formed by performing the non-high
7462 // version on an extract_subvector of each operand which gets the high half:
7464 // (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
7466 // However, there are cases which don't have an extract_high explicitly, but
7467 // have another operation that can be made compatible with one for free. For
7470 // (dupv64 scalar) --> (extract_high (dup128 scalar))
7472 // This routine does the actual conversion of such DUPs, once outer routines
7473 // have determined that everything else is in order.
7474 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
7475 // We can handle most types of duplicate, but the lane ones have an extra
7476 // operand saying *which* lane, so we need to know.
7478 switch (N.getOpcode()) {
7479 case AArch64ISD::DUP:
7482 case AArch64ISD::DUPLANE8:
7483 case AArch64ISD::DUPLANE16:
7484 case AArch64ISD::DUPLANE32:
7485 case AArch64ISD::DUPLANE64:
7492 MVT NarrowTy = N.getSimpleValueType();
7493 if (!NarrowTy.is64BitVector())
7496 MVT ElementTy = NarrowTy.getVectorElementType();
7497 unsigned NumElems = NarrowTy.getVectorNumElements();
7498 MVT NewDUPVT = MVT::getVectorVT(ElementTy, NumElems * 2);
7503 NewDUP = DAG.getNode(N.getOpcode(), dl, NewDUPVT, N.getOperand(0),
7506 NewDUP = DAG.getNode(AArch64ISD::DUP, dl, NewDUPVT, N.getOperand(0));
7508 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy, NewDUP,
7509 DAG.getConstant(NumElems, dl, MVT::i64));
7512 static bool isEssentiallyExtractSubvector(SDValue N) {
7513 if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
7516 return N.getOpcode() == ISD::BITCAST &&
7517 N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
7520 /// \brief Helper structure to keep track of ISD::SET_CC operands.
7521 struct GenericSetCCInfo {
7522 const SDValue *Opnd0;
7523 const SDValue *Opnd1;
7527 /// \brief Helper structure to keep track of a SET_CC lowered into AArch64 code.
7528 struct AArch64SetCCInfo {
7530 AArch64CC::CondCode CC;
7533 /// \brief Helper structure to keep track of SetCC information.
7535 GenericSetCCInfo Generic;
7536 AArch64SetCCInfo AArch64;
7539 /// \brief Helper structure to be able to read SetCC information. If set to
7540 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
7541 /// GenericSetCCInfo.
7542 struct SetCCInfoAndKind {
7547 /// \brief Check whether or not \p Op is a SET_CC operation, either a generic or
7549 /// AArch64 lowered one.
7550 /// \p SetCCInfo is filled accordingly.
7551 /// \post SetCCInfo is meanginfull only when this function returns true.
7552 /// \return True when Op is a kind of SET_CC operation.
7553 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
7554 // If this is a setcc, this is straight forward.
7555 if (Op.getOpcode() == ISD::SETCC) {
7556 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
7557 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
7558 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7559 SetCCInfo.IsAArch64 = false;
7562 // Otherwise, check if this is a matching csel instruction.
7566 if (Op.getOpcode() != AArch64ISD::CSEL)
7568 // Set the information about the operands.
7569 // TODO: we want the operands of the Cmp not the csel
7570 SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
7571 SetCCInfo.IsAArch64 = true;
7572 SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
7573 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
7575 // Check that the operands matches the constraints:
7576 // (1) Both operands must be constants.
7577 // (2) One must be 1 and the other must be 0.
7578 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
7579 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7582 if (!TValue || !FValue)
7586 if (!TValue->isOne()) {
7587 // Update the comparison when we are interested in !cc.
7588 std::swap(TValue, FValue);
7589 SetCCInfo.Info.AArch64.CC =
7590 AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
7592 return TValue->isOne() && FValue->isNullValue();
7595 // Returns true if Op is setcc or zext of setcc.
7596 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
7597 if (isSetCC(Op, Info))
7599 return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
7600 isSetCC(Op->getOperand(0), Info));
7603 // The folding we want to perform is:
7604 // (add x, [zext] (setcc cc ...) )
7606 // (csel x, (add x, 1), !cc ...)
7608 // The latter will get matched to a CSINC instruction.
7609 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
7610 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
7611 SDValue LHS = Op->getOperand(0);
7612 SDValue RHS = Op->getOperand(1);
7613 SetCCInfoAndKind InfoAndKind;
7615 // If neither operand is a SET_CC, give up.
7616 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
7617 std::swap(LHS, RHS);
7618 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
7622 // FIXME: This could be generatized to work for FP comparisons.
7623 EVT CmpVT = InfoAndKind.IsAArch64
7624 ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
7625 : InfoAndKind.Info.Generic.Opnd0->getValueType();
7626 if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
7632 if (InfoAndKind.IsAArch64) {
7633 CCVal = DAG.getConstant(
7634 AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
7636 Cmp = *InfoAndKind.Info.AArch64.Cmp;
7638 Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
7639 *InfoAndKind.Info.Generic.Opnd1,
7640 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
7643 EVT VT = Op->getValueType(0);
7644 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
7645 return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
7648 // The basic add/sub long vector instructions have variants with "2" on the end
7649 // which act on the high-half of their inputs. They are normally matched by
7652 // (add (zeroext (extract_high LHS)),
7653 // (zeroext (extract_high RHS)))
7654 // -> uaddl2 vD, vN, vM
7656 // However, if one of the extracts is something like a duplicate, this
7657 // instruction can still be used profitably. This function puts the DAG into a
7658 // more appropriate form for those patterns to trigger.
7659 static SDValue performAddSubLongCombine(SDNode *N,
7660 TargetLowering::DAGCombinerInfo &DCI,
7661 SelectionDAG &DAG) {
7662 if (DCI.isBeforeLegalizeOps())
7665 MVT VT = N->getSimpleValueType(0);
7666 if (!VT.is128BitVector()) {
7667 if (N->getOpcode() == ISD::ADD)
7668 return performSetccAddFolding(N, DAG);
7672 // Make sure both branches are extended in the same way.
7673 SDValue LHS = N->getOperand(0);
7674 SDValue RHS = N->getOperand(1);
7675 if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
7676 LHS.getOpcode() != ISD::SIGN_EXTEND) ||
7677 LHS.getOpcode() != RHS.getOpcode())
7680 unsigned ExtType = LHS.getOpcode();
7682 // It's not worth doing if at least one of the inputs isn't already an
7683 // extract, but we don't know which it'll be so we have to try both.
7684 if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
7685 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
7689 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
7690 } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
7691 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
7695 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
7698 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
7701 // Massage DAGs which we can use the high-half "long" operations on into
7702 // something isel will recognize better. E.g.
7704 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
7705 // (aarch64_neon_umull (extract_high (v2i64 vec)))
7706 // (extract_high (v2i64 (dup128 scalar)))))
7708 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
7709 TargetLowering::DAGCombinerInfo &DCI,
7710 SelectionDAG &DAG) {
7711 if (DCI.isBeforeLegalizeOps())
7714 SDValue LHS = N->getOperand(1);
7715 SDValue RHS = N->getOperand(2);
7716 assert(LHS.getValueType().is64BitVector() &&
7717 RHS.getValueType().is64BitVector() &&
7718 "unexpected shape for long operation");
7720 // Either node could be a DUP, but it's not worth doing both of them (you'd
7721 // just as well use the non-high version) so look for a corresponding extract
7722 // operation on the other "wing".
7723 if (isEssentiallyExtractSubvector(LHS)) {
7724 RHS = tryExtendDUPToExtractHigh(RHS, DAG);
7727 } else if (isEssentiallyExtractSubvector(RHS)) {
7728 LHS = tryExtendDUPToExtractHigh(LHS, DAG);
7733 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
7734 N->getOperand(0), LHS, RHS);
7737 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
7738 MVT ElemTy = N->getSimpleValueType(0).getScalarType();
7739 unsigned ElemBits = ElemTy.getSizeInBits();
7741 int64_t ShiftAmount;
7742 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
7743 APInt SplatValue, SplatUndef;
7744 unsigned SplatBitSize;
7746 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
7747 HasAnyUndefs, ElemBits) ||
7748 SplatBitSize != ElemBits)
7751 ShiftAmount = SplatValue.getSExtValue();
7752 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
7753 ShiftAmount = CVN->getSExtValue();
7761 llvm_unreachable("Unknown shift intrinsic");
7762 case Intrinsic::aarch64_neon_sqshl:
7763 Opcode = AArch64ISD::SQSHL_I;
7764 IsRightShift = false;
7766 case Intrinsic::aarch64_neon_uqshl:
7767 Opcode = AArch64ISD::UQSHL_I;
7768 IsRightShift = false;
7770 case Intrinsic::aarch64_neon_srshl:
7771 Opcode = AArch64ISD::SRSHR_I;
7772 IsRightShift = true;
7774 case Intrinsic::aarch64_neon_urshl:
7775 Opcode = AArch64ISD::URSHR_I;
7776 IsRightShift = true;
7778 case Intrinsic::aarch64_neon_sqshlu:
7779 Opcode = AArch64ISD::SQSHLU_I;
7780 IsRightShift = false;
7784 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
7786 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
7787 DAG.getConstant(-ShiftAmount, dl, MVT::i32));
7788 } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
7790 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
7791 DAG.getConstant(ShiftAmount, dl, MVT::i32));
7797 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
7798 // the intrinsics must be legal and take an i32, this means there's almost
7799 // certainly going to be a zext in the DAG which we can eliminate.
7800 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
7801 SDValue AndN = N->getOperand(2);
7802 if (AndN.getOpcode() != ISD::AND)
7805 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
7806 if (!CMask || CMask->getZExtValue() != Mask)
7809 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
7810 N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
7813 static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
7814 SelectionDAG &DAG) {
7816 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
7817 DAG.getNode(Opc, dl,
7818 N->getOperand(1).getSimpleValueType(),
7820 DAG.getConstant(0, dl, MVT::i64));
7823 static SDValue performIntrinsicCombine(SDNode *N,
7824 TargetLowering::DAGCombinerInfo &DCI,
7825 const AArch64Subtarget *Subtarget) {
7826 SelectionDAG &DAG = DCI.DAG;
7827 unsigned IID = getIntrinsicID(N);
7831 case Intrinsic::aarch64_neon_vcvtfxs2fp:
7832 case Intrinsic::aarch64_neon_vcvtfxu2fp:
7833 return tryCombineFixedPointConvert(N, DCI, DAG);
7835 case Intrinsic::aarch64_neon_saddv:
7836 return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
7837 case Intrinsic::aarch64_neon_uaddv:
7838 return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
7839 case Intrinsic::aarch64_neon_sminv:
7840 return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
7841 case Intrinsic::aarch64_neon_uminv:
7842 return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
7843 case Intrinsic::aarch64_neon_smaxv:
7844 return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
7845 case Intrinsic::aarch64_neon_umaxv:
7846 return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
7847 case Intrinsic::aarch64_neon_fmax:
7848 return DAG.getNode(AArch64ISD::FMAX, SDLoc(N), N->getValueType(0),
7849 N->getOperand(1), N->getOperand(2));
7850 case Intrinsic::aarch64_neon_fmin:
7851 return DAG.getNode(AArch64ISD::FMIN, SDLoc(N), N->getValueType(0),
7852 N->getOperand(1), N->getOperand(2));
7853 case Intrinsic::aarch64_neon_smull:
7854 case Intrinsic::aarch64_neon_umull:
7855 case Intrinsic::aarch64_neon_pmull:
7856 case Intrinsic::aarch64_neon_sqdmull:
7857 return tryCombineLongOpWithDup(IID, N, DCI, DAG);
7858 case Intrinsic::aarch64_neon_sqshl:
7859 case Intrinsic::aarch64_neon_uqshl:
7860 case Intrinsic::aarch64_neon_sqshlu:
7861 case Intrinsic::aarch64_neon_srshl:
7862 case Intrinsic::aarch64_neon_urshl:
7863 return tryCombineShiftImm(IID, N, DAG);
7864 case Intrinsic::aarch64_crc32b:
7865 case Intrinsic::aarch64_crc32cb:
7866 return tryCombineCRC32(0xff, N, DAG);
7867 case Intrinsic::aarch64_crc32h:
7868 case Intrinsic::aarch64_crc32ch:
7869 return tryCombineCRC32(0xffff, N, DAG);
7874 static SDValue performExtendCombine(SDNode *N,
7875 TargetLowering::DAGCombinerInfo &DCI,
7876 SelectionDAG &DAG) {
7877 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
7878 // we can convert that DUP into another extract_high (of a bigger DUP), which
7879 // helps the backend to decide that an sabdl2 would be useful, saving a real
7880 // extract_high operation.
7881 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
7882 N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
7883 SDNode *ABDNode = N->getOperand(0).getNode();
7884 unsigned IID = getIntrinsicID(ABDNode);
7885 if (IID == Intrinsic::aarch64_neon_sabd ||
7886 IID == Intrinsic::aarch64_neon_uabd) {
7887 SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
7888 if (!NewABD.getNode())
7891 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
7896 // This is effectively a custom type legalization for AArch64.
7898 // Type legalization will split an extend of a small, legal, type to a larger
7899 // illegal type by first splitting the destination type, often creating
7900 // illegal source types, which then get legalized in isel-confusing ways,
7901 // leading to really terrible codegen. E.g.,
7902 // %result = v8i32 sext v8i8 %value
7904 // %losrc = extract_subreg %value, ...
7905 // %hisrc = extract_subreg %value, ...
7906 // %lo = v4i32 sext v4i8 %losrc
7907 // %hi = v4i32 sext v4i8 %hisrc
7908 // Things go rapidly downhill from there.
7910 // For AArch64, the [sz]ext vector instructions can only go up one element
7911 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
7912 // take two instructions.
7914 // This implies that the most efficient way to do the extend from v8i8
7915 // to two v4i32 values is to first extend the v8i8 to v8i16, then do
7916 // the normal splitting to happen for the v8i16->v8i32.
7918 // This is pre-legalization to catch some cases where the default
7919 // type legalization will create ill-tempered code.
7920 if (!DCI.isBeforeLegalizeOps())
7923 // We're only interested in cleaning things up for non-legal vector types
7924 // here. If both the source and destination are legal, things will just
7925 // work naturally without any fiddling.
7926 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7927 EVT ResVT = N->getValueType(0);
7928 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
7930 // If the vector type isn't a simple VT, it's beyond the scope of what
7931 // we're worried about here. Let legalization do its thing and hope for
7933 SDValue Src = N->getOperand(0);
7934 EVT SrcVT = Src->getValueType(0);
7935 if (!ResVT.isSimple() || !SrcVT.isSimple())
7938 // If the source VT is a 64-bit vector, we can play games and get the
7939 // better results we want.
7940 if (SrcVT.getSizeInBits() != 64)
7943 unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits();
7944 unsigned ElementCount = SrcVT.getVectorNumElements();
7945 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
7947 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
7949 // Now split the rest of the operation into two halves, each with a 64
7953 unsigned NumElements = ResVT.getVectorNumElements();
7954 assert(!(NumElements & 1) && "Splitting vector, but not in half!");
7955 LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
7956 ResVT.getVectorElementType(), NumElements / 2);
7958 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
7959 LoVT.getVectorNumElements());
7960 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
7961 DAG.getConstant(0, DL, MVT::i64));
7962 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
7963 DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
7964 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
7965 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
7967 // Now combine the parts back together so we still have a single result
7968 // like the combiner expects.
7969 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
7972 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
7973 /// value. The load store optimizer pass will merge them to store pair stores.
7974 /// This has better performance than a splat of the scalar followed by a split
7975 /// vector store. Even if the stores are not merged it is four stores vs a dup,
7976 /// followed by an ext.b and two stores.
7977 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode *St) {
7978 SDValue StVal = St->getValue();
7979 EVT VT = StVal.getValueType();
7981 // Don't replace floating point stores, they possibly won't be transformed to
7982 // stp because of the store pair suppress pass.
7983 if (VT.isFloatingPoint())
7986 // Check for insert vector elements.
7987 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
7990 // We can express a splat as store pair(s) for 2 or 4 elements.
7991 unsigned NumVecElts = VT.getVectorNumElements();
7992 if (NumVecElts != 4 && NumVecElts != 2)
7994 SDValue SplatVal = StVal.getOperand(1);
7995 unsigned RemainInsertElts = NumVecElts - 1;
7997 // Check that this is a splat.
7998 while (--RemainInsertElts) {
7999 SDValue NextInsertElt = StVal.getOperand(0);
8000 if (NextInsertElt.getOpcode() != ISD::INSERT_VECTOR_ELT)
8002 if (NextInsertElt.getOperand(1) != SplatVal)
8004 StVal = NextInsertElt;
8006 unsigned OrigAlignment = St->getAlignment();
8007 unsigned EltOffset = NumVecElts == 4 ? 4 : 8;
8008 unsigned Alignment = std::min(OrigAlignment, EltOffset);
8010 // Create scalar stores. This is at least as good as the code sequence for a
8011 // split unaligned store wich is a dup.s, ext.b, and two stores.
8012 // Most of the time the three stores should be replaced by store pair
8013 // instructions (stp).
8015 SDValue BasePtr = St->getBasePtr();
8017 DAG.getStore(St->getChain(), DL, SplatVal, BasePtr, St->getPointerInfo(),
8018 St->isVolatile(), St->isNonTemporal(), St->getAlignment());
8020 unsigned Offset = EltOffset;
8021 while (--NumVecElts) {
8022 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
8023 DAG.getConstant(Offset, DL, MVT::i64));
8024 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
8025 St->getPointerInfo(), St->isVolatile(),
8026 St->isNonTemporal(), Alignment);
8027 Offset += EltOffset;
8032 static SDValue performSTORECombine(SDNode *N,
8033 TargetLowering::DAGCombinerInfo &DCI,
8035 const AArch64Subtarget *Subtarget) {
8036 if (!DCI.isBeforeLegalize())
8039 StoreSDNode *S = cast<StoreSDNode>(N);
8040 if (S->isVolatile())
8043 // Cyclone has bad performance on unaligned 16B stores when crossing line and
8044 // page boundaries. We want to split such stores.
8045 if (!Subtarget->isCyclone())
8048 // Don't split at Oz.
8049 MachineFunction &MF = DAG.getMachineFunction();
8050 bool IsMinSize = MF.getFunction()->hasFnAttribute(Attribute::MinSize);
8054 SDValue StVal = S->getValue();
8055 EVT VT = StVal.getValueType();
8057 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
8058 // those up regresses performance on micro-benchmarks and olden/bh.
8059 if (!VT.isVector() || VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
8062 // Split unaligned 16B stores. They are terrible for performance.
8063 // Don't split stores with alignment of 1 or 2. Code that uses clang vector
8064 // extensions can use this to mark that it does not want splitting to happen
8065 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
8066 // eliminating alignment hazards is only 1 in 8 for alignment of 2.
8067 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
8068 S->getAlignment() <= 2)
8071 // If we get a splat of a scalar convert this vector store to a store of
8072 // scalars. They will be merged into store pairs thereby removing two
8074 SDValue ReplacedSplat = replaceSplatVectorStore(DAG, S);
8075 if (ReplacedSplat != SDValue())
8076 return ReplacedSplat;
8079 unsigned NumElts = VT.getVectorNumElements() / 2;
8080 // Split VT into two.
8082 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
8083 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
8084 DAG.getConstant(0, DL, MVT::i64));
8085 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
8086 DAG.getConstant(NumElts, DL, MVT::i64));
8087 SDValue BasePtr = S->getBasePtr();
8089 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
8090 S->isVolatile(), S->isNonTemporal(), S->getAlignment());
8091 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
8092 DAG.getConstant(8, DL, MVT::i64));
8093 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
8094 S->getPointerInfo(), S->isVolatile(), S->isNonTemporal(),
8098 /// Target-specific DAG combine function for post-increment LD1 (lane) and
8099 /// post-increment LD1R.
8100 static SDValue performPostLD1Combine(SDNode *N,
8101 TargetLowering::DAGCombinerInfo &DCI,
8103 if (DCI.isBeforeLegalizeOps())
8106 SelectionDAG &DAG = DCI.DAG;
8107 EVT VT = N->getValueType(0);
8109 unsigned LoadIdx = IsLaneOp ? 1 : 0;
8110 SDNode *LD = N->getOperand(LoadIdx).getNode();
8111 // If it is not LOAD, can not do such combine.
8112 if (LD->getOpcode() != ISD::LOAD)
8115 LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
8116 EVT MemVT = LoadSDN->getMemoryVT();
8117 // Check if memory operand is the same type as the vector element.
8118 if (MemVT != VT.getVectorElementType())
8121 // Check if there are other uses. If so, do not combine as it will introduce
8123 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
8125 if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
8131 SDValue Addr = LD->getOperand(1);
8132 SDValue Vector = N->getOperand(0);
8133 // Search for a use of the address operand that is an increment.
8134 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
8135 Addr.getNode()->use_end(); UI != UE; ++UI) {
8137 if (User->getOpcode() != ISD::ADD
8138 || UI.getUse().getResNo() != Addr.getResNo())
8141 // Check that the add is independent of the load. Otherwise, folding it
8142 // would create a cycle.
8143 if (User->isPredecessorOf(LD) || LD->isPredecessorOf(User))
8145 // Also check that add is not used in the vector operand. This would also
8147 if (User->isPredecessorOf(Vector.getNode()))
8150 // If the increment is a constant, it must match the memory ref size.
8151 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8152 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8153 uint32_t IncVal = CInc->getZExtValue();
8154 unsigned NumBytes = VT.getScalarSizeInBits() / 8;
8155 if (IncVal != NumBytes)
8157 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
8160 // Finally, check that the vector doesn't depend on the load.
8161 // Again, this would create a cycle.
8162 // The load depending on the vector is fine, as that's the case for the
8163 // LD1*post we'll eventually generate anyway.
8164 if (LoadSDN->isPredecessorOf(Vector.getNode()))
8167 SmallVector<SDValue, 8> Ops;
8168 Ops.push_back(LD->getOperand(0)); // Chain
8170 Ops.push_back(Vector); // The vector to be inserted
8171 Ops.push_back(N->getOperand(2)); // The lane to be inserted in the vector
8173 Ops.push_back(Addr);
8176 EVT Tys[3] = { VT, MVT::i64, MVT::Other };
8177 SDVTList SDTys = DAG.getVTList(Tys);
8178 unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
8179 SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
8181 LoadSDN->getMemOperand());
8184 SmallVector<SDValue, 2> NewResults;
8185 NewResults.push_back(SDValue(LD, 0)); // The result of load
8186 NewResults.push_back(SDValue(UpdN.getNode(), 2)); // Chain
8187 DCI.CombineTo(LD, NewResults);
8188 DCI.CombineTo(N, SDValue(UpdN.getNode(), 0)); // Dup/Inserted Result
8189 DCI.CombineTo(User, SDValue(UpdN.getNode(), 1)); // Write back register
8196 /// Target-specific DAG combine function for NEON load/store intrinsics
8197 /// to merge base address updates.
8198 static SDValue performNEONPostLDSTCombine(SDNode *N,
8199 TargetLowering::DAGCombinerInfo &DCI,
8200 SelectionDAG &DAG) {
8201 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8204 unsigned AddrOpIdx = N->getNumOperands() - 1;
8205 SDValue Addr = N->getOperand(AddrOpIdx);
8207 // Search for a use of the address operand that is an increment.
8208 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8209 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8211 if (User->getOpcode() != ISD::ADD ||
8212 UI.getUse().getResNo() != Addr.getResNo())
8215 // Check that the add is independent of the load/store. Otherwise, folding
8216 // it would create a cycle.
8217 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8220 // Find the new opcode for the updating load/store.
8221 bool IsStore = false;
8222 bool IsLaneOp = false;
8223 bool IsDupOp = false;
8224 unsigned NewOpc = 0;
8225 unsigned NumVecs = 0;
8226 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8228 default: llvm_unreachable("unexpected intrinsic for Neon base update");
8229 case Intrinsic::aarch64_neon_ld2: NewOpc = AArch64ISD::LD2post;
8231 case Intrinsic::aarch64_neon_ld3: NewOpc = AArch64ISD::LD3post;
8233 case Intrinsic::aarch64_neon_ld4: NewOpc = AArch64ISD::LD4post;
8235 case Intrinsic::aarch64_neon_st2: NewOpc = AArch64ISD::ST2post;
8236 NumVecs = 2; IsStore = true; break;
8237 case Intrinsic::aarch64_neon_st3: NewOpc = AArch64ISD::ST3post;
8238 NumVecs = 3; IsStore = true; break;
8239 case Intrinsic::aarch64_neon_st4: NewOpc = AArch64ISD::ST4post;
8240 NumVecs = 4; IsStore = true; break;
8241 case Intrinsic::aarch64_neon_ld1x2: NewOpc = AArch64ISD::LD1x2post;
8243 case Intrinsic::aarch64_neon_ld1x3: NewOpc = AArch64ISD::LD1x3post;
8245 case Intrinsic::aarch64_neon_ld1x4: NewOpc = AArch64ISD::LD1x4post;
8247 case Intrinsic::aarch64_neon_st1x2: NewOpc = AArch64ISD::ST1x2post;
8248 NumVecs = 2; IsStore = true; break;
8249 case Intrinsic::aarch64_neon_st1x3: NewOpc = AArch64ISD::ST1x3post;
8250 NumVecs = 3; IsStore = true; break;
8251 case Intrinsic::aarch64_neon_st1x4: NewOpc = AArch64ISD::ST1x4post;
8252 NumVecs = 4; IsStore = true; break;
8253 case Intrinsic::aarch64_neon_ld2r: NewOpc = AArch64ISD::LD2DUPpost;
8254 NumVecs = 2; IsDupOp = true; break;
8255 case Intrinsic::aarch64_neon_ld3r: NewOpc = AArch64ISD::LD3DUPpost;
8256 NumVecs = 3; IsDupOp = true; break;
8257 case Intrinsic::aarch64_neon_ld4r: NewOpc = AArch64ISD::LD4DUPpost;
8258 NumVecs = 4; IsDupOp = true; break;
8259 case Intrinsic::aarch64_neon_ld2lane: NewOpc = AArch64ISD::LD2LANEpost;
8260 NumVecs = 2; IsLaneOp = true; break;
8261 case Intrinsic::aarch64_neon_ld3lane: NewOpc = AArch64ISD::LD3LANEpost;
8262 NumVecs = 3; IsLaneOp = true; break;
8263 case Intrinsic::aarch64_neon_ld4lane: NewOpc = AArch64ISD::LD4LANEpost;
8264 NumVecs = 4; IsLaneOp = true; break;
8265 case Intrinsic::aarch64_neon_st2lane: NewOpc = AArch64ISD::ST2LANEpost;
8266 NumVecs = 2; IsStore = true; IsLaneOp = true; break;
8267 case Intrinsic::aarch64_neon_st3lane: NewOpc = AArch64ISD::ST3LANEpost;
8268 NumVecs = 3; IsStore = true; IsLaneOp = true; break;
8269 case Intrinsic::aarch64_neon_st4lane: NewOpc = AArch64ISD::ST4LANEpost;
8270 NumVecs = 4; IsStore = true; IsLaneOp = true; break;
8275 VecTy = N->getOperand(2).getValueType();
8277 VecTy = N->getValueType(0);
8279 // If the increment is a constant, it must match the memory ref size.
8280 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8281 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8282 uint32_t IncVal = CInc->getZExtValue();
8283 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8284 if (IsLaneOp || IsDupOp)
8285 NumBytes /= VecTy.getVectorNumElements();
8286 if (IncVal != NumBytes)
8288 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
8290 SmallVector<SDValue, 8> Ops;
8291 Ops.push_back(N->getOperand(0)); // Incoming chain
8292 // Load lane and store have vector list as input.
8293 if (IsLaneOp || IsStore)
8294 for (unsigned i = 2; i < AddrOpIdx; ++i)
8295 Ops.push_back(N->getOperand(i));
8296 Ops.push_back(Addr); // Base register
8301 unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
8303 for (n = 0; n < NumResultVecs; ++n)
8305 Tys[n++] = MVT::i64; // Type of write back register
8306 Tys[n] = MVT::Other; // Type of the chain
8307 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
8309 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8310 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
8311 MemInt->getMemoryVT(),
8312 MemInt->getMemOperand());
8315 std::vector<SDValue> NewResults;
8316 for (unsigned i = 0; i < NumResultVecs; ++i) {
8317 NewResults.push_back(SDValue(UpdN.getNode(), i));
8319 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
8320 DCI.CombineTo(N, NewResults);
8321 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8328 // Checks to see if the value is the prescribed width and returns information
8329 // about its extension mode.
8331 bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
8332 ExtType = ISD::NON_EXTLOAD;
8333 switch(V.getNode()->getOpcode()) {
8337 LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
8338 if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
8339 || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
8340 ExtType = LoadNode->getExtensionType();
8345 case ISD::AssertSext: {
8346 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
8347 if ((TypeNode->getVT() == MVT::i8 && width == 8)
8348 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
8349 ExtType = ISD::SEXTLOAD;
8354 case ISD::AssertZext: {
8355 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
8356 if ((TypeNode->getVT() == MVT::i8 && width == 8)
8357 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
8358 ExtType = ISD::ZEXTLOAD;
8364 case ISD::TargetConstant: {
8365 if (std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
8375 // This function does a whole lot of voodoo to determine if the tests are
8376 // equivalent without and with a mask. Essentially what happens is that given a
8379 // +-------------+ +-------------+ +-------------+ +-------------+
8380 // | Input | | AddConstant | | CompConstant| | CC |
8381 // +-------------+ +-------------+ +-------------+ +-------------+
8383 // V V | +----------+
8384 // +-------------+ +----+ | |
8385 // | ADD | |0xff| | |
8386 // +-------------+ +----+ | |
8389 // +-------------+ | |
8391 // +-------------+ | |
8400 // The AND node may be safely removed for some combinations of inputs. In
8401 // particular we need to take into account the extension type of the Input,
8402 // the exact values of AddConstant, CompConstant, and CC, along with the nominal
8403 // width of the input (this can work for any width inputs, the above graph is
8404 // specific to 8 bits.
8406 // The specific equations were worked out by generating output tables for each
8407 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
8408 // problem was simplified by working with 4 bit inputs, which means we only
8409 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
8410 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
8411 // patterns present in both extensions (0,7). For every distinct set of
8412 // AddConstant and CompConstants bit patterns we can consider the masked and
8413 // unmasked versions to be equivalent if the result of this function is true for
8414 // all 16 distinct bit patterns of for the current extension type of Input (w0).
8417 // and w10, w8, #0x0f
8419 // cset w9, AArch64CC
8421 // cset w11, AArch64CC
8426 // Since the above function shows when the outputs are equivalent it defines
8427 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
8428 // would be expensive to run during compiles. The equations below were written
8429 // in a test harness that confirmed they gave equivalent outputs to the above
8430 // for all inputs function, so they can be used determine if the removal is
8433 // isEquivalentMaskless() is the code for testing if the AND can be removed
8434 // factored out of the DAG recognition as the DAG can take several forms.
8437 bool isEquivalentMaskless(unsigned CC, unsigned width,
8438 ISD::LoadExtType ExtType, signed AddConstant,
8439 signed CompConstant) {
8440 // By being careful about our equations and only writing the in term
8441 // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
8442 // make them generally applicable to all bit widths.
8443 signed MaxUInt = (1 << width);
8445 // For the purposes of these comparisons sign extending the type is
8446 // equivalent to zero extending the add and displacing it by half the integer
8447 // width. Provided we are careful and make sure our equations are valid over
8448 // the whole range we can just adjust the input and avoid writing equations
8449 // for sign extended inputs.
8450 if (ExtType == ISD::SEXTLOAD)
8451 AddConstant -= (1 << (width-1));
8455 case AArch64CC::GT: {
8456 if ((AddConstant == 0) ||
8457 (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
8458 (AddConstant >= 0 && CompConstant < 0) ||
8459 (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
8463 case AArch64CC::GE: {
8464 if ((AddConstant == 0) ||
8465 (AddConstant >= 0 && CompConstant <= 0) ||
8466 (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
8470 case AArch64CC::LS: {
8471 if ((AddConstant >= 0 && CompConstant < 0) ||
8472 (AddConstant <= 0 && CompConstant >= -1 &&
8473 CompConstant < AddConstant + MaxUInt))
8477 case AArch64CC::MI: {
8478 if ((AddConstant == 0) ||
8479 (AddConstant > 0 && CompConstant <= 0) ||
8480 (AddConstant < 0 && CompConstant <= AddConstant))
8484 case AArch64CC::HS: {
8485 if ((AddConstant >= 0 && CompConstant <= 0) ||
8486 (AddConstant <= 0 && CompConstant >= 0 &&
8487 CompConstant <= AddConstant + MaxUInt))
8491 case AArch64CC::NE: {
8492 if ((AddConstant > 0 && CompConstant < 0) ||
8493 (AddConstant < 0 && CompConstant >= 0 &&
8494 CompConstant < AddConstant + MaxUInt) ||
8495 (AddConstant >= 0 && CompConstant >= 0 &&
8496 CompConstant >= AddConstant) ||
8497 (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
8506 case AArch64CC::Invalid:
8514 SDValue performCONDCombine(SDNode *N,
8515 TargetLowering::DAGCombinerInfo &DCI,
8516 SelectionDAG &DAG, unsigned CCIndex,
8517 unsigned CmpIndex) {
8518 unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
8519 SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
8520 unsigned CondOpcode = SubsNode->getOpcode();
8522 if (CondOpcode != AArch64ISD::SUBS)
8525 // There is a SUBS feeding this condition. Is it fed by a mask we can
8528 SDNode *AndNode = SubsNode->getOperand(0).getNode();
8529 unsigned MaskBits = 0;
8531 if (AndNode->getOpcode() != ISD::AND)
8534 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
8535 uint32_t CNV = CN->getZExtValue();
8538 else if (CNV == 65535)
8545 SDValue AddValue = AndNode->getOperand(0);
8547 if (AddValue.getOpcode() != ISD::ADD)
8550 // The basic dag structure is correct, grab the inputs and validate them.
8552 SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
8553 SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
8554 SDValue SubsInputValue = SubsNode->getOperand(1);
8556 // The mask is present and the provenance of all the values is a smaller type,
8557 // lets see if the mask is superfluous.
8559 if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
8560 !isa<ConstantSDNode>(SubsInputValue.getNode()))
8563 ISD::LoadExtType ExtType;
8565 if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
8566 !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
8567 !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
8570 if(!isEquivalentMaskless(CC, MaskBits, ExtType,
8571 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
8572 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
8575 // The AND is not necessary, remove it.
8577 SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
8578 SubsNode->getValueType(1));
8579 SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
8581 SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
8582 DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
8584 return SDValue(N, 0);
8587 // Optimize compare with zero and branch.
8588 static SDValue performBRCONDCombine(SDNode *N,
8589 TargetLowering::DAGCombinerInfo &DCI,
8590 SelectionDAG &DAG) {
8591 SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3);
8594 SDValue Chain = N->getOperand(0);
8595 SDValue Dest = N->getOperand(1);
8596 SDValue CCVal = N->getOperand(2);
8597 SDValue Cmp = N->getOperand(3);
8599 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
8600 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
8601 if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
8604 unsigned CmpOpc = Cmp.getOpcode();
8605 if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
8608 // Only attempt folding if there is only one use of the flag and no use of the
8610 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
8613 SDValue LHS = Cmp.getOperand(0);
8614 SDValue RHS = Cmp.getOperand(1);
8616 assert(LHS.getValueType() == RHS.getValueType() &&
8617 "Expected the value type to be the same for both operands!");
8618 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
8621 if (isa<ConstantSDNode>(LHS) && cast<ConstantSDNode>(LHS)->isNullValue())
8622 std::swap(LHS, RHS);
8624 if (!isa<ConstantSDNode>(RHS) || !cast<ConstantSDNode>(RHS)->isNullValue())
8627 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
8628 LHS.getOpcode() == ISD::SRL)
8631 // Fold the compare into the branch instruction.
8633 if (CC == AArch64CC::EQ)
8634 BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
8636 BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
8638 // Do not add new nodes to DAG combiner worklist.
8639 DCI.CombineTo(N, BR, false);
8644 // vselect (v1i1 setcc) ->
8645 // vselect (v1iXX setcc) (XX is the size of the compared operand type)
8646 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
8647 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
8649 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
8650 SDValue N0 = N->getOperand(0);
8651 EVT CCVT = N0.getValueType();
8653 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
8654 CCVT.getVectorElementType() != MVT::i1)
8657 EVT ResVT = N->getValueType(0);
8658 EVT CmpVT = N0.getOperand(0).getValueType();
8659 // Only combine when the result type is of the same size as the compared
8661 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
8664 SDValue IfTrue = N->getOperand(1);
8665 SDValue IfFalse = N->getOperand(2);
8667 DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
8668 N0.getOperand(0), N0.getOperand(1),
8669 cast<CondCodeSDNode>(N0.getOperand(2))->get());
8670 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
8674 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
8675 /// the compare-mask instructions rather than going via NZCV, even if LHS and
8676 /// RHS are really scalar. This replaces any scalar setcc in the above pattern
8677 /// with a vector one followed by a DUP shuffle on the result.
8678 static SDValue performSelectCombine(SDNode *N,
8679 TargetLowering::DAGCombinerInfo &DCI) {
8680 SelectionDAG &DAG = DCI.DAG;
8681 SDValue N0 = N->getOperand(0);
8682 EVT ResVT = N->getValueType(0);
8684 if (N0.getOpcode() != ISD::SETCC)
8687 // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
8688 // scalar SetCCResultType. We also don't expect vectors, because we assume
8689 // that selects fed by vector SETCCs are canonicalized to VSELECT.
8690 assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
8691 "Scalar-SETCC feeding SELECT has unexpected result type!");
8693 // If NumMaskElts == 0, the comparison is larger than select result. The
8694 // largest real NEON comparison is 64-bits per lane, which means the result is
8695 // at most 32-bits and an illegal vector. Just bail out for now.
8696 EVT SrcVT = N0.getOperand(0).getValueType();
8698 // Don't try to do this optimization when the setcc itself has i1 operands.
8699 // There are no legal vectors of i1, so this would be pointless.
8700 if (SrcVT == MVT::i1)
8703 int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
8704 if (!ResVT.isVector() || NumMaskElts == 0)
8707 SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
8708 EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
8710 // Also bail out if the vector CCVT isn't the same size as ResVT.
8711 // This can happen if the SETCC operand size doesn't divide the ResVT size
8712 // (e.g., f64 vs v3f32).
8713 if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
8716 // Make sure we didn't create illegal types, if we're not supposed to.
8717 assert(DCI.isBeforeLegalize() ||
8718 DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
8720 // First perform a vector comparison, where lane 0 is the one we're interested
8724 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
8726 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
8727 SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
8729 // Now duplicate the comparison mask we want across all other lanes.
8730 SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
8731 SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask.data());
8732 Mask = DAG.getNode(ISD::BITCAST, DL,
8733 ResVT.changeVectorElementTypeToInteger(), Mask);
8735 return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
8738 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
8739 DAGCombinerInfo &DCI) const {
8740 SelectionDAG &DAG = DCI.DAG;
8741 switch (N->getOpcode()) {
8746 return performAddSubLongCombine(N, DCI, DAG);
8748 return performXorCombine(N, DAG, DCI, Subtarget);
8750 return performMulCombine(N, DAG, DCI, Subtarget);
8751 case ISD::SINT_TO_FP:
8752 case ISD::UINT_TO_FP:
8753 return performIntToFpCombine(N, DAG, Subtarget);
8755 return performORCombine(N, DCI, Subtarget);
8756 case ISD::INTRINSIC_WO_CHAIN:
8757 return performIntrinsicCombine(N, DCI, Subtarget);
8758 case ISD::ANY_EXTEND:
8759 case ISD::ZERO_EXTEND:
8760 case ISD::SIGN_EXTEND:
8761 return performExtendCombine(N, DCI, DAG);
8763 return performBitcastCombine(N, DCI, DAG);
8764 case ISD::CONCAT_VECTORS:
8765 return performConcatVectorsCombine(N, DCI, DAG);
8767 return performSelectCombine(N, DCI);
8769 return performVSelectCombine(N, DCI.DAG);
8771 return performSTORECombine(N, DCI, DAG, Subtarget);
8772 case AArch64ISD::BRCOND:
8773 return performBRCONDCombine(N, DCI, DAG);
8774 case AArch64ISD::CSEL:
8775 return performCONDCombine(N, DCI, DAG, 2, 3);
8776 case AArch64ISD::DUP:
8777 return performPostLD1Combine(N, DCI, false);
8778 case ISD::INSERT_VECTOR_ELT:
8779 return performPostLD1Combine(N, DCI, true);
8780 case ISD::INTRINSIC_VOID:
8781 case ISD::INTRINSIC_W_CHAIN:
8782 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
8783 case Intrinsic::aarch64_neon_ld2:
8784 case Intrinsic::aarch64_neon_ld3:
8785 case Intrinsic::aarch64_neon_ld4:
8786 case Intrinsic::aarch64_neon_ld1x2:
8787 case Intrinsic::aarch64_neon_ld1x3:
8788 case Intrinsic::aarch64_neon_ld1x4:
8789 case Intrinsic::aarch64_neon_ld2lane:
8790 case Intrinsic::aarch64_neon_ld3lane:
8791 case Intrinsic::aarch64_neon_ld4lane:
8792 case Intrinsic::aarch64_neon_ld2r:
8793 case Intrinsic::aarch64_neon_ld3r:
8794 case Intrinsic::aarch64_neon_ld4r:
8795 case Intrinsic::aarch64_neon_st2:
8796 case Intrinsic::aarch64_neon_st3:
8797 case Intrinsic::aarch64_neon_st4:
8798 case Intrinsic::aarch64_neon_st1x2:
8799 case Intrinsic::aarch64_neon_st1x3:
8800 case Intrinsic::aarch64_neon_st1x4:
8801 case Intrinsic::aarch64_neon_st2lane:
8802 case Intrinsic::aarch64_neon_st3lane:
8803 case Intrinsic::aarch64_neon_st4lane:
8804 return performNEONPostLDSTCombine(N, DCI, DAG);
8812 // Check if the return value is used as only a return value, as otherwise
8813 // we can't perform a tail-call. In particular, we need to check for
8814 // target ISD nodes that are returns and any other "odd" constructs
8815 // that the generic analysis code won't necessarily catch.
8816 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
8817 SDValue &Chain) const {
8818 if (N->getNumValues() != 1)
8820 if (!N->hasNUsesOfValue(1, 0))
8823 SDValue TCChain = Chain;
8824 SDNode *Copy = *N->use_begin();
8825 if (Copy->getOpcode() == ISD::CopyToReg) {
8826 // If the copy has a glue operand, we conservatively assume it isn't safe to
8827 // perform a tail call.
8828 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
8831 TCChain = Copy->getOperand(0);
8832 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
8835 bool HasRet = false;
8836 for (SDNode *Node : Copy->uses()) {
8837 if (Node->getOpcode() != AArch64ISD::RET_FLAG)
8849 // Return whether the an instruction can potentially be optimized to a tail
8850 // call. This will cause the optimizers to attempt to move, or duplicate,
8851 // return instructions to help enable tail call optimizations for this
8853 bool AArch64TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
8854 if (!CI->isTailCall())
8860 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
8862 ISD::MemIndexedMode &AM,
8864 SelectionDAG &DAG) const {
8865 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
8868 Base = Op->getOperand(0);
8869 // All of the indexed addressing mode instructions take a signed
8870 // 9 bit immediate offset.
8871 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
8872 int64_t RHSC = (int64_t)RHS->getZExtValue();
8873 if (RHSC >= 256 || RHSC <= -256)
8875 IsInc = (Op->getOpcode() == ISD::ADD);
8876 Offset = Op->getOperand(1);
8882 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
8884 ISD::MemIndexedMode &AM,
8885 SelectionDAG &DAG) const {
8888 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8889 VT = LD->getMemoryVT();
8890 Ptr = LD->getBasePtr();
8891 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
8892 VT = ST->getMemoryVT();
8893 Ptr = ST->getBasePtr();
8898 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
8900 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
8904 bool AArch64TargetLowering::getPostIndexedAddressParts(
8905 SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
8906 ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
8909 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8910 VT = LD->getMemoryVT();
8911 Ptr = LD->getBasePtr();
8912 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
8913 VT = ST->getMemoryVT();
8914 Ptr = ST->getBasePtr();
8919 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
8921 // Post-indexing updates the base, so it's not a valid transform
8922 // if that's not the same as the load's pointer.
8925 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
8929 static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
8930 SelectionDAG &DAG) {
8932 SDValue Op = N->getOperand(0);
8934 if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
8938 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
8939 DAG.getUNDEF(MVT::i32), Op,
8940 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
8942 Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
8943 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
8946 void AArch64TargetLowering::ReplaceNodeResults(
8947 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
8948 switch (N->getOpcode()) {
8950 llvm_unreachable("Don't know how to custom expand this");
8952 ReplaceBITCASTResults(N, Results, DAG);
8954 case ISD::FP_TO_UINT:
8955 case ISD::FP_TO_SINT:
8956 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
8957 // Let normal code take care of it by not adding anything to Results.
8962 bool AArch64TargetLowering::useLoadStackGuardNode() const {
8966 bool AArch64TargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
8967 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8968 // reciprocal if there are three or more FDIVs.
8969 return NumUsers > 2;
8972 TargetLoweringBase::LegalizeTypeAction
8973 AArch64TargetLowering::getPreferredVectorAction(EVT VT) const {
8974 MVT SVT = VT.getSimpleVT();
8975 // During type legalization, we prefer to widen v1i8, v1i16, v1i32 to v8i8,
8976 // v4i16, v2i32 instead of to promote.
8977 if (SVT == MVT::v1i8 || SVT == MVT::v1i16 || SVT == MVT::v1i32
8978 || SVT == MVT::v1f32)
8979 return TypeWidenVector;
8981 return TargetLoweringBase::getPreferredVectorAction(VT);
8984 // Loads and stores less than 128-bits are already atomic; ones above that
8985 // are doomed anyway, so defer to the default libcall and blame the OS when
8987 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
8988 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
8992 // Loads and stores less than 128-bits are already atomic; ones above that
8993 // are doomed anyway, so defer to the default libcall and blame the OS when
8995 bool AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
8996 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
9000 // For the real atomic operations, we have ldxr/stxr up to 128 bits,
9001 TargetLoweringBase::AtomicRMWExpansionKind
9002 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
9003 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
9004 return Size <= 128 ? AtomicRMWExpansionKind::LLSC
9005 : AtomicRMWExpansionKind::None;
9008 bool AArch64TargetLowering::hasLoadLinkedStoreConditional() const {
9012 Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
9013 AtomicOrdering Ord) const {
9014 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
9015 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
9016 bool IsAcquire = isAtLeastAcquire(Ord);
9018 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
9019 // intrinsic must return {i64, i64} and we have to recombine them into a
9020 // single i128 here.
9021 if (ValTy->getPrimitiveSizeInBits() == 128) {
9023 IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
9024 Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int);
9026 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
9027 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
9029 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
9030 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
9031 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
9032 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
9033 return Builder.CreateOr(
9034 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
9037 Type *Tys[] = { Addr->getType() };
9039 IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
9040 Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int, Tys);
9042 return Builder.CreateTruncOrBitCast(
9043 Builder.CreateCall(Ldxr, Addr),
9044 cast<PointerType>(Addr->getType())->getElementType());
9047 Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
9048 Value *Val, Value *Addr,
9049 AtomicOrdering Ord) const {
9050 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
9051 bool IsRelease = isAtLeastRelease(Ord);
9053 // Since the intrinsics must have legal type, the i128 intrinsics take two
9054 // parameters: "i64, i64". We must marshal Val into the appropriate form
9056 if (Val->getType()->getPrimitiveSizeInBits() == 128) {
9058 IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
9059 Function *Stxr = Intrinsic::getDeclaration(M, Int);
9060 Type *Int64Ty = Type::getInt64Ty(M->getContext());
9062 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
9063 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
9064 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
9065 return Builder.CreateCall3(Stxr, Lo, Hi, Addr);
9069 IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
9070 Type *Tys[] = { Addr->getType() };
9071 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
9073 return Builder.CreateCall2(
9074 Stxr, Builder.CreateZExtOrBitCast(
9075 Val, Stxr->getFunctionType()->getParamType(0)),
9079 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
9080 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
9081 return Ty->isArrayTy();