1 //===-- AArch64ISelLowering.cpp - AArch64 DAG Lowering Implementation ----===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the AArch64TargetLowering class.
12 //===----------------------------------------------------------------------===//
14 #include "AArch64ISelLowering.h"
15 #include "AArch64CallingConvention.h"
16 #include "AArch64MachineFunctionInfo.h"
17 #include "AArch64PerfectShuffle.h"
18 #include "AArch64Subtarget.h"
19 #include "AArch64TargetMachine.h"
20 #include "AArch64TargetObjectFile.h"
21 #include "MCTargetDesc/AArch64AddressingModes.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/CodeGen/CallingConvLower.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineInstrBuilder.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/GetElementPtrTypeIterator.h"
29 #include "llvm/IR/Intrinsics.h"
30 #include "llvm/IR/Type.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetOptions.h"
38 #define DEBUG_TYPE "aarch64-lower"
40 STATISTIC(NumTailCalls, "Number of tail calls");
41 STATISTIC(NumShiftInserts, "Number of vector shift inserts");
43 // Place holder until extr generation is tested fully.
45 EnableAArch64ExtrGeneration("aarch64-extr-generation", cl::Hidden,
46 cl::desc("Allow AArch64 (or (shift)(shift))->extract"),
50 EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden,
51 cl::desc("Allow AArch64 SLI/SRI formation"),
54 // FIXME: The necessary dtprel relocations don't seem to be supported
55 // well in the GNU bfd and gold linkers at the moment. Therefore, by
56 // default, for now, fall back to GeneralDynamic code generation.
57 cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration(
58 "aarch64-elf-ldtls-generation", cl::Hidden,
59 cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
62 /// Value type used for condition codes.
63 static const MVT MVT_CC = MVT::i32;
65 AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
66 const AArch64Subtarget &STI)
67 : TargetLowering(TM), Subtarget(&STI) {
69 // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
70 // we have to make something up. Arbitrarily, choose ZeroOrOne.
71 setBooleanContents(ZeroOrOneBooleanContent);
72 // When comparing vectors the result sets the different elements in the
73 // vector to all-one or all-zero.
74 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
76 // Set up the register classes.
77 addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
78 addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
80 if (Subtarget->hasFPARMv8()) {
81 addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
82 addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
83 addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
84 addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
87 if (Subtarget->hasNEON()) {
88 addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
89 addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
90 // Someone set us up the NEON.
91 addDRTypeForNEON(MVT::v2f32);
92 addDRTypeForNEON(MVT::v8i8);
93 addDRTypeForNEON(MVT::v4i16);
94 addDRTypeForNEON(MVT::v2i32);
95 addDRTypeForNEON(MVT::v1i64);
96 addDRTypeForNEON(MVT::v1f64);
97 addDRTypeForNEON(MVT::v4f16);
99 addQRTypeForNEON(MVT::v4f32);
100 addQRTypeForNEON(MVT::v2f64);
101 addQRTypeForNEON(MVT::v16i8);
102 addQRTypeForNEON(MVT::v8i16);
103 addQRTypeForNEON(MVT::v4i32);
104 addQRTypeForNEON(MVT::v2i64);
105 addQRTypeForNEON(MVT::v8f16);
108 // Compute derived properties from the register classes
109 computeRegisterProperties(Subtarget->getRegisterInfo());
111 // Provide all sorts of operation actions
112 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
113 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
114 setOperationAction(ISD::SETCC, MVT::i32, Custom);
115 setOperationAction(ISD::SETCC, MVT::i64, Custom);
116 setOperationAction(ISD::SETCC, MVT::f32, Custom);
117 setOperationAction(ISD::SETCC, MVT::f64, Custom);
118 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
119 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
120 setOperationAction(ISD::BR_CC, MVT::i64, Custom);
121 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
122 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
123 setOperationAction(ISD::SELECT, MVT::i32, Custom);
124 setOperationAction(ISD::SELECT, MVT::i64, Custom);
125 setOperationAction(ISD::SELECT, MVT::f32, Custom);
126 setOperationAction(ISD::SELECT, MVT::f64, Custom);
127 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
128 setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
129 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
130 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
131 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
132 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
134 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
135 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
136 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
138 setOperationAction(ISD::FREM, MVT::f32, Expand);
139 setOperationAction(ISD::FREM, MVT::f64, Expand);
140 setOperationAction(ISD::FREM, MVT::f80, Expand);
142 // Custom lowering hooks are needed for XOR
143 // to fold it into CSINC/CSINV.
144 setOperationAction(ISD::XOR, MVT::i32, Custom);
145 setOperationAction(ISD::XOR, MVT::i64, Custom);
147 // Virtually no operation on f128 is legal, but LLVM can't expand them when
148 // there's a valid register class, so we need custom operations in most cases.
149 setOperationAction(ISD::FABS, MVT::f128, Expand);
150 setOperationAction(ISD::FADD, MVT::f128, Custom);
151 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
152 setOperationAction(ISD::FCOS, MVT::f128, Expand);
153 setOperationAction(ISD::FDIV, MVT::f128, Custom);
154 setOperationAction(ISD::FMA, MVT::f128, Expand);
155 setOperationAction(ISD::FMUL, MVT::f128, Custom);
156 setOperationAction(ISD::FNEG, MVT::f128, Expand);
157 setOperationAction(ISD::FPOW, MVT::f128, Expand);
158 setOperationAction(ISD::FREM, MVT::f128, Expand);
159 setOperationAction(ISD::FRINT, MVT::f128, Expand);
160 setOperationAction(ISD::FSIN, MVT::f128, Expand);
161 setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
162 setOperationAction(ISD::FSQRT, MVT::f128, Expand);
163 setOperationAction(ISD::FSUB, MVT::f128, Custom);
164 setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
165 setOperationAction(ISD::SETCC, MVT::f128, Custom);
166 setOperationAction(ISD::BR_CC, MVT::f128, Custom);
167 setOperationAction(ISD::SELECT, MVT::f128, Custom);
168 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
169 setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
171 // Lowering for many of the conversions is actually specified by the non-f128
172 // type. The LowerXXX function will be trivial when f128 isn't involved.
173 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
174 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
175 setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
176 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
177 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
178 setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
179 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
180 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
181 setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
182 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
183 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
184 setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
185 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
186 setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
188 // Variable arguments.
189 setOperationAction(ISD::VASTART, MVT::Other, Custom);
190 setOperationAction(ISD::VAARG, MVT::Other, Custom);
191 setOperationAction(ISD::VACOPY, MVT::Other, Custom);
192 setOperationAction(ISD::VAEND, MVT::Other, Expand);
194 // Variable-sized objects.
195 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
196 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
197 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
199 // Constant pool entries
200 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
203 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
205 // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
206 setOperationAction(ISD::ADDC, MVT::i32, Custom);
207 setOperationAction(ISD::ADDE, MVT::i32, Custom);
208 setOperationAction(ISD::SUBC, MVT::i32, Custom);
209 setOperationAction(ISD::SUBE, MVT::i32, Custom);
210 setOperationAction(ISD::ADDC, MVT::i64, Custom);
211 setOperationAction(ISD::ADDE, MVT::i64, Custom);
212 setOperationAction(ISD::SUBC, MVT::i64, Custom);
213 setOperationAction(ISD::SUBE, MVT::i64, Custom);
215 // AArch64 lacks both left-rotate and popcount instructions.
216 setOperationAction(ISD::ROTL, MVT::i32, Expand);
217 setOperationAction(ISD::ROTL, MVT::i64, Expand);
218 for (MVT VT : MVT::vector_valuetypes()) {
219 setOperationAction(ISD::ROTL, VT, Expand);
220 setOperationAction(ISD::ROTR, VT, Expand);
223 // AArch64 doesn't have {U|S}MUL_LOHI.
224 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
225 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
228 // Expand the undefined-at-zero variants to cttz/ctlz to their defined-at-zero
229 // counterparts, which AArch64 supports directly.
230 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
231 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
232 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
233 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
235 setOperationAction(ISD::CTPOP, MVT::i32, Custom);
236 setOperationAction(ISD::CTPOP, MVT::i64, Custom);
238 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
239 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
240 for (MVT VT : MVT::vector_valuetypes()) {
241 setOperationAction(ISD::SDIVREM, VT, Expand);
242 setOperationAction(ISD::UDIVREM, VT, Expand);
244 setOperationAction(ISD::SREM, MVT::i32, Expand);
245 setOperationAction(ISD::SREM, MVT::i64, Expand);
246 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
247 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
248 setOperationAction(ISD::UREM, MVT::i32, Expand);
249 setOperationAction(ISD::UREM, MVT::i64, Expand);
251 // Custom lower Add/Sub/Mul with overflow.
252 setOperationAction(ISD::SADDO, MVT::i32, Custom);
253 setOperationAction(ISD::SADDO, MVT::i64, Custom);
254 setOperationAction(ISD::UADDO, MVT::i32, Custom);
255 setOperationAction(ISD::UADDO, MVT::i64, Custom);
256 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
257 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
258 setOperationAction(ISD::USUBO, MVT::i32, Custom);
259 setOperationAction(ISD::USUBO, MVT::i64, Custom);
260 setOperationAction(ISD::SMULO, MVT::i32, Custom);
261 setOperationAction(ISD::SMULO, MVT::i64, Custom);
262 setOperationAction(ISD::UMULO, MVT::i32, Custom);
263 setOperationAction(ISD::UMULO, MVT::i64, Custom);
265 setOperationAction(ISD::FSIN, MVT::f32, Expand);
266 setOperationAction(ISD::FSIN, MVT::f64, Expand);
267 setOperationAction(ISD::FCOS, MVT::f32, Expand);
268 setOperationAction(ISD::FCOS, MVT::f64, Expand);
269 setOperationAction(ISD::FPOW, MVT::f32, Expand);
270 setOperationAction(ISD::FPOW, MVT::f64, Expand);
271 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
272 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
274 // f16 is a storage-only type, always promote it to f32.
275 setOperationAction(ISD::SETCC, MVT::f16, Promote);
276 setOperationAction(ISD::BR_CC, MVT::f16, Promote);
277 setOperationAction(ISD::SELECT_CC, MVT::f16, Promote);
278 setOperationAction(ISD::SELECT, MVT::f16, Promote);
279 setOperationAction(ISD::FADD, MVT::f16, Promote);
280 setOperationAction(ISD::FSUB, MVT::f16, Promote);
281 setOperationAction(ISD::FMUL, MVT::f16, Promote);
282 setOperationAction(ISD::FDIV, MVT::f16, Promote);
283 setOperationAction(ISD::FREM, MVT::f16, Promote);
284 setOperationAction(ISD::FMA, MVT::f16, Promote);
285 setOperationAction(ISD::FNEG, MVT::f16, Promote);
286 setOperationAction(ISD::FABS, MVT::f16, Promote);
287 setOperationAction(ISD::FCEIL, MVT::f16, Promote);
288 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote);
289 setOperationAction(ISD::FCOS, MVT::f16, Promote);
290 setOperationAction(ISD::FFLOOR, MVT::f16, Promote);
291 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote);
292 setOperationAction(ISD::FPOW, MVT::f16, Promote);
293 setOperationAction(ISD::FPOWI, MVT::f16, Promote);
294 setOperationAction(ISD::FRINT, MVT::f16, Promote);
295 setOperationAction(ISD::FSIN, MVT::f16, Promote);
296 setOperationAction(ISD::FSINCOS, MVT::f16, Promote);
297 setOperationAction(ISD::FSQRT, MVT::f16, Promote);
298 setOperationAction(ISD::FEXP, MVT::f16, Promote);
299 setOperationAction(ISD::FEXP2, MVT::f16, Promote);
300 setOperationAction(ISD::FLOG, MVT::f16, Promote);
301 setOperationAction(ISD::FLOG2, MVT::f16, Promote);
302 setOperationAction(ISD::FLOG10, MVT::f16, Promote);
303 setOperationAction(ISD::FROUND, MVT::f16, Promote);
304 setOperationAction(ISD::FTRUNC, MVT::f16, Promote);
305 setOperationAction(ISD::FMINNUM, MVT::f16, Promote);
306 setOperationAction(ISD::FMAXNUM, MVT::f16, Promote);
307 setOperationAction(ISD::FMINNAN, MVT::f16, Promote);
308 setOperationAction(ISD::FMAXNAN, MVT::f16, Promote);
310 // v4f16 is also a storage-only type, so promote it to v4f32 when that is
312 setOperationAction(ISD::FADD, MVT::v4f16, Promote);
313 setOperationAction(ISD::FSUB, MVT::v4f16, Promote);
314 setOperationAction(ISD::FMUL, MVT::v4f16, Promote);
315 setOperationAction(ISD::FDIV, MVT::v4f16, Promote);
316 setOperationAction(ISD::FP_EXTEND, MVT::v4f16, Promote);
317 setOperationAction(ISD::FP_ROUND, MVT::v4f16, Promote);
318 AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32);
319 AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32);
320 AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32);
321 AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32);
322 AddPromotedToType(ISD::FP_EXTEND, MVT::v4f16, MVT::v4f32);
323 AddPromotedToType(ISD::FP_ROUND, MVT::v4f16, MVT::v4f32);
325 // Expand all other v4f16 operations.
326 // FIXME: We could generate better code by promoting some operations to
328 setOperationAction(ISD::FABS, MVT::v4f16, Expand);
329 setOperationAction(ISD::FCEIL, MVT::v4f16, Expand);
330 setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand);
331 setOperationAction(ISD::FCOS, MVT::v4f16, Expand);
332 setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand);
333 setOperationAction(ISD::FMA, MVT::v4f16, Expand);
334 setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand);
335 setOperationAction(ISD::FNEG, MVT::v4f16, Expand);
336 setOperationAction(ISD::FPOW, MVT::v4f16, Expand);
337 setOperationAction(ISD::FPOWI, MVT::v4f16, Expand);
338 setOperationAction(ISD::FREM, MVT::v4f16, Expand);
339 setOperationAction(ISD::FROUND, MVT::v4f16, Expand);
340 setOperationAction(ISD::FRINT, MVT::v4f16, Expand);
341 setOperationAction(ISD::FSIN, MVT::v4f16, Expand);
342 setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand);
343 setOperationAction(ISD::FSQRT, MVT::v4f16, Expand);
344 setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand);
345 setOperationAction(ISD::SETCC, MVT::v4f16, Expand);
346 setOperationAction(ISD::BR_CC, MVT::v4f16, Expand);
347 setOperationAction(ISD::SELECT, MVT::v4f16, Expand);
348 setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand);
349 setOperationAction(ISD::FEXP, MVT::v4f16, Expand);
350 setOperationAction(ISD::FEXP2, MVT::v4f16, Expand);
351 setOperationAction(ISD::FLOG, MVT::v4f16, Expand);
352 setOperationAction(ISD::FLOG2, MVT::v4f16, Expand);
353 setOperationAction(ISD::FLOG10, MVT::v4f16, Expand);
356 // v8f16 is also a storage-only type, so expand it.
357 setOperationAction(ISD::FABS, MVT::v8f16, Expand);
358 setOperationAction(ISD::FADD, MVT::v8f16, Expand);
359 setOperationAction(ISD::FCEIL, MVT::v8f16, Expand);
360 setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand);
361 setOperationAction(ISD::FCOS, MVT::v8f16, Expand);
362 setOperationAction(ISD::FDIV, MVT::v8f16, Expand);
363 setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand);
364 setOperationAction(ISD::FMA, MVT::v8f16, Expand);
365 setOperationAction(ISD::FMUL, MVT::v8f16, Expand);
366 setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand);
367 setOperationAction(ISD::FNEG, MVT::v8f16, Expand);
368 setOperationAction(ISD::FPOW, MVT::v8f16, Expand);
369 setOperationAction(ISD::FPOWI, MVT::v8f16, Expand);
370 setOperationAction(ISD::FREM, MVT::v8f16, Expand);
371 setOperationAction(ISD::FROUND, MVT::v8f16, Expand);
372 setOperationAction(ISD::FRINT, MVT::v8f16, Expand);
373 setOperationAction(ISD::FSIN, MVT::v8f16, Expand);
374 setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
375 setOperationAction(ISD::FSQRT, MVT::v8f16, Expand);
376 setOperationAction(ISD::FSUB, MVT::v8f16, Expand);
377 setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand);
378 setOperationAction(ISD::SETCC, MVT::v8f16, Expand);
379 setOperationAction(ISD::BR_CC, MVT::v8f16, Expand);
380 setOperationAction(ISD::SELECT, MVT::v8f16, Expand);
381 setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand);
382 setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand);
383 setOperationAction(ISD::FEXP, MVT::v8f16, Expand);
384 setOperationAction(ISD::FEXP2, MVT::v8f16, Expand);
385 setOperationAction(ISD::FLOG, MVT::v8f16, Expand);
386 setOperationAction(ISD::FLOG2, MVT::v8f16, Expand);
387 setOperationAction(ISD::FLOG10, MVT::v8f16, Expand);
389 // AArch64 has implementations of a lot of rounding-like FP operations.
390 for (MVT Ty : {MVT::f32, MVT::f64}) {
391 setOperationAction(ISD::FFLOOR, Ty, Legal);
392 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
393 setOperationAction(ISD::FCEIL, Ty, Legal);
394 setOperationAction(ISD::FRINT, Ty, Legal);
395 setOperationAction(ISD::FTRUNC, Ty, Legal);
396 setOperationAction(ISD::FROUND, Ty, Legal);
397 setOperationAction(ISD::FMINNUM, Ty, Legal);
398 setOperationAction(ISD::FMAXNUM, Ty, Legal);
399 setOperationAction(ISD::FMINNAN, Ty, Legal);
400 setOperationAction(ISD::FMAXNAN, Ty, Legal);
403 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
405 // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
406 // This requires the Performance Monitors extension.
407 if (Subtarget->hasPerfMon())
408 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
410 if (Subtarget->isTargetMachO()) {
411 // For iOS, we don't want to the normal expansion of a libcall to
412 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
414 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
415 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
417 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
418 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
421 // Make floating-point constants legal for the large code model, so they don't
422 // become loads from the constant pool.
423 if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
424 setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
425 setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
428 // AArch64 does not have floating-point extending loads, i1 sign-extending
429 // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
430 for (MVT VT : MVT::fp_valuetypes()) {
431 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
432 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
433 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
434 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
436 for (MVT VT : MVT::integer_valuetypes())
437 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
439 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
440 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
441 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
442 setTruncStoreAction(MVT::f128, MVT::f80, Expand);
443 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
444 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
445 setTruncStoreAction(MVT::f128, MVT::f16, Expand);
447 setOperationAction(ISD::BITCAST, MVT::i16, Custom);
448 setOperationAction(ISD::BITCAST, MVT::f16, Custom);
450 // Indexed loads and stores are supported.
451 for (unsigned im = (unsigned)ISD::PRE_INC;
452 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
453 setIndexedLoadAction(im, MVT::i8, Legal);
454 setIndexedLoadAction(im, MVT::i16, Legal);
455 setIndexedLoadAction(im, MVT::i32, Legal);
456 setIndexedLoadAction(im, MVT::i64, Legal);
457 setIndexedLoadAction(im, MVT::f64, Legal);
458 setIndexedLoadAction(im, MVT::f32, Legal);
459 setIndexedLoadAction(im, MVT::f16, Legal);
460 setIndexedStoreAction(im, MVT::i8, Legal);
461 setIndexedStoreAction(im, MVT::i16, Legal);
462 setIndexedStoreAction(im, MVT::i32, Legal);
463 setIndexedStoreAction(im, MVT::i64, Legal);
464 setIndexedStoreAction(im, MVT::f64, Legal);
465 setIndexedStoreAction(im, MVT::f32, Legal);
466 setIndexedStoreAction(im, MVT::f16, Legal);
470 setOperationAction(ISD::TRAP, MVT::Other, Legal);
472 // We combine OR nodes for bitfield operations.
473 setTargetDAGCombine(ISD::OR);
475 // Vector add and sub nodes may conceal a high-half opportunity.
476 // Also, try to fold ADD into CSINC/CSINV..
477 setTargetDAGCombine(ISD::ADD);
478 setTargetDAGCombine(ISD::SUB);
480 setTargetDAGCombine(ISD::XOR);
481 setTargetDAGCombine(ISD::SINT_TO_FP);
482 setTargetDAGCombine(ISD::UINT_TO_FP);
484 setTargetDAGCombine(ISD::FP_TO_SINT);
485 setTargetDAGCombine(ISD::FP_TO_UINT);
486 setTargetDAGCombine(ISD::FDIV);
488 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
490 setTargetDAGCombine(ISD::ANY_EXTEND);
491 setTargetDAGCombine(ISD::ZERO_EXTEND);
492 setTargetDAGCombine(ISD::SIGN_EXTEND);
493 setTargetDAGCombine(ISD::BITCAST);
494 setTargetDAGCombine(ISD::CONCAT_VECTORS);
495 setTargetDAGCombine(ISD::STORE);
496 if (Subtarget->supportsAddressTopByteIgnored())
497 setTargetDAGCombine(ISD::LOAD);
499 setTargetDAGCombine(ISD::MUL);
501 setTargetDAGCombine(ISD::SELECT);
502 setTargetDAGCombine(ISD::VSELECT);
504 setTargetDAGCombine(ISD::INTRINSIC_VOID);
505 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
506 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
507 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
509 MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 8;
510 MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 4;
511 MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = 4;
513 setStackPointerRegisterToSaveRestore(AArch64::SP);
515 setSchedulingPreference(Sched::Hybrid);
518 MaskAndBranchFoldingIsLegal = true;
519 EnableExtLdPromotion = true;
521 setMinFunctionAlignment(2);
523 setHasExtractBitsInsn(true);
525 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
527 if (Subtarget->hasNEON()) {
528 // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
529 // silliness like this:
530 setOperationAction(ISD::FABS, MVT::v1f64, Expand);
531 setOperationAction(ISD::FADD, MVT::v1f64, Expand);
532 setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
533 setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
534 setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
535 setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
536 setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
537 setOperationAction(ISD::FMA, MVT::v1f64, Expand);
538 setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
539 setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
540 setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
541 setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
542 setOperationAction(ISD::FREM, MVT::v1f64, Expand);
543 setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
544 setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
545 setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
546 setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
547 setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
548 setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
549 setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
550 setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
551 setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
552 setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
553 setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
554 setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
556 setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
557 setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
558 setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
559 setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
560 setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
562 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
564 // AArch64 doesn't have a direct vector ->f32 conversion instructions for
565 // elements smaller than i32, so promote the input to i32 first.
566 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Promote);
567 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Promote);
568 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Promote);
569 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Promote);
570 // i8 and i16 vector elements also need promotion to i32 for v8i8 or v8i16
571 // -> v8f16 conversions.
572 setOperationAction(ISD::SINT_TO_FP, MVT::v8i8, Promote);
573 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Promote);
574 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
575 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Promote);
576 // Similarly, there is no direct i32 -> f64 vector conversion instruction.
577 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
578 setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
579 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
580 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
581 // Or, direct i32 -> f16 vector conversion. Set it so custom, so the
582 // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
583 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
584 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
586 // AArch64 doesn't have MUL.2d:
587 setOperationAction(ISD::MUL, MVT::v2i64, Expand);
588 // Custom handling for some quad-vector types to detect MULL.
589 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
590 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
591 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
593 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
594 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
595 // Likewise, narrowing and extending vector loads/stores aren't handled
597 for (MVT VT : MVT::vector_valuetypes()) {
598 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
600 setOperationAction(ISD::MULHS, VT, Expand);
601 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
602 setOperationAction(ISD::MULHU, VT, Expand);
603 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
605 setOperationAction(ISD::BSWAP, VT, Expand);
607 for (MVT InnerVT : MVT::vector_valuetypes()) {
608 setTruncStoreAction(VT, InnerVT, Expand);
609 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
610 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
611 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
615 // AArch64 has implementations of a lot of rounding-like FP operations.
616 for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
617 setOperationAction(ISD::FFLOOR, Ty, Legal);
618 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
619 setOperationAction(ISD::FCEIL, Ty, Legal);
620 setOperationAction(ISD::FRINT, Ty, Legal);
621 setOperationAction(ISD::FTRUNC, Ty, Legal);
622 setOperationAction(ISD::FROUND, Ty, Legal);
626 // Prefer likely predicted branches to selects on out-of-order cores.
627 if (Subtarget->isCortexA57())
628 PredictableSelectIsExpensive = true;
631 void AArch64TargetLowering::addTypeForNEON(EVT VT, EVT PromotedBitwiseVT) {
632 if (VT == MVT::v2f32 || VT == MVT::v4f16) {
633 setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
634 AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i32);
636 setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
637 AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i32);
638 } else if (VT == MVT::v2f64 || VT == MVT::v4f32 || VT == MVT::v8f16) {
639 setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
640 AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i64);
642 setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
643 AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i64);
646 // Mark vector float intrinsics as expand.
647 if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
648 setOperationAction(ISD::FSIN, VT.getSimpleVT(), Expand);
649 setOperationAction(ISD::FCOS, VT.getSimpleVT(), Expand);
650 setOperationAction(ISD::FPOWI, VT.getSimpleVT(), Expand);
651 setOperationAction(ISD::FPOW, VT.getSimpleVT(), Expand);
652 setOperationAction(ISD::FLOG, VT.getSimpleVT(), Expand);
653 setOperationAction(ISD::FLOG2, VT.getSimpleVT(), Expand);
654 setOperationAction(ISD::FLOG10, VT.getSimpleVT(), Expand);
655 setOperationAction(ISD::FEXP, VT.getSimpleVT(), Expand);
656 setOperationAction(ISD::FEXP2, VT.getSimpleVT(), Expand);
658 // But we do support custom-lowering for FCOPYSIGN.
659 setOperationAction(ISD::FCOPYSIGN, VT.getSimpleVT(), Custom);
662 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT.getSimpleVT(), Custom);
663 setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getSimpleVT(), Custom);
664 setOperationAction(ISD::BUILD_VECTOR, VT.getSimpleVT(), Custom);
665 setOperationAction(ISD::VECTOR_SHUFFLE, VT.getSimpleVT(), Custom);
666 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT.getSimpleVT(), Custom);
667 setOperationAction(ISD::SRA, VT.getSimpleVT(), Custom);
668 setOperationAction(ISD::SRL, VT.getSimpleVT(), Custom);
669 setOperationAction(ISD::SHL, VT.getSimpleVT(), Custom);
670 setOperationAction(ISD::AND, VT.getSimpleVT(), Custom);
671 setOperationAction(ISD::OR, VT.getSimpleVT(), Custom);
672 setOperationAction(ISD::SETCC, VT.getSimpleVT(), Custom);
673 setOperationAction(ISD::CONCAT_VECTORS, VT.getSimpleVT(), Legal);
675 setOperationAction(ISD::SELECT, VT.getSimpleVT(), Expand);
676 setOperationAction(ISD::SELECT_CC, VT.getSimpleVT(), Expand);
677 setOperationAction(ISD::VSELECT, VT.getSimpleVT(), Expand);
678 for (MVT InnerVT : MVT::all_valuetypes())
679 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT.getSimpleVT(), Expand);
681 // CNT supports only B element sizes.
682 if (VT != MVT::v8i8 && VT != MVT::v16i8)
683 setOperationAction(ISD::CTPOP, VT.getSimpleVT(), Expand);
685 setOperationAction(ISD::UDIV, VT.getSimpleVT(), Expand);
686 setOperationAction(ISD::SDIV, VT.getSimpleVT(), Expand);
687 setOperationAction(ISD::UREM, VT.getSimpleVT(), Expand);
688 setOperationAction(ISD::SREM, VT.getSimpleVT(), Expand);
689 setOperationAction(ISD::FREM, VT.getSimpleVT(), Expand);
691 setOperationAction(ISD::FP_TO_SINT, VT.getSimpleVT(), Custom);
692 setOperationAction(ISD::FP_TO_UINT, VT.getSimpleVT(), Custom);
694 // [SU][MIN|MAX] and [SU]ABSDIFF are available for all NEON types apart from
696 if (!VT.isFloatingPoint() &&
697 VT.getSimpleVT() != MVT::v2i64 && VT.getSimpleVT() != MVT::v1i64)
698 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX,
699 ISD::SABSDIFF, ISD::UABSDIFF})
700 setOperationAction(Opcode, VT.getSimpleVT(), Legal);
702 // F[MIN|MAX][NUM|NAN] are available for all FP NEON types (not f16 though!).
703 if (VT.isFloatingPoint() && VT.getVectorElementType() != MVT::f16)
704 for (unsigned Opcode : {ISD::FMINNAN, ISD::FMAXNAN,
705 ISD::FMINNUM, ISD::FMAXNUM})
706 setOperationAction(Opcode, VT.getSimpleVT(), Legal);
708 if (Subtarget->isLittleEndian()) {
709 for (unsigned im = (unsigned)ISD::PRE_INC;
710 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
711 setIndexedLoadAction(im, VT.getSimpleVT(), Legal);
712 setIndexedStoreAction(im, VT.getSimpleVT(), Legal);
717 void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
718 addRegisterClass(VT, &AArch64::FPR64RegClass);
719 addTypeForNEON(VT, MVT::v2i32);
722 void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
723 addRegisterClass(VT, &AArch64::FPR128RegClass);
724 addTypeForNEON(VT, MVT::v4i32);
727 EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
731 return VT.changeVectorElementTypeToInteger();
734 /// computeKnownBitsForTargetNode - Determine which of the bits specified in
735 /// Mask are known to be either zero or one and return them in the
736 /// KnownZero/KnownOne bitsets.
737 void AArch64TargetLowering::computeKnownBitsForTargetNode(
738 const SDValue Op, APInt &KnownZero, APInt &KnownOne,
739 const SelectionDAG &DAG, unsigned Depth) const {
740 switch (Op.getOpcode()) {
743 case AArch64ISD::CSEL: {
744 APInt KnownZero2, KnownOne2;
745 DAG.computeKnownBits(Op->getOperand(0), KnownZero, KnownOne, Depth + 1);
746 DAG.computeKnownBits(Op->getOperand(1), KnownZero2, KnownOne2, Depth + 1);
747 KnownZero &= KnownZero2;
748 KnownOne &= KnownOne2;
751 case ISD::INTRINSIC_W_CHAIN: {
752 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
753 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
756 case Intrinsic::aarch64_ldaxr:
757 case Intrinsic::aarch64_ldxr: {
758 unsigned BitWidth = KnownOne.getBitWidth();
759 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
760 unsigned MemBits = VT.getScalarType().getSizeInBits();
761 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
767 case ISD::INTRINSIC_WO_CHAIN:
768 case ISD::INTRINSIC_VOID: {
769 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
773 case Intrinsic::aarch64_neon_umaxv:
774 case Intrinsic::aarch64_neon_uminv: {
775 // Figure out the datatype of the vector operand. The UMINV instruction
776 // will zero extend the result, so we can mark as known zero all the
777 // bits larger than the element datatype. 32-bit or larget doesn't need
778 // this as those are legal types and will be handled by isel directly.
779 MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
780 unsigned BitWidth = KnownZero.getBitWidth();
781 if (VT == MVT::v8i8 || VT == MVT::v16i8) {
782 assert(BitWidth >= 8 && "Unexpected width!");
783 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
785 } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
786 assert(BitWidth >= 16 && "Unexpected width!");
787 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
797 MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
802 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
806 if (Subtarget->requiresStrictAlign())
809 // FIXME: This is mostly true for Cyclone, but not necessarily others.
811 // FIXME: Define an attribute for slow unaligned accesses instead of
812 // relying on the CPU type as a proxy.
813 // On Cyclone, unaligned 128-bit stores are slow.
814 *Fast = !Subtarget->isCyclone() || VT.getStoreSize() != 16 ||
815 // See comments in performSTORECombine() for more details about
818 // Code that uses clang vector extensions can mark that it
819 // wants unaligned accesses to be treated as fast by
820 // underspecifying alignment to be 1 or 2.
823 // Disregard v2i64. Memcpy lowering produces those and splitting
824 // them regresses performance on micro-benchmarks and olden/bh.
831 AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
832 const TargetLibraryInfo *libInfo) const {
833 return AArch64::createFastISel(funcInfo, libInfo);
836 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
837 switch ((AArch64ISD::NodeType)Opcode) {
838 case AArch64ISD::FIRST_NUMBER: break;
839 case AArch64ISD::CALL: return "AArch64ISD::CALL";
840 case AArch64ISD::ADRP: return "AArch64ISD::ADRP";
841 case AArch64ISD::ADDlow: return "AArch64ISD::ADDlow";
842 case AArch64ISD::LOADgot: return "AArch64ISD::LOADgot";
843 case AArch64ISD::RET_FLAG: return "AArch64ISD::RET_FLAG";
844 case AArch64ISD::BRCOND: return "AArch64ISD::BRCOND";
845 case AArch64ISD::CSEL: return "AArch64ISD::CSEL";
846 case AArch64ISD::FCSEL: return "AArch64ISD::FCSEL";
847 case AArch64ISD::CSINV: return "AArch64ISD::CSINV";
848 case AArch64ISD::CSNEG: return "AArch64ISD::CSNEG";
849 case AArch64ISD::CSINC: return "AArch64ISD::CSINC";
850 case AArch64ISD::THREAD_POINTER: return "AArch64ISD::THREAD_POINTER";
851 case AArch64ISD::TLSDESC_CALLSEQ: return "AArch64ISD::TLSDESC_CALLSEQ";
852 case AArch64ISD::ADC: return "AArch64ISD::ADC";
853 case AArch64ISD::SBC: return "AArch64ISD::SBC";
854 case AArch64ISD::ADDS: return "AArch64ISD::ADDS";
855 case AArch64ISD::SUBS: return "AArch64ISD::SUBS";
856 case AArch64ISD::ADCS: return "AArch64ISD::ADCS";
857 case AArch64ISD::SBCS: return "AArch64ISD::SBCS";
858 case AArch64ISD::ANDS: return "AArch64ISD::ANDS";
859 case AArch64ISD::CCMP: return "AArch64ISD::CCMP";
860 case AArch64ISD::CCMN: return "AArch64ISD::CCMN";
861 case AArch64ISD::FCCMP: return "AArch64ISD::FCCMP";
862 case AArch64ISD::FCMP: return "AArch64ISD::FCMP";
863 case AArch64ISD::DUP: return "AArch64ISD::DUP";
864 case AArch64ISD::DUPLANE8: return "AArch64ISD::DUPLANE8";
865 case AArch64ISD::DUPLANE16: return "AArch64ISD::DUPLANE16";
866 case AArch64ISD::DUPLANE32: return "AArch64ISD::DUPLANE32";
867 case AArch64ISD::DUPLANE64: return "AArch64ISD::DUPLANE64";
868 case AArch64ISD::MOVI: return "AArch64ISD::MOVI";
869 case AArch64ISD::MOVIshift: return "AArch64ISD::MOVIshift";
870 case AArch64ISD::MOVIedit: return "AArch64ISD::MOVIedit";
871 case AArch64ISD::MOVImsl: return "AArch64ISD::MOVImsl";
872 case AArch64ISD::FMOV: return "AArch64ISD::FMOV";
873 case AArch64ISD::MVNIshift: return "AArch64ISD::MVNIshift";
874 case AArch64ISD::MVNImsl: return "AArch64ISD::MVNImsl";
875 case AArch64ISD::BICi: return "AArch64ISD::BICi";
876 case AArch64ISD::ORRi: return "AArch64ISD::ORRi";
877 case AArch64ISD::BSL: return "AArch64ISD::BSL";
878 case AArch64ISD::NEG: return "AArch64ISD::NEG";
879 case AArch64ISD::EXTR: return "AArch64ISD::EXTR";
880 case AArch64ISD::ZIP1: return "AArch64ISD::ZIP1";
881 case AArch64ISD::ZIP2: return "AArch64ISD::ZIP2";
882 case AArch64ISD::UZP1: return "AArch64ISD::UZP1";
883 case AArch64ISD::UZP2: return "AArch64ISD::UZP2";
884 case AArch64ISD::TRN1: return "AArch64ISD::TRN1";
885 case AArch64ISD::TRN2: return "AArch64ISD::TRN2";
886 case AArch64ISD::REV16: return "AArch64ISD::REV16";
887 case AArch64ISD::REV32: return "AArch64ISD::REV32";
888 case AArch64ISD::REV64: return "AArch64ISD::REV64";
889 case AArch64ISD::EXT: return "AArch64ISD::EXT";
890 case AArch64ISD::VSHL: return "AArch64ISD::VSHL";
891 case AArch64ISD::VLSHR: return "AArch64ISD::VLSHR";
892 case AArch64ISD::VASHR: return "AArch64ISD::VASHR";
893 case AArch64ISD::CMEQ: return "AArch64ISD::CMEQ";
894 case AArch64ISD::CMGE: return "AArch64ISD::CMGE";
895 case AArch64ISD::CMGT: return "AArch64ISD::CMGT";
896 case AArch64ISD::CMHI: return "AArch64ISD::CMHI";
897 case AArch64ISD::CMHS: return "AArch64ISD::CMHS";
898 case AArch64ISD::FCMEQ: return "AArch64ISD::FCMEQ";
899 case AArch64ISD::FCMGE: return "AArch64ISD::FCMGE";
900 case AArch64ISD::FCMGT: return "AArch64ISD::FCMGT";
901 case AArch64ISD::CMEQz: return "AArch64ISD::CMEQz";
902 case AArch64ISD::CMGEz: return "AArch64ISD::CMGEz";
903 case AArch64ISD::CMGTz: return "AArch64ISD::CMGTz";
904 case AArch64ISD::CMLEz: return "AArch64ISD::CMLEz";
905 case AArch64ISD::CMLTz: return "AArch64ISD::CMLTz";
906 case AArch64ISD::FCMEQz: return "AArch64ISD::FCMEQz";
907 case AArch64ISD::FCMGEz: return "AArch64ISD::FCMGEz";
908 case AArch64ISD::FCMGTz: return "AArch64ISD::FCMGTz";
909 case AArch64ISD::FCMLEz: return "AArch64ISD::FCMLEz";
910 case AArch64ISD::FCMLTz: return "AArch64ISD::FCMLTz";
911 case AArch64ISD::SADDV: return "AArch64ISD::SADDV";
912 case AArch64ISD::UADDV: return "AArch64ISD::UADDV";
913 case AArch64ISD::SMINV: return "AArch64ISD::SMINV";
914 case AArch64ISD::UMINV: return "AArch64ISD::UMINV";
915 case AArch64ISD::SMAXV: return "AArch64ISD::SMAXV";
916 case AArch64ISD::UMAXV: return "AArch64ISD::UMAXV";
917 case AArch64ISD::NOT: return "AArch64ISD::NOT";
918 case AArch64ISD::BIT: return "AArch64ISD::BIT";
919 case AArch64ISD::CBZ: return "AArch64ISD::CBZ";
920 case AArch64ISD::CBNZ: return "AArch64ISD::CBNZ";
921 case AArch64ISD::TBZ: return "AArch64ISD::TBZ";
922 case AArch64ISD::TBNZ: return "AArch64ISD::TBNZ";
923 case AArch64ISD::TC_RETURN: return "AArch64ISD::TC_RETURN";
924 case AArch64ISD::PREFETCH: return "AArch64ISD::PREFETCH";
925 case AArch64ISD::SITOF: return "AArch64ISD::SITOF";
926 case AArch64ISD::UITOF: return "AArch64ISD::UITOF";
927 case AArch64ISD::NVCAST: return "AArch64ISD::NVCAST";
928 case AArch64ISD::SQSHL_I: return "AArch64ISD::SQSHL_I";
929 case AArch64ISD::UQSHL_I: return "AArch64ISD::UQSHL_I";
930 case AArch64ISD::SRSHR_I: return "AArch64ISD::SRSHR_I";
931 case AArch64ISD::URSHR_I: return "AArch64ISD::URSHR_I";
932 case AArch64ISD::SQSHLU_I: return "AArch64ISD::SQSHLU_I";
933 case AArch64ISD::WrapperLarge: return "AArch64ISD::WrapperLarge";
934 case AArch64ISD::LD2post: return "AArch64ISD::LD2post";
935 case AArch64ISD::LD3post: return "AArch64ISD::LD3post";
936 case AArch64ISD::LD4post: return "AArch64ISD::LD4post";
937 case AArch64ISD::ST2post: return "AArch64ISD::ST2post";
938 case AArch64ISD::ST3post: return "AArch64ISD::ST3post";
939 case AArch64ISD::ST4post: return "AArch64ISD::ST4post";
940 case AArch64ISD::LD1x2post: return "AArch64ISD::LD1x2post";
941 case AArch64ISD::LD1x3post: return "AArch64ISD::LD1x3post";
942 case AArch64ISD::LD1x4post: return "AArch64ISD::LD1x4post";
943 case AArch64ISD::ST1x2post: return "AArch64ISD::ST1x2post";
944 case AArch64ISD::ST1x3post: return "AArch64ISD::ST1x3post";
945 case AArch64ISD::ST1x4post: return "AArch64ISD::ST1x4post";
946 case AArch64ISD::LD1DUPpost: return "AArch64ISD::LD1DUPpost";
947 case AArch64ISD::LD2DUPpost: return "AArch64ISD::LD2DUPpost";
948 case AArch64ISD::LD3DUPpost: return "AArch64ISD::LD3DUPpost";
949 case AArch64ISD::LD4DUPpost: return "AArch64ISD::LD4DUPpost";
950 case AArch64ISD::LD1LANEpost: return "AArch64ISD::LD1LANEpost";
951 case AArch64ISD::LD2LANEpost: return "AArch64ISD::LD2LANEpost";
952 case AArch64ISD::LD3LANEpost: return "AArch64ISD::LD3LANEpost";
953 case AArch64ISD::LD4LANEpost: return "AArch64ISD::LD4LANEpost";
954 case AArch64ISD::ST2LANEpost: return "AArch64ISD::ST2LANEpost";
955 case AArch64ISD::ST3LANEpost: return "AArch64ISD::ST3LANEpost";
956 case AArch64ISD::ST4LANEpost: return "AArch64ISD::ST4LANEpost";
957 case AArch64ISD::SMULL: return "AArch64ISD::SMULL";
958 case AArch64ISD::UMULL: return "AArch64ISD::UMULL";
964 AArch64TargetLowering::EmitF128CSEL(MachineInstr *MI,
965 MachineBasicBlock *MBB) const {
966 // We materialise the F128CSEL pseudo-instruction as some control flow and a
970 // [... previous instrs leading to comparison ...]
976 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
978 MachineFunction *MF = MBB->getParent();
979 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
980 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
981 DebugLoc DL = MI->getDebugLoc();
982 MachineFunction::iterator It = ++MBB->getIterator();
984 unsigned DestReg = MI->getOperand(0).getReg();
985 unsigned IfTrueReg = MI->getOperand(1).getReg();
986 unsigned IfFalseReg = MI->getOperand(2).getReg();
987 unsigned CondCode = MI->getOperand(3).getImm();
988 bool NZCVKilled = MI->getOperand(4).isKill();
990 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
991 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
992 MF->insert(It, TrueBB);
993 MF->insert(It, EndBB);
995 // Transfer rest of current basic-block to EndBB
996 EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
998 EndBB->transferSuccessorsAndUpdatePHIs(MBB);
1000 BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
1001 BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
1002 MBB->addSuccessor(TrueBB);
1003 MBB->addSuccessor(EndBB);
1005 // TrueBB falls through to the end.
1006 TrueBB->addSuccessor(EndBB);
1009 TrueBB->addLiveIn(AArch64::NZCV);
1010 EndBB->addLiveIn(AArch64::NZCV);
1013 BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
1019 MI->eraseFromParent();
1024 AArch64TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1025 MachineBasicBlock *BB) const {
1026 switch (MI->getOpcode()) {
1031 llvm_unreachable("Unexpected instruction for custom inserter!");
1033 case AArch64::F128CSEL:
1034 return EmitF128CSEL(MI, BB);
1036 case TargetOpcode::STACKMAP:
1037 case TargetOpcode::PATCHPOINT:
1038 return emitPatchPoint(MI, BB);
1042 //===----------------------------------------------------------------------===//
1043 // AArch64 Lowering private implementation.
1044 //===----------------------------------------------------------------------===//
1046 //===----------------------------------------------------------------------===//
1048 //===----------------------------------------------------------------------===//
1050 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1052 static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1055 llvm_unreachable("Unknown condition code!");
1057 return AArch64CC::NE;
1059 return AArch64CC::EQ;
1061 return AArch64CC::GT;
1063 return AArch64CC::GE;
1065 return AArch64CC::LT;
1067 return AArch64CC::LE;
1069 return AArch64CC::HI;
1071 return AArch64CC::HS;
1073 return AArch64CC::LO;
1075 return AArch64CC::LS;
1079 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1080 static void changeFPCCToAArch64CC(ISD::CondCode CC,
1081 AArch64CC::CondCode &CondCode,
1082 AArch64CC::CondCode &CondCode2) {
1083 CondCode2 = AArch64CC::AL;
1086 llvm_unreachable("Unknown FP condition!");
1089 CondCode = AArch64CC::EQ;
1093 CondCode = AArch64CC::GT;
1097 CondCode = AArch64CC::GE;
1100 CondCode = AArch64CC::MI;
1103 CondCode = AArch64CC::LS;
1106 CondCode = AArch64CC::MI;
1107 CondCode2 = AArch64CC::GT;
1110 CondCode = AArch64CC::VC;
1113 CondCode = AArch64CC::VS;
1116 CondCode = AArch64CC::EQ;
1117 CondCode2 = AArch64CC::VS;
1120 CondCode = AArch64CC::HI;
1123 CondCode = AArch64CC::PL;
1127 CondCode = AArch64CC::LT;
1131 CondCode = AArch64CC::LE;
1135 CondCode = AArch64CC::NE;
1140 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1141 /// CC usable with the vector instructions. Fewer operations are available
1142 /// without a real NZCV register, so we have to use less efficient combinations
1143 /// to get the same effect.
1144 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1145 AArch64CC::CondCode &CondCode,
1146 AArch64CC::CondCode &CondCode2,
1151 // Mostly the scalar mappings work fine.
1152 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1155 Invert = true; // Fallthrough
1157 CondCode = AArch64CC::MI;
1158 CondCode2 = AArch64CC::GE;
1165 // All of the compare-mask comparisons are ordered, but we can switch
1166 // between the two by a double inversion. E.g. ULE == !OGT.
1168 changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1173 static bool isLegalArithImmed(uint64_t C) {
1174 // Matches AArch64DAGToDAGISel::SelectArithImmed().
1175 return (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1178 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1179 SDLoc dl, SelectionDAG &DAG) {
1180 EVT VT = LHS.getValueType();
1182 if (VT.isFloatingPoint())
1183 return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
1185 // The CMP instruction is just an alias for SUBS, and representing it as
1186 // SUBS means that it's possible to get CSE with subtract operations.
1187 // A later phase can perform the optimization of setting the destination
1188 // register to WZR/XZR if it ends up being unused.
1189 unsigned Opcode = AArch64ISD::SUBS;
1191 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
1192 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1193 // We'd like to combine a (CMP op1, (sub 0, op2) into a CMN instruction on
1194 // the grounds that "op1 - (-op2) == op1 + op2". However, the C and V flags
1195 // can be set differently by this operation. It comes down to whether
1196 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1197 // everything is fine. If not then the optimization is wrong. Thus general
1198 // comparisons are only valid if op2 != 0.
1200 // So, finally, the only LLVM-native comparisons that don't mention C and V
1201 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1202 // the absence of information about op2.
1203 Opcode = AArch64ISD::ADDS;
1204 RHS = RHS.getOperand(1);
1205 } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) &&
1206 !isUnsignedIntSetCC(CC)) {
1207 // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1208 // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1209 // of the signed comparisons.
1210 Opcode = AArch64ISD::ANDS;
1211 RHS = LHS.getOperand(1);
1212 LHS = LHS.getOperand(0);
1215 return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
1219 /// \defgroup AArch64CCMP CMP;CCMP matching
1221 /// These functions deal with the formation of CMP;CCMP;... sequences.
1222 /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1223 /// a comparison. They set the NZCV flags to a predefined value if their
1224 /// predicate is false. This allows to express arbitrary conjunctions, for
1225 /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B))))"
1228 /// ccmp B, inv(CB), CA
1229 /// check for CB flags
1231 /// In general we can create code for arbitrary "... (and (and A B) C)"
1232 /// sequences. We can also implement some "or" expressions, because "(or A B)"
1233 /// is equivalent to "not (and (not A) (not B))" and we can implement some
1234 /// negation operations:
1235 /// We can negate the results of a single comparison by inverting the flags
1236 /// used when the predicate fails and inverting the flags tested in the next
1237 /// instruction; We can also negate the results of the whole previous
1238 /// conditional compare sequence by inverting the flags tested in the next
1239 /// instruction. However there is no way to negate the result of a partial
1242 /// Therefore on encountering an "or" expression we can negate the subtree on
1243 /// one side and have to be able to push the negate to the leafs of the subtree
1244 /// on the other side (see also the comments in code). As complete example:
1245 /// "or (or (setCA (cmp A)) (setCB (cmp B)))
1246 /// (and (setCC (cmp C)) (setCD (cmp D)))"
1247 /// is transformed to
1248 /// "not (and (not (and (setCC (cmp C)) (setCC (cmp D))))
1249 /// (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1250 /// and implemented as:
1252 /// ccmp D, inv(CD), CC
1253 /// ccmp A, CA, inv(CD)
1254 /// ccmp B, CB, inv(CA)
1255 /// check for CB flags
1256 /// A counterexample is "or (and A B) (and C D)" which cannot be implemented
1257 /// by conditional compare sequences.
1260 /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
1261 static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1262 ISD::CondCode CC, SDValue CCOp,
1263 SDValue Condition, unsigned NZCV,
1264 SDLoc DL, SelectionDAG &DAG) {
1265 unsigned Opcode = 0;
1266 if (LHS.getValueType().isFloatingPoint())
1267 Opcode = AArch64ISD::FCCMP;
1268 else if (RHS.getOpcode() == ISD::SUB) {
1269 SDValue SubOp0 = RHS.getOperand(0);
1270 if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1271 // See emitComparison() on why we can only do this for SETEQ and SETNE.
1272 Opcode = AArch64ISD::CCMN;
1273 RHS = RHS.getOperand(1);
1277 Opcode = AArch64ISD::CCMP;
1279 SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1280 return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1283 /// Returns true if @p Val is a tree of AND/OR/SETCC operations.
1284 /// CanPushNegate is set to true if we can push a negate operation through
1285 /// the tree in a was that we are left with AND operations and negate operations
1286 /// at the leafs only. i.e. "not (or (or x y) z)" can be changed to
1287 /// "and (and (not x) (not y)) (not z)"; "not (or (and x y) z)" cannot be
1288 /// brought into such a form.
1289 static bool isConjunctionDisjunctionTree(const SDValue Val, bool &CanPushNegate,
1290 unsigned Depth = 0) {
1291 if (!Val.hasOneUse())
1293 unsigned Opcode = Val->getOpcode();
1294 if (Opcode == ISD::SETCC) {
1295 CanPushNegate = true;
1298 // Protect against stack overflow.
1301 if (Opcode == ISD::AND || Opcode == ISD::OR) {
1302 SDValue O0 = Val->getOperand(0);
1303 SDValue O1 = Val->getOperand(1);
1304 bool CanPushNegateL;
1305 if (!isConjunctionDisjunctionTree(O0, CanPushNegateL, Depth+1))
1307 bool CanPushNegateR;
1308 if (!isConjunctionDisjunctionTree(O1, CanPushNegateR, Depth+1))
1310 // We cannot push a negate through an AND operation (it would become an OR),
1311 // we can however change a (not (or x y)) to (and (not x) (not y)) if we can
1312 // push the negate through the x/y subtrees.
1313 CanPushNegate = (Opcode == ISD::OR) && CanPushNegateL && CanPushNegateR;
1319 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1320 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1321 /// Tries to transform the given i1 producing node @p Val to a series compare
1322 /// and conditional compare operations. @returns an NZCV flags producing node
1323 /// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1324 /// transformation was not possible.
1325 /// On recursive invocations @p PushNegate may be set to true to have negation
1326 /// effects pushed to the tree leafs; @p Predicate is an NZCV flag predicate
1327 /// for the comparisons in the current subtree; @p Depth limits the search
1328 /// depth to avoid stack overflow.
1329 static SDValue emitConjunctionDisjunctionTree(SelectionDAG &DAG, SDValue Val,
1330 AArch64CC::CondCode &OutCC, bool PushNegate = false,
1331 SDValue CCOp = SDValue(), AArch64CC::CondCode Predicate = AArch64CC::AL,
1332 unsigned Depth = 0) {
1333 // We're at a tree leaf, produce a conditional comparison operation.
1334 unsigned Opcode = Val->getOpcode();
1335 if (Opcode == ISD::SETCC) {
1336 SDValue LHS = Val->getOperand(0);
1337 SDValue RHS = Val->getOperand(1);
1338 ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1339 bool isInteger = LHS.getValueType().isInteger();
1341 CC = getSetCCInverse(CC, isInteger);
1343 // Determine OutCC and handle FP special case.
1345 OutCC = changeIntCCToAArch64CC(CC);
1347 assert(LHS.getValueType().isFloatingPoint());
1348 AArch64CC::CondCode ExtraCC;
1349 changeFPCCToAArch64CC(CC, OutCC, ExtraCC);
1350 // Surpisingly some floating point conditions can't be tested with a
1351 // single condition code. Construct an additional comparison in this case.
1352 // See comment below on how we deal with OR conditions.
1353 if (ExtraCC != AArch64CC::AL) {
1355 if (!CCOp.getNode())
1356 ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
1358 SDValue ConditionOp = DAG.getConstant(Predicate, DL, MVT_CC);
1359 // Note that we want the inverse of ExtraCC, so NZCV is not inversed.
1360 unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(ExtraCC);
1361 ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, ConditionOp,
1365 Predicate = AArch64CC::getInvertedCondCode(ExtraCC);
1366 OutCC = AArch64CC::getInvertedCondCode(OutCC);
1370 // Produce a normal comparison if we are first in the chain
1371 if (!CCOp.getNode())
1372 return emitComparison(LHS, RHS, CC, DL, DAG);
1373 // Otherwise produce a ccmp.
1374 SDValue ConditionOp = DAG.getConstant(Predicate, DL, MVT_CC);
1375 AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1376 unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
1377 return emitConditionalComparison(LHS, RHS, CC, CCOp, ConditionOp, NZCV, DL,
1379 } else if ((Opcode != ISD::AND && Opcode != ISD::OR) || !Val->hasOneUse())
1382 assert((Opcode == ISD::OR || !PushNegate)
1383 && "Can only push negate through OR operation");
1385 // Check if both sides can be transformed.
1386 SDValue LHS = Val->getOperand(0);
1387 SDValue RHS = Val->getOperand(1);
1388 bool CanPushNegateL;
1389 if (!isConjunctionDisjunctionTree(LHS, CanPushNegateL, Depth+1))
1391 bool CanPushNegateR;
1392 if (!isConjunctionDisjunctionTree(RHS, CanPushNegateR, Depth+1))
1395 // Do we need to negate our operands?
1396 bool NegateOperands = Opcode == ISD::OR;
1397 // We can negate the results of all previous operations by inverting the
1398 // predicate flags giving us a free negation for one side. For the other side
1399 // we need to be able to push the negation to the leafs of the tree.
1400 if (NegateOperands) {
1401 if (!CanPushNegateL && !CanPushNegateR)
1403 // Order the side where we can push the negate through to LHS.
1404 if (!CanPushNegateL && CanPushNegateR)
1405 std::swap(LHS, RHS);
1407 bool NeedsNegOutL = LHS->getOpcode() == ISD::OR;
1408 bool NeedsNegOutR = RHS->getOpcode() == ISD::OR;
1409 if (NeedsNegOutL && NeedsNegOutR)
1411 // Order the side where we need to negate the output flags to RHS so it
1412 // gets emitted first.
1414 std::swap(LHS, RHS);
1417 // Emit RHS. If we want to negate the tree we only need to push a negate
1418 // through if we are already in a PushNegate case, otherwise we can negate
1419 // the "flags to test" afterwards.
1420 AArch64CC::CondCode RHSCC;
1421 SDValue CmpR = emitConjunctionDisjunctionTree(DAG, RHS, RHSCC, PushNegate,
1422 CCOp, Predicate, Depth+1);
1423 if (NegateOperands && !PushNegate)
1424 RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
1425 // Emit LHS. We must push the negate through if we need to negate it.
1426 SDValue CmpL = emitConjunctionDisjunctionTree(DAG, LHS, OutCC, NegateOperands,
1427 CmpR, RHSCC, Depth+1);
1428 // If we transformed an OR to and AND then we have to negate the result
1429 // (or absorb a PushNegate resulting in a double negation).
1430 if (Opcode == ISD::OR && !PushNegate)
1431 OutCC = AArch64CC::getInvertedCondCode(OutCC);
1437 static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1438 SDValue &AArch64cc, SelectionDAG &DAG, SDLoc dl) {
1439 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1440 EVT VT = RHS.getValueType();
1441 uint64_t C = RHSC->getZExtValue();
1442 if (!isLegalArithImmed(C)) {
1443 // Constant does not fit, try adjusting it by one?
1449 if ((VT == MVT::i32 && C != 0x80000000 &&
1450 isLegalArithImmed((uint32_t)(C - 1))) ||
1451 (VT == MVT::i64 && C != 0x80000000ULL &&
1452 isLegalArithImmed(C - 1ULL))) {
1453 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1454 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1455 RHS = DAG.getConstant(C, dl, VT);
1460 if ((VT == MVT::i32 && C != 0 &&
1461 isLegalArithImmed((uint32_t)(C - 1))) ||
1462 (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1463 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1464 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1465 RHS = DAG.getConstant(C, dl, VT);
1470 if ((VT == MVT::i32 && C != INT32_MAX &&
1471 isLegalArithImmed((uint32_t)(C + 1))) ||
1472 (VT == MVT::i64 && C != INT64_MAX &&
1473 isLegalArithImmed(C + 1ULL))) {
1474 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1475 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1476 RHS = DAG.getConstant(C, dl, VT);
1481 if ((VT == MVT::i32 && C != UINT32_MAX &&
1482 isLegalArithImmed((uint32_t)(C + 1))) ||
1483 (VT == MVT::i64 && C != UINT64_MAX &&
1484 isLegalArithImmed(C + 1ULL))) {
1485 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1486 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1487 RHS = DAG.getConstant(C, dl, VT);
1494 AArch64CC::CondCode AArch64CC;
1495 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
1496 const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
1498 // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
1499 // For the i8 operand, the largest immediate is 255, so this can be easily
1500 // encoded in the compare instruction. For the i16 operand, however, the
1501 // largest immediate cannot be encoded in the compare.
1502 // Therefore, use a sign extending load and cmn to avoid materializing the
1503 // -1 constant. For example,
1505 // ldrh w0, [x0, #0]
1508 // ldrsh w0, [x0, #0]
1510 // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
1511 // if and only if (sext LHS) == (sext RHS). The checks are in place to
1512 // ensure both the LHS and RHS are truly zero extended and to make sure the
1513 // transformation is profitable.
1514 if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
1515 cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
1516 cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
1517 LHS.getNode()->hasNUsesOfValue(1, 0)) {
1518 int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
1519 if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
1521 DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
1522 DAG.getValueType(MVT::i16));
1523 Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
1524 RHS.getValueType()),
1526 AArch64CC = changeIntCCToAArch64CC(CC);
1530 if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
1531 if ((Cmp = emitConjunctionDisjunctionTree(DAG, LHS, AArch64CC))) {
1532 if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
1533 AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
1539 Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
1540 AArch64CC = changeIntCCToAArch64CC(CC);
1542 AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
1546 static std::pair<SDValue, SDValue>
1547 getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
1548 assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
1549 "Unsupported value type");
1550 SDValue Value, Overflow;
1552 SDValue LHS = Op.getOperand(0);
1553 SDValue RHS = Op.getOperand(1);
1555 switch (Op.getOpcode()) {
1557 llvm_unreachable("Unknown overflow instruction!");
1559 Opc = AArch64ISD::ADDS;
1563 Opc = AArch64ISD::ADDS;
1567 Opc = AArch64ISD::SUBS;
1571 Opc = AArch64ISD::SUBS;
1574 // Multiply needs a little bit extra work.
1578 bool IsSigned = Op.getOpcode() == ISD::SMULO;
1579 if (Op.getValueType() == MVT::i32) {
1580 unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1581 // For a 32 bit multiply with overflow check we want the instruction
1582 // selector to generate a widening multiply (SMADDL/UMADDL). For that we
1583 // need to generate the following pattern:
1584 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
1585 LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
1586 RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
1587 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1588 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
1589 DAG.getConstant(0, DL, MVT::i64));
1590 // On AArch64 the upper 32 bits are always zero extended for a 32 bit
1591 // operation. We need to clear out the upper 32 bits, because we used a
1592 // widening multiply that wrote all 64 bits. In the end this should be a
1594 Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
1596 // The signed overflow check requires more than just a simple check for
1597 // any bit set in the upper 32 bits of the result. These bits could be
1598 // just the sign bits of a negative number. To perform the overflow
1599 // check we have to arithmetic shift right the 32nd bit of the result by
1600 // 31 bits. Then we compare the result to the upper 32 bits.
1601 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
1602 DAG.getConstant(32, DL, MVT::i64));
1603 UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
1604 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
1605 DAG.getConstant(31, DL, MVT::i64));
1606 // It is important that LowerBits is last, otherwise the arithmetic
1607 // shift will not be folded into the compare (SUBS).
1608 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
1609 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1612 // The overflow check for unsigned multiply is easy. We only need to
1613 // check if any of the upper 32 bits are set. This can be done with a
1614 // CMP (shifted register). For that we need to generate the following
1616 // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
1617 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
1618 DAG.getConstant(32, DL, MVT::i64));
1619 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1621 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1622 DAG.getConstant(0, DL, MVT::i64),
1623 UpperBits).getValue(1);
1627 assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
1628 // For the 64 bit multiply
1629 Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1631 SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
1632 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
1633 DAG.getConstant(63, DL, MVT::i64));
1634 // It is important that LowerBits is last, otherwise the arithmetic
1635 // shift will not be folded into the compare (SUBS).
1636 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1637 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1640 SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
1641 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1643 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1644 DAG.getConstant(0, DL, MVT::i64),
1645 UpperBits).getValue(1);
1652 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
1654 // Emit the AArch64 operation with overflow check.
1655 Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
1656 Overflow = Value.getValue(1);
1658 return std::make_pair(Value, Overflow);
1661 SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
1662 RTLIB::Libcall Call) const {
1663 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
1664 return makeLibCall(DAG, Call, MVT::f128, Ops, false, SDLoc(Op)).first;
1667 static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
1668 SDValue Sel = Op.getOperand(0);
1669 SDValue Other = Op.getOperand(1);
1671 // If neither operand is a SELECT_CC, give up.
1672 if (Sel.getOpcode() != ISD::SELECT_CC)
1673 std::swap(Sel, Other);
1674 if (Sel.getOpcode() != ISD::SELECT_CC)
1677 // The folding we want to perform is:
1678 // (xor x, (select_cc a, b, cc, 0, -1) )
1680 // (csel x, (xor x, -1), cc ...)
1682 // The latter will get matched to a CSINV instruction.
1684 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
1685 SDValue LHS = Sel.getOperand(0);
1686 SDValue RHS = Sel.getOperand(1);
1687 SDValue TVal = Sel.getOperand(2);
1688 SDValue FVal = Sel.getOperand(3);
1691 // FIXME: This could be generalized to non-integer comparisons.
1692 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
1695 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
1696 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
1698 // The values aren't constants, this isn't the pattern we're looking for.
1699 if (!CFVal || !CTVal)
1702 // We can commute the SELECT_CC by inverting the condition. This
1703 // might be needed to make this fit into a CSINV pattern.
1704 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
1705 std::swap(TVal, FVal);
1706 std::swap(CTVal, CFVal);
1707 CC = ISD::getSetCCInverse(CC, true);
1710 // If the constants line up, perform the transform!
1711 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
1713 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
1716 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
1717 DAG.getConstant(-1ULL, dl, Other.getValueType()));
1719 return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
1726 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
1727 EVT VT = Op.getValueType();
1729 // Let legalize expand this if it isn't a legal type yet.
1730 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
1733 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
1736 bool ExtraOp = false;
1737 switch (Op.getOpcode()) {
1739 llvm_unreachable("Invalid code");
1741 Opc = AArch64ISD::ADDS;
1744 Opc = AArch64ISD::SUBS;
1747 Opc = AArch64ISD::ADCS;
1751 Opc = AArch64ISD::SBCS;
1757 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
1758 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
1762 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
1763 // Let legalize expand this if it isn't a legal type yet.
1764 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
1768 AArch64CC::CondCode CC;
1769 // The actual operation that sets the overflow or carry flag.
1770 SDValue Value, Overflow;
1771 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
1773 // We use 0 and 1 as false and true values.
1774 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
1775 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
1777 // We use an inverted condition, because the conditional select is inverted
1778 // too. This will allow it to be selected to a single instruction:
1779 // CSINC Wd, WZR, WZR, invert(cond).
1780 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
1781 Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
1784 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
1785 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
1788 // Prefetch operands are:
1789 // 1: Address to prefetch
1791 // 3: int locality (0 = no locality ... 3 = extreme locality)
1792 // 4: bool isDataCache
1793 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
1795 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
1796 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
1797 unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
1799 bool IsStream = !Locality;
1800 // When the locality number is set
1802 // The front-end should have filtered out the out-of-range values
1803 assert(Locality <= 3 && "Prefetch locality out-of-range");
1804 // The locality degree is the opposite of the cache speed.
1805 // Put the number the other way around.
1806 // The encoding starts at 0 for level 1
1807 Locality = 3 - Locality;
1810 // built the mask value encoding the expected behavior.
1811 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit
1812 (!IsData << 3) | // IsDataCache bit
1813 (Locality << 1) | // Cache level bits
1814 (unsigned)IsStream; // Stream bit
1815 return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
1816 DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
1819 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
1820 SelectionDAG &DAG) const {
1821 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
1824 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
1826 return LowerF128Call(Op, DAG, LC);
1829 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
1830 SelectionDAG &DAG) const {
1831 if (Op.getOperand(0).getValueType() != MVT::f128) {
1832 // It's legal except when f128 is involved
1837 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
1839 // FP_ROUND node has a second operand indicating whether it is known to be
1840 // precise. That doesn't take part in the LibCall so we can't directly use
1842 SDValue SrcVal = Op.getOperand(0);
1843 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
1847 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
1848 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1849 // Any additional optimization in this function should be recorded
1850 // in the cost tables.
1851 EVT InVT = Op.getOperand(0).getValueType();
1852 EVT VT = Op.getValueType();
1854 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
1857 DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
1859 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
1862 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
1865 MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
1866 VT.getVectorNumElements());
1867 SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
1868 return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
1871 // Type changing conversions are illegal.
1875 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
1876 SelectionDAG &DAG) const {
1877 if (Op.getOperand(0).getValueType().isVector())
1878 return LowerVectorFP_TO_INT(Op, DAG);
1880 // f16 conversions are promoted to f32.
1881 if (Op.getOperand(0).getValueType() == MVT::f16) {
1884 Op.getOpcode(), dl, Op.getValueType(),
1885 DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
1888 if (Op.getOperand(0).getValueType() != MVT::f128) {
1889 // It's legal except when f128 is involved
1894 if (Op.getOpcode() == ISD::FP_TO_SINT)
1895 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
1897 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
1899 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
1900 return makeLibCall(DAG, LC, Op.getValueType(), Ops, false, SDLoc(Op)).first;
1903 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
1904 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1905 // Any additional optimization in this function should be recorded
1906 // in the cost tables.
1907 EVT VT = Op.getValueType();
1909 SDValue In = Op.getOperand(0);
1910 EVT InVT = In.getValueType();
1912 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
1914 MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
1915 InVT.getVectorNumElements());
1916 In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
1917 return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
1920 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
1922 Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1923 EVT CastVT = VT.changeVectorElementTypeToInteger();
1924 In = DAG.getNode(CastOpc, dl, CastVT, In);
1925 return DAG.getNode(Op.getOpcode(), dl, VT, In);
1931 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
1932 SelectionDAG &DAG) const {
1933 if (Op.getValueType().isVector())
1934 return LowerVectorINT_TO_FP(Op, DAG);
1936 // f16 conversions are promoted to f32.
1937 if (Op.getValueType() == MVT::f16) {
1940 ISD::FP_ROUND, dl, MVT::f16,
1941 DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
1942 DAG.getIntPtrConstant(0, dl));
1945 // i128 conversions are libcalls.
1946 if (Op.getOperand(0).getValueType() == MVT::i128)
1949 // Other conversions are legal, unless it's to the completely software-based
1951 if (Op.getValueType() != MVT::f128)
1955 if (Op.getOpcode() == ISD::SINT_TO_FP)
1956 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
1958 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
1960 return LowerF128Call(Op, DAG, LC);
1963 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
1964 SelectionDAG &DAG) const {
1965 // For iOS, we want to call an alternative entry point: __sincos_stret,
1966 // which returns the values in two S / D registers.
1968 SDValue Arg = Op.getOperand(0);
1969 EVT ArgVT = Arg.getValueType();
1970 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
1977 Entry.isSExt = false;
1978 Entry.isZExt = false;
1979 Args.push_back(Entry);
1981 const char *LibcallName =
1982 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
1984 DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
1986 StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
1987 TargetLowering::CallLoweringInfo CLI(DAG);
1988 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
1989 .setCallee(CallingConv::Fast, RetTy, Callee, std::move(Args), 0);
1991 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1992 return CallResult.first;
1995 static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
1996 if (Op.getValueType() != MVT::f16)
1999 assert(Op.getOperand(0).getValueType() == MVT::i16);
2002 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
2003 Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
2005 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
2006 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
2010 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
2011 if (OrigVT.getSizeInBits() >= 64)
2014 assert(OrigVT.isSimple() && "Expecting a simple value type");
2016 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
2017 switch (OrigSimpleTy) {
2018 default: llvm_unreachable("Unexpected Vector Type");
2027 static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2030 unsigned ExtOpcode) {
2031 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2032 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2033 // 64-bits we need to insert a new extension so that it will be 64-bits.
2034 assert(ExtTy.is128BitVector() && "Unexpected extension size");
2035 if (OrigTy.getSizeInBits() >= 64)
2038 // Must extend size to at least 64 bits to be used as an operand for VMULL.
2039 EVT NewVT = getExtensionTo64Bits(OrigTy);
2041 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2044 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2046 EVT VT = N->getValueType(0);
2048 if (N->getOpcode() != ISD::BUILD_VECTOR)
2051 for (const SDValue &Elt : N->op_values()) {
2052 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
2053 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
2054 unsigned HalfSize = EltSize / 2;
2056 if (!isIntN(HalfSize, C->getSExtValue()))
2059 if (!isUIntN(HalfSize, C->getZExtValue()))
2070 static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2071 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2072 return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2073 N->getOperand(0)->getValueType(0),
2077 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2078 EVT VT = N->getValueType(0);
2080 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
2081 unsigned NumElts = VT.getVectorNumElements();
2082 MVT TruncVT = MVT::getIntegerVT(EltSize);
2083 SmallVector<SDValue, 8> Ops;
2084 for (unsigned i = 0; i != NumElts; ++i) {
2085 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2086 const APInt &CInt = C->getAPIntValue();
2087 // Element types smaller than 32 bits are not legal, so use i32 elements.
2088 // The values are implicitly truncated so sext vs. zext doesn't matter.
2089 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
2091 return DAG.getNode(ISD::BUILD_VECTOR, dl,
2092 MVT::getVectorVT(TruncVT, NumElts), Ops);
2095 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
2096 if (N->getOpcode() == ISD::SIGN_EXTEND)
2098 if (isExtendedBUILD_VECTOR(N, DAG, true))
2103 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
2104 if (N->getOpcode() == ISD::ZERO_EXTEND)
2106 if (isExtendedBUILD_VECTOR(N, DAG, false))
2111 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2112 unsigned Opcode = N->getOpcode();
2113 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2114 SDNode *N0 = N->getOperand(0).getNode();
2115 SDNode *N1 = N->getOperand(1).getNode();
2116 return N0->hasOneUse() && N1->hasOneUse() &&
2117 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2122 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2123 unsigned Opcode = N->getOpcode();
2124 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2125 SDNode *N0 = N->getOperand(0).getNode();
2126 SDNode *N1 = N->getOperand(1).getNode();
2127 return N0->hasOneUse() && N1->hasOneUse() &&
2128 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2133 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2134 // Multiplications are only custom-lowered for 128-bit vectors so that
2135 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
2136 EVT VT = Op.getValueType();
2137 assert(VT.is128BitVector() && VT.isInteger() &&
2138 "unexpected type for custom-lowering ISD::MUL");
2139 SDNode *N0 = Op.getOperand(0).getNode();
2140 SDNode *N1 = Op.getOperand(1).getNode();
2141 unsigned NewOpc = 0;
2143 bool isN0SExt = isSignExtended(N0, DAG);
2144 bool isN1SExt = isSignExtended(N1, DAG);
2145 if (isN0SExt && isN1SExt)
2146 NewOpc = AArch64ISD::SMULL;
2148 bool isN0ZExt = isZeroExtended(N0, DAG);
2149 bool isN1ZExt = isZeroExtended(N1, DAG);
2150 if (isN0ZExt && isN1ZExt)
2151 NewOpc = AArch64ISD::UMULL;
2152 else if (isN1SExt || isN1ZExt) {
2153 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2154 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2155 if (isN1SExt && isAddSubSExt(N0, DAG)) {
2156 NewOpc = AArch64ISD::SMULL;
2158 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2159 NewOpc = AArch64ISD::UMULL;
2161 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2163 NewOpc = AArch64ISD::UMULL;
2169 if (VT == MVT::v2i64)
2170 // Fall through to expand this. It is not legal.
2173 // Other vector multiplications are legal.
2178 // Legalize to a S/UMULL instruction
2181 SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2183 Op0 = skipExtensionForVectorMULL(N0, DAG);
2184 assert(Op0.getValueType().is64BitVector() &&
2185 Op1.getValueType().is64BitVector() &&
2186 "unexpected types for extended operands to VMULL");
2187 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2189 // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2190 // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2191 // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2192 SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2193 SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2194 EVT Op1VT = Op1.getValueType();
2195 return DAG.getNode(N0->getOpcode(), DL, VT,
2196 DAG.getNode(NewOpc, DL, VT,
2197 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2198 DAG.getNode(NewOpc, DL, VT,
2199 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2202 SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2203 SelectionDAG &DAG) const {
2204 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2207 default: return SDValue(); // Don't custom lower most intrinsics.
2208 case Intrinsic::aarch64_thread_pointer: {
2209 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2210 return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
2212 case Intrinsic::aarch64_neon_smax:
2213 return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
2214 Op.getOperand(1), Op.getOperand(2));
2215 case Intrinsic::aarch64_neon_umax:
2216 return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
2217 Op.getOperand(1), Op.getOperand(2));
2218 case Intrinsic::aarch64_neon_smin:
2219 return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
2220 Op.getOperand(1), Op.getOperand(2));
2221 case Intrinsic::aarch64_neon_umin:
2222 return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
2223 Op.getOperand(1), Op.getOperand(2));
2227 SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
2228 SelectionDAG &DAG) const {
2229 switch (Op.getOpcode()) {
2231 llvm_unreachable("unimplemented operand");
2234 return LowerBITCAST(Op, DAG);
2235 case ISD::GlobalAddress:
2236 return LowerGlobalAddress(Op, DAG);
2237 case ISD::GlobalTLSAddress:
2238 return LowerGlobalTLSAddress(Op, DAG);
2240 return LowerSETCC(Op, DAG);
2242 return LowerBR_CC(Op, DAG);
2244 return LowerSELECT(Op, DAG);
2245 case ISD::SELECT_CC:
2246 return LowerSELECT_CC(Op, DAG);
2247 case ISD::JumpTable:
2248 return LowerJumpTable(Op, DAG);
2249 case ISD::ConstantPool:
2250 return LowerConstantPool(Op, DAG);
2251 case ISD::BlockAddress:
2252 return LowerBlockAddress(Op, DAG);
2254 return LowerVASTART(Op, DAG);
2256 return LowerVACOPY(Op, DAG);
2258 return LowerVAARG(Op, DAG);
2263 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
2270 return LowerXALUO(Op, DAG);
2272 return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
2274 return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
2276 return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
2278 return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
2280 return LowerFP_ROUND(Op, DAG);
2281 case ISD::FP_EXTEND:
2282 return LowerFP_EXTEND(Op, DAG);
2283 case ISD::FRAMEADDR:
2284 return LowerFRAMEADDR(Op, DAG);
2285 case ISD::RETURNADDR:
2286 return LowerRETURNADDR(Op, DAG);
2287 case ISD::INSERT_VECTOR_ELT:
2288 return LowerINSERT_VECTOR_ELT(Op, DAG);
2289 case ISD::EXTRACT_VECTOR_ELT:
2290 return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2291 case ISD::BUILD_VECTOR:
2292 return LowerBUILD_VECTOR(Op, DAG);
2293 case ISD::VECTOR_SHUFFLE:
2294 return LowerVECTOR_SHUFFLE(Op, DAG);
2295 case ISD::EXTRACT_SUBVECTOR:
2296 return LowerEXTRACT_SUBVECTOR(Op, DAG);
2300 return LowerVectorSRA_SRL_SHL(Op, DAG);
2301 case ISD::SHL_PARTS:
2302 return LowerShiftLeftParts(Op, DAG);
2303 case ISD::SRL_PARTS:
2304 case ISD::SRA_PARTS:
2305 return LowerShiftRightParts(Op, DAG);
2307 return LowerCTPOP(Op, DAG);
2308 case ISD::FCOPYSIGN:
2309 return LowerFCOPYSIGN(Op, DAG);
2311 return LowerVectorAND(Op, DAG);
2313 return LowerVectorOR(Op, DAG);
2315 return LowerXOR(Op, DAG);
2317 return LowerPREFETCH(Op, DAG);
2318 case ISD::SINT_TO_FP:
2319 case ISD::UINT_TO_FP:
2320 return LowerINT_TO_FP(Op, DAG);
2321 case ISD::FP_TO_SINT:
2322 case ISD::FP_TO_UINT:
2323 return LowerFP_TO_INT(Op, DAG);
2325 return LowerFSINCOS(Op, DAG);
2327 return LowerMUL(Op, DAG);
2328 case ISD::INTRINSIC_WO_CHAIN:
2329 return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2333 /// getFunctionAlignment - Return the Log2 alignment of this function.
2334 unsigned AArch64TargetLowering::getFunctionAlignment(const Function *F) const {
2338 //===----------------------------------------------------------------------===//
2339 // Calling Convention Implementation
2340 //===----------------------------------------------------------------------===//
2342 #include "AArch64GenCallingConv.inc"
2344 /// Selects the correct CCAssignFn for a given CallingConvention value.
2345 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2346 bool IsVarArg) const {
2349 llvm_unreachable("Unsupported calling convention.");
2350 case CallingConv::WebKit_JS:
2351 return CC_AArch64_WebKit_JS;
2352 case CallingConv::GHC:
2353 return CC_AArch64_GHC;
2354 case CallingConv::C:
2355 case CallingConv::Fast:
2356 if (!Subtarget->isTargetDarwin())
2357 return CC_AArch64_AAPCS;
2358 return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
2362 SDValue AArch64TargetLowering::LowerFormalArguments(
2363 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2364 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2365 SmallVectorImpl<SDValue> &InVals) const {
2366 MachineFunction &MF = DAG.getMachineFunction();
2367 MachineFrameInfo *MFI = MF.getFrameInfo();
2369 // Assign locations to all of the incoming arguments.
2370 SmallVector<CCValAssign, 16> ArgLocs;
2371 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2374 // At this point, Ins[].VT may already be promoted to i32. To correctly
2375 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2376 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2377 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
2378 // we use a special version of AnalyzeFormalArguments to pass in ValVT and
2380 unsigned NumArgs = Ins.size();
2381 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2382 unsigned CurArgIdx = 0;
2383 for (unsigned i = 0; i != NumArgs; ++i) {
2384 MVT ValVT = Ins[i].VT;
2385 if (Ins[i].isOrigArg()) {
2386 std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
2387 CurArgIdx = Ins[i].getOrigArgIndex();
2389 // Get type of the original argument.
2390 EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
2391 /*AllowUnknown*/ true);
2392 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
2393 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2394 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2396 else if (ActualMVT == MVT::i16)
2399 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2401 AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
2402 assert(!Res && "Call operand has unhandled type");
2405 assert(ArgLocs.size() == Ins.size());
2406 SmallVector<SDValue, 16> ArgValues;
2407 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2408 CCValAssign &VA = ArgLocs[i];
2410 if (Ins[i].Flags.isByVal()) {
2411 // Byval is used for HFAs in the PCS, but the system should work in a
2412 // non-compliant manner for larger structs.
2413 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2414 int Size = Ins[i].Flags.getByValSize();
2415 unsigned NumRegs = (Size + 7) / 8;
2417 // FIXME: This works on big-endian for composite byvals, which are the common
2418 // case. It should also work for fundamental types too.
2420 MFI->CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
2421 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
2422 InVals.push_back(FrameIdxN);
2427 if (VA.isRegLoc()) {
2428 // Arguments stored in registers.
2429 EVT RegVT = VA.getLocVT();
2432 const TargetRegisterClass *RC;
2434 if (RegVT == MVT::i32)
2435 RC = &AArch64::GPR32RegClass;
2436 else if (RegVT == MVT::i64)
2437 RC = &AArch64::GPR64RegClass;
2438 else if (RegVT == MVT::f16)
2439 RC = &AArch64::FPR16RegClass;
2440 else if (RegVT == MVT::f32)
2441 RC = &AArch64::FPR32RegClass;
2442 else if (RegVT == MVT::f64 || RegVT.is64BitVector())
2443 RC = &AArch64::FPR64RegClass;
2444 else if (RegVT == MVT::f128 || RegVT.is128BitVector())
2445 RC = &AArch64::FPR128RegClass;
2447 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2449 // Transform the arguments in physical registers into virtual ones.
2450 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2451 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2453 // If this is an 8, 16 or 32-bit value, it is really passed promoted
2454 // to 64 bits. Insert an assert[sz]ext to capture this, then
2455 // truncate to the right size.
2456 switch (VA.getLocInfo()) {
2458 llvm_unreachable("Unknown loc info!");
2459 case CCValAssign::Full:
2461 case CCValAssign::BCvt:
2462 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
2464 case CCValAssign::AExt:
2465 case CCValAssign::SExt:
2466 case CCValAssign::ZExt:
2467 // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
2468 // nodes after our lowering.
2469 assert(RegVT == Ins[i].VT && "incorrect register location selected");
2473 InVals.push_back(ArgValue);
2475 } else { // VA.isRegLoc()
2476 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
2477 unsigned ArgOffset = VA.getLocMemOffset();
2478 unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
2480 uint32_t BEAlign = 0;
2481 if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
2482 !Ins[i].Flags.isInConsecutiveRegs())
2483 BEAlign = 8 - ArgSize;
2485 int FI = MFI->CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
2487 // Create load nodes to retrieve arguments from the stack.
2488 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2491 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
2492 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
2493 MVT MemVT = VA.getValVT();
2495 switch (VA.getLocInfo()) {
2498 case CCValAssign::BCvt:
2499 MemVT = VA.getLocVT();
2501 case CCValAssign::SExt:
2502 ExtType = ISD::SEXTLOAD;
2504 case CCValAssign::ZExt:
2505 ExtType = ISD::ZEXTLOAD;
2507 case CCValAssign::AExt:
2508 ExtType = ISD::EXTLOAD;
2512 ArgValue = DAG.getExtLoad(
2513 ExtType, DL, VA.getLocVT(), Chain, FIN,
2514 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
2515 MemVT, false, false, false, 0);
2517 InVals.push_back(ArgValue);
2523 if (!Subtarget->isTargetDarwin()) {
2524 // The AAPCS variadic function ABI is identical to the non-variadic
2525 // one. As a result there may be more arguments in registers and we should
2526 // save them for future reference.
2527 saveVarArgRegisters(CCInfo, DAG, DL, Chain);
2530 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
2531 // This will point to the next argument passed via stack.
2532 unsigned StackOffset = CCInfo.getNextStackOffset();
2533 // We currently pass all varargs at 8-byte alignment.
2534 StackOffset = ((StackOffset + 7) & ~7);
2535 AFI->setVarArgsStackIndex(MFI->CreateFixedObject(4, StackOffset, true));
2538 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2539 unsigned StackArgSize = CCInfo.getNextStackOffset();
2540 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2541 if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
2542 // This is a non-standard ABI so by fiat I say we're allowed to make full
2543 // use of the stack area to be popped, which must be aligned to 16 bytes in
2545 StackArgSize = RoundUpToAlignment(StackArgSize, 16);
2547 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
2548 // a multiple of 16.
2549 FuncInfo->setArgumentStackToRestore(StackArgSize);
2551 // This realignment carries over to the available bytes below. Our own
2552 // callers will guarantee the space is free by giving an aligned value to
2555 // Even if we're not expected to free up the space, it's useful to know how
2556 // much is there while considering tail calls (because we can reuse it).
2557 FuncInfo->setBytesInStackArgArea(StackArgSize);
2562 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
2563 SelectionDAG &DAG, SDLoc DL,
2564 SDValue &Chain) const {
2565 MachineFunction &MF = DAG.getMachineFunction();
2566 MachineFrameInfo *MFI = MF.getFrameInfo();
2567 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2568 auto PtrVT = getPointerTy(DAG.getDataLayout());
2570 SmallVector<SDValue, 8> MemOps;
2572 static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
2573 AArch64::X3, AArch64::X4, AArch64::X5,
2574 AArch64::X6, AArch64::X7 };
2575 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
2576 unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
2578 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
2580 if (GPRSaveSize != 0) {
2581 GPRIdx = MFI->CreateStackObject(GPRSaveSize, 8, false);
2583 SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
2585 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
2586 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
2587 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
2588 SDValue Store = DAG.getStore(
2589 Val.getValue(1), DL, Val, FIN,
2590 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8), false,
2592 MemOps.push_back(Store);
2594 DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
2597 FuncInfo->setVarArgsGPRIndex(GPRIdx);
2598 FuncInfo->setVarArgsGPRSize(GPRSaveSize);
2600 if (Subtarget->hasFPARMv8()) {
2601 static const MCPhysReg FPRArgRegs[] = {
2602 AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
2603 AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
2604 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
2605 unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
2607 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
2609 if (FPRSaveSize != 0) {
2610 FPRIdx = MFI->CreateStackObject(FPRSaveSize, 16, false);
2612 SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
2614 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
2615 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
2616 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
2618 SDValue Store = DAG.getStore(
2619 Val.getValue(1), DL, Val, FIN,
2620 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16),
2622 MemOps.push_back(Store);
2623 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
2624 DAG.getConstant(16, DL, PtrVT));
2627 FuncInfo->setVarArgsFPRIndex(FPRIdx);
2628 FuncInfo->setVarArgsFPRSize(FPRSaveSize);
2631 if (!MemOps.empty()) {
2632 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
2636 /// LowerCallResult - Lower the result values of a call into the
2637 /// appropriate copies out of appropriate physical registers.
2638 SDValue AArch64TargetLowering::LowerCallResult(
2639 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
2640 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2641 SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
2642 SDValue ThisVal) const {
2643 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
2644 ? RetCC_AArch64_WebKit_JS
2645 : RetCC_AArch64_AAPCS;
2646 // Assign locations to each value returned by this call.
2647 SmallVector<CCValAssign, 16> RVLocs;
2648 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2650 CCInfo.AnalyzeCallResult(Ins, RetCC);
2652 // Copy all of the result registers out of their specified physreg.
2653 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2654 CCValAssign VA = RVLocs[i];
2656 // Pass 'this' value directly from the argument to return value, to avoid
2657 // reg unit interference
2658 if (i == 0 && isThisReturn) {
2659 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
2660 "unexpected return calling convention register assignment");
2661 InVals.push_back(ThisVal);
2666 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2667 Chain = Val.getValue(1);
2668 InFlag = Val.getValue(2);
2670 switch (VA.getLocInfo()) {
2672 llvm_unreachable("Unknown loc info!");
2673 case CCValAssign::Full:
2675 case CCValAssign::BCvt:
2676 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2680 InVals.push_back(Val);
2686 bool AArch64TargetLowering::isEligibleForTailCallOptimization(
2687 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
2688 bool isCalleeStructRet, bool isCallerStructRet,
2689 const SmallVectorImpl<ISD::OutputArg> &Outs,
2690 const SmallVectorImpl<SDValue> &OutVals,
2691 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2692 // For CallingConv::C this function knows whether the ABI needs
2693 // changing. That's not true for other conventions so they will have to opt in
2695 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
2698 const MachineFunction &MF = DAG.getMachineFunction();
2699 const Function *CallerF = MF.getFunction();
2700 CallingConv::ID CallerCC = CallerF->getCallingConv();
2701 bool CCMatch = CallerCC == CalleeCC;
2703 // Byval parameters hand the function a pointer directly into the stack area
2704 // we want to reuse during a tail call. Working around this *is* possible (see
2705 // X86) but less efficient and uglier in LowerCall.
2706 for (Function::const_arg_iterator i = CallerF->arg_begin(),
2707 e = CallerF->arg_end();
2709 if (i->hasByValAttr())
2712 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2713 if (IsTailCallConvention(CalleeCC) && CCMatch)
2718 // Externally-defined functions with weak linkage should not be
2719 // tail-called on AArch64 when the OS does not support dynamic
2720 // pre-emption of symbols, as the AAELF spec requires normal calls
2721 // to undefined weak functions to be replaced with a NOP or jump to the
2722 // next instruction. The behaviour of branch instructions in this
2723 // situation (as used for tail calls) is implementation-defined, so we
2724 // cannot rely on the linker replacing the tail call with a return.
2725 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2726 const GlobalValue *GV = G->getGlobal();
2727 const Triple &TT = getTargetMachine().getTargetTriple();
2728 if (GV->hasExternalWeakLinkage() &&
2729 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2733 // Now we search for cases where we can use a tail call without changing the
2734 // ABI. Sibcall is used in some places (particularly gcc) to refer to this
2737 // I want anyone implementing a new calling convention to think long and hard
2738 // about this assert.
2739 assert((!isVarArg || CalleeCC == CallingConv::C) &&
2740 "Unexpected variadic calling convention");
2742 if (isVarArg && !Outs.empty()) {
2743 // At least two cases here: if caller is fastcc then we can't have any
2744 // memory arguments (we'd be expected to clean up the stack afterwards). If
2745 // caller is C then we could potentially use its argument area.
2747 // FIXME: for now we take the most conservative of these in both cases:
2748 // disallow all variadic memory operands.
2749 SmallVector<CCValAssign, 16> ArgLocs;
2750 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2753 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
2754 for (const CCValAssign &ArgLoc : ArgLocs)
2755 if (!ArgLoc.isRegLoc())
2759 // If the calling conventions do not match, then we'd better make sure the
2760 // results are returned in the same way as what the caller expects.
2762 SmallVector<CCValAssign, 16> RVLocs1;
2763 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2765 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForCall(CalleeCC, isVarArg));
2767 SmallVector<CCValAssign, 16> RVLocs2;
2768 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2770 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForCall(CallerCC, isVarArg));
2772 if (RVLocs1.size() != RVLocs2.size())
2774 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2775 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2777 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2779 if (RVLocs1[i].isRegLoc()) {
2780 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2783 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2789 // Nothing more to check if the callee is taking no arguments
2793 SmallVector<CCValAssign, 16> ArgLocs;
2794 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2797 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2799 const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2801 // If the stack arguments for this call would fit into our own save area then
2802 // the call can be made tail.
2803 return CCInfo.getNextStackOffset() <= FuncInfo->getBytesInStackArgArea();
2806 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
2808 MachineFrameInfo *MFI,
2809 int ClobberedFI) const {
2810 SmallVector<SDValue, 8> ArgChains;
2811 int64_t FirstByte = MFI->getObjectOffset(ClobberedFI);
2812 int64_t LastByte = FirstByte + MFI->getObjectSize(ClobberedFI) - 1;
2814 // Include the original chain at the beginning of the list. When this is
2815 // used by target LowerCall hooks, this helps legalize find the
2816 // CALLSEQ_BEGIN node.
2817 ArgChains.push_back(Chain);
2819 // Add a chain value for each stack argument corresponding
2820 for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
2821 UE = DAG.getEntryNode().getNode()->use_end();
2823 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
2824 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
2825 if (FI->getIndex() < 0) {
2826 int64_t InFirstByte = MFI->getObjectOffset(FI->getIndex());
2827 int64_t InLastByte = InFirstByte;
2828 InLastByte += MFI->getObjectSize(FI->getIndex()) - 1;
2830 if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
2831 (FirstByte <= InFirstByte && InFirstByte <= LastByte))
2832 ArgChains.push_back(SDValue(L, 1));
2835 // Build a tokenfactor for all the chains.
2836 return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
2839 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
2840 bool TailCallOpt) const {
2841 return CallCC == CallingConv::Fast && TailCallOpt;
2844 bool AArch64TargetLowering::IsTailCallConvention(CallingConv::ID CallCC) const {
2845 return CallCC == CallingConv::Fast;
2848 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
2849 /// and add input and output parameter nodes.
2851 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
2852 SmallVectorImpl<SDValue> &InVals) const {
2853 SelectionDAG &DAG = CLI.DAG;
2855 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2856 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2857 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2858 SDValue Chain = CLI.Chain;
2859 SDValue Callee = CLI.Callee;
2860 bool &IsTailCall = CLI.IsTailCall;
2861 CallingConv::ID CallConv = CLI.CallConv;
2862 bool IsVarArg = CLI.IsVarArg;
2864 MachineFunction &MF = DAG.getMachineFunction();
2865 bool IsStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
2866 bool IsThisReturn = false;
2868 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2869 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2870 bool IsSibCall = false;
2873 // Check if it's really possible to do a tail call.
2874 IsTailCall = isEligibleForTailCallOptimization(
2875 Callee, CallConv, IsVarArg, IsStructRet,
2876 MF.getFunction()->hasStructRetAttr(), Outs, OutVals, Ins, DAG);
2877 if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
2878 report_fatal_error("failed to perform tail call elimination on a call "
2879 "site marked musttail");
2881 // A sibling call is one where we're under the usual C ABI and not planning
2882 // to change that but can still do a tail call:
2883 if (!TailCallOpt && IsTailCall)
2890 // Analyze operands of the call, assigning locations to each operand.
2891 SmallVector<CCValAssign, 16> ArgLocs;
2892 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
2896 // Handle fixed and variable vector arguments differently.
2897 // Variable vector arguments always go into memory.
2898 unsigned NumArgs = Outs.size();
2900 for (unsigned i = 0; i != NumArgs; ++i) {
2901 MVT ArgVT = Outs[i].VT;
2902 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2903 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
2904 /*IsVarArg=*/ !Outs[i].IsFixed);
2905 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
2906 assert(!Res && "Call operand has unhandled type");
2910 // At this point, Outs[].VT may already be promoted to i32. To correctly
2911 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2912 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2913 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
2914 // we use a special version of AnalyzeCallOperands to pass in ValVT and
2916 unsigned NumArgs = Outs.size();
2917 for (unsigned i = 0; i != NumArgs; ++i) {
2918 MVT ValVT = Outs[i].VT;
2919 // Get type of the original argument.
2920 EVT ActualVT = getValueType(DAG.getDataLayout(),
2921 CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
2922 /*AllowUnknown*/ true);
2923 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
2924 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2925 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2926 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2928 else if (ActualMVT == MVT::i16)
2931 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2932 bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
2933 assert(!Res && "Call operand has unhandled type");
2938 // Get a count of how many bytes are to be pushed on the stack.
2939 unsigned NumBytes = CCInfo.getNextStackOffset();
2942 // Since we're not changing the ABI to make this a tail call, the memory
2943 // operands are already available in the caller's incoming argument space.
2947 // FPDiff is the byte offset of the call's argument area from the callee's.
2948 // Stores to callee stack arguments will be placed in FixedStackSlots offset
2949 // by this amount for a tail call. In a sibling call it must be 0 because the
2950 // caller will deallocate the entire stack and the callee still expects its
2951 // arguments to begin at SP+0. Completely unused for non-tail calls.
2954 if (IsTailCall && !IsSibCall) {
2955 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
2957 // Since callee will pop argument stack as a tail call, we must keep the
2958 // popped size 16-byte aligned.
2959 NumBytes = RoundUpToAlignment(NumBytes, 16);
2961 // FPDiff will be negative if this tail call requires more space than we
2962 // would automatically have in our incoming argument space. Positive if we
2963 // can actually shrink the stack.
2964 FPDiff = NumReusableBytes - NumBytes;
2966 // The stack pointer must be 16-byte aligned at all times it's used for a
2967 // memory operation, which in practice means at *all* times and in
2968 // particular across call boundaries. Therefore our own arguments started at
2969 // a 16-byte aligned SP and the delta applied for the tail call should
2970 // satisfy the same constraint.
2971 assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
2974 // Adjust the stack pointer for the new arguments...
2975 // These operations are automatically eliminated by the prolog/epilog pass
2977 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, DL,
2981 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
2982 getPointerTy(DAG.getDataLayout()));
2984 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2985 SmallVector<SDValue, 8> MemOpChains;
2986 auto PtrVT = getPointerTy(DAG.getDataLayout());
2988 // Walk the register/memloc assignments, inserting copies/loads.
2989 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
2990 ++i, ++realArgIdx) {
2991 CCValAssign &VA = ArgLocs[i];
2992 SDValue Arg = OutVals[realArgIdx];
2993 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2995 // Promote the value if needed.
2996 switch (VA.getLocInfo()) {
2998 llvm_unreachable("Unknown loc info!");
2999 case CCValAssign::Full:
3001 case CCValAssign::SExt:
3002 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3004 case CCValAssign::ZExt:
3005 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3007 case CCValAssign::AExt:
3008 if (Outs[realArgIdx].ArgVT == MVT::i1) {
3009 // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
3010 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3011 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
3013 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3015 case CCValAssign::BCvt:
3016 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3018 case CCValAssign::FPExt:
3019 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3023 if (VA.isRegLoc()) {
3024 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i64) {
3025 assert(VA.getLocVT() == MVT::i64 &&
3026 "unexpected calling convention register assignment");
3027 assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
3028 "unexpected use of 'returned'");
3029 IsThisReturn = true;
3031 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3033 assert(VA.isMemLoc());
3036 MachinePointerInfo DstInfo;
3038 // FIXME: This works on big-endian for composite byvals, which are the
3039 // common case. It should also work for fundamental types too.
3040 uint32_t BEAlign = 0;
3041 unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
3042 : VA.getValVT().getSizeInBits();
3043 OpSize = (OpSize + 7) / 8;
3044 if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
3045 !Flags.isInConsecutiveRegs()) {
3047 BEAlign = 8 - OpSize;
3049 unsigned LocMemOffset = VA.getLocMemOffset();
3050 int32_t Offset = LocMemOffset + BEAlign;
3051 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3052 PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3055 Offset = Offset + FPDiff;
3056 int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3058 DstAddr = DAG.getFrameIndex(FI, PtrVT);
3060 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
3062 // Make sure any stack arguments overlapping with where we're storing
3063 // are loaded before this eventual operation. Otherwise they'll be
3065 Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
3067 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3069 DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3070 DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
3074 if (Outs[i].Flags.isByVal()) {
3076 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
3077 SDValue Cpy = DAG.getMemcpy(
3078 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
3079 /*isVol = */ false, /*AlwaysInline = */ false,
3080 /*isTailCall = */ false,
3081 DstInfo, MachinePointerInfo());
3083 MemOpChains.push_back(Cpy);
3085 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
3086 // promoted to a legal register type i32, we should truncate Arg back to
3088 if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
3089 VA.getValVT() == MVT::i16)
3090 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
3093 DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, false, false, 0);
3094 MemOpChains.push_back(Store);
3099 if (!MemOpChains.empty())
3100 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3102 // Build a sequence of copy-to-reg nodes chained together with token chain
3103 // and flag operands which copy the outgoing args into the appropriate regs.
3105 for (auto &RegToPass : RegsToPass) {
3106 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3107 RegToPass.second, InFlag);
3108 InFlag = Chain.getValue(1);
3111 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3112 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3113 // node so that legalize doesn't hack it.
3114 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3115 Subtarget->isTargetMachO()) {
3116 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3117 const GlobalValue *GV = G->getGlobal();
3118 bool InternalLinkage = GV->hasInternalLinkage();
3119 if (InternalLinkage)
3120 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3123 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT);
3124 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3126 } else if (ExternalSymbolSDNode *S =
3127 dyn_cast<ExternalSymbolSDNode>(Callee)) {
3128 const char *Sym = S->getSymbol();
3129 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
3130 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3132 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3133 const GlobalValue *GV = G->getGlobal();
3134 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3135 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3136 const char *Sym = S->getSymbol();
3137 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
3140 // We don't usually want to end the call-sequence here because we would tidy
3141 // the frame up *after* the call, however in the ABI-changing tail-call case
3142 // we've carefully laid out the parameters so that when sp is reset they'll be
3143 // in the correct location.
3144 if (IsTailCall && !IsSibCall) {
3145 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3146 DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
3147 InFlag = Chain.getValue(1);
3150 std::vector<SDValue> Ops;
3151 Ops.push_back(Chain);
3152 Ops.push_back(Callee);
3155 // Each tail call may have to adjust the stack by a different amount, so
3156 // this information must travel along with the operation for eventual
3157 // consumption by emitEpilogue.
3158 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3161 // Add argument registers to the end of the list so that they are known live
3163 for (auto &RegToPass : RegsToPass)
3164 Ops.push_back(DAG.getRegister(RegToPass.first,
3165 RegToPass.second.getValueType()));
3167 // Add a register mask operand representing the call-preserved registers.
3168 const uint32_t *Mask;
3169 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3171 // For 'this' returns, use the X0-preserving mask if applicable
3172 Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
3174 IsThisReturn = false;
3175 Mask = TRI->getCallPreservedMask(MF, CallConv);
3178 Mask = TRI->getCallPreservedMask(MF, CallConv);
3180 assert(Mask && "Missing call preserved mask for calling convention");
3181 Ops.push_back(DAG.getRegisterMask(Mask));
3183 if (InFlag.getNode())
3184 Ops.push_back(InFlag);
3186 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3188 // If we're doing a tall call, use a TC_RETURN here rather than an
3189 // actual call instruction.
3191 MF.getFrameInfo()->setHasTailCall();
3192 return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
3195 // Returns a chain and a flag for retval copy to use.
3196 Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
3197 InFlag = Chain.getValue(1);
3199 uint64_t CalleePopBytes = DoesCalleeRestoreStack(CallConv, TailCallOpt)
3200 ? RoundUpToAlignment(NumBytes, 16)
3203 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3204 DAG.getIntPtrConstant(CalleePopBytes, DL, true),
3207 InFlag = Chain.getValue(1);
3209 // Handle result values, copying them out of physregs into vregs that we
3211 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3212 InVals, IsThisReturn,
3213 IsThisReturn ? OutVals[0] : SDValue());
3216 bool AArch64TargetLowering::CanLowerReturn(
3217 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
3218 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
3219 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3220 ? RetCC_AArch64_WebKit_JS
3221 : RetCC_AArch64_AAPCS;
3222 SmallVector<CCValAssign, 16> RVLocs;
3223 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
3224 return CCInfo.CheckReturn(Outs, RetCC);
3228 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3230 const SmallVectorImpl<ISD::OutputArg> &Outs,
3231 const SmallVectorImpl<SDValue> &OutVals,
3232 SDLoc DL, SelectionDAG &DAG) const {
3233 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3234 ? RetCC_AArch64_WebKit_JS
3235 : RetCC_AArch64_AAPCS;
3236 SmallVector<CCValAssign, 16> RVLocs;
3237 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3239 CCInfo.AnalyzeReturn(Outs, RetCC);
3241 // Copy the result values into the output registers.
3243 SmallVector<SDValue, 4> RetOps(1, Chain);
3244 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
3245 ++i, ++realRVLocIdx) {
3246 CCValAssign &VA = RVLocs[i];
3247 assert(VA.isRegLoc() && "Can only return in registers!");
3248 SDValue Arg = OutVals[realRVLocIdx];
3250 switch (VA.getLocInfo()) {
3252 llvm_unreachable("Unknown loc info!");
3253 case CCValAssign::Full:
3254 if (Outs[i].ArgVT == MVT::i1) {
3255 // AAPCS requires i1 to be zero-extended to i8 by the producer of the
3256 // value. This is strictly redundant on Darwin (which uses "zeroext
3257 // i1"), but will be optimised out before ISel.
3258 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3259 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3262 case CCValAssign::BCvt:
3263 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3267 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
3268 Flag = Chain.getValue(1);
3269 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3272 RetOps[0] = Chain; // Update chain.
3274 // Add the flag if we have it.
3276 RetOps.push_back(Flag);
3278 return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
3281 //===----------------------------------------------------------------------===//
3282 // Other Lowering Code
3283 //===----------------------------------------------------------------------===//
3285 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
3286 SelectionDAG &DAG) const {
3287 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3289 const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
3290 const GlobalValue *GV = GN->getGlobal();
3291 unsigned char OpFlags =
3292 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
3294 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
3295 "unexpected offset in global node");
3297 // This also catched the large code model case for Darwin.
3298 if ((OpFlags & AArch64II::MO_GOT) != 0) {
3299 SDValue GotAddr = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
3300 // FIXME: Once remat is capable of dealing with instructions with register
3301 // operands, expand this into two nodes instead of using a wrapper node.
3302 return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
3305 if ((OpFlags & AArch64II::MO_CONSTPOOL) != 0) {
3306 assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
3307 "use of MO_CONSTPOOL only supported on small model");
3308 SDValue Hi = DAG.getTargetConstantPool(GV, PtrVT, 0, 0, AArch64II::MO_PAGE);
3309 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3310 unsigned char LoFlags = AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
3311 SDValue Lo = DAG.getTargetConstantPool(GV, PtrVT, 0, 0, LoFlags);
3312 SDValue PoolAddr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3313 SDValue GlobalAddr = DAG.getLoad(
3314 PtrVT, DL, DAG.getEntryNode(), PoolAddr,
3315 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
3316 /*isVolatile=*/false,
3317 /*isNonTemporal=*/true,
3318 /*isInvariant=*/true, 8);
3319 if (GN->getOffset() != 0)
3320 return DAG.getNode(ISD::ADD, DL, PtrVT, GlobalAddr,
3321 DAG.getConstant(GN->getOffset(), DL, PtrVT));
3325 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
3326 const unsigned char MO_NC = AArch64II::MO_NC;
3328 AArch64ISD::WrapperLarge, DL, PtrVT,
3329 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G3),
3330 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
3331 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
3332 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
3334 // Use ADRP/ADD or ADRP/LDR for everything else: the small model on ELF and
3335 // the only correct model on Darwin.
3336 SDValue Hi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
3337 OpFlags | AArch64II::MO_PAGE);
3338 unsigned char LoFlags = OpFlags | AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
3339 SDValue Lo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, LoFlags);
3341 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3342 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3346 /// \brief Convert a TLS address reference into the correct sequence of loads
3347 /// and calls to compute the variable's address (for Darwin, currently) and
3348 /// return an SDValue containing the final node.
3350 /// Darwin only has one TLS scheme which must be capable of dealing with the
3351 /// fully general situation, in the worst case. This means:
3352 /// + "extern __thread" declaration.
3353 /// + Defined in a possibly unknown dynamic library.
3355 /// The general system is that each __thread variable has a [3 x i64] descriptor
3356 /// which contains information used by the runtime to calculate the address. The
3357 /// only part of this the compiler needs to know about is the first xword, which
3358 /// contains a function pointer that must be called with the address of the
3359 /// entire descriptor in "x0".
3361 /// Since this descriptor may be in a different unit, in general even the
3362 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
3364 /// adrp x0, _var@TLVPPAGE
3365 /// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor
3366 /// ldr x1, [x0] ; x1 contains 1st entry of descriptor,
3367 /// ; the function pointer
3368 /// blr x1 ; Uses descriptor address in x0
3369 /// ; Address of _var is now in x0.
3371 /// If the address of _var's descriptor *is* known to the linker, then it can
3372 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
3373 /// a slight efficiency gain.
3375 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
3376 SelectionDAG &DAG) const {
3377 assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
3380 MVT PtrVT = getPointerTy(DAG.getDataLayout());
3381 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3384 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3385 SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
3387 // The first entry in the descriptor is a function pointer that we must call
3388 // to obtain the address of the variable.
3389 SDValue Chain = DAG.getEntryNode();
3390 SDValue FuncTLVGet =
3391 DAG.getLoad(MVT::i64, DL, Chain, DescAddr,
3392 MachinePointerInfo::getGOT(DAG.getMachineFunction()), false,
3394 Chain = FuncTLVGet.getValue(1);
3396 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3397 MFI->setAdjustsStack(true);
3399 // TLS calls preserve all registers except those that absolutely must be
3400 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
3402 const uint32_t *Mask =
3403 Subtarget->getRegisterInfo()->getTLSCallPreservedMask();
3405 // Finally, we can make the call. This is just a degenerate version of a
3406 // normal AArch64 call node: x0 takes the address of the descriptor, and
3407 // returns the address of the variable in this thread.
3408 Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
3410 DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3411 Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
3412 DAG.getRegisterMask(Mask), Chain.getValue(1));
3413 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
3416 /// When accessing thread-local variables under either the general-dynamic or
3417 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
3418 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
3419 /// is a function pointer to carry out the resolution.
3421 /// The sequence is:
3422 /// adrp x0, :tlsdesc:var
3423 /// ldr x1, [x0, #:tlsdesc_lo12:var]
3424 /// add x0, x0, #:tlsdesc_lo12:var
3425 /// .tlsdesccall var
3427 /// (TPIDR_EL0 offset now in x0)
3429 /// The above sequence must be produced unscheduled, to enable the linker to
3430 /// optimize/relax this sequence.
3431 /// Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
3432 /// above sequence, and expanded really late in the compilation flow, to ensure
3433 /// the sequence is produced as per above.
3434 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr, SDLoc DL,
3435 SelectionDAG &DAG) const {
3436 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3438 SDValue Chain = DAG.getEntryNode();
3439 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3441 SmallVector<SDValue, 2> Ops;
3442 Ops.push_back(Chain);
3443 Ops.push_back(SymAddr);
3445 Chain = DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, Ops);
3446 SDValue Glue = Chain.getValue(1);
3448 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
3452 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
3453 SelectionDAG &DAG) const {
3454 assert(Subtarget->isTargetELF() && "This function expects an ELF target");
3455 assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
3456 "ELF TLS only supported in small memory model");
3457 // Different choices can be made for the maximum size of the TLS area for a
3458 // module. For the small address model, the default TLS size is 16MiB and the
3459 // maximum TLS size is 4GiB.
3460 // FIXME: add -mtls-size command line option and make it control the 16MiB
3461 // vs. 4GiB code sequence generation.
3462 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3464 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
3466 if (DAG.getTarget().Options.EmulatedTLS)
3467 return LowerToTLSEmulatedModel(GA, DAG);
3469 if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
3470 if (Model == TLSModel::LocalDynamic)
3471 Model = TLSModel::GeneralDynamic;
3475 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3477 const GlobalValue *GV = GA->getGlobal();
3479 SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
3481 if (Model == TLSModel::LocalExec) {
3482 SDValue HiVar = DAG.getTargetGlobalAddress(
3483 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
3484 SDValue LoVar = DAG.getTargetGlobalAddress(
3486 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3488 SDValue TPWithOff_lo =
3489 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
3491 DAG.getTargetConstant(0, DL, MVT::i32)),
3494 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
3496 DAG.getTargetConstant(0, DL, MVT::i32)),
3499 } else if (Model == TLSModel::InitialExec) {
3500 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3501 TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
3502 } else if (Model == TLSModel::LocalDynamic) {
3503 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
3504 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
3505 // the beginning of the module's TLS region, followed by a DTPREL offset
3508 // These accesses will need deduplicating if there's more than one.
3509 AArch64FunctionInfo *MFI =
3510 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
3511 MFI->incNumLocalDynamicTLSAccesses();
3513 // The call needs a relocation too for linker relaxation. It doesn't make
3514 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3516 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
3519 // Now we can calculate the offset from TPIDR_EL0 to this module's
3520 // thread-local area.
3521 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
3523 // Now use :dtprel_whatever: operations to calculate this variable's offset
3524 // in its thread-storage area.
3525 SDValue HiVar = DAG.getTargetGlobalAddress(
3526 GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
3527 SDValue LoVar = DAG.getTargetGlobalAddress(
3528 GV, DL, MVT::i64, 0,
3529 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3531 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
3532 DAG.getTargetConstant(0, DL, MVT::i32)),
3534 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
3535 DAG.getTargetConstant(0, DL, MVT::i32)),
3537 } else if (Model == TLSModel::GeneralDynamic) {
3538 // The call needs a relocation too for linker relaxation. It doesn't make
3539 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3542 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3544 // Finally we can make a call to calculate the offset from tpidr_el0.
3545 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
3547 llvm_unreachable("Unsupported ELF TLS access model");
3549 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
3552 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
3553 SelectionDAG &DAG) const {
3554 if (Subtarget->isTargetDarwin())
3555 return LowerDarwinGlobalTLSAddress(Op, DAG);
3556 else if (Subtarget->isTargetELF())
3557 return LowerELFGlobalTLSAddress(Op, DAG);
3559 llvm_unreachable("Unexpected platform trying to use TLS");
3561 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3562 SDValue Chain = Op.getOperand(0);
3563 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3564 SDValue LHS = Op.getOperand(2);
3565 SDValue RHS = Op.getOperand(3);
3566 SDValue Dest = Op.getOperand(4);
3569 // Handle f128 first, since lowering it will result in comparing the return
3570 // value of a libcall against zero, which is just what the rest of LowerBR_CC
3571 // is expecting to deal with.
3572 if (LHS.getValueType() == MVT::f128) {
3573 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3575 // If softenSetCCOperands returned a scalar, we need to compare the result
3576 // against zero to select between true and false values.
3577 if (!RHS.getNode()) {
3578 RHS = DAG.getConstant(0, dl, LHS.getValueType());
3583 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
3585 unsigned Opc = LHS.getOpcode();
3586 if (LHS.getResNo() == 1 && isOneConstant(RHS) &&
3587 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3588 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
3589 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
3590 "Unexpected condition code.");
3591 // Only lower legal XALUO ops.
3592 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
3595 // The actual operation with overflow check.
3596 AArch64CC::CondCode OFCC;
3597 SDValue Value, Overflow;
3598 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
3600 if (CC == ISD::SETNE)
3601 OFCC = getInvertedCondCode(OFCC);
3602 SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
3604 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3608 if (LHS.getValueType().isInteger()) {
3609 assert((LHS.getValueType() == RHS.getValueType()) &&
3610 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3612 // If the RHS of the comparison is zero, we can potentially fold this
3613 // to a specialized branch.
3614 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
3615 if (RHSC && RHSC->getZExtValue() == 0) {
3616 if (CC == ISD::SETEQ) {
3617 // See if we can use a TBZ to fold in an AND as well.
3618 // TBZ has a smaller branch displacement than CBZ. If the offset is
3619 // out of bounds, a late MI-layer pass rewrites branches.
3620 // 403.gcc is an example that hits this case.
3621 if (LHS.getOpcode() == ISD::AND &&
3622 isa<ConstantSDNode>(LHS.getOperand(1)) &&
3623 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3624 SDValue Test = LHS.getOperand(0);
3625 uint64_t Mask = LHS.getConstantOperandVal(1);
3626 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
3627 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3631 return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
3632 } else if (CC == ISD::SETNE) {
3633 // See if we can use a TBZ to fold in an AND as well.
3634 // TBZ has a smaller branch displacement than CBZ. If the offset is
3635 // out of bounds, a late MI-layer pass rewrites branches.
3636 // 403.gcc is an example that hits this case.
3637 if (LHS.getOpcode() == ISD::AND &&
3638 isa<ConstantSDNode>(LHS.getOperand(1)) &&
3639 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3640 SDValue Test = LHS.getOperand(0);
3641 uint64_t Mask = LHS.getConstantOperandVal(1);
3642 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
3643 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3647 return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
3648 } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
3649 // Don't combine AND since emitComparison converts the AND to an ANDS
3650 // (a.k.a. TST) and the test in the test bit and branch instruction
3651 // becomes redundant. This would also increase register pressure.
3652 uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
3653 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
3654 DAG.getConstant(Mask, dl, MVT::i64), Dest);
3657 if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
3658 LHS.getOpcode() != ISD::AND) {
3659 // Don't combine AND since emitComparison converts the AND to an ANDS
3660 // (a.k.a. TST) and the test in the test bit and branch instruction
3661 // becomes redundant. This would also increase register pressure.
3662 uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
3663 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
3664 DAG.getConstant(Mask, dl, MVT::i64), Dest);
3668 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3669 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3673 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3675 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
3676 // clean. Some of them require two branches to implement.
3677 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3678 AArch64CC::CondCode CC1, CC2;
3679 changeFPCCToAArch64CC(CC, CC1, CC2);
3680 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3682 DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
3683 if (CC2 != AArch64CC::AL) {
3684 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
3685 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
3692 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
3693 SelectionDAG &DAG) const {
3694 EVT VT = Op.getValueType();
3697 SDValue In1 = Op.getOperand(0);
3698 SDValue In2 = Op.getOperand(1);
3699 EVT SrcVT = In2.getValueType();
3701 if (SrcVT.bitsLT(VT))
3702 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
3703 else if (SrcVT.bitsGT(VT))
3704 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
3709 SDValue VecVal1, VecVal2;
3710 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
3712 VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
3713 EltMask = 0x80000000ULL;
3715 if (!VT.isVector()) {
3716 VecVal1 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3717 DAG.getUNDEF(VecVT), In1);
3718 VecVal2 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3719 DAG.getUNDEF(VecVT), In2);
3721 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3722 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3724 } else if (VT == MVT::f64 || VT == MVT::v2f64) {
3728 // We want to materialize a mask with the high bit set, but the AdvSIMD
3729 // immediate moves cannot materialize that in a single instruction for
3730 // 64-bit elements. Instead, materialize zero and then negate it.
3733 if (!VT.isVector()) {
3734 VecVal1 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3735 DAG.getUNDEF(VecVT), In1);
3736 VecVal2 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3737 DAG.getUNDEF(VecVT), In2);
3739 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3740 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3743 llvm_unreachable("Invalid type for copysign!");
3746 SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
3748 // If we couldn't materialize the mask above, then the mask vector will be
3749 // the zero vector, and we need to negate it here.
3750 if (VT == MVT::f64 || VT == MVT::v2f64) {
3751 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
3752 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
3753 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
3757 DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
3760 return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
3761 else if (VT == MVT::f64)
3762 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
3764 return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
3767 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
3768 if (DAG.getMachineFunction().getFunction()->hasFnAttribute(
3769 Attribute::NoImplicitFloat))
3772 if (!Subtarget->hasNEON())
3775 // While there is no integer popcount instruction, it can
3776 // be more efficiently lowered to the following sequence that uses
3777 // AdvSIMD registers/instructions as long as the copies to/from
3778 // the AdvSIMD registers are cheap.
3779 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd
3780 // CNT V0.8B, V0.8B // 8xbyte pop-counts
3781 // ADDV B0, V0.8B // sum 8xbyte pop-counts
3782 // UMOV X0, V0.B[0] // copy byte result back to integer reg
3783 SDValue Val = Op.getOperand(0);
3785 EVT VT = Op.getValueType();
3788 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
3789 Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
3791 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
3792 SDValue UaddLV = DAG.getNode(
3793 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
3794 DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
3797 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
3801 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3803 if (Op.getValueType().isVector())
3804 return LowerVSETCC(Op, DAG);
3806 SDValue LHS = Op.getOperand(0);
3807 SDValue RHS = Op.getOperand(1);
3808 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3811 // We chose ZeroOrOneBooleanContents, so use zero and one.
3812 EVT VT = Op.getValueType();
3813 SDValue TVal = DAG.getConstant(1, dl, VT);
3814 SDValue FVal = DAG.getConstant(0, dl, VT);
3816 // Handle f128 first, since one possible outcome is a normal integer
3817 // comparison which gets picked up by the next if statement.
3818 if (LHS.getValueType() == MVT::f128) {
3819 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3821 // If softenSetCCOperands returned a scalar, use it.
3822 if (!RHS.getNode()) {
3823 assert(LHS.getValueType() == Op.getValueType() &&
3824 "Unexpected setcc expansion!");
3829 if (LHS.getValueType().isInteger()) {
3832 getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
3834 // Note that we inverted the condition above, so we reverse the order of
3835 // the true and false operands here. This will allow the setcc to be
3836 // matched to a single CSINC instruction.
3837 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
3840 // Now we know we're dealing with FP values.
3841 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3843 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
3844 // and do the comparison.
3845 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3847 AArch64CC::CondCode CC1, CC2;
3848 changeFPCCToAArch64CC(CC, CC1, CC2);
3849 if (CC2 == AArch64CC::AL) {
3850 changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
3851 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3853 // Note that we inverted the condition above, so we reverse the order of
3854 // the true and false operands here. This will allow the setcc to be
3855 // matched to a single CSINC instruction.
3856 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
3858 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
3859 // totally clean. Some of them require two CSELs to implement. As is in
3860 // this case, we emit the first CSEL and then emit a second using the output
3861 // of the first as the RHS. We're effectively OR'ing the two CC's together.
3863 // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
3864 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
3866 DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3868 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
3869 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3873 SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
3874 SDValue RHS, SDValue TVal,
3875 SDValue FVal, SDLoc dl,
3876 SelectionDAG &DAG) const {
3877 // Handle f128 first, because it will result in a comparison of some RTLIB
3878 // call result against zero.
3879 if (LHS.getValueType() == MVT::f128) {
3880 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3882 // If softenSetCCOperands returned a scalar, we need to compare the result
3883 // against zero to select between true and false values.
3884 if (!RHS.getNode()) {
3885 RHS = DAG.getConstant(0, dl, LHS.getValueType());
3890 // Also handle f16, for which we need to do a f32 comparison.
3891 if (LHS.getValueType() == MVT::f16) {
3892 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
3893 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
3896 // Next, handle integers.
3897 if (LHS.getValueType().isInteger()) {
3898 assert((LHS.getValueType() == RHS.getValueType()) &&
3899 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3901 unsigned Opcode = AArch64ISD::CSEL;
3903 // If both the TVal and the FVal are constants, see if we can swap them in
3904 // order to for a CSINV or CSINC out of them.
3905 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
3906 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
3908 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
3909 std::swap(TVal, FVal);
3910 std::swap(CTVal, CFVal);
3911 CC = ISD::getSetCCInverse(CC, true);
3912 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
3913 std::swap(TVal, FVal);
3914 std::swap(CTVal, CFVal);
3915 CC = ISD::getSetCCInverse(CC, true);
3916 } else if (TVal.getOpcode() == ISD::XOR) {
3917 // If TVal is a NOT we want to swap TVal and FVal so that we can match
3918 // with a CSINV rather than a CSEL.
3919 if (isAllOnesConstant(TVal.getOperand(1))) {
3920 std::swap(TVal, FVal);
3921 std::swap(CTVal, CFVal);
3922 CC = ISD::getSetCCInverse(CC, true);
3924 } else if (TVal.getOpcode() == ISD::SUB) {
3925 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
3926 // that we can match with a CSNEG rather than a CSEL.
3927 if (isNullConstant(TVal.getOperand(0))) {
3928 std::swap(TVal, FVal);
3929 std::swap(CTVal, CFVal);
3930 CC = ISD::getSetCCInverse(CC, true);
3932 } else if (CTVal && CFVal) {
3933 const int64_t TrueVal = CTVal->getSExtValue();
3934 const int64_t FalseVal = CFVal->getSExtValue();
3937 // If both TVal and FVal are constants, see if FVal is the
3938 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
3939 // instead of a CSEL in that case.
3940 if (TrueVal == ~FalseVal) {
3941 Opcode = AArch64ISD::CSINV;
3942 } else if (TrueVal == -FalseVal) {
3943 Opcode = AArch64ISD::CSNEG;
3944 } else if (TVal.getValueType() == MVT::i32) {
3945 // If our operands are only 32-bit wide, make sure we use 32-bit
3946 // arithmetic for the check whether we can use CSINC. This ensures that
3947 // the addition in the check will wrap around properly in case there is
3948 // an overflow (which would not be the case if we do the check with
3949 // 64-bit arithmetic).
3950 const uint32_t TrueVal32 = CTVal->getZExtValue();
3951 const uint32_t FalseVal32 = CFVal->getZExtValue();
3953 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
3954 Opcode = AArch64ISD::CSINC;
3956 if (TrueVal32 > FalseVal32) {
3960 // 64-bit check whether we can use CSINC.
3961 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
3962 Opcode = AArch64ISD::CSINC;
3964 if (TrueVal > FalseVal) {
3969 // Swap TVal and FVal if necessary.
3971 std::swap(TVal, FVal);
3972 std::swap(CTVal, CFVal);
3973 CC = ISD::getSetCCInverse(CC, true);
3976 if (Opcode != AArch64ISD::CSEL) {
3977 // Drop FVal since we can get its value by simply inverting/negating
3984 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3986 EVT VT = TVal.getValueType();
3987 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
3990 // Now we know we're dealing with FP values.
3991 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3992 assert(LHS.getValueType() == RHS.getValueType());
3993 EVT VT = TVal.getValueType();
3994 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3996 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
3997 // clean. Some of them require two CSELs to implement.
3998 AArch64CC::CondCode CC1, CC2;
3999 changeFPCCToAArch64CC(CC, CC1, CC2);
4000 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
4001 SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4003 // If we need a second CSEL, emit it, using the output of the first as the
4004 // RHS. We're effectively OR'ing the two CC's together.
4005 if (CC2 != AArch64CC::AL) {
4006 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
4007 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4010 // Otherwise, return the output of the first CSEL.
4014 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
4015 SelectionDAG &DAG) const {
4016 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4017 SDValue LHS = Op.getOperand(0);
4018 SDValue RHS = Op.getOperand(1);
4019 SDValue TVal = Op.getOperand(2);
4020 SDValue FVal = Op.getOperand(3);
4022 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4025 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
4026 SelectionDAG &DAG) const {
4027 SDValue CCVal = Op->getOperand(0);
4028 SDValue TVal = Op->getOperand(1);
4029 SDValue FVal = Op->getOperand(2);
4032 unsigned Opc = CCVal.getOpcode();
4033 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
4035 if (CCVal.getResNo() == 1 &&
4036 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4037 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
4038 // Only lower legal XALUO ops.
4039 if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
4042 AArch64CC::CondCode OFCC;
4043 SDValue Value, Overflow;
4044 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
4045 SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
4047 return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
4051 // Lower it the same way as we would lower a SELECT_CC node.
4054 if (CCVal.getOpcode() == ISD::SETCC) {
4055 LHS = CCVal.getOperand(0);
4056 RHS = CCVal.getOperand(1);
4057 CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
4060 RHS = DAG.getConstant(0, DL, CCVal.getValueType());
4063 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4066 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
4067 SelectionDAG &DAG) const {
4068 // Jump table entries as PC relative offsets. No additional tweaking
4069 // is necessary here. Just get the address of the jump table.
4070 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4071 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4074 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4075 !Subtarget->isTargetMachO()) {
4076 const unsigned char MO_NC = AArch64II::MO_NC;
4078 AArch64ISD::WrapperLarge, DL, PtrVT,
4079 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G3),
4080 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G2 | MO_NC),
4081 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G1 | MO_NC),
4082 DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4083 AArch64II::MO_G0 | MO_NC));
4087 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_PAGE);
4088 SDValue Lo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4089 AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4090 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4091 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4094 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
4095 SelectionDAG &DAG) const {
4096 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4097 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4100 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4101 // Use the GOT for the large code model on iOS.
4102 if (Subtarget->isTargetMachO()) {
4103 SDValue GotAddr = DAG.getTargetConstantPool(
4104 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4106 return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
4109 const unsigned char MO_NC = AArch64II::MO_NC;
4111 AArch64ISD::WrapperLarge, DL, PtrVT,
4112 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4113 CP->getOffset(), AArch64II::MO_G3),
4114 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4115 CP->getOffset(), AArch64II::MO_G2 | MO_NC),
4116 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4117 CP->getOffset(), AArch64II::MO_G1 | MO_NC),
4118 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4119 CP->getOffset(), AArch64II::MO_G0 | MO_NC));
4121 // Use ADRP/ADD or ADRP/LDR for everything else: the small memory model on
4122 // ELF, the only valid one on Darwin.
4124 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4125 CP->getOffset(), AArch64II::MO_PAGE);
4126 SDValue Lo = DAG.getTargetConstantPool(
4127 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4128 AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4130 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4131 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4135 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
4136 SelectionDAG &DAG) const {
4137 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
4138 EVT PtrVT = getPointerTy(DAG.getDataLayout());
4140 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4141 !Subtarget->isTargetMachO()) {
4142 const unsigned char MO_NC = AArch64II::MO_NC;
4144 AArch64ISD::WrapperLarge, DL, PtrVT,
4145 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G3),
4146 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
4147 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
4148 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
4150 SDValue Hi = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGE);
4151 SDValue Lo = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGEOFF |
4153 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4154 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4158 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
4159 SelectionDAG &DAG) const {
4160 AArch64FunctionInfo *FuncInfo =
4161 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4164 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
4165 getPointerTy(DAG.getDataLayout()));
4166 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4167 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
4168 MachinePointerInfo(SV), false, false, 0);
4171 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
4172 SelectionDAG &DAG) const {
4173 // The layout of the va_list struct is specified in the AArch64 Procedure Call
4174 // Standard, section B.3.
4175 MachineFunction &MF = DAG.getMachineFunction();
4176 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4177 auto PtrVT = getPointerTy(DAG.getDataLayout());
4180 SDValue Chain = Op.getOperand(0);
4181 SDValue VAList = Op.getOperand(1);
4182 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4183 SmallVector<SDValue, 4> MemOps;
4185 // void *__stack at offset 0
4186 SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
4187 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
4188 MachinePointerInfo(SV), false, false, 8));
4190 // void *__gr_top at offset 8
4191 int GPRSize = FuncInfo->getVarArgsGPRSize();
4193 SDValue GRTop, GRTopAddr;
4196 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
4198 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
4199 GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
4200 DAG.getConstant(GPRSize, DL, PtrVT));
4202 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
4203 MachinePointerInfo(SV, 8), false, false, 8));
4206 // void *__vr_top at offset 16
4207 int FPRSize = FuncInfo->getVarArgsFPRSize();
4209 SDValue VRTop, VRTopAddr;
4210 VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4211 DAG.getConstant(16, DL, PtrVT));
4213 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
4214 VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
4215 DAG.getConstant(FPRSize, DL, PtrVT));
4217 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
4218 MachinePointerInfo(SV, 16), false, false, 8));
4221 // int __gr_offs at offset 24
4222 SDValue GROffsAddr =
4223 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
4224 MemOps.push_back(DAG.getStore(Chain, DL,
4225 DAG.getConstant(-GPRSize, DL, MVT::i32),
4226 GROffsAddr, MachinePointerInfo(SV, 24), false,
4229 // int __vr_offs at offset 28
4230 SDValue VROffsAddr =
4231 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
4232 MemOps.push_back(DAG.getStore(Chain, DL,
4233 DAG.getConstant(-FPRSize, DL, MVT::i32),
4234 VROffsAddr, MachinePointerInfo(SV, 28), false,
4237 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
4240 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
4241 SelectionDAG &DAG) const {
4242 return Subtarget->isTargetDarwin() ? LowerDarwin_VASTART(Op, DAG)
4243 : LowerAAPCS_VASTART(Op, DAG);
4246 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
4247 SelectionDAG &DAG) const {
4248 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
4251 unsigned VaListSize = Subtarget->isTargetDarwin() ? 8 : 32;
4252 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4253 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4255 return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1),
4257 DAG.getConstant(VaListSize, DL, MVT::i32),
4258 8, false, false, false, MachinePointerInfo(DestSV),
4259 MachinePointerInfo(SrcSV));
4262 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
4263 assert(Subtarget->isTargetDarwin() &&
4264 "automatic va_arg instruction only works on Darwin");
4266 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4267 EVT VT = Op.getValueType();
4269 SDValue Chain = Op.getOperand(0);
4270 SDValue Addr = Op.getOperand(1);
4271 unsigned Align = Op.getConstantOperandVal(3);
4272 auto PtrVT = getPointerTy(DAG.getDataLayout());
4274 SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V),
4275 false, false, false, 0);
4276 Chain = VAList.getValue(1);
4279 assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
4280 VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4281 DAG.getConstant(Align - 1, DL, PtrVT));
4282 VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
4283 DAG.getConstant(-(int64_t)Align, DL, PtrVT));
4286 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
4287 uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
4289 // Scalar integer and FP values smaller than 64 bits are implicitly extended
4290 // up to 64 bits. At the very least, we have to increase the striding of the
4291 // vaargs list to match this, and for FP values we need to introduce
4292 // FP_ROUND nodes as well.
4293 if (VT.isInteger() && !VT.isVector())
4295 bool NeedFPTrunc = false;
4296 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
4301 // Increment the pointer, VAList, to the next vaarg
4302 SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4303 DAG.getConstant(ArgSize, DL, PtrVT));
4304 // Store the incremented VAList to the legalized pointer
4305 SDValue APStore = DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V),
4308 // Load the actual argument out of the pointer VAList
4310 // Load the value as an f64.
4311 SDValue WideFP = DAG.getLoad(MVT::f64, DL, APStore, VAList,
4312 MachinePointerInfo(), false, false, false, 0);
4313 // Round the value down to an f32.
4314 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
4315 DAG.getIntPtrConstant(1, DL));
4316 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
4317 // Merge the rounded value with the chain output of the load.
4318 return DAG.getMergeValues(Ops, DL);
4321 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo(), false,
4325 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
4326 SelectionDAG &DAG) const {
4327 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4328 MFI->setFrameAddressIsTaken(true);
4330 EVT VT = Op.getValueType();
4332 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4334 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
4336 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
4337 MachinePointerInfo(), false, false, false, 0);
4341 // FIXME? Maybe this could be a TableGen attribute on some registers and
4342 // this table could be generated automatically from RegInfo.
4343 unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT,
4344 SelectionDAG &DAG) const {
4345 unsigned Reg = StringSwitch<unsigned>(RegName)
4346 .Case("sp", AArch64::SP)
4350 report_fatal_error(Twine("Invalid register name \""
4351 + StringRef(RegName) + "\"."));
4354 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
4355 SelectionDAG &DAG) const {
4356 MachineFunction &MF = DAG.getMachineFunction();
4357 MachineFrameInfo *MFI = MF.getFrameInfo();
4358 MFI->setReturnAddressIsTaken(true);
4360 EVT VT = Op.getValueType();
4362 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4364 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4365 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
4366 return DAG.getLoad(VT, DL, DAG.getEntryNode(),
4367 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
4368 MachinePointerInfo(), false, false, false, 0);
4371 // Return LR, which contains the return address. Mark it an implicit live-in.
4372 unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
4373 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4376 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4377 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
4378 SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
4379 SelectionDAG &DAG) const {
4380 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4381 EVT VT = Op.getValueType();
4382 unsigned VTBits = VT.getSizeInBits();
4384 SDValue ShOpLo = Op.getOperand(0);
4385 SDValue ShOpHi = Op.getOperand(1);
4386 SDValue ShAmt = Op.getOperand(2);
4387 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4389 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4391 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
4392 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
4393 SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4395 // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
4396 // is "undef". We wanted 0, so CSEL it directly.
4397 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
4398 ISD::SETEQ, dl, DAG);
4399 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
4401 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
4402 HiBitsForLo, CCVal, Cmp);
4404 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
4405 DAG.getConstant(VTBits, dl, MVT::i64));
4407 SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4408 SDValue LoForNormalShift =
4409 DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
4411 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
4413 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4414 SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4415 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
4416 LoForNormalShift, CCVal, Cmp);
4418 // AArch64 shifts larger than the register width are wrapped rather than
4419 // clamped, so we can't just emit "hi >> x".
4420 SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4421 SDValue HiForBigShift =
4423 ? DAG.getNode(Opc, dl, VT, ShOpHi,
4424 DAG.getConstant(VTBits - 1, dl, MVT::i64))
4425 : DAG.getConstant(0, dl, VT);
4426 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
4427 HiForNormalShift, CCVal, Cmp);
4429 SDValue Ops[2] = { Lo, Hi };
4430 return DAG.getMergeValues(Ops, dl);
4434 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4435 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
4436 SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
4437 SelectionDAG &DAG) const {
4438 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4439 EVT VT = Op.getValueType();
4440 unsigned VTBits = VT.getSizeInBits();
4442 SDValue ShOpLo = Op.getOperand(0);
4443 SDValue ShOpHi = Op.getOperand(1);
4444 SDValue ShAmt = Op.getOperand(2);
4446 assert(Op.getOpcode() == ISD::SHL_PARTS);
4447 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
4448 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
4449 SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4451 // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
4452 // is "undef". We wanted 0, so CSEL it directly.
4453 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
4454 ISD::SETEQ, dl, DAG);
4455 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
4457 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
4458 LoBitsForHi, CCVal, Cmp);
4460 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
4461 DAG.getConstant(VTBits, dl, MVT::i64));
4462 SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4463 SDValue HiForNormalShift =
4464 DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
4466 SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4468 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
4470 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4471 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
4472 HiForNormalShift, CCVal, Cmp);
4474 // AArch64 shifts of larger than register sizes are wrapped rather than
4475 // clamped, so we can't just emit "lo << a" if a is too big.
4476 SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
4477 SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4478 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
4479 LoForNormalShift, CCVal, Cmp);
4481 SDValue Ops[2] = { Lo, Hi };
4482 return DAG.getMergeValues(Ops, dl);
4485 bool AArch64TargetLowering::isOffsetFoldingLegal(
4486 const GlobalAddressSDNode *GA) const {
4487 // The AArch64 target doesn't support folding offsets into global addresses.
4491 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4492 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
4493 // FIXME: We should be able to handle f128 as well with a clever lowering.
4494 if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32))
4498 return AArch64_AM::getFP64Imm(Imm) != -1;
4499 else if (VT == MVT::f32)
4500 return AArch64_AM::getFP32Imm(Imm) != -1;
4504 //===----------------------------------------------------------------------===//
4505 // AArch64 Optimization Hooks
4506 //===----------------------------------------------------------------------===//
4508 //===----------------------------------------------------------------------===//
4509 // AArch64 Inline Assembly Support
4510 //===----------------------------------------------------------------------===//
4512 // Table of Constraints
4513 // TODO: This is the current set of constraints supported by ARM for the
4514 // compiler, not all of them may make sense, e.g. S may be difficult to support.
4516 // r - A general register
4517 // w - An FP/SIMD register of some size in the range v0-v31
4518 // x - An FP/SIMD register of some size in the range v0-v15
4519 // I - Constant that can be used with an ADD instruction
4520 // J - Constant that can be used with a SUB instruction
4521 // K - Constant that can be used with a 32-bit logical instruction
4522 // L - Constant that can be used with a 64-bit logical instruction
4523 // M - Constant that can be used as a 32-bit MOV immediate
4524 // N - Constant that can be used as a 64-bit MOV immediate
4525 // Q - A memory reference with base register and no offset
4526 // S - A symbolic address
4527 // Y - Floating point constant zero
4528 // Z - Integer constant zero
4530 // Note that general register operands will be output using their 64-bit x
4531 // register name, whatever the size of the variable, unless the asm operand
4532 // is prefixed by the %w modifier. Floating-point and SIMD register operands
4533 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
4536 /// getConstraintType - Given a constraint letter, return the type of
4537 /// constraint it is for this target.
4538 AArch64TargetLowering::ConstraintType
4539 AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
4540 if (Constraint.size() == 1) {
4541 switch (Constraint[0]) {
4548 return C_RegisterClass;
4549 // An address with a single base register. Due to the way we
4550 // currently handle addresses it is the same as 'r'.
4555 return TargetLowering::getConstraintType(Constraint);
4558 /// Examine constraint type and operand type and determine a weight value.
4559 /// This object must already have been set up with the operand type
4560 /// and the current alternative constraint selected.
4561 TargetLowering::ConstraintWeight
4562 AArch64TargetLowering::getSingleConstraintMatchWeight(
4563 AsmOperandInfo &info, const char *constraint) const {
4564 ConstraintWeight weight = CW_Invalid;
4565 Value *CallOperandVal = info.CallOperandVal;
4566 // If we don't have a value, we can't do a match,
4567 // but allow it at the lowest weight.
4568 if (!CallOperandVal)
4570 Type *type = CallOperandVal->getType();
4571 // Look at the constraint type.
4572 switch (*constraint) {
4574 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
4578 if (type->isFloatingPointTy() || type->isVectorTy())
4579 weight = CW_Register;
4582 weight = CW_Constant;
4588 std::pair<unsigned, const TargetRegisterClass *>
4589 AArch64TargetLowering::getRegForInlineAsmConstraint(
4590 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
4591 if (Constraint.size() == 1) {
4592 switch (Constraint[0]) {
4594 if (VT.getSizeInBits() == 64)
4595 return std::make_pair(0U, &AArch64::GPR64commonRegClass);
4596 return std::make_pair(0U, &AArch64::GPR32commonRegClass);
4599 return std::make_pair(0U, &AArch64::FPR32RegClass);
4600 if (VT.getSizeInBits() == 64)
4601 return std::make_pair(0U, &AArch64::FPR64RegClass);
4602 if (VT.getSizeInBits() == 128)
4603 return std::make_pair(0U, &AArch64::FPR128RegClass);
4605 // The instructions that this constraint is designed for can
4606 // only take 128-bit registers so just use that regclass.
4608 if (VT.getSizeInBits() == 128)
4609 return std::make_pair(0U, &AArch64::FPR128_loRegClass);
4613 if (StringRef("{cc}").equals_lower(Constraint))
4614 return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
4616 // Use the default implementation in TargetLowering to convert the register
4617 // constraint into a member of a register class.
4618 std::pair<unsigned, const TargetRegisterClass *> Res;
4619 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
4621 // Not found as a standard register?
4623 unsigned Size = Constraint.size();
4624 if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
4625 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
4627 bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
4628 if (!Failed && RegNo >= 0 && RegNo <= 31) {
4629 // v0 - v31 are aliases of q0 - q31.
4630 // By default we'll emit v0-v31 for this unless there's a modifier where
4631 // we'll emit the correct register as well.
4632 Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
4633 Res.second = &AArch64::FPR128RegClass;
4641 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
4642 /// vector. If it is invalid, don't add anything to Ops.
4643 void AArch64TargetLowering::LowerAsmOperandForConstraint(
4644 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
4645 SelectionDAG &DAG) const {
4648 // Currently only support length 1 constraints.
4649 if (Constraint.length() != 1)
4652 char ConstraintLetter = Constraint[0];
4653 switch (ConstraintLetter) {
4657 // This set of constraints deal with valid constants for various instructions.
4658 // Validate and return a target constant for them if we can.
4660 // 'z' maps to xzr or wzr so it needs an input of 0.
4661 if (!isNullConstant(Op))
4664 if (Op.getValueType() == MVT::i64)
4665 Result = DAG.getRegister(AArch64::XZR, MVT::i64);
4667 Result = DAG.getRegister(AArch64::WZR, MVT::i32);
4677 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4681 // Grab the value and do some validation.
4682 uint64_t CVal = C->getZExtValue();
4683 switch (ConstraintLetter) {
4684 // The I constraint applies only to simple ADD or SUB immediate operands:
4685 // i.e. 0 to 4095 with optional shift by 12
4686 // The J constraint applies only to ADD or SUB immediates that would be
4687 // valid when negated, i.e. if [an add pattern] were to be output as a SUB
4688 // instruction [or vice versa], in other words -1 to -4095 with optional
4689 // left shift by 12.
4691 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
4695 uint64_t NVal = -C->getSExtValue();
4696 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
4697 CVal = C->getSExtValue();
4702 // The K and L constraints apply *only* to logical immediates, including
4703 // what used to be the MOVI alias for ORR (though the MOVI alias has now
4704 // been removed and MOV should be used). So these constraints have to
4705 // distinguish between bit patterns that are valid 32-bit or 64-bit
4706 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
4707 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
4710 if (AArch64_AM::isLogicalImmediate(CVal, 32))
4714 if (AArch64_AM::isLogicalImmediate(CVal, 64))
4717 // The M and N constraints are a superset of K and L respectively, for use
4718 // with the MOV (immediate) alias. As well as the logical immediates they
4719 // also match 32 or 64-bit immediates that can be loaded either using a
4720 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
4721 // (M) or 64-bit 0x1234000000000000 (N) etc.
4722 // As a note some of this code is liberally stolen from the asm parser.
4724 if (!isUInt<32>(CVal))
4726 if (AArch64_AM::isLogicalImmediate(CVal, 32))
4728 if ((CVal & 0xFFFF) == CVal)
4730 if ((CVal & 0xFFFF0000ULL) == CVal)
4732 uint64_t NCVal = ~(uint32_t)CVal;
4733 if ((NCVal & 0xFFFFULL) == NCVal)
4735 if ((NCVal & 0xFFFF0000ULL) == NCVal)
4740 if (AArch64_AM::isLogicalImmediate(CVal, 64))
4742 if ((CVal & 0xFFFFULL) == CVal)
4744 if ((CVal & 0xFFFF0000ULL) == CVal)
4746 if ((CVal & 0xFFFF00000000ULL) == CVal)
4748 if ((CVal & 0xFFFF000000000000ULL) == CVal)
4750 uint64_t NCVal = ~CVal;
4751 if ((NCVal & 0xFFFFULL) == NCVal)
4753 if ((NCVal & 0xFFFF0000ULL) == NCVal)
4755 if ((NCVal & 0xFFFF00000000ULL) == NCVal)
4757 if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
4765 // All assembler immediates are 64-bit integers.
4766 Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
4770 if (Result.getNode()) {
4771 Ops.push_back(Result);
4775 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
4778 //===----------------------------------------------------------------------===//
4779 // AArch64 Advanced SIMD Support
4780 //===----------------------------------------------------------------------===//
4782 /// WidenVector - Given a value in the V64 register class, produce the
4783 /// equivalent value in the V128 register class.
4784 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
4785 EVT VT = V64Reg.getValueType();
4786 unsigned NarrowSize = VT.getVectorNumElements();
4787 MVT EltTy = VT.getVectorElementType().getSimpleVT();
4788 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
4791 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
4792 V64Reg, DAG.getConstant(0, DL, MVT::i32));
4795 /// getExtFactor - Determine the adjustment factor for the position when
4796 /// generating an "extract from vector registers" instruction.
4797 static unsigned getExtFactor(SDValue &V) {
4798 EVT EltType = V.getValueType().getVectorElementType();
4799 return EltType.getSizeInBits() / 8;
4802 /// NarrowVector - Given a value in the V128 register class, produce the
4803 /// equivalent value in the V64 register class.
4804 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
4805 EVT VT = V128Reg.getValueType();
4806 unsigned WideSize = VT.getVectorNumElements();
4807 MVT EltTy = VT.getVectorElementType().getSimpleVT();
4808 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
4811 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
4814 // Gather data to see if the operation can be modelled as a
4815 // shuffle in combination with VEXTs.
4816 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
4817 SelectionDAG &DAG) const {
4818 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
4820 EVT VT = Op.getValueType();
4821 unsigned NumElts = VT.getVectorNumElements();
4823 struct ShuffleSourceInfo {
4828 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
4829 // be compatible with the shuffle we intend to construct. As a result
4830 // ShuffleVec will be some sliding window into the original Vec.
4833 // Code should guarantee that element i in Vec starts at element "WindowBase
4834 // + i * WindowScale in ShuffleVec".
4838 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
4839 ShuffleSourceInfo(SDValue Vec)
4840 : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
4844 // First gather all vectors used as an immediate source for this BUILD_VECTOR
4846 SmallVector<ShuffleSourceInfo, 2> Sources;
4847 for (unsigned i = 0; i < NumElts; ++i) {
4848 SDValue V = Op.getOperand(i);
4849 if (V.getOpcode() == ISD::UNDEF)
4851 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4852 // A shuffle can only come from building a vector from various
4853 // elements of other vectors.
4857 // Add this element source to the list if it's not already there.
4858 SDValue SourceVec = V.getOperand(0);
4859 auto Source = std::find(Sources.begin(), Sources.end(), SourceVec);
4860 if (Source == Sources.end())
4861 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
4863 // Update the minimum and maximum lane number seen.
4864 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4865 Source->MinElt = std::min(Source->MinElt, EltNo);
4866 Source->MaxElt = std::max(Source->MaxElt, EltNo);
4869 // Currently only do something sane when at most two source vectors
4871 if (Sources.size() > 2)
4874 // Find out the smallest element size among result and two sources, and use
4875 // it as element size to build the shuffle_vector.
4876 EVT SmallestEltTy = VT.getVectorElementType();
4877 for (auto &Source : Sources) {
4878 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
4879 if (SrcEltTy.bitsLT(SmallestEltTy)) {
4880 SmallestEltTy = SrcEltTy;
4883 unsigned ResMultiplier =
4884 VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
4885 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
4886 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
4888 // If the source vector is too wide or too narrow, we may nevertheless be able
4889 // to construct a compatible shuffle either by concatenating it with UNDEF or
4890 // extracting a suitable range of elements.
4891 for (auto &Src : Sources) {
4892 EVT SrcVT = Src.ShuffleVec.getValueType();
4894 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
4897 // This stage of the search produces a source with the same element type as
4898 // the original, but with a total width matching the BUILD_VECTOR output.
4899 EVT EltVT = SrcVT.getVectorElementType();
4900 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
4901 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
4903 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
4904 assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
4905 // We can pad out the smaller vector for free, so if it's part of a
4908 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
4909 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
4913 assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
4915 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
4916 // Span too large for a VEXT to cope
4920 if (Src.MinElt >= NumSrcElts) {
4921 // The extraction can just take the second half
4923 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4924 DAG.getConstant(NumSrcElts, dl, MVT::i64));
4925 Src.WindowBase = -NumSrcElts;
4926 } else if (Src.MaxElt < NumSrcElts) {
4927 // The extraction can just take the first half
4929 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4930 DAG.getConstant(0, dl, MVT::i64));
4932 // An actual VEXT is needed
4934 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4935 DAG.getConstant(0, dl, MVT::i64));
4937 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
4938 DAG.getConstant(NumSrcElts, dl, MVT::i64));
4939 unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
4941 Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
4943 DAG.getConstant(Imm, dl, MVT::i32));
4944 Src.WindowBase = -Src.MinElt;
4948 // Another possible incompatibility occurs from the vector element types. We
4949 // can fix this by bitcasting the source vectors to the same type we intend
4951 for (auto &Src : Sources) {
4952 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
4953 if (SrcEltTy == SmallestEltTy)
4955 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
4956 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
4957 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
4958 Src.WindowBase *= Src.WindowScale;
4961 // Final sanity check before we try to actually produce a shuffle.
4963 for (auto Src : Sources)
4964 assert(Src.ShuffleVec.getValueType() == ShuffleVT);
4967 // The stars all align, our next step is to produce the mask for the shuffle.
4968 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
4969 int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
4970 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
4971 SDValue Entry = Op.getOperand(i);
4972 if (Entry.getOpcode() == ISD::UNDEF)
4975 auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0));
4976 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
4978 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
4979 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
4981 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
4982 int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
4983 VT.getVectorElementType().getSizeInBits());
4984 int LanesDefined = BitsDefined / BitsPerShuffleLane;
4986 // This source is expected to fill ResMultiplier lanes of the final shuffle,
4987 // starting at the appropriate offset.
4988 int *LaneMask = &Mask[i * ResMultiplier];
4990 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
4991 ExtractBase += NumElts * (Src - Sources.begin());
4992 for (int j = 0; j < LanesDefined; ++j)
4993 LaneMask[j] = ExtractBase + j;
4996 // Final check before we try to produce nonsense...
4997 if (!isShuffleMaskLegal(Mask, ShuffleVT))
5000 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
5001 for (unsigned i = 0; i < Sources.size(); ++i)
5002 ShuffleOps[i] = Sources[i].ShuffleVec;
5004 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
5005 ShuffleOps[1], &Mask[0]);
5006 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
5009 // check if an EXT instruction can handle the shuffle mask when the
5010 // vector sources of the shuffle are the same.
5011 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
5012 unsigned NumElts = VT.getVectorNumElements();
5014 // Assume that the first shuffle index is not UNDEF. Fail if it is.
5020 // If this is a VEXT shuffle, the immediate value is the index of the first
5021 // element. The other shuffle indices must be the successive elements after
5023 unsigned ExpectedElt = Imm;
5024 for (unsigned i = 1; i < NumElts; ++i) {
5025 // Increment the expected index. If it wraps around, just follow it
5026 // back to index zero and keep going.
5028 if (ExpectedElt == NumElts)
5032 continue; // ignore UNDEF indices
5033 if (ExpectedElt != static_cast<unsigned>(M[i]))
5040 // check if an EXT instruction can handle the shuffle mask when the
5041 // vector sources of the shuffle are different.
5042 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
5044 // Look for the first non-undef element.
5045 const int *FirstRealElt = std::find_if(M.begin(), M.end(),
5046 [](int Elt) {return Elt >= 0;});
5048 // Benefit form APInt to handle overflow when calculating expected element.
5049 unsigned NumElts = VT.getVectorNumElements();
5050 unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
5051 APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
5052 // The following shuffle indices must be the successive elements after the
5053 // first real element.
5054 const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
5055 [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
5056 if (FirstWrongElt != M.end())
5059 // The index of an EXT is the first element if it is not UNDEF.
5060 // Watch out for the beginning UNDEFs. The EXT index should be the expected
5061 // value of the first element. E.g.
5062 // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
5063 // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
5064 // ExpectedElt is the last mask index plus 1.
5065 Imm = ExpectedElt.getZExtValue();
5067 // There are two difference cases requiring to reverse input vectors.
5068 // For example, for vector <4 x i32> we have the following cases,
5069 // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
5070 // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
5071 // For both cases, we finally use mask <5, 6, 7, 0>, which requires
5072 // to reverse two input vectors.
5081 /// isREVMask - Check if a vector shuffle corresponds to a REV
5082 /// instruction with the specified blocksize. (The order of the elements
5083 /// within each block of the vector is reversed.)
5084 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5085 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
5086 "Only possible block sizes for REV are: 16, 32, 64");
5088 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5092 unsigned NumElts = VT.getVectorNumElements();
5093 unsigned BlockElts = M[0] + 1;
5094 // If the first shuffle index is UNDEF, be optimistic.
5096 BlockElts = BlockSize / EltSz;
5098 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5101 for (unsigned i = 0; i < NumElts; ++i) {
5103 continue; // ignore UNDEF indices
5104 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
5111 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5112 unsigned NumElts = VT.getVectorNumElements();
5113 WhichResult = (M[0] == 0 ? 0 : 1);
5114 unsigned Idx = WhichResult * NumElts / 2;
5115 for (unsigned i = 0; i != NumElts; i += 2) {
5116 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5117 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
5125 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5126 unsigned NumElts = VT.getVectorNumElements();
5127 WhichResult = (M[0] == 0 ? 0 : 1);
5128 for (unsigned i = 0; i != NumElts; ++i) {
5130 continue; // ignore UNDEF indices
5131 if ((unsigned)M[i] != 2 * i + WhichResult)
5138 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5139 unsigned NumElts = VT.getVectorNumElements();
5140 WhichResult = (M[0] == 0 ? 0 : 1);
5141 for (unsigned i = 0; i < NumElts; i += 2) {
5142 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5143 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
5149 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
5150 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5151 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5152 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5153 unsigned NumElts = VT.getVectorNumElements();
5154 WhichResult = (M[0] == 0 ? 0 : 1);
5155 unsigned Idx = WhichResult * NumElts / 2;
5156 for (unsigned i = 0; i != NumElts; i += 2) {
5157 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5158 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
5166 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
5167 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5168 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5169 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5170 unsigned Half = VT.getVectorNumElements() / 2;
5171 WhichResult = (M[0] == 0 ? 0 : 1);
5172 for (unsigned j = 0; j != 2; ++j) {
5173 unsigned Idx = WhichResult;
5174 for (unsigned i = 0; i != Half; ++i) {
5175 int MIdx = M[i + j * Half];
5176 if (MIdx >= 0 && (unsigned)MIdx != Idx)
5185 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
5186 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5187 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5188 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5189 unsigned NumElts = VT.getVectorNumElements();
5190 WhichResult = (M[0] == 0 ? 0 : 1);
5191 for (unsigned i = 0; i < NumElts; i += 2) {
5192 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5193 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
5199 static bool isINSMask(ArrayRef<int> M, int NumInputElements,
5200 bool &DstIsLeft, int &Anomaly) {
5201 if (M.size() != static_cast<size_t>(NumInputElements))
5204 int NumLHSMatch = 0, NumRHSMatch = 0;
5205 int LastLHSMismatch = -1, LastRHSMismatch = -1;
5207 for (int i = 0; i < NumInputElements; ++i) {
5217 LastLHSMismatch = i;
5219 if (M[i] == i + NumInputElements)
5222 LastRHSMismatch = i;
5225 if (NumLHSMatch == NumInputElements - 1) {
5227 Anomaly = LastLHSMismatch;
5229 } else if (NumRHSMatch == NumInputElements - 1) {
5231 Anomaly = LastRHSMismatch;
5238 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
5239 if (VT.getSizeInBits() != 128)
5242 unsigned NumElts = VT.getVectorNumElements();
5244 for (int I = 0, E = NumElts / 2; I != E; I++) {
5249 int Offset = NumElts / 2;
5250 for (int I = NumElts / 2, E = NumElts; I != E; I++) {
5251 if (Mask[I] != I + SplitLHS * Offset)
5258 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
5260 EVT VT = Op.getValueType();
5261 SDValue V0 = Op.getOperand(0);
5262 SDValue V1 = Op.getOperand(1);
5263 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
5265 if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
5266 VT.getVectorElementType() != V1.getValueType().getVectorElementType())
5269 bool SplitV0 = V0.getValueType().getSizeInBits() == 128;
5271 if (!isConcatMask(Mask, VT, SplitV0))
5274 EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
5275 VT.getVectorNumElements() / 2);
5277 V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
5278 DAG.getConstant(0, DL, MVT::i64));
5280 if (V1.getValueType().getSizeInBits() == 128) {
5281 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
5282 DAG.getConstant(0, DL, MVT::i64));
5284 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
5287 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5288 /// the specified operations to build the shuffle.
5289 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5290 SDValue RHS, SelectionDAG &DAG,
5292 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5293 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
5294 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
5297 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5306 OP_VUZPL, // VUZP, left result
5307 OP_VUZPR, // VUZP, right result
5308 OP_VZIPL, // VZIP, left result
5309 OP_VZIPR, // VZIP, right result
5310 OP_VTRNL, // VTRN, left result
5311 OP_VTRNR // VTRN, right result
5314 if (OpNum == OP_COPY) {
5315 if (LHSID == (1 * 9 + 2) * 9 + 3)
5317 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
5321 SDValue OpLHS, OpRHS;
5322 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5323 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5324 EVT VT = OpLHS.getValueType();
5328 llvm_unreachable("Unknown shuffle opcode!");
5330 // VREV divides the vector in half and swaps within the half.
5331 if (VT.getVectorElementType() == MVT::i32 ||
5332 VT.getVectorElementType() == MVT::f32)
5333 return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
5334 // vrev <4 x i16> -> REV32
5335 if (VT.getVectorElementType() == MVT::i16 ||
5336 VT.getVectorElementType() == MVT::f16)
5337 return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
5338 // vrev <4 x i8> -> REV16
5339 assert(VT.getVectorElementType() == MVT::i8);
5340 return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
5345 EVT EltTy = VT.getVectorElementType();
5347 if (EltTy == MVT::i8)
5348 Opcode = AArch64ISD::DUPLANE8;
5349 else if (EltTy == MVT::i16 || EltTy == MVT::f16)
5350 Opcode = AArch64ISD::DUPLANE16;
5351 else if (EltTy == MVT::i32 || EltTy == MVT::f32)
5352 Opcode = AArch64ISD::DUPLANE32;
5353 else if (EltTy == MVT::i64 || EltTy == MVT::f64)
5354 Opcode = AArch64ISD::DUPLANE64;
5356 llvm_unreachable("Invalid vector element type?");
5358 if (VT.getSizeInBits() == 64)
5359 OpLHS = WidenVector(OpLHS, DAG);
5360 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
5361 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
5366 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
5367 return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
5368 DAG.getConstant(Imm, dl, MVT::i32));
5371 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
5374 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
5377 return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
5380 return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
5383 return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
5386 return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
5391 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
5392 SelectionDAG &DAG) {
5393 // Check to see if we can use the TBL instruction.
5394 SDValue V1 = Op.getOperand(0);
5395 SDValue V2 = Op.getOperand(1);
5398 EVT EltVT = Op.getValueType().getVectorElementType();
5399 unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
5401 SmallVector<SDValue, 8> TBLMask;
5402 for (int Val : ShuffleMask) {
5403 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
5404 unsigned Offset = Byte + Val * BytesPerElt;
5405 TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
5409 MVT IndexVT = MVT::v8i8;
5410 unsigned IndexLen = 8;
5411 if (Op.getValueType().getSizeInBits() == 128) {
5412 IndexVT = MVT::v16i8;
5416 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
5417 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
5420 if (V2.getNode()->getOpcode() == ISD::UNDEF) {
5422 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
5423 Shuffle = DAG.getNode(
5424 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5425 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
5426 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5427 makeArrayRef(TBLMask.data(), IndexLen)));
5429 if (IndexLen == 8) {
5430 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
5431 Shuffle = DAG.getNode(
5432 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5433 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
5434 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5435 makeArrayRef(TBLMask.data(), IndexLen)));
5437 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
5438 // cannot currently represent the register constraints on the input
5440 // Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
5441 // DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5442 // &TBLMask[0], IndexLen));
5443 Shuffle = DAG.getNode(
5444 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5445 DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32),
5447 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5448 makeArrayRef(TBLMask.data(), IndexLen)));
5451 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
5454 static unsigned getDUPLANEOp(EVT EltType) {
5455 if (EltType == MVT::i8)
5456 return AArch64ISD::DUPLANE8;
5457 if (EltType == MVT::i16 || EltType == MVT::f16)
5458 return AArch64ISD::DUPLANE16;
5459 if (EltType == MVT::i32 || EltType == MVT::f32)
5460 return AArch64ISD::DUPLANE32;
5461 if (EltType == MVT::i64 || EltType == MVT::f64)
5462 return AArch64ISD::DUPLANE64;
5464 llvm_unreachable("Invalid vector element type?");
5467 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5468 SelectionDAG &DAG) const {
5470 EVT VT = Op.getValueType();
5472 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5474 // Convert shuffles that are directly supported on NEON to target-specific
5475 // DAG nodes, instead of keeping them as shuffles and matching them again
5476 // during code selection. This is more efficient and avoids the possibility
5477 // of inconsistencies between legalization and selection.
5478 ArrayRef<int> ShuffleMask = SVN->getMask();
5480 SDValue V1 = Op.getOperand(0);
5481 SDValue V2 = Op.getOperand(1);
5483 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0],
5484 V1.getValueType().getSimpleVT())) {
5485 int Lane = SVN->getSplatIndex();
5486 // If this is undef splat, generate it via "just" vdup, if possible.
5490 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
5491 return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
5493 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
5494 // constant. If so, we can just reference the lane's definition directly.
5495 if (V1.getOpcode() == ISD::BUILD_VECTOR &&
5496 !isa<ConstantSDNode>(V1.getOperand(Lane)))
5497 return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
5499 // Otherwise, duplicate from the lane of the input vector.
5500 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
5502 // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
5503 // to make a vector of the same size as this SHUFFLE. We can ignore the
5504 // extract entirely, and canonicalise the concat using WidenVector.
5505 if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
5506 Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
5507 V1 = V1.getOperand(0);
5508 } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
5509 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
5510 Lane -= Idx * VT.getVectorNumElements() / 2;
5511 V1 = WidenVector(V1.getOperand(Idx), DAG);
5512 } else if (VT.getSizeInBits() == 64)
5513 V1 = WidenVector(V1, DAG);
5515 return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
5518 if (isREVMask(ShuffleMask, VT, 64))
5519 return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
5520 if (isREVMask(ShuffleMask, VT, 32))
5521 return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
5522 if (isREVMask(ShuffleMask, VT, 16))
5523 return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
5525 bool ReverseEXT = false;
5527 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
5530 Imm *= getExtFactor(V1);
5531 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
5532 DAG.getConstant(Imm, dl, MVT::i32));
5533 } else if (V2->getOpcode() == ISD::UNDEF &&
5534 isSingletonEXTMask(ShuffleMask, VT, Imm)) {
5535 Imm *= getExtFactor(V1);
5536 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
5537 DAG.getConstant(Imm, dl, MVT::i32));
5540 unsigned WhichResult;
5541 if (isZIPMask(ShuffleMask, VT, WhichResult)) {
5542 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5543 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5545 if (isUZPMask(ShuffleMask, VT, WhichResult)) {
5546 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5547 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5549 if (isTRNMask(ShuffleMask, VT, WhichResult)) {
5550 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5551 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5554 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5555 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5556 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5558 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5559 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5560 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5562 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5563 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5564 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5567 SDValue Concat = tryFormConcatFromShuffle(Op, DAG);
5568 if (Concat.getNode())
5573 int NumInputElements = V1.getValueType().getVectorNumElements();
5574 if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
5575 SDValue DstVec = DstIsLeft ? V1 : V2;
5576 SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
5578 SDValue SrcVec = V1;
5579 int SrcLane = ShuffleMask[Anomaly];
5580 if (SrcLane >= NumInputElements) {
5582 SrcLane -= VT.getVectorNumElements();
5584 SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
5586 EVT ScalarVT = VT.getVectorElementType();
5588 if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
5589 ScalarVT = MVT::i32;
5592 ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5593 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
5597 // If the shuffle is not directly supported and it has 4 elements, use
5598 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5599 unsigned NumElts = VT.getVectorNumElements();
5601 unsigned PFIndexes[4];
5602 for (unsigned i = 0; i != 4; ++i) {
5603 if (ShuffleMask[i] < 0)
5606 PFIndexes[i] = ShuffleMask[i];
5609 // Compute the index in the perfect shuffle table.
5610 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
5611 PFIndexes[2] * 9 + PFIndexes[3];
5612 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5613 unsigned Cost = (PFEntry >> 30);
5616 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5619 return GenerateTBL(Op, ShuffleMask, DAG);
5622 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
5624 EVT VT = BVN->getValueType(0);
5625 APInt SplatBits, SplatUndef;
5626 unsigned SplatBitSize;
5628 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5629 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
5631 for (unsigned i = 0; i < NumSplats; ++i) {
5632 CnstBits <<= SplatBitSize;
5633 UndefBits <<= SplatBitSize;
5634 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
5635 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
5644 SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op,
5645 SelectionDAG &DAG) const {
5646 BuildVectorSDNode *BVN =
5647 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5648 SDValue LHS = Op.getOperand(0);
5650 EVT VT = Op.getValueType();
5655 APInt CnstBits(VT.getSizeInBits(), 0);
5656 APInt UndefBits(VT.getSizeInBits(), 0);
5657 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5658 // We only have BIC vector immediate instruction, which is and-not.
5659 CnstBits = ~CnstBits;
5661 // We make use of a little bit of goto ickiness in order to avoid having to
5662 // duplicate the immediate matching logic for the undef toggled case.
5663 bool SecondTry = false;
5666 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5667 CnstBits = CnstBits.zextOrTrunc(64);
5668 uint64_t CnstVal = CnstBits.getZExtValue();
5670 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5671 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5672 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5673 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5674 DAG.getConstant(CnstVal, dl, MVT::i32),
5675 DAG.getConstant(0, dl, MVT::i32));
5676 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5679 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5680 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5681 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5682 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5683 DAG.getConstant(CnstVal, dl, MVT::i32),
5684 DAG.getConstant(8, dl, MVT::i32));
5685 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5688 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5689 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5690 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5691 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5692 DAG.getConstant(CnstVal, dl, MVT::i32),
5693 DAG.getConstant(16, dl, MVT::i32));
5694 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5697 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5698 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5699 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5700 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5701 DAG.getConstant(CnstVal, dl, MVT::i32),
5702 DAG.getConstant(24, dl, MVT::i32));
5703 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5706 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5707 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5708 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5709 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5710 DAG.getConstant(CnstVal, dl, MVT::i32),
5711 DAG.getConstant(0, dl, MVT::i32));
5712 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5715 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5716 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5717 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5718 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
5719 DAG.getConstant(CnstVal, dl, MVT::i32),
5720 DAG.getConstant(8, dl, MVT::i32));
5721 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5728 CnstBits = ~UndefBits;
5732 // We can always fall back to a non-immediate AND.
5737 // Specialized code to quickly find if PotentialBVec is a BuildVector that
5738 // consists of only the same constant int value, returned in reference arg
5740 static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
5741 uint64_t &ConstVal) {
5742 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
5745 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
5748 EVT VT = Bvec->getValueType(0);
5749 unsigned NumElts = VT.getVectorNumElements();
5750 for (unsigned i = 1; i < NumElts; ++i)
5751 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
5753 ConstVal = FirstElt->getZExtValue();
5757 static unsigned getIntrinsicID(const SDNode *N) {
5758 unsigned Opcode = N->getOpcode();
5761 return Intrinsic::not_intrinsic;
5762 case ISD::INTRINSIC_WO_CHAIN: {
5763 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
5764 if (IID < Intrinsic::num_intrinsics)
5766 return Intrinsic::not_intrinsic;
5771 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
5772 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
5773 // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
5774 // Also, logical shift right -> sri, with the same structure.
5775 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
5776 EVT VT = N->getValueType(0);
5783 // Is the first op an AND?
5784 const SDValue And = N->getOperand(0);
5785 if (And.getOpcode() != ISD::AND)
5788 // Is the second op an shl or lshr?
5789 SDValue Shift = N->getOperand(1);
5790 // This will have been turned into: AArch64ISD::VSHL vector, #shift
5791 // or AArch64ISD::VLSHR vector, #shift
5792 unsigned ShiftOpc = Shift.getOpcode();
5793 if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
5795 bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
5797 // Is the shift amount constant?
5798 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
5802 // Is the and mask vector all constant?
5804 if (!isAllConstantBuildVector(And.getOperand(1), C1))
5807 // Is C1 == ~C2, taking into account how much one can shift elements of a
5809 uint64_t C2 = C2node->getZExtValue();
5810 unsigned ElemSizeInBits = VT.getVectorElementType().getSizeInBits();
5811 if (C2 > ElemSizeInBits)
5813 unsigned ElemMask = (1 << ElemSizeInBits) - 1;
5814 if ((C1 & ElemMask) != (~C2 & ElemMask))
5817 SDValue X = And.getOperand(0);
5818 SDValue Y = Shift.getOperand(0);
5821 IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
5823 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
5824 DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
5825 Shift.getOperand(1));
5827 DEBUG(dbgs() << "aarch64-lower: transformed: \n");
5828 DEBUG(N->dump(&DAG));
5829 DEBUG(dbgs() << "into: \n");
5830 DEBUG(ResultSLI->dump(&DAG));
5836 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
5837 SelectionDAG &DAG) const {
5838 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
5839 if (EnableAArch64SlrGeneration) {
5840 SDValue Res = tryLowerToSLI(Op.getNode(), DAG);
5845 BuildVectorSDNode *BVN =
5846 dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
5847 SDValue LHS = Op.getOperand(1);
5849 EVT VT = Op.getValueType();
5851 // OR commutes, so try swapping the operands.
5853 LHS = Op.getOperand(0);
5854 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5859 APInt CnstBits(VT.getSizeInBits(), 0);
5860 APInt UndefBits(VT.getSizeInBits(), 0);
5861 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5862 // We make use of a little bit of goto ickiness in order to avoid having to
5863 // duplicate the immediate matching logic for the undef toggled case.
5864 bool SecondTry = false;
5867 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5868 CnstBits = CnstBits.zextOrTrunc(64);
5869 uint64_t CnstVal = CnstBits.getZExtValue();
5871 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5872 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5873 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5874 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5875 DAG.getConstant(CnstVal, dl, MVT::i32),
5876 DAG.getConstant(0, dl, MVT::i32));
5877 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5880 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5881 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5882 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5883 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5884 DAG.getConstant(CnstVal, dl, MVT::i32),
5885 DAG.getConstant(8, dl, MVT::i32));
5886 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5889 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5890 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5891 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5892 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5893 DAG.getConstant(CnstVal, dl, MVT::i32),
5894 DAG.getConstant(16, dl, MVT::i32));
5895 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5898 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5899 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5900 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5901 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5902 DAG.getConstant(CnstVal, dl, MVT::i32),
5903 DAG.getConstant(24, dl, MVT::i32));
5904 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5907 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5908 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5909 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5910 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5911 DAG.getConstant(CnstVal, dl, MVT::i32),
5912 DAG.getConstant(0, dl, MVT::i32));
5913 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5916 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5917 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5918 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5919 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
5920 DAG.getConstant(CnstVal, dl, MVT::i32),
5921 DAG.getConstant(8, dl, MVT::i32));
5922 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5929 CnstBits = UndefBits;
5933 // We can always fall back to a non-immediate OR.
5938 // Normalize the operands of BUILD_VECTOR. The value of constant operands will
5939 // be truncated to fit element width.
5940 static SDValue NormalizeBuildVector(SDValue Op,
5941 SelectionDAG &DAG) {
5942 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
5944 EVT VT = Op.getValueType();
5945 EVT EltTy= VT.getVectorElementType();
5947 if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
5950 SmallVector<SDValue, 16> Ops;
5951 for (SDValue Lane : Op->ops()) {
5952 if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
5953 APInt LowBits(EltTy.getSizeInBits(),
5954 CstLane->getZExtValue());
5955 Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
5957 Ops.push_back(Lane);
5959 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5962 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
5963 SelectionDAG &DAG) const {
5965 EVT VT = Op.getValueType();
5966 Op = NormalizeBuildVector(Op, DAG);
5967 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
5969 APInt CnstBits(VT.getSizeInBits(), 0);
5970 APInt UndefBits(VT.getSizeInBits(), 0);
5971 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5972 // We make use of a little bit of goto ickiness in order to avoid having to
5973 // duplicate the immediate matching logic for the undef toggled case.
5974 bool SecondTry = false;
5977 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5978 CnstBits = CnstBits.zextOrTrunc(64);
5979 uint64_t CnstVal = CnstBits.getZExtValue();
5981 // Certain magic vector constants (used to express things like NOT
5982 // and NEG) are passed through unmodified. This allows codegen patterns
5983 // for these operations to match. Special-purpose patterns will lower
5984 // these immediates to MOVIs if it proves necessary.
5985 if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL))
5988 // The many faces of MOVI...
5989 if (AArch64_AM::isAdvSIMDModImmType10(CnstVal)) {
5990 CnstVal = AArch64_AM::encodeAdvSIMDModImmType10(CnstVal);
5991 if (VT.getSizeInBits() == 128) {
5992 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::v2i64,
5993 DAG.getConstant(CnstVal, dl, MVT::i32));
5994 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
5997 // Support the V64 version via subregister insertion.
5998 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::f64,
5999 DAG.getConstant(CnstVal, dl, MVT::i32));
6000 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6003 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6004 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6005 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6006 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6007 DAG.getConstant(CnstVal, dl, MVT::i32),
6008 DAG.getConstant(0, dl, MVT::i32));
6009 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6012 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6013 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6014 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6015 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6016 DAG.getConstant(CnstVal, dl, MVT::i32),
6017 DAG.getConstant(8, dl, MVT::i32));
6018 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6021 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6022 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6023 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6024 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6025 DAG.getConstant(CnstVal, dl, MVT::i32),
6026 DAG.getConstant(16, dl, MVT::i32));
6027 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6030 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6031 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6032 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6033 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6034 DAG.getConstant(CnstVal, dl, MVT::i32),
6035 DAG.getConstant(24, dl, MVT::i32));
6036 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6039 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6040 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6041 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6042 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6043 DAG.getConstant(CnstVal, dl, MVT::i32),
6044 DAG.getConstant(0, dl, MVT::i32));
6045 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6048 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6049 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6050 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6051 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6052 DAG.getConstant(CnstVal, dl, MVT::i32),
6053 DAG.getConstant(8, dl, MVT::i32));
6054 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6057 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6058 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6059 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6060 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
6061 DAG.getConstant(CnstVal, dl, MVT::i32),
6062 DAG.getConstant(264, dl, MVT::i32));
6063 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6066 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6067 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6068 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6069 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
6070 DAG.getConstant(CnstVal, dl, MVT::i32),
6071 DAG.getConstant(272, dl, MVT::i32));
6072 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6075 if (AArch64_AM::isAdvSIMDModImmType9(CnstVal)) {
6076 CnstVal = AArch64_AM::encodeAdvSIMDModImmType9(CnstVal);
6077 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
6078 SDValue Mov = DAG.getNode(AArch64ISD::MOVI, dl, MovTy,
6079 DAG.getConstant(CnstVal, dl, MVT::i32));
6080 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6083 // The few faces of FMOV...
6084 if (AArch64_AM::isAdvSIMDModImmType11(CnstVal)) {
6085 CnstVal = AArch64_AM::encodeAdvSIMDModImmType11(CnstVal);
6086 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32;
6087 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MovTy,
6088 DAG.getConstant(CnstVal, dl, MVT::i32));
6089 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6092 if (AArch64_AM::isAdvSIMDModImmType12(CnstVal) &&
6093 VT.getSizeInBits() == 128) {
6094 CnstVal = AArch64_AM::encodeAdvSIMDModImmType12(CnstVal);
6095 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MVT::v2f64,
6096 DAG.getConstant(CnstVal, dl, MVT::i32));
6097 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6100 // The many faces of MVNI...
6102 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6103 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6104 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6105 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6106 DAG.getConstant(CnstVal, dl, MVT::i32),
6107 DAG.getConstant(0, dl, MVT::i32));
6108 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6111 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6112 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6113 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6114 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6115 DAG.getConstant(CnstVal, dl, MVT::i32),
6116 DAG.getConstant(8, dl, MVT::i32));
6117 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6120 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6121 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6122 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6123 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6124 DAG.getConstant(CnstVal, dl, MVT::i32),
6125 DAG.getConstant(16, dl, MVT::i32));
6126 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6129 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6130 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6131 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6132 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6133 DAG.getConstant(CnstVal, dl, MVT::i32),
6134 DAG.getConstant(24, dl, MVT::i32));
6135 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6138 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6139 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6140 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6141 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6142 DAG.getConstant(CnstVal, dl, MVT::i32),
6143 DAG.getConstant(0, dl, MVT::i32));
6144 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6147 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6148 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6149 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6150 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6151 DAG.getConstant(CnstVal, dl, MVT::i32),
6152 DAG.getConstant(8, dl, MVT::i32));
6153 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6156 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6157 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6158 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6159 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
6160 DAG.getConstant(CnstVal, dl, MVT::i32),
6161 DAG.getConstant(264, dl, MVT::i32));
6162 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6165 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6166 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6167 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6168 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
6169 DAG.getConstant(CnstVal, dl, MVT::i32),
6170 DAG.getConstant(272, dl, MVT::i32));
6171 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6178 CnstBits = UndefBits;
6183 // Scan through the operands to find some interesting properties we can
6185 // 1) If only one value is used, we can use a DUP, or
6186 // 2) if only the low element is not undef, we can just insert that, or
6187 // 3) if only one constant value is used (w/ some non-constant lanes),
6188 // we can splat the constant value into the whole vector then fill
6189 // in the non-constant lanes.
6190 // 4) FIXME: If different constant values are used, but we can intelligently
6191 // select the values we'll be overwriting for the non-constant
6192 // lanes such that we can directly materialize the vector
6193 // some other way (MOVI, e.g.), we can be sneaky.
6194 unsigned NumElts = VT.getVectorNumElements();
6195 bool isOnlyLowElement = true;
6196 bool usesOnlyOneValue = true;
6197 bool usesOnlyOneConstantValue = true;
6198 bool isConstant = true;
6199 unsigned NumConstantLanes = 0;
6201 SDValue ConstantValue;
6202 for (unsigned i = 0; i < NumElts; ++i) {
6203 SDValue V = Op.getOperand(i);
6204 if (V.getOpcode() == ISD::UNDEF)
6207 isOnlyLowElement = false;
6208 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6211 if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
6213 if (!ConstantValue.getNode())
6215 else if (ConstantValue != V)
6216 usesOnlyOneConstantValue = false;
6219 if (!Value.getNode())
6221 else if (V != Value)
6222 usesOnlyOneValue = false;
6225 if (!Value.getNode())
6226 return DAG.getUNDEF(VT);
6228 if (isOnlyLowElement)
6229 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
6231 // Use DUP for non-constant splats. For f32 constant splats, reduce to
6232 // i32 and try again.
6233 if (usesOnlyOneValue) {
6235 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6236 Value.getValueType() != VT)
6237 return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
6239 // This is actually a DUPLANExx operation, which keeps everything vectory.
6241 // DUPLANE works on 128-bit vectors, widen it if necessary.
6242 SDValue Lane = Value.getOperand(1);
6243 Value = Value.getOperand(0);
6244 if (Value.getValueType().getSizeInBits() == 64)
6245 Value = WidenVector(Value, DAG);
6247 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
6248 return DAG.getNode(Opcode, dl, VT, Value, Lane);
6251 if (VT.getVectorElementType().isFloatingPoint()) {
6252 SmallVector<SDValue, 8> Ops;
6253 EVT EltTy = VT.getVectorElementType();
6254 assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
6255 "Unsupported floating-point vector type");
6256 MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
6257 for (unsigned i = 0; i < NumElts; ++i)
6258 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
6259 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
6260 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
6261 Val = LowerBUILD_VECTOR(Val, DAG);
6263 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6267 // If there was only one constant value used and for more than one lane,
6268 // start by splatting that value, then replace the non-constant lanes. This
6269 // is better than the default, which will perform a separate initialization
6271 if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
6272 SDValue Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
6273 // Now insert the non-constant lanes.
6274 for (unsigned i = 0; i < NumElts; ++i) {
6275 SDValue V = Op.getOperand(i);
6276 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
6277 if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) {
6278 // Note that type legalization likely mucked about with the VT of the
6279 // source operand, so we may have to convert it here before inserting.
6280 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
6286 // If all elements are constants and the case above didn't get hit, fall back
6287 // to the default expansion, which will generate a load from the constant
6292 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6294 if (SDValue shuffle = ReconstructShuffle(Op, DAG))
6298 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6299 // know the default expansion would otherwise fall back on something even
6300 // worse. For a vector with one or two non-undef values, that's
6301 // scalar_to_vector for the elements followed by a shuffle (provided the
6302 // shuffle is valid for the target) and materialization element by element
6303 // on the stack followed by a load for everything else.
6304 if (!isConstant && !usesOnlyOneValue) {
6305 SDValue Vec = DAG.getUNDEF(VT);
6306 SDValue Op0 = Op.getOperand(0);
6307 unsigned ElemSize = VT.getVectorElementType().getSizeInBits();
6309 // For 32 and 64 bit types, use INSERT_SUBREG for lane zero to
6310 // a) Avoid a RMW dependency on the full vector register, and
6311 // b) Allow the register coalescer to fold away the copy if the
6312 // value is already in an S or D register.
6313 // Do not do this for UNDEF/LOAD nodes because we have better patterns
6314 // for those avoiding the SCALAR_TO_VECTOR/BUILD_VECTOR.
6315 if (Op0.getOpcode() != ISD::UNDEF && Op0.getOpcode() != ISD::LOAD &&
6316 (ElemSize == 32 || ElemSize == 64)) {
6317 unsigned SubIdx = ElemSize == 32 ? AArch64::ssub : AArch64::dsub;
6319 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl, VT, Vec, Op0,
6320 DAG.getTargetConstant(SubIdx, dl, MVT::i32));
6321 Vec = SDValue(N, 0);
6324 for (; i < NumElts; ++i) {
6325 SDValue V = Op.getOperand(i);
6326 if (V.getOpcode() == ISD::UNDEF)
6328 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
6329 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6334 // Just use the default expansion. We failed to find a better alternative.
6338 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
6339 SelectionDAG &DAG) const {
6340 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
6342 // Check for non-constant or out of range lane.
6343 EVT VT = Op.getOperand(0).getValueType();
6344 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
6345 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
6349 // Insertion/extraction are legal for V128 types.
6350 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
6351 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6355 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
6356 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
6359 // For V64 types, we perform insertion by expanding the value
6360 // to a V128 type and perform the insertion on that.
6362 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6363 EVT WideTy = WideVec.getValueType();
6365 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
6366 Op.getOperand(1), Op.getOperand(2));
6367 // Re-narrow the resultant vector.
6368 return NarrowVector(Node, DAG);
6372 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6373 SelectionDAG &DAG) const {
6374 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
6376 // Check for non-constant or out of range lane.
6377 EVT VT = Op.getOperand(0).getValueType();
6378 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6379 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
6383 // Insertion/extraction are legal for V128 types.
6384 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
6385 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6389 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
6390 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
6393 // For V64 types, we perform extraction by expanding the value
6394 // to a V128 type and perform the extraction on that.
6396 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6397 EVT WideTy = WideVec.getValueType();
6399 EVT ExtrTy = WideTy.getVectorElementType();
6400 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
6403 // For extractions, we just return the result directly.
6404 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
6408 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
6409 SelectionDAG &DAG) const {
6410 EVT VT = Op.getOperand(0).getValueType();
6416 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6419 unsigned Val = Cst->getZExtValue();
6421 unsigned Size = Op.getValueType().getSizeInBits();
6423 // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
6427 // If this is extracting the upper 64-bits of a 128-bit vector, we match
6429 if (Size == 64 && Val * VT.getVectorElementType().getSizeInBits() == 64)
6435 bool AArch64TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
6437 if (VT.getVectorNumElements() == 4 &&
6438 (VT.is128BitVector() || VT.is64BitVector())) {
6439 unsigned PFIndexes[4];
6440 for (unsigned i = 0; i != 4; ++i) {
6444 PFIndexes[i] = M[i];
6447 // Compute the index in the perfect shuffle table.
6448 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6449 PFIndexes[2] * 9 + PFIndexes[3];
6450 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6451 unsigned Cost = (PFEntry >> 30);
6459 unsigned DummyUnsigned;
6461 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
6462 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
6463 isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
6464 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
6465 isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
6466 isZIPMask(M, VT, DummyUnsigned) ||
6467 isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
6468 isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
6469 isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
6470 isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
6471 isConcatMask(M, VT, VT.getSizeInBits() == 128));
6474 /// getVShiftImm - Check if this is a valid build_vector for the immediate
6475 /// operand of a vector shift operation, where all the elements of the
6476 /// build_vector must have the same constant integer value.
6477 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
6478 // Ignore bit_converts.
6479 while (Op.getOpcode() == ISD::BITCAST)
6480 Op = Op.getOperand(0);
6481 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6482 APInt SplatBits, SplatUndef;
6483 unsigned SplatBitSize;
6485 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
6486 HasAnyUndefs, ElementBits) ||
6487 SplatBitSize > ElementBits)
6489 Cnt = SplatBits.getSExtValue();
6493 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
6494 /// operand of a vector shift left operation. That value must be in the range:
6495 /// 0 <= Value < ElementBits for a left shift; or
6496 /// 0 <= Value <= ElementBits for a long left shift.
6497 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
6498 assert(VT.isVector() && "vector shift count is not a vector type");
6499 int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
6500 if (!getVShiftImm(Op, ElementBits, Cnt))
6502 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
6505 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
6506 /// operand of a vector shift right operation. The value must be in the range:
6507 /// 1 <= Value <= ElementBits for a right shift; or
6508 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
6509 assert(VT.isVector() && "vector shift count is not a vector type");
6510 int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
6511 if (!getVShiftImm(Op, ElementBits, Cnt))
6513 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
6516 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
6517 SelectionDAG &DAG) const {
6518 EVT VT = Op.getValueType();
6522 if (!Op.getOperand(1).getValueType().isVector())
6524 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6526 switch (Op.getOpcode()) {
6528 llvm_unreachable("unexpected shift opcode");
6531 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
6532 return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
6533 DAG.getConstant(Cnt, DL, MVT::i32));
6534 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
6535 DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
6537 Op.getOperand(0), Op.getOperand(1));
6540 // Right shift immediate
6541 if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
6543 (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
6544 return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
6545 DAG.getConstant(Cnt, DL, MVT::i32));
6548 // Right shift register. Note, there is not a shift right register
6549 // instruction, but the shift left register instruction takes a signed
6550 // value, where negative numbers specify a right shift.
6551 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
6552 : Intrinsic::aarch64_neon_ushl;
6553 // negate the shift amount
6554 SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
6555 SDValue NegShiftLeft =
6556 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
6557 DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
6559 return NegShiftLeft;
6565 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
6566 AArch64CC::CondCode CC, bool NoNans, EVT VT,
6567 SDLoc dl, SelectionDAG &DAG) {
6568 EVT SrcVT = LHS.getValueType();
6569 assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
6570 "function only supposed to emit natural comparisons");
6572 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
6573 APInt CnstBits(VT.getSizeInBits(), 0);
6574 APInt UndefBits(VT.getSizeInBits(), 0);
6575 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
6576 bool IsZero = IsCnst && (CnstBits == 0);
6578 if (SrcVT.getVectorElementType().isFloatingPoint()) {
6582 case AArch64CC::NE: {
6585 Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6587 Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6588 return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
6592 return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6593 return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6596 return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
6597 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
6600 return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
6601 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
6604 return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
6605 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
6609 // If we ignore NaNs then we can use to the MI implementation.
6613 return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
6614 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
6621 case AArch64CC::NE: {
6624 Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6626 Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6627 return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
6631 return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6632 return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6635 return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
6636 return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
6639 return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
6640 return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
6643 return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
6644 return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
6646 return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
6648 return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
6651 return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
6652 return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
6654 return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
6656 return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
6660 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
6661 SelectionDAG &DAG) const {
6662 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6663 SDValue LHS = Op.getOperand(0);
6664 SDValue RHS = Op.getOperand(1);
6665 EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
6668 if (LHS.getValueType().getVectorElementType().isInteger()) {
6669 assert(LHS.getValueType() == RHS.getValueType());
6670 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
6672 EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
6673 return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
6676 assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
6677 LHS.getValueType().getVectorElementType() == MVT::f64);
6679 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
6680 // clean. Some of them require two branches to implement.
6681 AArch64CC::CondCode CC1, CC2;
6683 changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
6685 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
6687 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
6691 if (CC2 != AArch64CC::AL) {
6693 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
6694 if (!Cmp2.getNode())
6697 Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
6700 Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
6703 return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
6708 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
6709 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
6710 /// specified in the intrinsic calls.
6711 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
6713 unsigned Intrinsic) const {
6714 auto &DL = I.getModule()->getDataLayout();
6715 switch (Intrinsic) {
6716 case Intrinsic::aarch64_neon_ld2:
6717 case Intrinsic::aarch64_neon_ld3:
6718 case Intrinsic::aarch64_neon_ld4:
6719 case Intrinsic::aarch64_neon_ld1x2:
6720 case Intrinsic::aarch64_neon_ld1x3:
6721 case Intrinsic::aarch64_neon_ld1x4:
6722 case Intrinsic::aarch64_neon_ld2lane:
6723 case Intrinsic::aarch64_neon_ld3lane:
6724 case Intrinsic::aarch64_neon_ld4lane:
6725 case Intrinsic::aarch64_neon_ld2r:
6726 case Intrinsic::aarch64_neon_ld3r:
6727 case Intrinsic::aarch64_neon_ld4r: {
6728 Info.opc = ISD::INTRINSIC_W_CHAIN;
6729 // Conservatively set memVT to the entire set of vectors loaded.
6730 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
6731 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6732 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6735 Info.vol = false; // volatile loads with NEON intrinsics not supported
6736 Info.readMem = true;
6737 Info.writeMem = false;
6740 case Intrinsic::aarch64_neon_st2:
6741 case Intrinsic::aarch64_neon_st3:
6742 case Intrinsic::aarch64_neon_st4:
6743 case Intrinsic::aarch64_neon_st1x2:
6744 case Intrinsic::aarch64_neon_st1x3:
6745 case Intrinsic::aarch64_neon_st1x4:
6746 case Intrinsic::aarch64_neon_st2lane:
6747 case Intrinsic::aarch64_neon_st3lane:
6748 case Intrinsic::aarch64_neon_st4lane: {
6749 Info.opc = ISD::INTRINSIC_VOID;
6750 // Conservatively set memVT to the entire set of vectors stored.
6751 unsigned NumElts = 0;
6752 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
6753 Type *ArgTy = I.getArgOperand(ArgI)->getType();
6754 if (!ArgTy->isVectorTy())
6756 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
6758 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6759 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6762 Info.vol = false; // volatile stores with NEON intrinsics not supported
6763 Info.readMem = false;
6764 Info.writeMem = true;
6767 case Intrinsic::aarch64_ldaxr:
6768 case Intrinsic::aarch64_ldxr: {
6769 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
6770 Info.opc = ISD::INTRINSIC_W_CHAIN;
6771 Info.memVT = MVT::getVT(PtrTy->getElementType());
6772 Info.ptrVal = I.getArgOperand(0);
6774 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
6776 Info.readMem = true;
6777 Info.writeMem = false;
6780 case Intrinsic::aarch64_stlxr:
6781 case Intrinsic::aarch64_stxr: {
6782 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
6783 Info.opc = ISD::INTRINSIC_W_CHAIN;
6784 Info.memVT = MVT::getVT(PtrTy->getElementType());
6785 Info.ptrVal = I.getArgOperand(1);
6787 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
6789 Info.readMem = false;
6790 Info.writeMem = true;
6793 case Intrinsic::aarch64_ldaxp:
6794 case Intrinsic::aarch64_ldxp: {
6795 Info.opc = ISD::INTRINSIC_W_CHAIN;
6796 Info.memVT = MVT::i128;
6797 Info.ptrVal = I.getArgOperand(0);
6801 Info.readMem = true;
6802 Info.writeMem = false;
6805 case Intrinsic::aarch64_stlxp:
6806 case Intrinsic::aarch64_stxp: {
6807 Info.opc = ISD::INTRINSIC_W_CHAIN;
6808 Info.memVT = MVT::i128;
6809 Info.ptrVal = I.getArgOperand(2);
6813 Info.readMem = false;
6814 Info.writeMem = true;
6824 // Truncations from 64-bit GPR to 32-bit GPR is free.
6825 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
6826 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6828 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6829 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6830 return NumBits1 > NumBits2;
6832 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
6833 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
6835 unsigned NumBits1 = VT1.getSizeInBits();
6836 unsigned NumBits2 = VT2.getSizeInBits();
6837 return NumBits1 > NumBits2;
6840 /// Check if it is profitable to hoist instruction in then/else to if.
6841 /// Not profitable if I and it's user can form a FMA instruction
6842 /// because we prefer FMSUB/FMADD.
6843 bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
6844 if (I->getOpcode() != Instruction::FMul)
6847 if (I->getNumUses() != 1)
6850 Instruction *User = I->user_back();
6853 !(User->getOpcode() == Instruction::FSub ||
6854 User->getOpcode() == Instruction::FAdd))
6857 const TargetOptions &Options = getTargetMachine().Options;
6858 const DataLayout &DL = I->getModule()->getDataLayout();
6859 EVT VT = getValueType(DL, User->getOperand(0)->getType());
6861 if (isFMAFasterThanFMulAndFAdd(VT) &&
6862 isOperationLegalOrCustom(ISD::FMA, VT) &&
6863 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath))
6869 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
6871 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
6872 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6874 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6875 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
6876 return NumBits1 == 32 && NumBits2 == 64;
6878 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
6879 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
6881 unsigned NumBits1 = VT1.getSizeInBits();
6882 unsigned NumBits2 = VT2.getSizeInBits();
6883 return NumBits1 == 32 && NumBits2 == 64;
6886 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
6887 EVT VT1 = Val.getValueType();
6888 if (isZExtFree(VT1, VT2)) {
6892 if (Val.getOpcode() != ISD::LOAD)
6895 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
6896 return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
6897 VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
6898 VT1.getSizeInBits() <= 32);
6901 bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
6902 if (isa<FPExtInst>(Ext))
6905 // Vector types are next free.
6906 if (Ext->getType()->isVectorTy())
6909 for (const Use &U : Ext->uses()) {
6910 // The extension is free if we can fold it with a left shift in an
6911 // addressing mode or an arithmetic operation: add, sub, and cmp.
6913 // Is there a shift?
6914 const Instruction *Instr = cast<Instruction>(U.getUser());
6916 // Is this a constant shift?
6917 switch (Instr->getOpcode()) {
6918 case Instruction::Shl:
6919 if (!isa<ConstantInt>(Instr->getOperand(1)))
6922 case Instruction::GetElementPtr: {
6923 gep_type_iterator GTI = gep_type_begin(Instr);
6924 auto &DL = Ext->getModule()->getDataLayout();
6925 std::advance(GTI, U.getOperandNo());
6927 // This extension will end up with a shift because of the scaling factor.
6928 // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
6929 // Get the shift amount based on the scaling factor:
6930 // log2(sizeof(IdxTy)) - log2(8).
6932 countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3;
6933 // Is the constant foldable in the shift of the addressing mode?
6934 // I.e., shift amount is between 1 and 4 inclusive.
6935 if (ShiftAmt == 0 || ShiftAmt > 4)
6939 case Instruction::Trunc:
6940 // Check if this is a noop.
6941 // trunc(sext ty1 to ty2) to ty1.
6942 if (Instr->getType() == Ext->getOperand(0)->getType())
6949 // At this point we can use the bfm family, so this extension is free
6955 bool AArch64TargetLowering::hasPairedLoad(Type *LoadedType,
6956 unsigned &RequiredAligment) const {
6957 if (!LoadedType->isIntegerTy() && !LoadedType->isFloatTy())
6959 // Cyclone supports unaligned accesses.
6960 RequiredAligment = 0;
6961 unsigned NumBits = LoadedType->getPrimitiveSizeInBits();
6962 return NumBits == 32 || NumBits == 64;
6965 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
6966 unsigned &RequiredAligment) const {
6967 if (!LoadedType.isSimple() ||
6968 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
6970 // Cyclone supports unaligned accesses.
6971 RequiredAligment = 0;
6972 unsigned NumBits = LoadedType.getSizeInBits();
6973 return NumBits == 32 || NumBits == 64;
6976 /// \brief Lower an interleaved load into a ldN intrinsic.
6978 /// E.g. Lower an interleaved load (Factor = 2):
6979 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr
6980 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
6981 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
6984 /// %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
6985 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
6986 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
6987 bool AArch64TargetLowering::lowerInterleavedLoad(
6988 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
6989 ArrayRef<unsigned> Indices, unsigned Factor) const {
6990 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
6991 "Invalid interleave factor");
6992 assert(!Shuffles.empty() && "Empty shufflevector input");
6993 assert(Shuffles.size() == Indices.size() &&
6994 "Unmatched number of shufflevectors and indices");
6996 const DataLayout &DL = LI->getModule()->getDataLayout();
6998 VectorType *VecTy = Shuffles[0]->getType();
6999 unsigned VecSize = DL.getTypeSizeInBits(VecTy);
7001 // Skip if we do not have NEON and skip illegal vector types.
7002 if (!Subtarget->hasNEON() || (VecSize != 64 && VecSize != 128))
7005 // A pointer vector can not be the return type of the ldN intrinsics. Need to
7006 // load integer vectors first and then convert to pointer vectors.
7007 Type *EltTy = VecTy->getVectorElementType();
7008 if (EltTy->isPointerTy())
7010 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
7012 Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
7013 Type *Tys[2] = {VecTy, PtrTy};
7014 static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
7015 Intrinsic::aarch64_neon_ld3,
7016 Intrinsic::aarch64_neon_ld4};
7018 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
7020 IRBuilder<> Builder(LI);
7021 Value *Ptr = Builder.CreateBitCast(LI->getPointerOperand(), PtrTy);
7023 CallInst *LdN = Builder.CreateCall(LdNFunc, Ptr, "ldN");
7025 // Replace uses of each shufflevector with the corresponding vector loaded
7027 for (unsigned i = 0; i < Shuffles.size(); i++) {
7028 ShuffleVectorInst *SVI = Shuffles[i];
7029 unsigned Index = Indices[i];
7031 Value *SubVec = Builder.CreateExtractValue(LdN, Index);
7033 // Convert the integer vector to pointer vector if the element is pointer.
7034 if (EltTy->isPointerTy())
7035 SubVec = Builder.CreateIntToPtr(SubVec, SVI->getType());
7037 SVI->replaceAllUsesWith(SubVec);
7043 /// \brief Get a mask consisting of sequential integers starting from \p Start.
7045 /// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
7046 static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
7048 SmallVector<Constant *, 16> Mask;
7049 for (unsigned i = 0; i < NumElts; i++)
7050 Mask.push_back(Builder.getInt32(Start + i));
7052 return ConstantVector::get(Mask);
7055 /// \brief Lower an interleaved store into a stN intrinsic.
7057 /// E.g. Lower an interleaved store (Factor = 3):
7058 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
7059 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
7060 /// store <12 x i32> %i.vec, <12 x i32>* %ptr
7063 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
7064 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
7065 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
7066 /// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
7068 /// Note that the new shufflevectors will be removed and we'll only generate one
7069 /// st3 instruction in CodeGen.
7070 bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
7071 ShuffleVectorInst *SVI,
7072 unsigned Factor) const {
7073 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7074 "Invalid interleave factor");
7076 VectorType *VecTy = SVI->getType();
7077 assert(VecTy->getVectorNumElements() % Factor == 0 &&
7078 "Invalid interleaved store");
7080 unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
7081 Type *EltTy = VecTy->getVectorElementType();
7082 VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
7084 const DataLayout &DL = SI->getModule()->getDataLayout();
7085 unsigned SubVecSize = DL.getTypeSizeInBits(SubVecTy);
7087 // Skip if we do not have NEON and skip illegal vector types.
7088 if (!Subtarget->hasNEON() || (SubVecSize != 64 && SubVecSize != 128))
7091 Value *Op0 = SVI->getOperand(0);
7092 Value *Op1 = SVI->getOperand(1);
7093 IRBuilder<> Builder(SI);
7095 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
7096 // vectors to integer vectors.
7097 if (EltTy->isPointerTy()) {
7098 Type *IntTy = DL.getIntPtrType(EltTy);
7099 unsigned NumOpElts =
7100 dyn_cast<VectorType>(Op0->getType())->getVectorNumElements();
7102 // Convert to the corresponding integer vector.
7103 Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
7104 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
7105 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
7107 SubVecTy = VectorType::get(IntTy, NumSubElts);
7110 Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
7111 Type *Tys[2] = {SubVecTy, PtrTy};
7112 static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
7113 Intrinsic::aarch64_neon_st3,
7114 Intrinsic::aarch64_neon_st4};
7116 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
7118 SmallVector<Value *, 5> Ops;
7120 // Split the shufflevector operands into sub vectors for the new stN call.
7121 for (unsigned i = 0; i < Factor; i++)
7122 Ops.push_back(Builder.CreateShuffleVector(
7123 Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
7125 Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), PtrTy));
7126 Builder.CreateCall(StNFunc, Ops);
7130 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
7131 unsigned AlignCheck) {
7132 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
7133 (DstAlign == 0 || DstAlign % AlignCheck == 0));
7136 EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
7137 unsigned SrcAlign, bool IsMemset,
7140 MachineFunction &MF) const {
7141 // Don't use AdvSIMD to implement 16-byte memset. It would have taken one
7142 // instruction to materialize the v2i64 zero and one store (with restrictive
7143 // addressing mode). Just do two i64 store of zero-registers.
7145 const Function *F = MF.getFunction();
7146 if (Subtarget->hasFPARMv8() && !IsMemset && Size >= 16 &&
7147 !F->hasFnAttribute(Attribute::NoImplicitFloat) &&
7148 (memOpAlign(SrcAlign, DstAlign, 16) ||
7149 (allowsMisalignedMemoryAccesses(MVT::f128, 0, 1, &Fast) && Fast)))
7153 (memOpAlign(SrcAlign, DstAlign, 8) ||
7154 (allowsMisalignedMemoryAccesses(MVT::i64, 0, 1, &Fast) && Fast)))
7158 (memOpAlign(SrcAlign, DstAlign, 4) ||
7159 (allowsMisalignedMemoryAccesses(MVT::i32, 0, 1, &Fast) && Fast)))
7165 // 12-bit optionally shifted immediates are legal for adds.
7166 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
7167 if ((Immed >> 12) == 0 || ((Immed & 0xfff) == 0 && Immed >> 24 == 0))
7172 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
7173 // immediates is the same as for an add or a sub.
7174 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
7177 return isLegalAddImmediate(Immed);
7180 /// isLegalAddressingMode - Return true if the addressing mode represented
7181 /// by AM is legal for this target, for a load/store of the specified type.
7182 bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
7183 const AddrMode &AM, Type *Ty,
7184 unsigned AS) const {
7185 // AArch64 has five basic addressing modes:
7187 // reg + 9-bit signed offset
7188 // reg + SIZE_IN_BYTES * 12-bit unsigned offset
7190 // reg + SIZE_IN_BYTES * reg
7192 // No global is ever allowed as a base.
7196 // No reg+reg+imm addressing.
7197 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
7200 // check reg + imm case:
7201 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
7202 uint64_t NumBytes = 0;
7203 if (Ty->isSized()) {
7204 uint64_t NumBits = DL.getTypeSizeInBits(Ty);
7205 NumBytes = NumBits / 8;
7206 if (!isPowerOf2_64(NumBits))
7211 int64_t Offset = AM.BaseOffs;
7213 // 9-bit signed offset
7214 if (Offset >= -(1LL << 9) && Offset <= (1LL << 9) - 1)
7217 // 12-bit unsigned offset
7218 unsigned shift = Log2_64(NumBytes);
7219 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
7220 // Must be a multiple of NumBytes (NumBytes is a power of 2)
7221 (Offset >> shift) << shift == Offset)
7226 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
7228 if (!AM.Scale || AM.Scale == 1 ||
7229 (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes))
7234 int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
7235 const AddrMode &AM, Type *Ty,
7236 unsigned AS) const {
7237 // Scaling factors are not free at all.
7238 // Operands | Rt Latency
7239 // -------------------------------------------
7241 // -------------------------------------------
7242 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5
7243 // Rt, [Xn, Wm, <extend> #imm] |
7244 if (isLegalAddressingMode(DL, AM, Ty, AS))
7245 // Scale represents reg2 * scale, thus account for 1 if
7246 // it is not equal to 0 or 1.
7247 return AM.Scale != 0 && AM.Scale != 1;
7251 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
7252 VT = VT.getScalarType();
7257 switch (VT.getSimpleVT().SimpleTy) {
7269 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
7270 // LR is a callee-save register, but we must treat it as clobbered by any call
7271 // site. Hence we include LR in the scratch registers, which are in turn added
7272 // as implicit-defs for stackmaps and patchpoints.
7273 static const MCPhysReg ScratchRegs[] = {
7274 AArch64::X16, AArch64::X17, AArch64::LR, 0
7280 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N) const {
7281 EVT VT = N->getValueType(0);
7282 // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
7283 // it with shift to let it be lowered to UBFX.
7284 if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
7285 isa<ConstantSDNode>(N->getOperand(1))) {
7286 uint64_t TruncMask = N->getConstantOperandVal(1);
7287 if (isMask_64(TruncMask) &&
7288 N->getOperand(0).getOpcode() == ISD::SRL &&
7289 isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
7295 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
7297 assert(Ty->isIntegerTy());
7299 unsigned BitSize = Ty->getPrimitiveSizeInBits();
7303 int64_t Val = Imm.getSExtValue();
7304 if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
7307 if ((int64_t)Val < 0)
7310 Val &= (1LL << 32) - 1;
7312 unsigned LZ = countLeadingZeros((uint64_t)Val);
7313 unsigned Shift = (63 - LZ) / 16;
7314 // MOVZ is free so return true for one or fewer MOVK.
7318 // Generate SUBS and CSEL for integer abs.
7319 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
7320 EVT VT = N->getValueType(0);
7322 SDValue N0 = N->getOperand(0);
7323 SDValue N1 = N->getOperand(1);
7326 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
7327 // and change it to SUB and CSEL.
7328 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
7329 N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
7330 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
7331 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
7332 if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
7333 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
7335 // Generate SUBS & CSEL.
7337 DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
7338 N0.getOperand(0), DAG.getConstant(0, DL, VT));
7339 return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
7340 DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
7341 SDValue(Cmp.getNode(), 1));
7346 // performXorCombine - Attempts to handle integer ABS.
7347 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
7348 TargetLowering::DAGCombinerInfo &DCI,
7349 const AArch64Subtarget *Subtarget) {
7350 if (DCI.isBeforeLegalizeOps())
7353 return performIntegerAbsCombine(N, DAG);
7357 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
7359 std::vector<SDNode *> *Created) const {
7360 // fold (sdiv X, pow2)
7361 EVT VT = N->getValueType(0);
7362 if ((VT != MVT::i32 && VT != MVT::i64) ||
7363 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
7367 SDValue N0 = N->getOperand(0);
7368 unsigned Lg2 = Divisor.countTrailingZeros();
7369 SDValue Zero = DAG.getConstant(0, DL, VT);
7370 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
7372 // Add (N0 < 0) ? Pow2 - 1 : 0;
7374 SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
7375 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
7376 SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
7379 Created->push_back(Cmp.getNode());
7380 Created->push_back(Add.getNode());
7381 Created->push_back(CSel.getNode());
7386 DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
7388 // If we're dividing by a positive value, we're done. Otherwise, we must
7389 // negate the result.
7390 if (Divisor.isNonNegative())
7394 Created->push_back(SRA.getNode());
7395 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
7398 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
7399 TargetLowering::DAGCombinerInfo &DCI,
7400 const AArch64Subtarget *Subtarget) {
7401 if (DCI.isBeforeLegalizeOps())
7404 // Multiplication of a power of two plus/minus one can be done more
7405 // cheaply as as shift+add/sub. For now, this is true unilaterally. If
7406 // future CPUs have a cheaper MADD instruction, this may need to be
7407 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
7408 // 64-bit is 5 cycles, so this is always a win.
7409 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
7410 APInt Value = C->getAPIntValue();
7411 EVT VT = N->getValueType(0);
7413 if (Value.isNonNegative()) {
7414 // (mul x, 2^N + 1) => (add (shl x, N), x)
7415 APInt VM1 = Value - 1;
7416 if (VM1.isPowerOf2()) {
7417 SDValue ShiftedVal =
7418 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7419 DAG.getConstant(VM1.logBase2(), DL, MVT::i64));
7420 return DAG.getNode(ISD::ADD, DL, VT, ShiftedVal,
7423 // (mul x, 2^N - 1) => (sub (shl x, N), x)
7424 APInt VP1 = Value + 1;
7425 if (VP1.isPowerOf2()) {
7426 SDValue ShiftedVal =
7427 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7428 DAG.getConstant(VP1.logBase2(), DL, MVT::i64));
7429 return DAG.getNode(ISD::SUB, DL, VT, ShiftedVal,
7433 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7434 APInt VNP1 = -Value + 1;
7435 if (VNP1.isPowerOf2()) {
7436 SDValue ShiftedVal =
7437 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7438 DAG.getConstant(VNP1.logBase2(), DL, MVT::i64));
7439 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0),
7442 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7443 APInt VNM1 = -Value - 1;
7444 if (VNM1.isPowerOf2()) {
7445 SDValue ShiftedVal =
7446 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7447 DAG.getConstant(VNM1.logBase2(), DL, MVT::i64));
7449 DAG.getNode(ISD::ADD, DL, VT, ShiftedVal, N->getOperand(0));
7450 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Add);
7457 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
7458 SelectionDAG &DAG) {
7459 // Take advantage of vector comparisons producing 0 or -1 in each lane to
7460 // optimize away operation when it's from a constant.
7462 // The general transformation is:
7463 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
7464 // AND(VECTOR_CMP(x,y), constant2)
7465 // constant2 = UNARYOP(constant)
7467 // Early exit if this isn't a vector operation, the operand of the
7468 // unary operation isn't a bitwise AND, or if the sizes of the operations
7470 EVT VT = N->getValueType(0);
7471 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
7472 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
7473 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
7476 // Now check that the other operand of the AND is a constant. We could
7477 // make the transformation for non-constant splats as well, but it's unclear
7478 // that would be a benefit as it would not eliminate any operations, just
7479 // perform one more step in scalar code before moving to the vector unit.
7480 if (BuildVectorSDNode *BV =
7481 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
7482 // Bail out if the vector isn't a constant.
7483 if (!BV->isConstant())
7486 // Everything checks out. Build up the new and improved node.
7488 EVT IntVT = BV->getValueType(0);
7489 // Create a new constant of the appropriate type for the transformed
7491 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
7492 // The AND node needs bitcasts to/from an integer vector type around it.
7493 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
7494 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
7495 N->getOperand(0)->getOperand(0), MaskConst);
7496 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
7503 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
7504 const AArch64Subtarget *Subtarget) {
7505 // First try to optimize away the conversion when it's conditionally from
7506 // a constant. Vectors only.
7507 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
7510 EVT VT = N->getValueType(0);
7511 if (VT != MVT::f32 && VT != MVT::f64)
7514 // Only optimize when the source and destination types have the same width.
7515 if (VT.getSizeInBits() != N->getOperand(0).getValueType().getSizeInBits())
7518 // If the result of an integer load is only used by an integer-to-float
7519 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
7520 // This eliminates an "integer-to-vector-move" UOP and improves throughput.
7521 SDValue N0 = N->getOperand(0);
7522 if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7523 // Do not change the width of a volatile load.
7524 !cast<LoadSDNode>(N0)->isVolatile()) {
7525 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7526 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
7527 LN0->getPointerInfo(), LN0->isVolatile(),
7528 LN0->isNonTemporal(), LN0->isInvariant(),
7529 LN0->getAlignment());
7531 // Make sure successors of the original load stay after it by updating them
7532 // to use the new Chain.
7533 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
7536 (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
7537 return DAG.getNode(Opcode, SDLoc(N), VT, Load);
7543 /// Fold a floating-point multiply by power of two into floating-point to
7544 /// fixed-point conversion.
7545 static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
7546 const AArch64Subtarget *Subtarget) {
7547 if (!Subtarget->hasNEON())
7550 SDValue Op = N->getOperand(0);
7551 if (!Op.getValueType().isVector() || Op.getOpcode() != ISD::FMUL)
7554 SDValue ConstVec = Op->getOperand(1);
7555 if (!isa<BuildVectorSDNode>(ConstVec))
7558 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
7559 uint32_t FloatBits = FloatTy.getSizeInBits();
7560 if (FloatBits != 32 && FloatBits != 64)
7563 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
7564 uint32_t IntBits = IntTy.getSizeInBits();
7565 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
7568 // Avoid conversions where iN is larger than the float (e.g., float -> i64).
7569 if (IntBits > FloatBits)
7572 BitVector UndefElements;
7573 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
7574 int32_t Bits = IntBits == 64 ? 64 : 32;
7575 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
7576 if (C == -1 || C == 0 || C > Bits)
7580 unsigned NumLanes = Op.getValueType().getVectorNumElements();
7585 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
7593 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
7594 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
7595 : Intrinsic::aarch64_neon_vcvtfp2fxu;
7597 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
7598 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
7599 Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
7600 // We can handle smaller integers by generating an extra trunc.
7601 if (IntBits < FloatBits)
7602 FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
7607 /// Fold a floating-point divide by power of two into fixed-point to
7608 /// floating-point conversion.
7609 static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
7610 const AArch64Subtarget *Subtarget) {
7611 if (!Subtarget->hasNEON())
7614 SDValue Op = N->getOperand(0);
7615 unsigned Opc = Op->getOpcode();
7616 if (!Op.getValueType().isVector() ||
7617 (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
7620 SDValue ConstVec = N->getOperand(1);
7621 if (!isa<BuildVectorSDNode>(ConstVec))
7624 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
7625 int32_t IntBits = IntTy.getSizeInBits();
7626 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
7629 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
7630 int32_t FloatBits = FloatTy.getSizeInBits();
7631 if (FloatBits != 32 && FloatBits != 64)
7634 // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
7635 if (IntBits > FloatBits)
7638 BitVector UndefElements;
7639 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
7640 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
7641 if (C == -1 || C == 0 || C > FloatBits)
7645 unsigned NumLanes = Op.getValueType().getVectorNumElements();
7650 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
7658 SDValue ConvInput = Op.getOperand(0);
7659 bool IsSigned = Opc == ISD::SINT_TO_FP;
7660 if (IntBits < FloatBits)
7661 ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
7664 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
7665 : Intrinsic::aarch64_neon_vcvtfxu2fp;
7666 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
7667 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
7668 DAG.getConstant(C, DL, MVT::i32));
7671 /// An EXTR instruction is made up of two shifts, ORed together. This helper
7672 /// searches for and classifies those shifts.
7673 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
7675 if (N.getOpcode() == ISD::SHL)
7677 else if (N.getOpcode() == ISD::SRL)
7682 if (!isa<ConstantSDNode>(N.getOperand(1)))
7685 ShiftAmount = N->getConstantOperandVal(1);
7686 Src = N->getOperand(0);
7690 /// EXTR instruction extracts a contiguous chunk of bits from two existing
7691 /// registers viewed as a high/low pair. This function looks for the pattern:
7692 /// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an
7693 /// EXTR. Can't quite be done in TableGen because the two immediates aren't
7695 static SDValue tryCombineToEXTR(SDNode *N,
7696 TargetLowering::DAGCombinerInfo &DCI) {
7697 SelectionDAG &DAG = DCI.DAG;
7699 EVT VT = N->getValueType(0);
7701 assert(N->getOpcode() == ISD::OR && "Unexpected root");
7703 if (VT != MVT::i32 && VT != MVT::i64)
7707 uint32_t ShiftLHS = 0;
7709 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
7713 uint32_t ShiftRHS = 0;
7715 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
7718 // If they're both trying to come from the high part of the register, they're
7719 // not really an EXTR.
7720 if (LHSFromHi == RHSFromHi)
7723 if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
7727 std::swap(LHS, RHS);
7728 std::swap(ShiftLHS, ShiftRHS);
7731 return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
7732 DAG.getConstant(ShiftRHS, DL, MVT::i64));
7735 static SDValue tryCombineToBSL(SDNode *N,
7736 TargetLowering::DAGCombinerInfo &DCI) {
7737 EVT VT = N->getValueType(0);
7738 SelectionDAG &DAG = DCI.DAG;
7744 SDValue N0 = N->getOperand(0);
7745 if (N0.getOpcode() != ISD::AND)
7748 SDValue N1 = N->getOperand(1);
7749 if (N1.getOpcode() != ISD::AND)
7752 // We only have to look for constant vectors here since the general, variable
7753 // case can be handled in TableGen.
7754 unsigned Bits = VT.getVectorElementType().getSizeInBits();
7755 uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
7756 for (int i = 1; i >= 0; --i)
7757 for (int j = 1; j >= 0; --j) {
7758 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
7759 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
7763 bool FoundMatch = true;
7764 for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
7765 ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
7766 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
7768 CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
7775 return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
7776 N0->getOperand(1 - i), N1->getOperand(1 - j));
7782 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
7783 const AArch64Subtarget *Subtarget) {
7784 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
7785 if (!EnableAArch64ExtrGeneration)
7787 SelectionDAG &DAG = DCI.DAG;
7788 EVT VT = N->getValueType(0);
7790 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7793 SDValue Res = tryCombineToEXTR(N, DCI);
7797 Res = tryCombineToBSL(N, DCI);
7804 static SDValue performBitcastCombine(SDNode *N,
7805 TargetLowering::DAGCombinerInfo &DCI,
7806 SelectionDAG &DAG) {
7807 // Wait 'til after everything is legalized to try this. That way we have
7808 // legal vector types and such.
7809 if (DCI.isBeforeLegalizeOps())
7812 // Remove extraneous bitcasts around an extract_subvector.
7814 // (v4i16 (bitconvert
7815 // (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
7817 // (extract_subvector ((v8i16 ...), (i64 4)))
7819 // Only interested in 64-bit vectors as the ultimate result.
7820 EVT VT = N->getValueType(0);
7823 if (VT.getSimpleVT().getSizeInBits() != 64)
7825 // Is the operand an extract_subvector starting at the beginning or halfway
7826 // point of the vector? A low half may also come through as an
7827 // EXTRACT_SUBREG, so look for that, too.
7828 SDValue Op0 = N->getOperand(0);
7829 if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
7830 !(Op0->isMachineOpcode() &&
7831 Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
7833 uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
7834 if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
7835 if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
7837 } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
7838 if (idx != AArch64::dsub)
7840 // The dsub reference is equivalent to a lane zero subvector reference.
7843 // Look through the bitcast of the input to the extract.
7844 if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
7846 SDValue Source = Op0->getOperand(0)->getOperand(0);
7847 // If the source type has twice the number of elements as our destination
7848 // type, we know this is an extract of the high or low half of the vector.
7849 EVT SVT = Source->getValueType(0);
7850 if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
7853 DEBUG(dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
7855 // Create the simplified form to just extract the low or high half of the
7856 // vector directly rather than bothering with the bitcasts.
7858 unsigned NumElements = VT.getVectorNumElements();
7860 SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
7861 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
7863 SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
7864 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
7870 static SDValue performConcatVectorsCombine(SDNode *N,
7871 TargetLowering::DAGCombinerInfo &DCI,
7872 SelectionDAG &DAG) {
7874 EVT VT = N->getValueType(0);
7875 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
7877 // Optimize concat_vectors of truncated vectors, where the intermediate
7878 // type is illegal, to avoid said illegality, e.g.,
7879 // (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
7880 // (v2i16 (truncate (v2i64)))))
7882 // (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
7883 // (v4i32 (bitcast (v2i64))),
7885 // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
7886 // on both input and result type, so we might generate worse code.
7887 // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
7888 if (N->getNumOperands() == 2 &&
7889 N0->getOpcode() == ISD::TRUNCATE &&
7890 N1->getOpcode() == ISD::TRUNCATE) {
7891 SDValue N00 = N0->getOperand(0);
7892 SDValue N10 = N1->getOperand(0);
7893 EVT N00VT = N00.getValueType();
7895 if (N00VT == N10.getValueType() &&
7896 (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
7897 N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
7898 MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
7899 SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
7900 for (size_t i = 0; i < Mask.size(); ++i)
7902 return DAG.getNode(ISD::TRUNCATE, dl, VT,
7903 DAG.getVectorShuffle(
7905 DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
7906 DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
7910 // Wait 'til after everything is legalized to try this. That way we have
7911 // legal vector types and such.
7912 if (DCI.isBeforeLegalizeOps())
7915 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
7916 // splat. The indexed instructions are going to be expecting a DUPLANE64, so
7917 // canonicalise to that.
7918 if (N0 == N1 && VT.getVectorNumElements() == 2) {
7919 assert(VT.getVectorElementType().getSizeInBits() == 64);
7920 return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
7921 DAG.getConstant(0, dl, MVT::i64));
7924 // Canonicalise concat_vectors so that the right-hand vector has as few
7925 // bit-casts as possible before its real operation. The primary matching
7926 // destination for these operations will be the narrowing "2" instructions,
7927 // which depend on the operation being performed on this right-hand vector.
7929 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS))))
7931 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
7933 if (N1->getOpcode() != ISD::BITCAST)
7935 SDValue RHS = N1->getOperand(0);
7936 MVT RHSTy = RHS.getValueType().getSimpleVT();
7937 // If the RHS is not a vector, this is not the pattern we're looking for.
7938 if (!RHSTy.isVector())
7941 DEBUG(dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
7943 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
7944 RHSTy.getVectorNumElements() * 2);
7945 return DAG.getNode(ISD::BITCAST, dl, VT,
7946 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
7947 DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
7951 static SDValue tryCombineFixedPointConvert(SDNode *N,
7952 TargetLowering::DAGCombinerInfo &DCI,
7953 SelectionDAG &DAG) {
7954 // Wait 'til after everything is legalized to try this. That way we have
7955 // legal vector types and such.
7956 if (DCI.isBeforeLegalizeOps())
7958 // Transform a scalar conversion of a value from a lane extract into a
7959 // lane extract of a vector conversion. E.g., from foo1 to foo2:
7960 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
7961 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
7963 // The second form interacts better with instruction selection and the
7964 // register allocator to avoid cross-class register copies that aren't
7965 // coalescable due to a lane reference.
7967 // Check the operand and see if it originates from a lane extract.
7968 SDValue Op1 = N->getOperand(1);
7969 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7970 // Yep, no additional predication needed. Perform the transform.
7971 SDValue IID = N->getOperand(0);
7972 SDValue Shift = N->getOperand(2);
7973 SDValue Vec = Op1.getOperand(0);
7974 SDValue Lane = Op1.getOperand(1);
7975 EVT ResTy = N->getValueType(0);
7979 // The vector width should be 128 bits by the time we get here, even
7980 // if it started as 64 bits (the extract_vector handling will have
7982 assert(Vec.getValueType().getSizeInBits() == 128 &&
7983 "unexpected vector size on extract_vector_elt!");
7984 if (Vec.getValueType() == MVT::v4i32)
7985 VecResTy = MVT::v4f32;
7986 else if (Vec.getValueType() == MVT::v2i64)
7987 VecResTy = MVT::v2f64;
7989 llvm_unreachable("unexpected vector type!");
7992 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
7993 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
7998 // AArch64 high-vector "long" operations are formed by performing the non-high
7999 // version on an extract_subvector of each operand which gets the high half:
8001 // (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
8003 // However, there are cases which don't have an extract_high explicitly, but
8004 // have another operation that can be made compatible with one for free. For
8007 // (dupv64 scalar) --> (extract_high (dup128 scalar))
8009 // This routine does the actual conversion of such DUPs, once outer routines
8010 // have determined that everything else is in order.
8011 // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
8013 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
8014 switch (N.getOpcode()) {
8015 case AArch64ISD::DUP:
8016 case AArch64ISD::DUPLANE8:
8017 case AArch64ISD::DUPLANE16:
8018 case AArch64ISD::DUPLANE32:
8019 case AArch64ISD::DUPLANE64:
8020 case AArch64ISD::MOVI:
8021 case AArch64ISD::MOVIshift:
8022 case AArch64ISD::MOVIedit:
8023 case AArch64ISD::MOVImsl:
8024 case AArch64ISD::MVNIshift:
8025 case AArch64ISD::MVNImsl:
8028 // FMOV could be supported, but isn't very useful, as it would only occur
8029 // if you passed a bitcast' floating point immediate to an eligible long
8030 // integer op (addl, smull, ...).
8034 MVT NarrowTy = N.getSimpleValueType();
8035 if (!NarrowTy.is64BitVector())
8038 MVT ElementTy = NarrowTy.getVectorElementType();
8039 unsigned NumElems = NarrowTy.getVectorNumElements();
8040 MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
8043 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
8044 DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
8045 DAG.getConstant(NumElems, dl, MVT::i64));
8048 static bool isEssentiallyExtractSubvector(SDValue N) {
8049 if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
8052 return N.getOpcode() == ISD::BITCAST &&
8053 N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
8056 /// \brief Helper structure to keep track of ISD::SET_CC operands.
8057 struct GenericSetCCInfo {
8058 const SDValue *Opnd0;
8059 const SDValue *Opnd1;
8063 /// \brief Helper structure to keep track of a SET_CC lowered into AArch64 code.
8064 struct AArch64SetCCInfo {
8066 AArch64CC::CondCode CC;
8069 /// \brief Helper structure to keep track of SetCC information.
8071 GenericSetCCInfo Generic;
8072 AArch64SetCCInfo AArch64;
8075 /// \brief Helper structure to be able to read SetCC information. If set to
8076 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
8077 /// GenericSetCCInfo.
8078 struct SetCCInfoAndKind {
8083 /// \brief Check whether or not \p Op is a SET_CC operation, either a generic or
8085 /// AArch64 lowered one.
8086 /// \p SetCCInfo is filled accordingly.
8087 /// \post SetCCInfo is meanginfull only when this function returns true.
8088 /// \return True when Op is a kind of SET_CC operation.
8089 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
8090 // If this is a setcc, this is straight forward.
8091 if (Op.getOpcode() == ISD::SETCC) {
8092 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
8093 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
8094 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8095 SetCCInfo.IsAArch64 = false;
8098 // Otherwise, check if this is a matching csel instruction.
8102 if (Op.getOpcode() != AArch64ISD::CSEL)
8104 // Set the information about the operands.
8105 // TODO: we want the operands of the Cmp not the csel
8106 SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
8107 SetCCInfo.IsAArch64 = true;
8108 SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
8109 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
8111 // Check that the operands matches the constraints:
8112 // (1) Both operands must be constants.
8113 // (2) One must be 1 and the other must be 0.
8114 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
8115 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8118 if (!TValue || !FValue)
8122 if (!TValue->isOne()) {
8123 // Update the comparison when we are interested in !cc.
8124 std::swap(TValue, FValue);
8125 SetCCInfo.Info.AArch64.CC =
8126 AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
8128 return TValue->isOne() && FValue->isNullValue();
8131 // Returns true if Op is setcc or zext of setcc.
8132 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
8133 if (isSetCC(Op, Info))
8135 return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
8136 isSetCC(Op->getOperand(0), Info));
8139 // The folding we want to perform is:
8140 // (add x, [zext] (setcc cc ...) )
8142 // (csel x, (add x, 1), !cc ...)
8144 // The latter will get matched to a CSINC instruction.
8145 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
8146 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
8147 SDValue LHS = Op->getOperand(0);
8148 SDValue RHS = Op->getOperand(1);
8149 SetCCInfoAndKind InfoAndKind;
8151 // If neither operand is a SET_CC, give up.
8152 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
8153 std::swap(LHS, RHS);
8154 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
8158 // FIXME: This could be generatized to work for FP comparisons.
8159 EVT CmpVT = InfoAndKind.IsAArch64
8160 ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
8161 : InfoAndKind.Info.Generic.Opnd0->getValueType();
8162 if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
8168 if (InfoAndKind.IsAArch64) {
8169 CCVal = DAG.getConstant(
8170 AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
8172 Cmp = *InfoAndKind.Info.AArch64.Cmp;
8174 Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
8175 *InfoAndKind.Info.Generic.Opnd1,
8176 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
8179 EVT VT = Op->getValueType(0);
8180 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
8181 return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
8184 // The basic add/sub long vector instructions have variants with "2" on the end
8185 // which act on the high-half of their inputs. They are normally matched by
8188 // (add (zeroext (extract_high LHS)),
8189 // (zeroext (extract_high RHS)))
8190 // -> uaddl2 vD, vN, vM
8192 // However, if one of the extracts is something like a duplicate, this
8193 // instruction can still be used profitably. This function puts the DAG into a
8194 // more appropriate form for those patterns to trigger.
8195 static SDValue performAddSubLongCombine(SDNode *N,
8196 TargetLowering::DAGCombinerInfo &DCI,
8197 SelectionDAG &DAG) {
8198 if (DCI.isBeforeLegalizeOps())
8201 MVT VT = N->getSimpleValueType(0);
8202 if (!VT.is128BitVector()) {
8203 if (N->getOpcode() == ISD::ADD)
8204 return performSetccAddFolding(N, DAG);
8208 // Make sure both branches are extended in the same way.
8209 SDValue LHS = N->getOperand(0);
8210 SDValue RHS = N->getOperand(1);
8211 if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
8212 LHS.getOpcode() != ISD::SIGN_EXTEND) ||
8213 LHS.getOpcode() != RHS.getOpcode())
8216 unsigned ExtType = LHS.getOpcode();
8218 // It's not worth doing if at least one of the inputs isn't already an
8219 // extract, but we don't know which it'll be so we have to try both.
8220 if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
8221 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
8225 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
8226 } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
8227 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
8231 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
8234 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
8237 // Massage DAGs which we can use the high-half "long" operations on into
8238 // something isel will recognize better. E.g.
8240 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
8241 // (aarch64_neon_umull (extract_high (v2i64 vec)))
8242 // (extract_high (v2i64 (dup128 scalar)))))
8244 static SDValue tryCombineLongOpWithDup(SDNode *N,
8245 TargetLowering::DAGCombinerInfo &DCI,
8246 SelectionDAG &DAG) {
8247 if (DCI.isBeforeLegalizeOps())
8250 bool IsIntrinsic = N->getOpcode() == ISD::INTRINSIC_WO_CHAIN;
8251 SDValue LHS = N->getOperand(IsIntrinsic ? 1 : 0);
8252 SDValue RHS = N->getOperand(IsIntrinsic ? 2 : 1);
8253 assert(LHS.getValueType().is64BitVector() &&
8254 RHS.getValueType().is64BitVector() &&
8255 "unexpected shape for long operation");
8257 // Either node could be a DUP, but it's not worth doing both of them (you'd
8258 // just as well use the non-high version) so look for a corresponding extract
8259 // operation on the other "wing".
8260 if (isEssentiallyExtractSubvector(LHS)) {
8261 RHS = tryExtendDUPToExtractHigh(RHS, DAG);
8264 } else if (isEssentiallyExtractSubvector(RHS)) {
8265 LHS = tryExtendDUPToExtractHigh(LHS, DAG);
8270 // N could either be an intrinsic or a sabsdiff/uabsdiff node.
8272 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
8273 N->getOperand(0), LHS, RHS);
8275 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
8279 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
8280 MVT ElemTy = N->getSimpleValueType(0).getScalarType();
8281 unsigned ElemBits = ElemTy.getSizeInBits();
8283 int64_t ShiftAmount;
8284 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
8285 APInt SplatValue, SplatUndef;
8286 unsigned SplatBitSize;
8288 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
8289 HasAnyUndefs, ElemBits) ||
8290 SplatBitSize != ElemBits)
8293 ShiftAmount = SplatValue.getSExtValue();
8294 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
8295 ShiftAmount = CVN->getSExtValue();
8303 llvm_unreachable("Unknown shift intrinsic");
8304 case Intrinsic::aarch64_neon_sqshl:
8305 Opcode = AArch64ISD::SQSHL_I;
8306 IsRightShift = false;
8308 case Intrinsic::aarch64_neon_uqshl:
8309 Opcode = AArch64ISD::UQSHL_I;
8310 IsRightShift = false;
8312 case Intrinsic::aarch64_neon_srshl:
8313 Opcode = AArch64ISD::SRSHR_I;
8314 IsRightShift = true;
8316 case Intrinsic::aarch64_neon_urshl:
8317 Opcode = AArch64ISD::URSHR_I;
8318 IsRightShift = true;
8320 case Intrinsic::aarch64_neon_sqshlu:
8321 Opcode = AArch64ISD::SQSHLU_I;
8322 IsRightShift = false;
8326 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
8328 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8329 DAG.getConstant(-ShiftAmount, dl, MVT::i32));
8330 } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
8332 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8333 DAG.getConstant(ShiftAmount, dl, MVT::i32));
8339 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
8340 // the intrinsics must be legal and take an i32, this means there's almost
8341 // certainly going to be a zext in the DAG which we can eliminate.
8342 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
8343 SDValue AndN = N->getOperand(2);
8344 if (AndN.getOpcode() != ISD::AND)
8347 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
8348 if (!CMask || CMask->getZExtValue() != Mask)
8351 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
8352 N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
8355 static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
8356 SelectionDAG &DAG) {
8358 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
8359 DAG.getNode(Opc, dl,
8360 N->getOperand(1).getSimpleValueType(),
8362 DAG.getConstant(0, dl, MVT::i64));
8365 static SDValue performIntrinsicCombine(SDNode *N,
8366 TargetLowering::DAGCombinerInfo &DCI,
8367 const AArch64Subtarget *Subtarget) {
8368 SelectionDAG &DAG = DCI.DAG;
8369 unsigned IID = getIntrinsicID(N);
8373 case Intrinsic::aarch64_neon_vcvtfxs2fp:
8374 case Intrinsic::aarch64_neon_vcvtfxu2fp:
8375 return tryCombineFixedPointConvert(N, DCI, DAG);
8376 case Intrinsic::aarch64_neon_saddv:
8377 return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
8378 case Intrinsic::aarch64_neon_uaddv:
8379 return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
8380 case Intrinsic::aarch64_neon_sminv:
8381 return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
8382 case Intrinsic::aarch64_neon_uminv:
8383 return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
8384 case Intrinsic::aarch64_neon_smaxv:
8385 return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
8386 case Intrinsic::aarch64_neon_umaxv:
8387 return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
8388 case Intrinsic::aarch64_neon_fmax:
8389 return DAG.getNode(ISD::FMAXNAN, SDLoc(N), N->getValueType(0),
8390 N->getOperand(1), N->getOperand(2));
8391 case Intrinsic::aarch64_neon_fmin:
8392 return DAG.getNode(ISD::FMINNAN, SDLoc(N), N->getValueType(0),
8393 N->getOperand(1), N->getOperand(2));
8394 case Intrinsic::aarch64_neon_sabd:
8395 return DAG.getNode(ISD::SABSDIFF, SDLoc(N), N->getValueType(0),
8396 N->getOperand(1), N->getOperand(2));
8397 case Intrinsic::aarch64_neon_uabd:
8398 return DAG.getNode(ISD::UABSDIFF, SDLoc(N), N->getValueType(0),
8399 N->getOperand(1), N->getOperand(2));
8400 case Intrinsic::aarch64_neon_fmaxnm:
8401 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
8402 N->getOperand(1), N->getOperand(2));
8403 case Intrinsic::aarch64_neon_fminnm:
8404 return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
8405 N->getOperand(1), N->getOperand(2));
8406 case Intrinsic::aarch64_neon_smull:
8407 case Intrinsic::aarch64_neon_umull:
8408 case Intrinsic::aarch64_neon_pmull:
8409 case Intrinsic::aarch64_neon_sqdmull:
8410 return tryCombineLongOpWithDup(N, DCI, DAG);
8411 case Intrinsic::aarch64_neon_sqshl:
8412 case Intrinsic::aarch64_neon_uqshl:
8413 case Intrinsic::aarch64_neon_sqshlu:
8414 case Intrinsic::aarch64_neon_srshl:
8415 case Intrinsic::aarch64_neon_urshl:
8416 return tryCombineShiftImm(IID, N, DAG);
8417 case Intrinsic::aarch64_crc32b:
8418 case Intrinsic::aarch64_crc32cb:
8419 return tryCombineCRC32(0xff, N, DAG);
8420 case Intrinsic::aarch64_crc32h:
8421 case Intrinsic::aarch64_crc32ch:
8422 return tryCombineCRC32(0xffff, N, DAG);
8427 static SDValue performExtendCombine(SDNode *N,
8428 TargetLowering::DAGCombinerInfo &DCI,
8429 SelectionDAG &DAG) {
8430 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
8431 // we can convert that DUP into another extract_high (of a bigger DUP), which
8432 // helps the backend to decide that an sabdl2 would be useful, saving a real
8433 // extract_high operation.
8434 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
8435 (N->getOperand(0).getOpcode() == ISD::SABSDIFF ||
8436 N->getOperand(0).getOpcode() == ISD::UABSDIFF)) {
8437 SDNode *ABDNode = N->getOperand(0).getNode();
8438 SDValue NewABD = tryCombineLongOpWithDup(ABDNode, DCI, DAG);
8439 if (!NewABD.getNode())
8442 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
8446 // This is effectively a custom type legalization for AArch64.
8448 // Type legalization will split an extend of a small, legal, type to a larger
8449 // illegal type by first splitting the destination type, often creating
8450 // illegal source types, which then get legalized in isel-confusing ways,
8451 // leading to really terrible codegen. E.g.,
8452 // %result = v8i32 sext v8i8 %value
8454 // %losrc = extract_subreg %value, ...
8455 // %hisrc = extract_subreg %value, ...
8456 // %lo = v4i32 sext v4i8 %losrc
8457 // %hi = v4i32 sext v4i8 %hisrc
8458 // Things go rapidly downhill from there.
8460 // For AArch64, the [sz]ext vector instructions can only go up one element
8461 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
8462 // take two instructions.
8464 // This implies that the most efficient way to do the extend from v8i8
8465 // to two v4i32 values is to first extend the v8i8 to v8i16, then do
8466 // the normal splitting to happen for the v8i16->v8i32.
8468 // This is pre-legalization to catch some cases where the default
8469 // type legalization will create ill-tempered code.
8470 if (!DCI.isBeforeLegalizeOps())
8473 // We're only interested in cleaning things up for non-legal vector types
8474 // here. If both the source and destination are legal, things will just
8475 // work naturally without any fiddling.
8476 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8477 EVT ResVT = N->getValueType(0);
8478 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
8480 // If the vector type isn't a simple VT, it's beyond the scope of what
8481 // we're worried about here. Let legalization do its thing and hope for
8483 SDValue Src = N->getOperand(0);
8484 EVT SrcVT = Src->getValueType(0);
8485 if (!ResVT.isSimple() || !SrcVT.isSimple())
8488 // If the source VT is a 64-bit vector, we can play games and get the
8489 // better results we want.
8490 if (SrcVT.getSizeInBits() != 64)
8493 unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits();
8494 unsigned ElementCount = SrcVT.getVectorNumElements();
8495 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
8497 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
8499 // Now split the rest of the operation into two halves, each with a 64
8503 unsigned NumElements = ResVT.getVectorNumElements();
8504 assert(!(NumElements & 1) && "Splitting vector, but not in half!");
8505 LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
8506 ResVT.getVectorElementType(), NumElements / 2);
8508 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
8509 LoVT.getVectorNumElements());
8510 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
8511 DAG.getConstant(0, DL, MVT::i64));
8512 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
8513 DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
8514 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
8515 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
8517 // Now combine the parts back together so we still have a single result
8518 // like the combiner expects.
8519 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
8522 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
8523 /// value. The load store optimizer pass will merge them to store pair stores.
8524 /// This has better performance than a splat of the scalar followed by a split
8525 /// vector store. Even if the stores are not merged it is four stores vs a dup,
8526 /// followed by an ext.b and two stores.
8527 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode *St) {
8528 SDValue StVal = St->getValue();
8529 EVT VT = StVal.getValueType();
8531 // Don't replace floating point stores, they possibly won't be transformed to
8532 // stp because of the store pair suppress pass.
8533 if (VT.isFloatingPoint())
8536 // Check for insert vector elements.
8537 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
8540 // We can express a splat as store pair(s) for 2 or 4 elements.
8541 unsigned NumVecElts = VT.getVectorNumElements();
8542 if (NumVecElts != 4 && NumVecElts != 2)
8544 SDValue SplatVal = StVal.getOperand(1);
8545 unsigned RemainInsertElts = NumVecElts - 1;
8547 // Check that this is a splat.
8548 while (--RemainInsertElts) {
8549 SDValue NextInsertElt = StVal.getOperand(0);
8550 if (NextInsertElt.getOpcode() != ISD::INSERT_VECTOR_ELT)
8552 if (NextInsertElt.getOperand(1) != SplatVal)
8554 StVal = NextInsertElt;
8556 unsigned OrigAlignment = St->getAlignment();
8557 unsigned EltOffset = NumVecElts == 4 ? 4 : 8;
8558 unsigned Alignment = std::min(OrigAlignment, EltOffset);
8560 // Create scalar stores. This is at least as good as the code sequence for a
8561 // split unaligned store which is a dup.s, ext.b, and two stores.
8562 // Most of the time the three stores should be replaced by store pair
8563 // instructions (stp).
8565 SDValue BasePtr = St->getBasePtr();
8567 DAG.getStore(St->getChain(), DL, SplatVal, BasePtr, St->getPointerInfo(),
8568 St->isVolatile(), St->isNonTemporal(), St->getAlignment());
8570 unsigned Offset = EltOffset;
8571 while (--NumVecElts) {
8572 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
8573 DAG.getConstant(Offset, DL, MVT::i64));
8574 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
8575 St->getPointerInfo(), St->isVolatile(),
8576 St->isNonTemporal(), Alignment);
8577 Offset += EltOffset;
8582 static SDValue split16BStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
8584 const AArch64Subtarget *Subtarget) {
8585 if (!DCI.isBeforeLegalize())
8588 StoreSDNode *S = cast<StoreSDNode>(N);
8589 if (S->isVolatile())
8592 // FIXME: The logic for deciding if an unaligned store should be split should
8593 // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
8594 // a call to that function here.
8596 // Cyclone has bad performance on unaligned 16B stores when crossing line and
8597 // page boundaries. We want to split such stores.
8598 if (!Subtarget->isCyclone())
8601 // Don't split at -Oz.
8602 if (DAG.getMachineFunction().getFunction()->optForMinSize())
8605 SDValue StVal = S->getValue();
8606 EVT VT = StVal.getValueType();
8608 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
8609 // those up regresses performance on micro-benchmarks and olden/bh.
8610 if (!VT.isVector() || VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
8613 // Split unaligned 16B stores. They are terrible for performance.
8614 // Don't split stores with alignment of 1 or 2. Code that uses clang vector
8615 // extensions can use this to mark that it does not want splitting to happen
8616 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
8617 // eliminating alignment hazards is only 1 in 8 for alignment of 2.
8618 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
8619 S->getAlignment() <= 2)
8622 // If we get a splat of a scalar convert this vector store to a store of
8623 // scalars. They will be merged into store pairs thereby removing two
8625 if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, S))
8626 return ReplacedSplat;
8629 unsigned NumElts = VT.getVectorNumElements() / 2;
8630 // Split VT into two.
8632 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
8633 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
8634 DAG.getConstant(0, DL, MVT::i64));
8635 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
8636 DAG.getConstant(NumElts, DL, MVT::i64));
8637 SDValue BasePtr = S->getBasePtr();
8639 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
8640 S->isVolatile(), S->isNonTemporal(), S->getAlignment());
8641 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
8642 DAG.getConstant(8, DL, MVT::i64));
8643 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
8644 S->getPointerInfo(), S->isVolatile(), S->isNonTemporal(),
8648 /// Target-specific DAG combine function for post-increment LD1 (lane) and
8649 /// post-increment LD1R.
8650 static SDValue performPostLD1Combine(SDNode *N,
8651 TargetLowering::DAGCombinerInfo &DCI,
8653 if (DCI.isBeforeLegalizeOps())
8656 SelectionDAG &DAG = DCI.DAG;
8657 EVT VT = N->getValueType(0);
8659 unsigned LoadIdx = IsLaneOp ? 1 : 0;
8660 SDNode *LD = N->getOperand(LoadIdx).getNode();
8661 // If it is not LOAD, can not do such combine.
8662 if (LD->getOpcode() != ISD::LOAD)
8665 LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
8666 EVT MemVT = LoadSDN->getMemoryVT();
8667 // Check if memory operand is the same type as the vector element.
8668 if (MemVT != VT.getVectorElementType())
8671 // Check if there are other uses. If so, do not combine as it will introduce
8673 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
8675 if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
8681 SDValue Addr = LD->getOperand(1);
8682 SDValue Vector = N->getOperand(0);
8683 // Search for a use of the address operand that is an increment.
8684 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
8685 Addr.getNode()->use_end(); UI != UE; ++UI) {
8687 if (User->getOpcode() != ISD::ADD
8688 || UI.getUse().getResNo() != Addr.getResNo())
8691 // Check that the add is independent of the load. Otherwise, folding it
8692 // would create a cycle.
8693 if (User->isPredecessorOf(LD) || LD->isPredecessorOf(User))
8695 // Also check that add is not used in the vector operand. This would also
8697 if (User->isPredecessorOf(Vector.getNode()))
8700 // If the increment is a constant, it must match the memory ref size.
8701 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8702 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8703 uint32_t IncVal = CInc->getZExtValue();
8704 unsigned NumBytes = VT.getScalarSizeInBits() / 8;
8705 if (IncVal != NumBytes)
8707 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
8710 // Finally, check that the vector doesn't depend on the load.
8711 // Again, this would create a cycle.
8712 // The load depending on the vector is fine, as that's the case for the
8713 // LD1*post we'll eventually generate anyway.
8714 if (LoadSDN->isPredecessorOf(Vector.getNode()))
8717 SmallVector<SDValue, 8> Ops;
8718 Ops.push_back(LD->getOperand(0)); // Chain
8720 Ops.push_back(Vector); // The vector to be inserted
8721 Ops.push_back(N->getOperand(2)); // The lane to be inserted in the vector
8723 Ops.push_back(Addr);
8726 EVT Tys[3] = { VT, MVT::i64, MVT::Other };
8727 SDVTList SDTys = DAG.getVTList(Tys);
8728 unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
8729 SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
8731 LoadSDN->getMemOperand());
8734 SmallVector<SDValue, 2> NewResults;
8735 NewResults.push_back(SDValue(LD, 0)); // The result of load
8736 NewResults.push_back(SDValue(UpdN.getNode(), 2)); // Chain
8737 DCI.CombineTo(LD, NewResults);
8738 DCI.CombineTo(N, SDValue(UpdN.getNode(), 0)); // Dup/Inserted Result
8739 DCI.CombineTo(User, SDValue(UpdN.getNode(), 1)); // Write back register
8746 /// Simplify \Addr given that the top byte of it is ignored by HW during
8747 /// address translation.
8748 static bool performTBISimplification(SDValue Addr,
8749 TargetLowering::DAGCombinerInfo &DCI,
8750 SelectionDAG &DAG) {
8751 APInt DemandedMask = APInt::getLowBitsSet(64, 56);
8752 APInt KnownZero, KnownOne;
8753 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
8754 DCI.isBeforeLegalizeOps());
8755 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8756 if (TLI.SimplifyDemandedBits(Addr, DemandedMask, KnownZero, KnownOne, TLO)) {
8757 DCI.CommitTargetLoweringOpt(TLO);
8763 static SDValue performSTORECombine(SDNode *N,
8764 TargetLowering::DAGCombinerInfo &DCI,
8766 const AArch64Subtarget *Subtarget) {
8767 SDValue Split = split16BStores(N, DCI, DAG, Subtarget);
8768 if (Split.getNode())
8771 if (Subtarget->supportsAddressTopByteIgnored() &&
8772 performTBISimplification(N->getOperand(2), DCI, DAG))
8773 return SDValue(N, 0);
8778 /// This function handles the log2-shuffle pattern produced by the
8779 /// LoopVectorizer for the across vector reduction. It consists of
8780 /// log2(NumVectorElements) steps and, in each step, 2^(s) elements
8781 /// are reduced, where s is an induction variable from 0 to
8782 /// log2(NumVectorElements).
8783 static SDValue tryMatchAcrossLaneShuffleForReduction(SDNode *N, SDValue OpV,
8785 SelectionDAG &DAG) {
8786 EVT VTy = OpV->getOperand(0).getValueType();
8787 if (!VTy.isVector())
8790 int NumVecElts = VTy.getVectorNumElements();
8791 if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) {
8792 if (NumVecElts != 4)
8795 if (NumVecElts != 4 && NumVecElts != 8 && NumVecElts != 16)
8799 int NumExpectedSteps = APInt(8, NumVecElts).logBase2();
8800 SDValue PreOp = OpV;
8801 // Iterate over each step of the across vector reduction.
8802 for (int CurStep = 0; CurStep != NumExpectedSteps; ++CurStep) {
8803 SDValue CurOp = PreOp.getOperand(0);
8804 SDValue Shuffle = PreOp.getOperand(1);
8805 if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE) {
8806 // Try to swap the 1st and 2nd operand as add and min/max instructions
8808 CurOp = PreOp.getOperand(1);
8809 Shuffle = PreOp.getOperand(0);
8810 if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE)
8814 // Check if the input vector is fed by the operator we want to handle,
8815 // except the last step; the very first input vector is not necessarily
8816 // the same operator we are handling.
8817 if (CurOp.getOpcode() != Op && (CurStep != (NumExpectedSteps - 1)))
8820 // Check if it forms one step of the across vector reduction.
8822 // %cur = add %1, %0
8823 // %shuffle = vector_shuffle %cur, <2, 3, u, u>
8824 // %pre = add %cur, %shuffle
8825 if (Shuffle.getOperand(0) != CurOp)
8828 int NumMaskElts = 1 << CurStep;
8829 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Shuffle)->getMask();
8830 // Check mask values in each step.
8831 // We expect the shuffle mask in each step follows a specific pattern
8832 // denoted here by the <M, U> form, where M is a sequence of integers
8833 // starting from NumMaskElts, increasing by 1, and the number integers
8834 // in M should be NumMaskElts. U is a sequence of UNDEFs and the number
8835 // of undef in U should be NumVecElts - NumMaskElts.
8836 // E.g., for <8 x i16>, mask values in each step should be :
8837 // step 0 : <1,u,u,u,u,u,u,u>
8838 // step 1 : <2,3,u,u,u,u,u,u>
8839 // step 2 : <4,5,6,7,u,u,u,u>
8840 for (int i = 0; i < NumVecElts; ++i)
8841 if ((i < NumMaskElts && Mask[i] != (NumMaskElts + i)) ||
8842 (i >= NumMaskElts && !(Mask[i] < 0)))
8848 bool IsIntrinsic = false;
8852 llvm_unreachable("Unexpected operator for across vector reduction");
8854 Opcode = AArch64ISD::UADDV;
8857 Opcode = AArch64ISD::SMAXV;
8860 Opcode = AArch64ISD::UMAXV;
8863 Opcode = AArch64ISD::SMINV;
8866 Opcode = AArch64ISD::UMINV;
8869 Opcode = Intrinsic::aarch64_neon_fmaxnmv;
8873 Opcode = Intrinsic::aarch64_neon_fminnmv;
8880 ? DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, N->getValueType(0),
8881 DAG.getConstant(Opcode, DL, MVT::i32), PreOp)
8883 ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0),
8884 DAG.getNode(Opcode, DL, PreOp.getSimpleValueType(), PreOp),
8885 DAG.getConstant(0, DL, MVT::i64));
8888 /// Target-specific DAG combine for the across vector min/max reductions.
8889 /// This function specifically handles the final clean-up step of the vector
8890 /// min/max reductions produced by the LoopVectorizer. It is the log2-shuffle
8891 /// pattern, which narrows down and finds the final min/max value from all
8892 /// elements of the vector.
8893 /// For example, for a <16 x i8> vector :
8894 /// svn0 = vector_shuffle %0, undef<8,9,10,11,12,13,14,15,u,u,u,u,u,u,u,u>
8895 /// %smax0 = smax %arr, svn0
8896 /// %svn1 = vector_shuffle %smax0, undef<4,5,6,7,u,u,u,u,u,u,u,u,u,u,u,u>
8897 /// %smax1 = smax %smax0, %svn1
8898 /// %svn2 = vector_shuffle %smax1, undef<2,3,u,u,u,u,u,u,u,u,u,u,u,u,u,u>
8899 /// %smax2 = smax %smax1, svn2
8900 /// %svn3 = vector_shuffle %smax2, undef<1,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u>
8901 /// %sc = setcc %smax2, %svn3, gt
8902 /// %n0 = extract_vector_elt %sc, #0
8903 /// %n1 = extract_vector_elt %smax2, #0
8904 /// %n2 = extract_vector_elt $smax2, #1
8905 /// %result = select %n0, %n1, n2
8908 /// %result = extract_vector_elt %1, 0
8910 performAcrossLaneMinMaxReductionCombine(SDNode *N, SelectionDAG &DAG,
8911 const AArch64Subtarget *Subtarget) {
8912 if (!Subtarget->hasNEON())
8915 SDValue N0 = N->getOperand(0);
8916 SDValue IfTrue = N->getOperand(1);
8917 SDValue IfFalse = N->getOperand(2);
8919 // Check if the SELECT merges up the final result of the min/max
8921 if (N0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
8922 IfTrue.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
8923 IfFalse.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8926 // Expect N0 is fed by SETCC.
8927 SDValue SetCC = N0.getOperand(0);
8928 EVT SetCCVT = SetCC.getValueType();
8929 if (SetCC.getOpcode() != ISD::SETCC || !SetCCVT.isVector() ||
8930 SetCCVT.getVectorElementType() != MVT::i1)
8933 SDValue VectorOp = SetCC.getOperand(0);
8934 unsigned Op = VectorOp->getOpcode();
8935 // Check if the input vector is fed by the operator we want to handle.
8936 if (Op != ISD::SMAX && Op != ISD::UMAX && Op != ISD::SMIN &&
8937 Op != ISD::UMIN && Op != ISD::FMAXNUM && Op != ISD::FMINNUM)
8940 EVT VTy = VectorOp.getValueType();
8941 if (!VTy.isVector())
8944 if (VTy.getSizeInBits() < 64)
8947 EVT EltTy = VTy.getVectorElementType();
8948 if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) {
8949 if (EltTy != MVT::f32)
8952 if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8)
8956 // Check if extracting from the same vector.
8958 // %sc = setcc %vector, %svn1, gt
8959 // %n0 = extract_vector_elt %sc, #0
8960 // %n1 = extract_vector_elt %vector, #0
8961 // %n2 = extract_vector_elt $vector, #1
8962 if (!(VectorOp == IfTrue->getOperand(0) &&
8963 VectorOp == IfFalse->getOperand(0)))
8966 // Check if the condition code is matched with the operator type.
8967 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get();
8968 if ((Op == ISD::SMAX && CC != ISD::SETGT && CC != ISD::SETGE) ||
8969 (Op == ISD::UMAX && CC != ISD::SETUGT && CC != ISD::SETUGE) ||
8970 (Op == ISD::SMIN && CC != ISD::SETLT && CC != ISD::SETLE) ||
8971 (Op == ISD::UMIN && CC != ISD::SETULT && CC != ISD::SETULE) ||
8972 (Op == ISD::FMAXNUM && CC != ISD::SETOGT && CC != ISD::SETOGE &&
8973 CC != ISD::SETUGT && CC != ISD::SETUGE && CC != ISD::SETGT &&
8974 CC != ISD::SETGE) ||
8975 (Op == ISD::FMINNUM && CC != ISD::SETOLT && CC != ISD::SETOLE &&
8976 CC != ISD::SETULT && CC != ISD::SETULE && CC != ISD::SETLT &&
8980 // Expect to check only lane 0 from the vector SETCC.
8981 if (!isNullConstant(N0.getOperand(1)))
8984 // Expect to extract the true value from lane 0.
8985 if (!isNullConstant(IfTrue.getOperand(1)))
8988 // Expect to extract the false value from lane 1.
8989 if (!isOneConstant(IfFalse.getOperand(1)))
8992 return tryMatchAcrossLaneShuffleForReduction(N, SetCC, Op, DAG);
8995 /// Target-specific DAG combine for the across vector add reduction.
8996 /// This function specifically handles the final clean-up step of the vector
8997 /// add reduction produced by the LoopVectorizer. It is the log2-shuffle
8998 /// pattern, which adds all elements of a vector together.
8999 /// For example, for a <4 x i32> vector :
9000 /// %1 = vector_shuffle %0, <2,3,u,u>
9002 /// %3 = vector_shuffle %2, <1,u,u,u>
9004 /// %result = extract_vector_elt %4, 0
9007 /// %result = extract_vector_elt %0, 0
9009 performAcrossLaneAddReductionCombine(SDNode *N, SelectionDAG &DAG,
9010 const AArch64Subtarget *Subtarget) {
9011 if (!Subtarget->hasNEON())
9013 SDValue N0 = N->getOperand(0);
9014 SDValue N1 = N->getOperand(1);
9016 // Check if the input vector is fed by the ADD.
9017 if (N0->getOpcode() != ISD::ADD)
9020 // The vector extract idx must constant zero because we only expect the final
9021 // result of the reduction is placed in lane 0.
9022 if (!isNullConstant(N1))
9025 EVT VTy = N0.getValueType();
9026 if (!VTy.isVector())
9029 EVT EltTy = VTy.getVectorElementType();
9030 if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8)
9033 if (VTy.getSizeInBits() < 64)
9036 return tryMatchAcrossLaneShuffleForReduction(N, N0, ISD::ADD, DAG);
9039 /// Target-specific DAG combine function for NEON load/store intrinsics
9040 /// to merge base address updates.
9041 static SDValue performNEONPostLDSTCombine(SDNode *N,
9042 TargetLowering::DAGCombinerInfo &DCI,
9043 SelectionDAG &DAG) {
9044 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9047 unsigned AddrOpIdx = N->getNumOperands() - 1;
9048 SDValue Addr = N->getOperand(AddrOpIdx);
9050 // Search for a use of the address operand that is an increment.
9051 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9052 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9054 if (User->getOpcode() != ISD::ADD ||
9055 UI.getUse().getResNo() != Addr.getResNo())
9058 // Check that the add is independent of the load/store. Otherwise, folding
9059 // it would create a cycle.
9060 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9063 // Find the new opcode for the updating load/store.
9064 bool IsStore = false;
9065 bool IsLaneOp = false;
9066 bool IsDupOp = false;
9067 unsigned NewOpc = 0;
9068 unsigned NumVecs = 0;
9069 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9071 default: llvm_unreachable("unexpected intrinsic for Neon base update");
9072 case Intrinsic::aarch64_neon_ld2: NewOpc = AArch64ISD::LD2post;
9074 case Intrinsic::aarch64_neon_ld3: NewOpc = AArch64ISD::LD3post;
9076 case Intrinsic::aarch64_neon_ld4: NewOpc = AArch64ISD::LD4post;
9078 case Intrinsic::aarch64_neon_st2: NewOpc = AArch64ISD::ST2post;
9079 NumVecs = 2; IsStore = true; break;
9080 case Intrinsic::aarch64_neon_st3: NewOpc = AArch64ISD::ST3post;
9081 NumVecs = 3; IsStore = true; break;
9082 case Intrinsic::aarch64_neon_st4: NewOpc = AArch64ISD::ST4post;
9083 NumVecs = 4; IsStore = true; break;
9084 case Intrinsic::aarch64_neon_ld1x2: NewOpc = AArch64ISD::LD1x2post;
9086 case Intrinsic::aarch64_neon_ld1x3: NewOpc = AArch64ISD::LD1x3post;
9088 case Intrinsic::aarch64_neon_ld1x4: NewOpc = AArch64ISD::LD1x4post;
9090 case Intrinsic::aarch64_neon_st1x2: NewOpc = AArch64ISD::ST1x2post;
9091 NumVecs = 2; IsStore = true; break;
9092 case Intrinsic::aarch64_neon_st1x3: NewOpc = AArch64ISD::ST1x3post;
9093 NumVecs = 3; IsStore = true; break;
9094 case Intrinsic::aarch64_neon_st1x4: NewOpc = AArch64ISD::ST1x4post;
9095 NumVecs = 4; IsStore = true; break;
9096 case Intrinsic::aarch64_neon_ld2r: NewOpc = AArch64ISD::LD2DUPpost;
9097 NumVecs = 2; IsDupOp = true; break;
9098 case Intrinsic::aarch64_neon_ld3r: NewOpc = AArch64ISD::LD3DUPpost;
9099 NumVecs = 3; IsDupOp = true; break;
9100 case Intrinsic::aarch64_neon_ld4r: NewOpc = AArch64ISD::LD4DUPpost;
9101 NumVecs = 4; IsDupOp = true; break;
9102 case Intrinsic::aarch64_neon_ld2lane: NewOpc = AArch64ISD::LD2LANEpost;
9103 NumVecs = 2; IsLaneOp = true; break;
9104 case Intrinsic::aarch64_neon_ld3lane: NewOpc = AArch64ISD::LD3LANEpost;
9105 NumVecs = 3; IsLaneOp = true; break;
9106 case Intrinsic::aarch64_neon_ld4lane: NewOpc = AArch64ISD::LD4LANEpost;
9107 NumVecs = 4; IsLaneOp = true; break;
9108 case Intrinsic::aarch64_neon_st2lane: NewOpc = AArch64ISD::ST2LANEpost;
9109 NumVecs = 2; IsStore = true; IsLaneOp = true; break;
9110 case Intrinsic::aarch64_neon_st3lane: NewOpc = AArch64ISD::ST3LANEpost;
9111 NumVecs = 3; IsStore = true; IsLaneOp = true; break;
9112 case Intrinsic::aarch64_neon_st4lane: NewOpc = AArch64ISD::ST4LANEpost;
9113 NumVecs = 4; IsStore = true; IsLaneOp = true; break;
9118 VecTy = N->getOperand(2).getValueType();
9120 VecTy = N->getValueType(0);
9122 // If the increment is a constant, it must match the memory ref size.
9123 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9124 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9125 uint32_t IncVal = CInc->getZExtValue();
9126 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9127 if (IsLaneOp || IsDupOp)
9128 NumBytes /= VecTy.getVectorNumElements();
9129 if (IncVal != NumBytes)
9131 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
9133 SmallVector<SDValue, 8> Ops;
9134 Ops.push_back(N->getOperand(0)); // Incoming chain
9135 // Load lane and store have vector list as input.
9136 if (IsLaneOp || IsStore)
9137 for (unsigned i = 2; i < AddrOpIdx; ++i)
9138 Ops.push_back(N->getOperand(i));
9139 Ops.push_back(Addr); // Base register
9144 unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
9146 for (n = 0; n < NumResultVecs; ++n)
9148 Tys[n++] = MVT::i64; // Type of write back register
9149 Tys[n] = MVT::Other; // Type of the chain
9150 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
9152 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9153 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
9154 MemInt->getMemoryVT(),
9155 MemInt->getMemOperand());
9158 std::vector<SDValue> NewResults;
9159 for (unsigned i = 0; i < NumResultVecs; ++i) {
9160 NewResults.push_back(SDValue(UpdN.getNode(), i));
9162 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
9163 DCI.CombineTo(N, NewResults);
9164 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9171 // Checks to see if the value is the prescribed width and returns information
9172 // about its extension mode.
9174 bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
9175 ExtType = ISD::NON_EXTLOAD;
9176 switch(V.getNode()->getOpcode()) {
9180 LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
9181 if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
9182 || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
9183 ExtType = LoadNode->getExtensionType();
9188 case ISD::AssertSext: {
9189 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9190 if ((TypeNode->getVT() == MVT::i8 && width == 8)
9191 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9192 ExtType = ISD::SEXTLOAD;
9197 case ISD::AssertZext: {
9198 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9199 if ((TypeNode->getVT() == MVT::i8 && width == 8)
9200 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9201 ExtType = ISD::ZEXTLOAD;
9207 case ISD::TargetConstant: {
9208 if (std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
9218 // This function does a whole lot of voodoo to determine if the tests are
9219 // equivalent without and with a mask. Essentially what happens is that given a
9222 // +-------------+ +-------------+ +-------------+ +-------------+
9223 // | Input | | AddConstant | | CompConstant| | CC |
9224 // +-------------+ +-------------+ +-------------+ +-------------+
9226 // V V | +----------+
9227 // +-------------+ +----+ | |
9228 // | ADD | |0xff| | |
9229 // +-------------+ +----+ | |
9232 // +-------------+ | |
9234 // +-------------+ | |
9243 // The AND node may be safely removed for some combinations of inputs. In
9244 // particular we need to take into account the extension type of the Input,
9245 // the exact values of AddConstant, CompConstant, and CC, along with the nominal
9246 // width of the input (this can work for any width inputs, the above graph is
9247 // specific to 8 bits.
9249 // The specific equations were worked out by generating output tables for each
9250 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
9251 // problem was simplified by working with 4 bit inputs, which means we only
9252 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
9253 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
9254 // patterns present in both extensions (0,7). For every distinct set of
9255 // AddConstant and CompConstants bit patterns we can consider the masked and
9256 // unmasked versions to be equivalent if the result of this function is true for
9257 // all 16 distinct bit patterns of for the current extension type of Input (w0).
9260 // and w10, w8, #0x0f
9262 // cset w9, AArch64CC
9264 // cset w11, AArch64CC
9269 // Since the above function shows when the outputs are equivalent it defines
9270 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
9271 // would be expensive to run during compiles. The equations below were written
9272 // in a test harness that confirmed they gave equivalent outputs to the above
9273 // for all inputs function, so they can be used determine if the removal is
9276 // isEquivalentMaskless() is the code for testing if the AND can be removed
9277 // factored out of the DAG recognition as the DAG can take several forms.
9280 bool isEquivalentMaskless(unsigned CC, unsigned width,
9281 ISD::LoadExtType ExtType, signed AddConstant,
9282 signed CompConstant) {
9283 // By being careful about our equations and only writing the in term
9284 // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
9285 // make them generally applicable to all bit widths.
9286 signed MaxUInt = (1 << width);
9288 // For the purposes of these comparisons sign extending the type is
9289 // equivalent to zero extending the add and displacing it by half the integer
9290 // width. Provided we are careful and make sure our equations are valid over
9291 // the whole range we can just adjust the input and avoid writing equations
9292 // for sign extended inputs.
9293 if (ExtType == ISD::SEXTLOAD)
9294 AddConstant -= (1 << (width-1));
9298 case AArch64CC::GT: {
9299 if ((AddConstant == 0) ||
9300 (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
9301 (AddConstant >= 0 && CompConstant < 0) ||
9302 (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
9306 case AArch64CC::GE: {
9307 if ((AddConstant == 0) ||
9308 (AddConstant >= 0 && CompConstant <= 0) ||
9309 (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
9313 case AArch64CC::LS: {
9314 if ((AddConstant >= 0 && CompConstant < 0) ||
9315 (AddConstant <= 0 && CompConstant >= -1 &&
9316 CompConstant < AddConstant + MaxUInt))
9320 case AArch64CC::MI: {
9321 if ((AddConstant == 0) ||
9322 (AddConstant > 0 && CompConstant <= 0) ||
9323 (AddConstant < 0 && CompConstant <= AddConstant))
9327 case AArch64CC::HS: {
9328 if ((AddConstant >= 0 && CompConstant <= 0) ||
9329 (AddConstant <= 0 && CompConstant >= 0 &&
9330 CompConstant <= AddConstant + MaxUInt))
9334 case AArch64CC::NE: {
9335 if ((AddConstant > 0 && CompConstant < 0) ||
9336 (AddConstant < 0 && CompConstant >= 0 &&
9337 CompConstant < AddConstant + MaxUInt) ||
9338 (AddConstant >= 0 && CompConstant >= 0 &&
9339 CompConstant >= AddConstant) ||
9340 (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
9349 case AArch64CC::Invalid:
9357 SDValue performCONDCombine(SDNode *N,
9358 TargetLowering::DAGCombinerInfo &DCI,
9359 SelectionDAG &DAG, unsigned CCIndex,
9360 unsigned CmpIndex) {
9361 unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
9362 SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
9363 unsigned CondOpcode = SubsNode->getOpcode();
9365 if (CondOpcode != AArch64ISD::SUBS)
9368 // There is a SUBS feeding this condition. Is it fed by a mask we can
9371 SDNode *AndNode = SubsNode->getOperand(0).getNode();
9372 unsigned MaskBits = 0;
9374 if (AndNode->getOpcode() != ISD::AND)
9377 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
9378 uint32_t CNV = CN->getZExtValue();
9381 else if (CNV == 65535)
9388 SDValue AddValue = AndNode->getOperand(0);
9390 if (AddValue.getOpcode() != ISD::ADD)
9393 // The basic dag structure is correct, grab the inputs and validate them.
9395 SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
9396 SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
9397 SDValue SubsInputValue = SubsNode->getOperand(1);
9399 // The mask is present and the provenance of all the values is a smaller type,
9400 // lets see if the mask is superfluous.
9402 if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
9403 !isa<ConstantSDNode>(SubsInputValue.getNode()))
9406 ISD::LoadExtType ExtType;
9408 if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
9409 !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
9410 !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
9413 if(!isEquivalentMaskless(CC, MaskBits, ExtType,
9414 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
9415 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
9418 // The AND is not necessary, remove it.
9420 SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
9421 SubsNode->getValueType(1));
9422 SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
9424 SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
9425 DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
9427 return SDValue(N, 0);
9430 // Optimize compare with zero and branch.
9431 static SDValue performBRCONDCombine(SDNode *N,
9432 TargetLowering::DAGCombinerInfo &DCI,
9433 SelectionDAG &DAG) {
9434 SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3);
9437 SDValue Chain = N->getOperand(0);
9438 SDValue Dest = N->getOperand(1);
9439 SDValue CCVal = N->getOperand(2);
9440 SDValue Cmp = N->getOperand(3);
9442 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
9443 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
9444 if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
9447 unsigned CmpOpc = Cmp.getOpcode();
9448 if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
9451 // Only attempt folding if there is only one use of the flag and no use of the
9453 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
9456 SDValue LHS = Cmp.getOperand(0);
9457 SDValue RHS = Cmp.getOperand(1);
9459 assert(LHS.getValueType() == RHS.getValueType() &&
9460 "Expected the value type to be the same for both operands!");
9461 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
9464 if (isNullConstant(LHS))
9465 std::swap(LHS, RHS);
9467 if (!isNullConstant(RHS))
9470 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
9471 LHS.getOpcode() == ISD::SRL)
9474 // Fold the compare into the branch instruction.
9476 if (CC == AArch64CC::EQ)
9477 BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9479 BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9481 // Do not add new nodes to DAG combiner worklist.
9482 DCI.CombineTo(N, BR, false);
9487 // vselect (v1i1 setcc) ->
9488 // vselect (v1iXX setcc) (XX is the size of the compared operand type)
9489 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
9490 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
9492 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
9493 SDValue N0 = N->getOperand(0);
9494 EVT CCVT = N0.getValueType();
9496 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
9497 CCVT.getVectorElementType() != MVT::i1)
9500 EVT ResVT = N->getValueType(0);
9501 EVT CmpVT = N0.getOperand(0).getValueType();
9502 // Only combine when the result type is of the same size as the compared
9504 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
9507 SDValue IfTrue = N->getOperand(1);
9508 SDValue IfFalse = N->getOperand(2);
9510 DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
9511 N0.getOperand(0), N0.getOperand(1),
9512 cast<CondCodeSDNode>(N0.getOperand(2))->get());
9513 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
9517 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
9518 /// the compare-mask instructions rather than going via NZCV, even if LHS and
9519 /// RHS are really scalar. This replaces any scalar setcc in the above pattern
9520 /// with a vector one followed by a DUP shuffle on the result.
9521 static SDValue performSelectCombine(SDNode *N,
9522 TargetLowering::DAGCombinerInfo &DCI) {
9523 SelectionDAG &DAG = DCI.DAG;
9524 SDValue N0 = N->getOperand(0);
9525 EVT ResVT = N->getValueType(0);
9527 if (N0.getOpcode() != ISD::SETCC)
9530 // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
9531 // scalar SetCCResultType. We also don't expect vectors, because we assume
9532 // that selects fed by vector SETCCs are canonicalized to VSELECT.
9533 assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
9534 "Scalar-SETCC feeding SELECT has unexpected result type!");
9536 // If NumMaskElts == 0, the comparison is larger than select result. The
9537 // largest real NEON comparison is 64-bits per lane, which means the result is
9538 // at most 32-bits and an illegal vector. Just bail out for now.
9539 EVT SrcVT = N0.getOperand(0).getValueType();
9541 // Don't try to do this optimization when the setcc itself has i1 operands.
9542 // There are no legal vectors of i1, so this would be pointless.
9543 if (SrcVT == MVT::i1)
9546 int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
9547 if (!ResVT.isVector() || NumMaskElts == 0)
9550 SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
9551 EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
9553 // Also bail out if the vector CCVT isn't the same size as ResVT.
9554 // This can happen if the SETCC operand size doesn't divide the ResVT size
9555 // (e.g., f64 vs v3f32).
9556 if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
9559 // Make sure we didn't create illegal types, if we're not supposed to.
9560 assert(DCI.isBeforeLegalize() ||
9561 DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
9563 // First perform a vector comparison, where lane 0 is the one we're interested
9567 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
9569 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
9570 SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
9572 // Now duplicate the comparison mask we want across all other lanes.
9573 SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
9574 SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask.data());
9575 Mask = DAG.getNode(ISD::BITCAST, DL,
9576 ResVT.changeVectorElementTypeToInteger(), Mask);
9578 return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
9581 /// Get rid of unnecessary NVCASTs (that don't change the type).
9582 static SDValue performNVCASTCombine(SDNode *N) {
9583 if (N->getValueType(0) == N->getOperand(0).getValueType())
9584 return N->getOperand(0);
9589 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
9590 DAGCombinerInfo &DCI) const {
9591 SelectionDAG &DAG = DCI.DAG;
9592 switch (N->getOpcode()) {
9597 return performAddSubLongCombine(N, DCI, DAG);
9599 return performXorCombine(N, DAG, DCI, Subtarget);
9601 return performMulCombine(N, DAG, DCI, Subtarget);
9602 case ISD::SINT_TO_FP:
9603 case ISD::UINT_TO_FP:
9604 return performIntToFpCombine(N, DAG, Subtarget);
9605 case ISD::FP_TO_SINT:
9606 case ISD::FP_TO_UINT:
9607 return performFpToIntCombine(N, DAG, Subtarget);
9609 return performFDivCombine(N, DAG, Subtarget);
9611 return performORCombine(N, DCI, Subtarget);
9612 case ISD::INTRINSIC_WO_CHAIN:
9613 return performIntrinsicCombine(N, DCI, Subtarget);
9614 case ISD::ANY_EXTEND:
9615 case ISD::ZERO_EXTEND:
9616 case ISD::SIGN_EXTEND:
9617 return performExtendCombine(N, DCI, DAG);
9619 return performBitcastCombine(N, DCI, DAG);
9620 case ISD::CONCAT_VECTORS:
9621 return performConcatVectorsCombine(N, DCI, DAG);
9623 SDValue RV = performSelectCombine(N, DCI);
9625 RV = performAcrossLaneMinMaxReductionCombine(N, DAG, Subtarget);
9629 return performVSelectCombine(N, DCI.DAG);
9631 if (performTBISimplification(N->getOperand(1), DCI, DAG))
9632 return SDValue(N, 0);
9635 return performSTORECombine(N, DCI, DAG, Subtarget);
9636 case AArch64ISD::BRCOND:
9637 return performBRCONDCombine(N, DCI, DAG);
9638 case AArch64ISD::CSEL:
9639 return performCONDCombine(N, DCI, DAG, 2, 3);
9640 case AArch64ISD::DUP:
9641 return performPostLD1Combine(N, DCI, false);
9642 case AArch64ISD::NVCAST:
9643 return performNVCASTCombine(N);
9644 case ISD::INSERT_VECTOR_ELT:
9645 return performPostLD1Combine(N, DCI, true);
9646 case ISD::EXTRACT_VECTOR_ELT:
9647 return performAcrossLaneAddReductionCombine(N, DAG, Subtarget);
9648 case ISD::INTRINSIC_VOID:
9649 case ISD::INTRINSIC_W_CHAIN:
9650 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9651 case Intrinsic::aarch64_neon_ld2:
9652 case Intrinsic::aarch64_neon_ld3:
9653 case Intrinsic::aarch64_neon_ld4:
9654 case Intrinsic::aarch64_neon_ld1x2:
9655 case Intrinsic::aarch64_neon_ld1x3:
9656 case Intrinsic::aarch64_neon_ld1x4:
9657 case Intrinsic::aarch64_neon_ld2lane:
9658 case Intrinsic::aarch64_neon_ld3lane:
9659 case Intrinsic::aarch64_neon_ld4lane:
9660 case Intrinsic::aarch64_neon_ld2r:
9661 case Intrinsic::aarch64_neon_ld3r:
9662 case Intrinsic::aarch64_neon_ld4r:
9663 case Intrinsic::aarch64_neon_st2:
9664 case Intrinsic::aarch64_neon_st3:
9665 case Intrinsic::aarch64_neon_st4:
9666 case Intrinsic::aarch64_neon_st1x2:
9667 case Intrinsic::aarch64_neon_st1x3:
9668 case Intrinsic::aarch64_neon_st1x4:
9669 case Intrinsic::aarch64_neon_st2lane:
9670 case Intrinsic::aarch64_neon_st3lane:
9671 case Intrinsic::aarch64_neon_st4lane:
9672 return performNEONPostLDSTCombine(N, DCI, DAG);
9680 // Check if the return value is used as only a return value, as otherwise
9681 // we can't perform a tail-call. In particular, we need to check for
9682 // target ISD nodes that are returns and any other "odd" constructs
9683 // that the generic analysis code won't necessarily catch.
9684 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
9685 SDValue &Chain) const {
9686 if (N->getNumValues() != 1)
9688 if (!N->hasNUsesOfValue(1, 0))
9691 SDValue TCChain = Chain;
9692 SDNode *Copy = *N->use_begin();
9693 if (Copy->getOpcode() == ISD::CopyToReg) {
9694 // If the copy has a glue operand, we conservatively assume it isn't safe to
9695 // perform a tail call.
9696 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
9699 TCChain = Copy->getOperand(0);
9700 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
9703 bool HasRet = false;
9704 for (SDNode *Node : Copy->uses()) {
9705 if (Node->getOpcode() != AArch64ISD::RET_FLAG)
9717 // Return whether the an instruction can potentially be optimized to a tail
9718 // call. This will cause the optimizers to attempt to move, or duplicate,
9719 // return instructions to help enable tail call optimizations for this
9721 bool AArch64TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
9722 if (!CI->isTailCall())
9728 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
9730 ISD::MemIndexedMode &AM,
9732 SelectionDAG &DAG) const {
9733 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
9736 Base = Op->getOperand(0);
9737 // All of the indexed addressing mode instructions take a signed
9738 // 9 bit immediate offset.
9739 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
9740 int64_t RHSC = (int64_t)RHS->getZExtValue();
9741 if (RHSC >= 256 || RHSC <= -256)
9743 IsInc = (Op->getOpcode() == ISD::ADD);
9744 Offset = Op->getOperand(1);
9750 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
9752 ISD::MemIndexedMode &AM,
9753 SelectionDAG &DAG) const {
9756 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9757 VT = LD->getMemoryVT();
9758 Ptr = LD->getBasePtr();
9759 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9760 VT = ST->getMemoryVT();
9761 Ptr = ST->getBasePtr();
9766 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
9768 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
9772 bool AArch64TargetLowering::getPostIndexedAddressParts(
9773 SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
9774 ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
9777 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9778 VT = LD->getMemoryVT();
9779 Ptr = LD->getBasePtr();
9780 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9781 VT = ST->getMemoryVT();
9782 Ptr = ST->getBasePtr();
9787 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
9789 // Post-indexing updates the base, so it's not a valid transform
9790 // if that's not the same as the load's pointer.
9793 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
9797 static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
9798 SelectionDAG &DAG) {
9800 SDValue Op = N->getOperand(0);
9802 if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
9806 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
9807 DAG.getUNDEF(MVT::i32), Op,
9808 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
9810 Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
9811 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
9814 static void ReplaceReductionResults(SDNode *N,
9815 SmallVectorImpl<SDValue> &Results,
9816 SelectionDAG &DAG, unsigned InterOp,
9817 unsigned AcrossOp) {
9821 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
9822 std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
9823 SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
9824 SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
9825 Results.push_back(SplitVal);
9828 void AArch64TargetLowering::ReplaceNodeResults(
9829 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
9830 switch (N->getOpcode()) {
9832 llvm_unreachable("Don't know how to custom expand this");
9834 ReplaceBITCASTResults(N, Results, DAG);
9836 case AArch64ISD::SADDV:
9837 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
9839 case AArch64ISD::UADDV:
9840 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
9842 case AArch64ISD::SMINV:
9843 ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
9845 case AArch64ISD::UMINV:
9846 ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
9848 case AArch64ISD::SMAXV:
9849 ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
9851 case AArch64ISD::UMAXV:
9852 ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
9854 case ISD::FP_TO_UINT:
9855 case ISD::FP_TO_SINT:
9856 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
9857 // Let normal code take care of it by not adding anything to Results.
9862 bool AArch64TargetLowering::useLoadStackGuardNode() const {
9866 unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
9867 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
9868 // reciprocal if there are three or more FDIVs.
9872 TargetLoweringBase::LegalizeTypeAction
9873 AArch64TargetLowering::getPreferredVectorAction(EVT VT) const {
9874 MVT SVT = VT.getSimpleVT();
9875 // During type legalization, we prefer to widen v1i8, v1i16, v1i32 to v8i8,
9876 // v4i16, v2i32 instead of to promote.
9877 if (SVT == MVT::v1i8 || SVT == MVT::v1i16 || SVT == MVT::v1i32
9878 || SVT == MVT::v1f32)
9879 return TypeWidenVector;
9881 return TargetLoweringBase::getPreferredVectorAction(VT);
9884 // Loads and stores less than 128-bits are already atomic; ones above that
9885 // are doomed anyway, so defer to the default libcall and blame the OS when
9887 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
9888 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
9892 // Loads and stores less than 128-bits are already atomic; ones above that
9893 // are doomed anyway, so defer to the default libcall and blame the OS when
9895 TargetLowering::AtomicExpansionKind
9896 AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
9897 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
9898 return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
9901 // For the real atomic operations, we have ldxr/stxr up to 128 bits,
9902 TargetLowering::AtomicExpansionKind
9903 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
9904 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
9905 return Size <= 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
9908 bool AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
9909 AtomicCmpXchgInst *AI) const {
9913 Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
9914 AtomicOrdering Ord) const {
9915 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
9916 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
9917 bool IsAcquire = isAtLeastAcquire(Ord);
9919 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
9920 // intrinsic must return {i64, i64} and we have to recombine them into a
9921 // single i128 here.
9922 if (ValTy->getPrimitiveSizeInBits() == 128) {
9924 IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
9925 Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int);
9927 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
9928 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
9930 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
9931 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
9932 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
9933 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
9934 return Builder.CreateOr(
9935 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
9938 Type *Tys[] = { Addr->getType() };
9940 IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
9941 Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int, Tys);
9943 return Builder.CreateTruncOrBitCast(
9944 Builder.CreateCall(Ldxr, Addr),
9945 cast<PointerType>(Addr->getType())->getElementType());
9948 void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
9949 IRBuilder<> &Builder) const {
9950 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
9952 llvm::Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
9955 Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
9956 Value *Val, Value *Addr,
9957 AtomicOrdering Ord) const {
9958 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
9959 bool IsRelease = isAtLeastRelease(Ord);
9961 // Since the intrinsics must have legal type, the i128 intrinsics take two
9962 // parameters: "i64, i64". We must marshal Val into the appropriate form
9964 if (Val->getType()->getPrimitiveSizeInBits() == 128) {
9966 IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
9967 Function *Stxr = Intrinsic::getDeclaration(M, Int);
9968 Type *Int64Ty = Type::getInt64Ty(M->getContext());
9970 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
9971 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
9972 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
9973 return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
9977 IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
9978 Type *Tys[] = { Addr->getType() };
9979 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
9981 return Builder.CreateCall(Stxr,
9982 {Builder.CreateZExtOrBitCast(
9983 Val, Stxr->getFunctionType()->getParamType(0)),
9987 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
9988 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
9989 return Ty->isArrayTy();
9992 bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
9997 Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
9998 if (!Subtarget->isTargetAndroid())
9999 return TargetLowering::getSafeStackPointerLocation(IRB);
10001 // Android provides a fixed TLS slot for the SafeStack pointer. See the
10002 // definition of TLS_SLOT_SAFESTACK in
10003 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
10004 const unsigned TlsOffset = 0x48;
10005 Module *M = IRB.GetInsertBlock()->getParent()->getParent();
10006 Function *ThreadPointerFunc =
10007 Intrinsic::getDeclaration(M, Intrinsic::aarch64_thread_pointer);
10008 return IRB.CreatePointerCast(
10009 IRB.CreateConstGEP1_32(IRB.CreateCall(ThreadPointerFunc), TlsOffset),
10010 Type::getInt8PtrTy(IRB.getContext())->getPointerTo(0));