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 "AArch64RegisterInfo.h"
19 #include "AArch64Subtarget.h"
20 #include "MCTargetDesc/AArch64AddressingModes.h"
21 #include "Utils/AArch64BaseInfo.h"
22 #include "llvm/ADT/APFloat.h"
23 #include "llvm/ADT/APInt.h"
24 #include "llvm/ADT/ArrayRef.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/ADT/StringRef.h"
29 #include "llvm/ADT/StringSwitch.h"
30 #include "llvm/ADT/Triple.h"
31 #include "llvm/ADT/Twine.h"
32 #include "llvm/Analysis/VectorUtils.h"
33 #include "llvm/CodeGen/CallingConvLower.h"
34 #include "llvm/CodeGen/MachineBasicBlock.h"
35 #include "llvm/CodeGen/MachineFrameInfo.h"
36 #include "llvm/CodeGen/MachineFunction.h"
37 #include "llvm/CodeGen/MachineInstr.h"
38 #include "llvm/CodeGen/MachineInstrBuilder.h"
39 #include "llvm/CodeGen/MachineMemOperand.h"
40 #include "llvm/CodeGen/MachineRegisterInfo.h"
41 #include "llvm/CodeGen/MachineValueType.h"
42 #include "llvm/CodeGen/RuntimeLibcalls.h"
43 #include "llvm/CodeGen/SelectionDAG.h"
44 #include "llvm/CodeGen/SelectionDAGNodes.h"
45 #include "llvm/CodeGen/TargetCallingConv.h"
46 #include "llvm/CodeGen/TargetInstrInfo.h"
47 #include "llvm/CodeGen/ValueTypes.h"
48 #include "llvm/IR/Attributes.h"
49 #include "llvm/IR/Constants.h"
50 #include "llvm/IR/DataLayout.h"
51 #include "llvm/IR/DebugLoc.h"
52 #include "llvm/IR/DerivedTypes.h"
53 #include "llvm/IR/Function.h"
54 #include "llvm/IR/GetElementPtrTypeIterator.h"
55 #include "llvm/IR/GlobalValue.h"
56 #include "llvm/IR/IRBuilder.h"
57 #include "llvm/IR/Instruction.h"
58 #include "llvm/IR/Instructions.h"
59 #include "llvm/IR/Intrinsics.h"
60 #include "llvm/IR/Module.h"
61 #include "llvm/IR/OperandTraits.h"
62 #include "llvm/IR/Type.h"
63 #include "llvm/IR/Use.h"
64 #include "llvm/IR/Value.h"
65 #include "llvm/MC/MCRegisterInfo.h"
66 #include "llvm/Support/Casting.h"
67 #include "llvm/Support/CodeGen.h"
68 #include "llvm/Support/CommandLine.h"
69 #include "llvm/Support/Compiler.h"
70 #include "llvm/Support/Debug.h"
71 #include "llvm/Support/ErrorHandling.h"
72 #include "llvm/Support/KnownBits.h"
73 #include "llvm/Support/MathExtras.h"
74 #include "llvm/Support/raw_ostream.h"
75 #include "llvm/Target/TargetMachine.h"
76 #include "llvm/Target/TargetOptions.h"
91 #define DEBUG_TYPE "aarch64-lower"
93 STATISTIC(NumTailCalls, "Number of tail calls");
94 STATISTIC(NumShiftInserts, "Number of vector shift inserts");
95 STATISTIC(NumOptimizedImms, "Number of times immediates were optimized");
98 EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden,
99 cl::desc("Allow AArch64 SLI/SRI formation"),
102 // FIXME: The necessary dtprel relocations don't seem to be supported
103 // well in the GNU bfd and gold linkers at the moment. Therefore, by
104 // default, for now, fall back to GeneralDynamic code generation.
105 cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration(
106 "aarch64-elf-ldtls-generation", cl::Hidden,
107 cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
111 EnableOptimizeLogicalImm("aarch64-enable-logical-imm", cl::Hidden,
112 cl::desc("Enable AArch64 logical imm instruction "
116 /// Value type used for condition codes.
117 static const MVT MVT_CC = MVT::i32;
119 AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
120 const AArch64Subtarget &STI)
121 : TargetLowering(TM), Subtarget(&STI) {
122 // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
123 // we have to make something up. Arbitrarily, choose ZeroOrOne.
124 setBooleanContents(ZeroOrOneBooleanContent);
125 // When comparing vectors the result sets the different elements in the
126 // vector to all-one or all-zero.
127 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
129 // Set up the register classes.
130 addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
131 addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
133 if (Subtarget->hasFPARMv8()) {
134 addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
135 addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
136 addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
137 addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
140 if (Subtarget->hasNEON()) {
141 addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
142 addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
143 // Someone set us up the NEON.
144 addDRTypeForNEON(MVT::v2f32);
145 addDRTypeForNEON(MVT::v8i8);
146 addDRTypeForNEON(MVT::v4i16);
147 addDRTypeForNEON(MVT::v2i32);
148 addDRTypeForNEON(MVT::v1i64);
149 addDRTypeForNEON(MVT::v1f64);
150 addDRTypeForNEON(MVT::v4f16);
152 addQRTypeForNEON(MVT::v4f32);
153 addQRTypeForNEON(MVT::v2f64);
154 addQRTypeForNEON(MVT::v16i8);
155 addQRTypeForNEON(MVT::v8i16);
156 addQRTypeForNEON(MVT::v4i32);
157 addQRTypeForNEON(MVT::v2i64);
158 addQRTypeForNEON(MVT::v8f16);
161 // Compute derived properties from the register classes
162 computeRegisterProperties(Subtarget->getRegisterInfo());
164 // Provide all sorts of operation actions
165 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
166 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
167 setOperationAction(ISD::SETCC, MVT::i32, Custom);
168 setOperationAction(ISD::SETCC, MVT::i64, Custom);
169 setOperationAction(ISD::SETCC, MVT::f16, Custom);
170 setOperationAction(ISD::SETCC, MVT::f32, Custom);
171 setOperationAction(ISD::SETCC, MVT::f64, Custom);
172 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
173 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
174 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
175 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
176 setOperationAction(ISD::BR_CC, MVT::i64, Custom);
177 setOperationAction(ISD::BR_CC, MVT::f16, Custom);
178 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
179 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
180 setOperationAction(ISD::SELECT, MVT::i32, Custom);
181 setOperationAction(ISD::SELECT, MVT::i64, Custom);
182 setOperationAction(ISD::SELECT, MVT::f16, Custom);
183 setOperationAction(ISD::SELECT, MVT::f32, Custom);
184 setOperationAction(ISD::SELECT, MVT::f64, Custom);
185 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
186 setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
187 setOperationAction(ISD::SELECT_CC, MVT::f16, Custom);
188 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
189 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
190 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
191 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
193 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
194 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
195 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
197 setOperationAction(ISD::FREM, MVT::f32, Expand);
198 setOperationAction(ISD::FREM, MVT::f64, Expand);
199 setOperationAction(ISD::FREM, MVT::f80, Expand);
201 // Custom lowering hooks are needed for XOR
202 // to fold it into CSINC/CSINV.
203 setOperationAction(ISD::XOR, MVT::i32, Custom);
204 setOperationAction(ISD::XOR, MVT::i64, Custom);
206 // Virtually no operation on f128 is legal, but LLVM can't expand them when
207 // there's a valid register class, so we need custom operations in most cases.
208 setOperationAction(ISD::FABS, MVT::f128, Expand);
209 setOperationAction(ISD::FADD, MVT::f128, Custom);
210 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
211 setOperationAction(ISD::FCOS, MVT::f128, Expand);
212 setOperationAction(ISD::FDIV, MVT::f128, Custom);
213 setOperationAction(ISD::FMA, MVT::f128, Expand);
214 setOperationAction(ISD::FMUL, MVT::f128, Custom);
215 setOperationAction(ISD::FNEG, MVT::f128, Expand);
216 setOperationAction(ISD::FPOW, MVT::f128, Expand);
217 setOperationAction(ISD::FREM, MVT::f128, Expand);
218 setOperationAction(ISD::FRINT, MVT::f128, Expand);
219 setOperationAction(ISD::FSIN, MVT::f128, Expand);
220 setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
221 setOperationAction(ISD::FSQRT, MVT::f128, Expand);
222 setOperationAction(ISD::FSUB, MVT::f128, Custom);
223 setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
224 setOperationAction(ISD::SETCC, MVT::f128, Custom);
225 setOperationAction(ISD::BR_CC, MVT::f128, Custom);
226 setOperationAction(ISD::SELECT, MVT::f128, Custom);
227 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
228 setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
230 // Lowering for many of the conversions is actually specified by the non-f128
231 // type. The LowerXXX function will be trivial when f128 isn't involved.
232 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
233 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
234 setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
235 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
236 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
237 setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
238 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
239 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
240 setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
241 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
242 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
243 setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
244 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
245 setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
247 // Variable arguments.
248 setOperationAction(ISD::VASTART, MVT::Other, Custom);
249 setOperationAction(ISD::VAARG, MVT::Other, Custom);
250 setOperationAction(ISD::VACOPY, MVT::Other, Custom);
251 setOperationAction(ISD::VAEND, MVT::Other, Expand);
253 // Variable-sized objects.
254 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
255 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
256 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
258 // Constant pool entries
259 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
262 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
264 // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
265 setOperationAction(ISD::ADDC, MVT::i32, Custom);
266 setOperationAction(ISD::ADDE, MVT::i32, Custom);
267 setOperationAction(ISD::SUBC, MVT::i32, Custom);
268 setOperationAction(ISD::SUBE, MVT::i32, Custom);
269 setOperationAction(ISD::ADDC, MVT::i64, Custom);
270 setOperationAction(ISD::ADDE, MVT::i64, Custom);
271 setOperationAction(ISD::SUBC, MVT::i64, Custom);
272 setOperationAction(ISD::SUBE, MVT::i64, Custom);
274 // AArch64 lacks both left-rotate and popcount instructions.
275 setOperationAction(ISD::ROTL, MVT::i32, Expand);
276 setOperationAction(ISD::ROTL, MVT::i64, Expand);
277 for (MVT VT : MVT::vector_valuetypes()) {
278 setOperationAction(ISD::ROTL, VT, Expand);
279 setOperationAction(ISD::ROTR, VT, Expand);
282 // AArch64 doesn't have {U|S}MUL_LOHI.
283 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
284 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
286 setOperationAction(ISD::CTPOP, MVT::i32, Custom);
287 setOperationAction(ISD::CTPOP, MVT::i64, Custom);
289 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
290 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
291 for (MVT VT : MVT::vector_valuetypes()) {
292 setOperationAction(ISD::SDIVREM, VT, Expand);
293 setOperationAction(ISD::UDIVREM, VT, Expand);
295 setOperationAction(ISD::SREM, MVT::i32, Expand);
296 setOperationAction(ISD::SREM, MVT::i64, Expand);
297 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
298 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
299 setOperationAction(ISD::UREM, MVT::i32, Expand);
300 setOperationAction(ISD::UREM, MVT::i64, Expand);
302 // Custom lower Add/Sub/Mul with overflow.
303 setOperationAction(ISD::SADDO, MVT::i32, Custom);
304 setOperationAction(ISD::SADDO, MVT::i64, Custom);
305 setOperationAction(ISD::UADDO, MVT::i32, Custom);
306 setOperationAction(ISD::UADDO, MVT::i64, Custom);
307 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
308 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
309 setOperationAction(ISD::USUBO, MVT::i32, Custom);
310 setOperationAction(ISD::USUBO, MVT::i64, Custom);
311 setOperationAction(ISD::SMULO, MVT::i32, Custom);
312 setOperationAction(ISD::SMULO, MVT::i64, Custom);
313 setOperationAction(ISD::UMULO, MVT::i32, Custom);
314 setOperationAction(ISD::UMULO, MVT::i64, Custom);
316 setOperationAction(ISD::FSIN, MVT::f32, Expand);
317 setOperationAction(ISD::FSIN, MVT::f64, Expand);
318 setOperationAction(ISD::FCOS, MVT::f32, Expand);
319 setOperationAction(ISD::FCOS, MVT::f64, Expand);
320 setOperationAction(ISD::FPOW, MVT::f32, Expand);
321 setOperationAction(ISD::FPOW, MVT::f64, Expand);
322 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
323 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
324 if (Subtarget->hasFullFP16())
325 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Custom);
327 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote);
329 setOperationAction(ISD::FREM, MVT::f16, Promote);
330 setOperationAction(ISD::FREM, MVT::v4f16, Promote);
331 setOperationAction(ISD::FREM, MVT::v8f16, Promote);
332 setOperationAction(ISD::FPOW, MVT::f16, Promote);
333 setOperationAction(ISD::FPOW, MVT::v4f16, Promote);
334 setOperationAction(ISD::FPOW, MVT::v8f16, Promote);
335 setOperationAction(ISD::FPOWI, MVT::f16, Promote);
336 setOperationAction(ISD::FCOS, MVT::f16, Promote);
337 setOperationAction(ISD::FCOS, MVT::v4f16, Promote);
338 setOperationAction(ISD::FCOS, MVT::v8f16, Promote);
339 setOperationAction(ISD::FSIN, MVT::f16, Promote);
340 setOperationAction(ISD::FSIN, MVT::v4f16, Promote);
341 setOperationAction(ISD::FSIN, MVT::v8f16, Promote);
342 setOperationAction(ISD::FSINCOS, MVT::f16, Promote);
343 setOperationAction(ISD::FSINCOS, MVT::v4f16, Promote);
344 setOperationAction(ISD::FSINCOS, MVT::v8f16, Promote);
345 setOperationAction(ISD::FEXP, MVT::f16, Promote);
346 setOperationAction(ISD::FEXP, MVT::v4f16, Promote);
347 setOperationAction(ISD::FEXP, MVT::v8f16, Promote);
348 setOperationAction(ISD::FEXP2, MVT::f16, Promote);
349 setOperationAction(ISD::FEXP2, MVT::v4f16, Promote);
350 setOperationAction(ISD::FEXP2, MVT::v8f16, Promote);
351 setOperationAction(ISD::FLOG, MVT::f16, Promote);
352 setOperationAction(ISD::FLOG, MVT::v4f16, Promote);
353 setOperationAction(ISD::FLOG, MVT::v8f16, Promote);
354 setOperationAction(ISD::FLOG2, MVT::f16, Promote);
355 setOperationAction(ISD::FLOG2, MVT::v4f16, Promote);
356 setOperationAction(ISD::FLOG2, MVT::v8f16, Promote);
357 setOperationAction(ISD::FLOG10, MVT::f16, Promote);
358 setOperationAction(ISD::FLOG10, MVT::v4f16, Promote);
359 setOperationAction(ISD::FLOG10, MVT::v8f16, Promote);
361 if (!Subtarget->hasFullFP16()) {
362 setOperationAction(ISD::SELECT, MVT::f16, Promote);
363 setOperationAction(ISD::SELECT_CC, MVT::f16, Promote);
364 setOperationAction(ISD::SETCC, MVT::f16, Promote);
365 setOperationAction(ISD::BR_CC, MVT::f16, Promote);
366 setOperationAction(ISD::FADD, MVT::f16, Promote);
367 setOperationAction(ISD::FSUB, MVT::f16, Promote);
368 setOperationAction(ISD::FMUL, MVT::f16, Promote);
369 setOperationAction(ISD::FDIV, MVT::f16, Promote);
370 setOperationAction(ISD::FMA, MVT::f16, Promote);
371 setOperationAction(ISD::FNEG, MVT::f16, Promote);
372 setOperationAction(ISD::FABS, MVT::f16, Promote);
373 setOperationAction(ISD::FCEIL, MVT::f16, Promote);
374 setOperationAction(ISD::FSQRT, MVT::f16, Promote);
375 setOperationAction(ISD::FFLOOR, MVT::f16, Promote);
376 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote);
377 setOperationAction(ISD::FRINT, MVT::f16, Promote);
378 setOperationAction(ISD::FROUND, MVT::f16, Promote);
379 setOperationAction(ISD::FTRUNC, MVT::f16, Promote);
380 setOperationAction(ISD::FMINNUM, MVT::f16, Promote);
381 setOperationAction(ISD::FMAXNUM, MVT::f16, Promote);
382 setOperationAction(ISD::FMINNAN, MVT::f16, Promote);
383 setOperationAction(ISD::FMAXNAN, MVT::f16, Promote);
385 // promote v4f16 to v4f32 when that is known to be safe.
386 setOperationAction(ISD::FADD, MVT::v4f16, Promote);
387 setOperationAction(ISD::FSUB, MVT::v4f16, Promote);
388 setOperationAction(ISD::FMUL, MVT::v4f16, Promote);
389 setOperationAction(ISD::FDIV, MVT::v4f16, Promote);
390 setOperationAction(ISD::FP_EXTEND, MVT::v4f16, Promote);
391 setOperationAction(ISD::FP_ROUND, MVT::v4f16, Promote);
392 AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32);
393 AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32);
394 AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32);
395 AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32);
396 AddPromotedToType(ISD::FP_EXTEND, MVT::v4f16, MVT::v4f32);
397 AddPromotedToType(ISD::FP_ROUND, MVT::v4f16, MVT::v4f32);
399 setOperationAction(ISD::FABS, MVT::v4f16, Expand);
400 setOperationAction(ISD::FNEG, MVT::v4f16, Expand);
401 setOperationAction(ISD::FROUND, MVT::v4f16, Expand);
402 setOperationAction(ISD::FMA, MVT::v4f16, Expand);
403 setOperationAction(ISD::SETCC, MVT::v4f16, Expand);
404 setOperationAction(ISD::BR_CC, MVT::v4f16, Expand);
405 setOperationAction(ISD::SELECT, MVT::v4f16, Expand);
406 setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand);
407 setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand);
408 setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand);
409 setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand);
410 setOperationAction(ISD::FCEIL, MVT::v4f16, Expand);
411 setOperationAction(ISD::FRINT, MVT::v4f16, Expand);
412 setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand);
413 setOperationAction(ISD::FSQRT, MVT::v4f16, Expand);
415 setOperationAction(ISD::FABS, MVT::v8f16, Expand);
416 setOperationAction(ISD::FADD, MVT::v8f16, Expand);
417 setOperationAction(ISD::FCEIL, MVT::v8f16, Expand);
418 setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand);
419 setOperationAction(ISD::FDIV, MVT::v8f16, Expand);
420 setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand);
421 setOperationAction(ISD::FMA, MVT::v8f16, Expand);
422 setOperationAction(ISD::FMUL, MVT::v8f16, Expand);
423 setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand);
424 setOperationAction(ISD::FNEG, MVT::v8f16, Expand);
425 setOperationAction(ISD::FROUND, MVT::v8f16, Expand);
426 setOperationAction(ISD::FRINT, MVT::v8f16, Expand);
427 setOperationAction(ISD::FSQRT, MVT::v8f16, Expand);
428 setOperationAction(ISD::FSUB, MVT::v8f16, Expand);
429 setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand);
430 setOperationAction(ISD::SETCC, MVT::v8f16, Expand);
431 setOperationAction(ISD::BR_CC, MVT::v8f16, Expand);
432 setOperationAction(ISD::SELECT, MVT::v8f16, Expand);
433 setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand);
434 setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand);
437 // AArch64 has implementations of a lot of rounding-like FP operations.
438 for (MVT Ty : {MVT::f32, MVT::f64}) {
439 setOperationAction(ISD::FFLOOR, Ty, Legal);
440 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
441 setOperationAction(ISD::FCEIL, Ty, Legal);
442 setOperationAction(ISD::FRINT, Ty, Legal);
443 setOperationAction(ISD::FTRUNC, Ty, Legal);
444 setOperationAction(ISD::FROUND, Ty, Legal);
445 setOperationAction(ISD::FMINNUM, Ty, Legal);
446 setOperationAction(ISD::FMAXNUM, Ty, Legal);
447 setOperationAction(ISD::FMINNAN, Ty, Legal);
448 setOperationAction(ISD::FMAXNAN, Ty, Legal);
451 if (Subtarget->hasFullFP16()) {
452 setOperationAction(ISD::FNEARBYINT, MVT::f16, Legal);
453 setOperationAction(ISD::FFLOOR, MVT::f16, Legal);
454 setOperationAction(ISD::FCEIL, MVT::f16, Legal);
455 setOperationAction(ISD::FRINT, MVT::f16, Legal);
456 setOperationAction(ISD::FTRUNC, MVT::f16, Legal);
457 setOperationAction(ISD::FROUND, MVT::f16, Legal);
458 setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
459 setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
460 setOperationAction(ISD::FMINNAN, MVT::f16, Legal);
461 setOperationAction(ISD::FMAXNAN, MVT::f16, Legal);
464 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
466 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
468 // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
469 // This requires the Performance Monitors extension.
470 if (Subtarget->hasPerfMon())
471 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
473 if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
474 getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
475 // Issue __sincos_stret if available.
476 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
477 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
479 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
480 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
483 // Make floating-point constants legal for the large code model, so they don't
484 // become loads from the constant pool.
485 if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
486 setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
487 setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
490 // AArch64 does not have floating-point extending loads, i1 sign-extending
491 // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
492 for (MVT VT : MVT::fp_valuetypes()) {
493 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
494 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
495 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
496 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
498 for (MVT VT : MVT::integer_valuetypes())
499 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
501 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
502 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
503 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
504 setTruncStoreAction(MVT::f128, MVT::f80, Expand);
505 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
506 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
507 setTruncStoreAction(MVT::f128, MVT::f16, Expand);
509 setOperationAction(ISD::BITCAST, MVT::i16, Custom);
510 setOperationAction(ISD::BITCAST, MVT::f16, Custom);
512 // Indexed loads and stores are supported.
513 for (unsigned im = (unsigned)ISD::PRE_INC;
514 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
515 setIndexedLoadAction(im, MVT::i8, Legal);
516 setIndexedLoadAction(im, MVT::i16, Legal);
517 setIndexedLoadAction(im, MVT::i32, Legal);
518 setIndexedLoadAction(im, MVT::i64, Legal);
519 setIndexedLoadAction(im, MVT::f64, Legal);
520 setIndexedLoadAction(im, MVT::f32, Legal);
521 setIndexedLoadAction(im, MVT::f16, Legal);
522 setIndexedStoreAction(im, MVT::i8, Legal);
523 setIndexedStoreAction(im, MVT::i16, Legal);
524 setIndexedStoreAction(im, MVT::i32, Legal);
525 setIndexedStoreAction(im, MVT::i64, Legal);
526 setIndexedStoreAction(im, MVT::f64, Legal);
527 setIndexedStoreAction(im, MVT::f32, Legal);
528 setIndexedStoreAction(im, MVT::f16, Legal);
532 setOperationAction(ISD::TRAP, MVT::Other, Legal);
534 // We combine OR nodes for bitfield operations.
535 setTargetDAGCombine(ISD::OR);
537 // Vector add and sub nodes may conceal a high-half opportunity.
538 // Also, try to fold ADD into CSINC/CSINV..
539 setTargetDAGCombine(ISD::ADD);
540 setTargetDAGCombine(ISD::SUB);
541 setTargetDAGCombine(ISD::SRL);
542 setTargetDAGCombine(ISD::XOR);
543 setTargetDAGCombine(ISD::SINT_TO_FP);
544 setTargetDAGCombine(ISD::UINT_TO_FP);
546 setTargetDAGCombine(ISD::FP_TO_SINT);
547 setTargetDAGCombine(ISD::FP_TO_UINT);
548 setTargetDAGCombine(ISD::FDIV);
550 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
552 setTargetDAGCombine(ISD::ANY_EXTEND);
553 setTargetDAGCombine(ISD::ZERO_EXTEND);
554 setTargetDAGCombine(ISD::SIGN_EXTEND);
555 setTargetDAGCombine(ISD::BITCAST);
556 setTargetDAGCombine(ISD::CONCAT_VECTORS);
557 setTargetDAGCombine(ISD::STORE);
558 if (Subtarget->supportsAddressTopByteIgnored())
559 setTargetDAGCombine(ISD::LOAD);
561 setTargetDAGCombine(ISD::MUL);
563 setTargetDAGCombine(ISD::SELECT);
564 setTargetDAGCombine(ISD::VSELECT);
566 setTargetDAGCombine(ISD::INTRINSIC_VOID);
567 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
568 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
570 MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 8;
571 MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 4;
572 MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = 4;
574 setStackPointerRegisterToSaveRestore(AArch64::SP);
576 setSchedulingPreference(Sched::Hybrid);
578 EnableExtLdPromotion = true;
580 // Set required alignment.
581 setMinFunctionAlignment(2);
582 // Set preferred alignments.
583 setPrefFunctionAlignment(STI.getPrefFunctionAlignment());
584 setPrefLoopAlignment(STI.getPrefLoopAlignment());
586 // Only change the limit for entries in a jump table if specified by
587 // the subtarget, but not at the command line.
588 unsigned MaxJT = STI.getMaximumJumpTableSize();
589 if (MaxJT && getMaximumJumpTableSize() == 0)
590 setMaximumJumpTableSize(MaxJT);
592 setHasExtractBitsInsn(true);
594 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
596 if (Subtarget->hasNEON()) {
597 // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
598 // silliness like this:
599 setOperationAction(ISD::FABS, MVT::v1f64, Expand);
600 setOperationAction(ISD::FADD, MVT::v1f64, Expand);
601 setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
602 setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
603 setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
604 setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
605 setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
606 setOperationAction(ISD::FMA, MVT::v1f64, Expand);
607 setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
608 setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
609 setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
610 setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
611 setOperationAction(ISD::FREM, MVT::v1f64, Expand);
612 setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
613 setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
614 setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
615 setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
616 setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
617 setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
618 setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
619 setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
620 setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
621 setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
622 setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
623 setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
625 setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
626 setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
627 setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
628 setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
629 setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
631 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
633 // AArch64 doesn't have a direct vector ->f32 conversion instructions for
634 // elements smaller than i32, so promote the input to i32 first.
635 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i8, MVT::v4i32);
636 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i8, MVT::v4i32);
637 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i16, MVT::v4i32);
638 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i16, MVT::v4i32);
639 // i8 and i16 vector elements also need promotion to i32 for v8i8 or v8i16
640 // -> v8f16 conversions.
641 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i8, MVT::v8i32);
642 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i8, MVT::v8i32);
643 setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i16, MVT::v8i32);
644 setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i16, MVT::v8i32);
645 // Similarly, there is no direct i32 -> f64 vector conversion instruction.
646 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
647 setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
648 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
649 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
650 // Or, direct i32 -> f16 vector conversion. Set it so custom, so the
651 // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
652 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
653 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
655 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand);
656 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand);
658 setOperationAction(ISD::CTTZ, MVT::v2i8, Expand);
659 setOperationAction(ISD::CTTZ, MVT::v4i16, Expand);
660 setOperationAction(ISD::CTTZ, MVT::v2i32, Expand);
661 setOperationAction(ISD::CTTZ, MVT::v1i64, Expand);
662 setOperationAction(ISD::CTTZ, MVT::v16i8, Expand);
663 setOperationAction(ISD::CTTZ, MVT::v8i16, Expand);
664 setOperationAction(ISD::CTTZ, MVT::v4i32, Expand);
665 setOperationAction(ISD::CTTZ, MVT::v2i64, Expand);
667 // AArch64 doesn't have MUL.2d:
668 setOperationAction(ISD::MUL, MVT::v2i64, Expand);
669 // Custom handling for some quad-vector types to detect MULL.
670 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
671 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
672 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
675 for (MVT VT : MVT::integer_valuetypes()) {
676 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
677 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
678 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
679 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
680 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
682 for (MVT VT : MVT::fp_valuetypes()) {
683 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
684 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
687 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
688 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
689 // Likewise, narrowing and extending vector loads/stores aren't handled
691 for (MVT VT : MVT::vector_valuetypes()) {
692 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
694 setOperationAction(ISD::MULHS, VT, Expand);
695 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
696 setOperationAction(ISD::MULHU, VT, Expand);
697 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
699 setOperationAction(ISD::BSWAP, VT, Expand);
701 for (MVT InnerVT : MVT::vector_valuetypes()) {
702 setTruncStoreAction(VT, InnerVT, Expand);
703 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
704 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
705 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
709 // AArch64 has implementations of a lot of rounding-like FP operations.
710 for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
711 setOperationAction(ISD::FFLOOR, Ty, Legal);
712 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
713 setOperationAction(ISD::FCEIL, Ty, Legal);
714 setOperationAction(ISD::FRINT, Ty, Legal);
715 setOperationAction(ISD::FTRUNC, Ty, Legal);
716 setOperationAction(ISD::FROUND, Ty, Legal);
720 PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive();
723 void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) {
724 if (VT == MVT::v2f32 || VT == MVT::v4f16) {
725 setOperationAction(ISD::LOAD, VT, Promote);
726 AddPromotedToType(ISD::LOAD, VT, MVT::v2i32);
728 setOperationAction(ISD::STORE, VT, Promote);
729 AddPromotedToType(ISD::STORE, VT, MVT::v2i32);
730 } else if (VT == MVT::v2f64 || VT == MVT::v4f32 || VT == MVT::v8f16) {
731 setOperationAction(ISD::LOAD, VT, Promote);
732 AddPromotedToType(ISD::LOAD, VT, MVT::v2i64);
734 setOperationAction(ISD::STORE, VT, Promote);
735 AddPromotedToType(ISD::STORE, VT, MVT::v2i64);
738 // Mark vector float intrinsics as expand.
739 if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
740 setOperationAction(ISD::FSIN, VT, Expand);
741 setOperationAction(ISD::FCOS, VT, Expand);
742 setOperationAction(ISD::FPOW, VT, Expand);
743 setOperationAction(ISD::FLOG, VT, Expand);
744 setOperationAction(ISD::FLOG2, VT, Expand);
745 setOperationAction(ISD::FLOG10, VT, Expand);
746 setOperationAction(ISD::FEXP, VT, Expand);
747 setOperationAction(ISD::FEXP2, VT, Expand);
749 // But we do support custom-lowering for FCOPYSIGN.
750 setOperationAction(ISD::FCOPYSIGN, VT, Custom);
753 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
754 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
755 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
756 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
757 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
758 setOperationAction(ISD::SRA, VT, Custom);
759 setOperationAction(ISD::SRL, VT, Custom);
760 setOperationAction(ISD::SHL, VT, Custom);
761 setOperationAction(ISD::AND, VT, Custom);
762 setOperationAction(ISD::OR, VT, Custom);
763 setOperationAction(ISD::SETCC, VT, Custom);
764 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
766 setOperationAction(ISD::SELECT, VT, Expand);
767 setOperationAction(ISD::SELECT_CC, VT, Expand);
768 setOperationAction(ISD::VSELECT, VT, Expand);
769 for (MVT InnerVT : MVT::all_valuetypes())
770 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
772 // CNT supports only B element sizes.
773 if (VT != MVT::v8i8 && VT != MVT::v16i8)
774 setOperationAction(ISD::CTPOP, VT, Expand);
776 setOperationAction(ISD::UDIV, VT, Expand);
777 setOperationAction(ISD::SDIV, VT, Expand);
778 setOperationAction(ISD::UREM, VT, Expand);
779 setOperationAction(ISD::SREM, VT, Expand);
780 setOperationAction(ISD::FREM, VT, Expand);
782 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
783 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
785 if (!VT.isFloatingPoint())
786 setOperationAction(ISD::ABS, VT, Legal);
788 // [SU][MIN|MAX] are available for all NEON types apart from i64.
789 if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64)
790 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
791 setOperationAction(Opcode, VT, Legal);
793 // F[MIN|MAX][NUM|NAN] are available for all FP NEON types.
794 if (VT.isFloatingPoint() &&
795 (VT.getVectorElementType() != MVT::f16 || Subtarget->hasFullFP16()))
796 for (unsigned Opcode : {ISD::FMINNAN, ISD::FMAXNAN,
797 ISD::FMINNUM, ISD::FMAXNUM})
798 setOperationAction(Opcode, VT, Legal);
800 if (Subtarget->isLittleEndian()) {
801 for (unsigned im = (unsigned)ISD::PRE_INC;
802 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
803 setIndexedLoadAction(im, VT, Legal);
804 setIndexedStoreAction(im, VT, Legal);
809 void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
810 addRegisterClass(VT, &AArch64::FPR64RegClass);
811 addTypeForNEON(VT, MVT::v2i32);
814 void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
815 addRegisterClass(VT, &AArch64::FPR128RegClass);
816 addTypeForNEON(VT, MVT::v4i32);
819 EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
823 return VT.changeVectorElementTypeToInteger();
826 static bool optimizeLogicalImm(SDValue Op, unsigned Size, uint64_t Imm,
827 const APInt &Demanded,
828 TargetLowering::TargetLoweringOpt &TLO,
830 uint64_t OldImm = Imm, NewImm, Enc;
831 uint64_t Mask = ((uint64_t)(-1LL) >> (64 - Size)), OrigMask = Mask;
833 // Return if the immediate is already all zeros, all ones, a bimm32 or a
835 if (Imm == 0 || Imm == Mask ||
836 AArch64_AM::isLogicalImmediate(Imm & Mask, Size))
839 unsigned EltSize = Size;
840 uint64_t DemandedBits = Demanded.getZExtValue();
842 // Clear bits that are not demanded.
846 // The goal here is to set the non-demanded bits in a way that minimizes
847 // the number of switching between 0 and 1. In order to achieve this goal,
848 // we set the non-demanded bits to the value of the preceding demanded bits.
849 // For example, if we have an immediate 0bx10xx0x1 ('x' indicates a
850 // non-demanded bit), we copy bit0 (1) to the least significant 'x',
851 // bit2 (0) to 'xx', and bit6 (1) to the most significant 'x'.
852 // The final result is 0b11000011.
853 uint64_t NonDemandedBits = ~DemandedBits;
854 uint64_t InvertedImm = ~Imm & DemandedBits;
855 uint64_t RotatedImm =
856 ((InvertedImm << 1) | (InvertedImm >> (EltSize - 1) & 1)) &
858 uint64_t Sum = RotatedImm + NonDemandedBits;
859 bool Carry = NonDemandedBits & ~Sum & (1ULL << (EltSize - 1));
860 uint64_t Ones = (Sum + Carry) & NonDemandedBits;
861 NewImm = (Imm | Ones) & Mask;
863 // If NewImm or its bitwise NOT is a shifted mask, it is a bitmask immediate
864 // or all-ones or all-zeros, in which case we can stop searching. Otherwise,
865 // we halve the element size and continue the search.
866 if (isShiftedMask_64(NewImm) || isShiftedMask_64(~(NewImm | ~Mask)))
869 // We cannot shrink the element size any further if it is 2-bits.
875 uint64_t Hi = Imm >> EltSize, DemandedBitsHi = DemandedBits >> EltSize;
877 // Return if there is mismatch in any of the demanded bits of Imm and Hi.
878 if (((Imm ^ Hi) & (DemandedBits & DemandedBitsHi) & Mask) != 0)
881 // Merge the upper and lower halves of Imm and DemandedBits.
883 DemandedBits |= DemandedBitsHi;
888 // Replicate the element across the register width.
889 while (EltSize < Size) {
890 NewImm |= NewImm << EltSize;
895 assert(((OldImm ^ NewImm) & Demanded.getZExtValue()) == 0 &&
896 "demanded bits should never be altered");
897 assert(OldImm != NewImm && "the new imm shouldn't be equal to the old imm");
899 // Create the new constant immediate node.
900 EVT VT = Op.getValueType();
904 // If the new constant immediate is all-zeros or all-ones, let the target
905 // independent DAG combine optimize this node.
906 if (NewImm == 0 || NewImm == OrigMask) {
907 New = TLO.DAG.getNode(Op.getOpcode(), DL, VT, Op.getOperand(0),
908 TLO.DAG.getConstant(NewImm, DL, VT));
909 // Otherwise, create a machine node so that target independent DAG combine
910 // doesn't undo this optimization.
912 Enc = AArch64_AM::encodeLogicalImmediate(NewImm, Size);
913 SDValue EncConst = TLO.DAG.getTargetConstant(Enc, DL, VT);
915 TLO.DAG.getMachineNode(NewOpc, DL, VT, Op.getOperand(0), EncConst), 0);
918 return TLO.CombineTo(Op, New);
921 bool AArch64TargetLowering::targetShrinkDemandedConstant(
922 SDValue Op, const APInt &Demanded, TargetLoweringOpt &TLO) const {
923 // Delay this optimization to as late as possible.
927 if (!EnableOptimizeLogicalImm)
930 EVT VT = Op.getValueType();
934 unsigned Size = VT.getSizeInBits();
935 assert((Size == 32 || Size == 64) &&
936 "i32 or i64 is expected after legalization.");
938 // Exit early if we demand all bits.
939 if (Demanded.countPopulation() == Size)
943 switch (Op.getOpcode()) {
947 NewOpc = Size == 32 ? AArch64::ANDWri : AArch64::ANDXri;
950 NewOpc = Size == 32 ? AArch64::ORRWri : AArch64::ORRXri;
953 NewOpc = Size == 32 ? AArch64::EORWri : AArch64::EORXri;
956 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
959 uint64_t Imm = C->getZExtValue();
960 return optimizeLogicalImm(Op, Size, Imm, Demanded, TLO, NewOpc);
963 /// computeKnownBitsForTargetNode - Determine which of the bits specified in
964 /// Mask are known to be either zero or one and return them Known.
965 void AArch64TargetLowering::computeKnownBitsForTargetNode(
966 const SDValue Op, KnownBits &Known,
967 const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const {
968 switch (Op.getOpcode()) {
971 case AArch64ISD::CSEL: {
973 DAG.computeKnownBits(Op->getOperand(0), Known, Depth + 1);
974 DAG.computeKnownBits(Op->getOperand(1), Known2, Depth + 1);
975 Known.Zero &= Known2.Zero;
976 Known.One &= Known2.One;
979 case ISD::INTRINSIC_W_CHAIN: {
980 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
981 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
984 case Intrinsic::aarch64_ldaxr:
985 case Intrinsic::aarch64_ldxr: {
986 unsigned BitWidth = Known.getBitWidth();
987 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
988 unsigned MemBits = VT.getScalarSizeInBits();
989 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
995 case ISD::INTRINSIC_WO_CHAIN:
996 case ISD::INTRINSIC_VOID: {
997 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
1001 case Intrinsic::aarch64_neon_umaxv:
1002 case Intrinsic::aarch64_neon_uminv: {
1003 // Figure out the datatype of the vector operand. The UMINV instruction
1004 // will zero extend the result, so we can mark as known zero all the
1005 // bits larger than the element datatype. 32-bit or larget doesn't need
1006 // this as those are legal types and will be handled by isel directly.
1007 MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
1008 unsigned BitWidth = Known.getBitWidth();
1009 if (VT == MVT::v8i8 || VT == MVT::v16i8) {
1010 assert(BitWidth >= 8 && "Unexpected width!");
1011 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
1013 } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
1014 assert(BitWidth >= 16 && "Unexpected width!");
1015 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
1025 MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
1030 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1034 if (Subtarget->requiresStrictAlign())
1038 // Some CPUs are fine with unaligned stores except for 128-bit ones.
1039 *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 ||
1040 // See comments in performSTORECombine() for more details about
1041 // these conditions.
1043 // Code that uses clang vector extensions can mark that it
1044 // wants unaligned accesses to be treated as fast by
1045 // underspecifying alignment to be 1 or 2.
1048 // Disregard v2i64. Memcpy lowering produces those and splitting
1049 // them regresses performance on micro-benchmarks and olden/bh.
1056 AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1057 const TargetLibraryInfo *libInfo) const {
1058 return AArch64::createFastISel(funcInfo, libInfo);
1061 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
1062 switch ((AArch64ISD::NodeType)Opcode) {
1063 case AArch64ISD::FIRST_NUMBER: break;
1064 case AArch64ISD::CALL: return "AArch64ISD::CALL";
1065 case AArch64ISD::ADRP: return "AArch64ISD::ADRP";
1066 case AArch64ISD::ADDlow: return "AArch64ISD::ADDlow";
1067 case AArch64ISD::LOADgot: return "AArch64ISD::LOADgot";
1068 case AArch64ISD::RET_FLAG: return "AArch64ISD::RET_FLAG";
1069 case AArch64ISD::BRCOND: return "AArch64ISD::BRCOND";
1070 case AArch64ISD::CSEL: return "AArch64ISD::CSEL";
1071 case AArch64ISD::FCSEL: return "AArch64ISD::FCSEL";
1072 case AArch64ISD::CSINV: return "AArch64ISD::CSINV";
1073 case AArch64ISD::CSNEG: return "AArch64ISD::CSNEG";
1074 case AArch64ISD::CSINC: return "AArch64ISD::CSINC";
1075 case AArch64ISD::THREAD_POINTER: return "AArch64ISD::THREAD_POINTER";
1076 case AArch64ISD::TLSDESC_CALLSEQ: return "AArch64ISD::TLSDESC_CALLSEQ";
1077 case AArch64ISD::ADC: return "AArch64ISD::ADC";
1078 case AArch64ISD::SBC: return "AArch64ISD::SBC";
1079 case AArch64ISD::ADDS: return "AArch64ISD::ADDS";
1080 case AArch64ISD::SUBS: return "AArch64ISD::SUBS";
1081 case AArch64ISD::ADCS: return "AArch64ISD::ADCS";
1082 case AArch64ISD::SBCS: return "AArch64ISD::SBCS";
1083 case AArch64ISD::ANDS: return "AArch64ISD::ANDS";
1084 case AArch64ISD::CCMP: return "AArch64ISD::CCMP";
1085 case AArch64ISD::CCMN: return "AArch64ISD::CCMN";
1086 case AArch64ISD::FCCMP: return "AArch64ISD::FCCMP";
1087 case AArch64ISD::FCMP: return "AArch64ISD::FCMP";
1088 case AArch64ISD::DUP: return "AArch64ISD::DUP";
1089 case AArch64ISD::DUPLANE8: return "AArch64ISD::DUPLANE8";
1090 case AArch64ISD::DUPLANE16: return "AArch64ISD::DUPLANE16";
1091 case AArch64ISD::DUPLANE32: return "AArch64ISD::DUPLANE32";
1092 case AArch64ISD::DUPLANE64: return "AArch64ISD::DUPLANE64";
1093 case AArch64ISD::MOVI: return "AArch64ISD::MOVI";
1094 case AArch64ISD::MOVIshift: return "AArch64ISD::MOVIshift";
1095 case AArch64ISD::MOVIedit: return "AArch64ISD::MOVIedit";
1096 case AArch64ISD::MOVImsl: return "AArch64ISD::MOVImsl";
1097 case AArch64ISD::FMOV: return "AArch64ISD::FMOV";
1098 case AArch64ISD::MVNIshift: return "AArch64ISD::MVNIshift";
1099 case AArch64ISD::MVNImsl: return "AArch64ISD::MVNImsl";
1100 case AArch64ISD::BICi: return "AArch64ISD::BICi";
1101 case AArch64ISD::ORRi: return "AArch64ISD::ORRi";
1102 case AArch64ISD::BSL: return "AArch64ISD::BSL";
1103 case AArch64ISD::NEG: return "AArch64ISD::NEG";
1104 case AArch64ISD::EXTR: return "AArch64ISD::EXTR";
1105 case AArch64ISD::ZIP1: return "AArch64ISD::ZIP1";
1106 case AArch64ISD::ZIP2: return "AArch64ISD::ZIP2";
1107 case AArch64ISD::UZP1: return "AArch64ISD::UZP1";
1108 case AArch64ISD::UZP2: return "AArch64ISD::UZP2";
1109 case AArch64ISD::TRN1: return "AArch64ISD::TRN1";
1110 case AArch64ISD::TRN2: return "AArch64ISD::TRN2";
1111 case AArch64ISD::REV16: return "AArch64ISD::REV16";
1112 case AArch64ISD::REV32: return "AArch64ISD::REV32";
1113 case AArch64ISD::REV64: return "AArch64ISD::REV64";
1114 case AArch64ISD::EXT: return "AArch64ISD::EXT";
1115 case AArch64ISD::VSHL: return "AArch64ISD::VSHL";
1116 case AArch64ISD::VLSHR: return "AArch64ISD::VLSHR";
1117 case AArch64ISD::VASHR: return "AArch64ISD::VASHR";
1118 case AArch64ISD::CMEQ: return "AArch64ISD::CMEQ";
1119 case AArch64ISD::CMGE: return "AArch64ISD::CMGE";
1120 case AArch64ISD::CMGT: return "AArch64ISD::CMGT";
1121 case AArch64ISD::CMHI: return "AArch64ISD::CMHI";
1122 case AArch64ISD::CMHS: return "AArch64ISD::CMHS";
1123 case AArch64ISD::FCMEQ: return "AArch64ISD::FCMEQ";
1124 case AArch64ISD::FCMGE: return "AArch64ISD::FCMGE";
1125 case AArch64ISD::FCMGT: return "AArch64ISD::FCMGT";
1126 case AArch64ISD::CMEQz: return "AArch64ISD::CMEQz";
1127 case AArch64ISD::CMGEz: return "AArch64ISD::CMGEz";
1128 case AArch64ISD::CMGTz: return "AArch64ISD::CMGTz";
1129 case AArch64ISD::CMLEz: return "AArch64ISD::CMLEz";
1130 case AArch64ISD::CMLTz: return "AArch64ISD::CMLTz";
1131 case AArch64ISD::FCMEQz: return "AArch64ISD::FCMEQz";
1132 case AArch64ISD::FCMGEz: return "AArch64ISD::FCMGEz";
1133 case AArch64ISD::FCMGTz: return "AArch64ISD::FCMGTz";
1134 case AArch64ISD::FCMLEz: return "AArch64ISD::FCMLEz";
1135 case AArch64ISD::FCMLTz: return "AArch64ISD::FCMLTz";
1136 case AArch64ISD::SADDV: return "AArch64ISD::SADDV";
1137 case AArch64ISD::UADDV: return "AArch64ISD::UADDV";
1138 case AArch64ISD::SMINV: return "AArch64ISD::SMINV";
1139 case AArch64ISD::UMINV: return "AArch64ISD::UMINV";
1140 case AArch64ISD::SMAXV: return "AArch64ISD::SMAXV";
1141 case AArch64ISD::UMAXV: return "AArch64ISD::UMAXV";
1142 case AArch64ISD::NOT: return "AArch64ISD::NOT";
1143 case AArch64ISD::BIT: return "AArch64ISD::BIT";
1144 case AArch64ISD::CBZ: return "AArch64ISD::CBZ";
1145 case AArch64ISD::CBNZ: return "AArch64ISD::CBNZ";
1146 case AArch64ISD::TBZ: return "AArch64ISD::TBZ";
1147 case AArch64ISD::TBNZ: return "AArch64ISD::TBNZ";
1148 case AArch64ISD::TC_RETURN: return "AArch64ISD::TC_RETURN";
1149 case AArch64ISD::PREFETCH: return "AArch64ISD::PREFETCH";
1150 case AArch64ISD::SITOF: return "AArch64ISD::SITOF";
1151 case AArch64ISD::UITOF: return "AArch64ISD::UITOF";
1152 case AArch64ISD::NVCAST: return "AArch64ISD::NVCAST";
1153 case AArch64ISD::SQSHL_I: return "AArch64ISD::SQSHL_I";
1154 case AArch64ISD::UQSHL_I: return "AArch64ISD::UQSHL_I";
1155 case AArch64ISD::SRSHR_I: return "AArch64ISD::SRSHR_I";
1156 case AArch64ISD::URSHR_I: return "AArch64ISD::URSHR_I";
1157 case AArch64ISD::SQSHLU_I: return "AArch64ISD::SQSHLU_I";
1158 case AArch64ISD::WrapperLarge: return "AArch64ISD::WrapperLarge";
1159 case AArch64ISD::LD2post: return "AArch64ISD::LD2post";
1160 case AArch64ISD::LD3post: return "AArch64ISD::LD3post";
1161 case AArch64ISD::LD4post: return "AArch64ISD::LD4post";
1162 case AArch64ISD::ST2post: return "AArch64ISD::ST2post";
1163 case AArch64ISD::ST3post: return "AArch64ISD::ST3post";
1164 case AArch64ISD::ST4post: return "AArch64ISD::ST4post";
1165 case AArch64ISD::LD1x2post: return "AArch64ISD::LD1x2post";
1166 case AArch64ISD::LD1x3post: return "AArch64ISD::LD1x3post";
1167 case AArch64ISD::LD1x4post: return "AArch64ISD::LD1x4post";
1168 case AArch64ISD::ST1x2post: return "AArch64ISD::ST1x2post";
1169 case AArch64ISD::ST1x3post: return "AArch64ISD::ST1x3post";
1170 case AArch64ISD::ST1x4post: return "AArch64ISD::ST1x4post";
1171 case AArch64ISD::LD1DUPpost: return "AArch64ISD::LD1DUPpost";
1172 case AArch64ISD::LD2DUPpost: return "AArch64ISD::LD2DUPpost";
1173 case AArch64ISD::LD3DUPpost: return "AArch64ISD::LD3DUPpost";
1174 case AArch64ISD::LD4DUPpost: return "AArch64ISD::LD4DUPpost";
1175 case AArch64ISD::LD1LANEpost: return "AArch64ISD::LD1LANEpost";
1176 case AArch64ISD::LD2LANEpost: return "AArch64ISD::LD2LANEpost";
1177 case AArch64ISD::LD3LANEpost: return "AArch64ISD::LD3LANEpost";
1178 case AArch64ISD::LD4LANEpost: return "AArch64ISD::LD4LANEpost";
1179 case AArch64ISD::ST2LANEpost: return "AArch64ISD::ST2LANEpost";
1180 case AArch64ISD::ST3LANEpost: return "AArch64ISD::ST3LANEpost";
1181 case AArch64ISD::ST4LANEpost: return "AArch64ISD::ST4LANEpost";
1182 case AArch64ISD::SMULL: return "AArch64ISD::SMULL";
1183 case AArch64ISD::UMULL: return "AArch64ISD::UMULL";
1184 case AArch64ISD::FRECPE: return "AArch64ISD::FRECPE";
1185 case AArch64ISD::FRECPS: return "AArch64ISD::FRECPS";
1186 case AArch64ISD::FRSQRTE: return "AArch64ISD::FRSQRTE";
1187 case AArch64ISD::FRSQRTS: return "AArch64ISD::FRSQRTS";
1193 AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI,
1194 MachineBasicBlock *MBB) const {
1195 // We materialise the F128CSEL pseudo-instruction as some control flow and a
1199 // [... previous instrs leading to comparison ...]
1205 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
1207 MachineFunction *MF = MBB->getParent();
1208 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1209 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
1210 DebugLoc DL = MI.getDebugLoc();
1211 MachineFunction::iterator It = ++MBB->getIterator();
1213 unsigned DestReg = MI.getOperand(0).getReg();
1214 unsigned IfTrueReg = MI.getOperand(1).getReg();
1215 unsigned IfFalseReg = MI.getOperand(2).getReg();
1216 unsigned CondCode = MI.getOperand(3).getImm();
1217 bool NZCVKilled = MI.getOperand(4).isKill();
1219 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
1220 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
1221 MF->insert(It, TrueBB);
1222 MF->insert(It, EndBB);
1224 // Transfer rest of current basic-block to EndBB
1225 EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
1227 EndBB->transferSuccessorsAndUpdatePHIs(MBB);
1229 BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
1230 BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
1231 MBB->addSuccessor(TrueBB);
1232 MBB->addSuccessor(EndBB);
1234 // TrueBB falls through to the end.
1235 TrueBB->addSuccessor(EndBB);
1238 TrueBB->addLiveIn(AArch64::NZCV);
1239 EndBB->addLiveIn(AArch64::NZCV);
1242 BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
1248 MI.eraseFromParent();
1252 MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter(
1253 MachineInstr &MI, MachineBasicBlock *BB) const {
1254 switch (MI.getOpcode()) {
1259 llvm_unreachable("Unexpected instruction for custom inserter!");
1261 case AArch64::F128CSEL:
1262 return EmitF128CSEL(MI, BB);
1264 case TargetOpcode::STACKMAP:
1265 case TargetOpcode::PATCHPOINT:
1266 return emitPatchPoint(MI, BB);
1270 //===----------------------------------------------------------------------===//
1271 // AArch64 Lowering private implementation.
1272 //===----------------------------------------------------------------------===//
1274 //===----------------------------------------------------------------------===//
1276 //===----------------------------------------------------------------------===//
1278 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1280 static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1283 llvm_unreachable("Unknown condition code!");
1285 return AArch64CC::NE;
1287 return AArch64CC::EQ;
1289 return AArch64CC::GT;
1291 return AArch64CC::GE;
1293 return AArch64CC::LT;
1295 return AArch64CC::LE;
1297 return AArch64CC::HI;
1299 return AArch64CC::HS;
1301 return AArch64CC::LO;
1303 return AArch64CC::LS;
1307 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1308 static void changeFPCCToAArch64CC(ISD::CondCode CC,
1309 AArch64CC::CondCode &CondCode,
1310 AArch64CC::CondCode &CondCode2) {
1311 CondCode2 = AArch64CC::AL;
1314 llvm_unreachable("Unknown FP condition!");
1317 CondCode = AArch64CC::EQ;
1321 CondCode = AArch64CC::GT;
1325 CondCode = AArch64CC::GE;
1328 CondCode = AArch64CC::MI;
1331 CondCode = AArch64CC::LS;
1334 CondCode = AArch64CC::MI;
1335 CondCode2 = AArch64CC::GT;
1338 CondCode = AArch64CC::VC;
1341 CondCode = AArch64CC::VS;
1344 CondCode = AArch64CC::EQ;
1345 CondCode2 = AArch64CC::VS;
1348 CondCode = AArch64CC::HI;
1351 CondCode = AArch64CC::PL;
1355 CondCode = AArch64CC::LT;
1359 CondCode = AArch64CC::LE;
1363 CondCode = AArch64CC::NE;
1368 /// Convert a DAG fp condition code to an AArch64 CC.
1369 /// This differs from changeFPCCToAArch64CC in that it returns cond codes that
1370 /// should be AND'ed instead of OR'ed.
1371 static void changeFPCCToANDAArch64CC(ISD::CondCode CC,
1372 AArch64CC::CondCode &CondCode,
1373 AArch64CC::CondCode &CondCode2) {
1374 CondCode2 = AArch64CC::AL;
1377 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1378 assert(CondCode2 == AArch64CC::AL);
1382 // == ((a olt b) || (a ogt b))
1383 // == ((a ord b) && (a une b))
1384 CondCode = AArch64CC::VC;
1385 CondCode2 = AArch64CC::NE;
1389 // == ((a uno b) || (a oeq b))
1390 // == ((a ule b) && (a uge b))
1391 CondCode = AArch64CC::PL;
1392 CondCode2 = AArch64CC::LE;
1397 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1398 /// CC usable with the vector instructions. Fewer operations are available
1399 /// without a real NZCV register, so we have to use less efficient combinations
1400 /// to get the same effect.
1401 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1402 AArch64CC::CondCode &CondCode,
1403 AArch64CC::CondCode &CondCode2,
1408 // Mostly the scalar mappings work fine.
1409 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1415 CondCode = AArch64CC::MI;
1416 CondCode2 = AArch64CC::GE;
1423 // All of the compare-mask comparisons are ordered, but we can switch
1424 // between the two by a double inversion. E.g. ULE == !OGT.
1426 changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1431 static bool isLegalArithImmed(uint64_t C) {
1432 // Matches AArch64DAGToDAGISel::SelectArithImmed().
1433 bool IsLegal = (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1434 DEBUG(dbgs() << "Is imm " << C << " legal: " << (IsLegal ? "yes\n" : "no\n"));
1438 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1439 const SDLoc &dl, SelectionDAG &DAG) {
1440 EVT VT = LHS.getValueType();
1441 const bool FullFP16 =
1442 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
1444 if (VT.isFloatingPoint()) {
1445 assert(VT != MVT::f128);
1446 if (VT == MVT::f16 && !FullFP16) {
1447 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
1448 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
1451 return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
1454 // The CMP instruction is just an alias for SUBS, and representing it as
1455 // SUBS means that it's possible to get CSE with subtract operations.
1456 // A later phase can perform the optimization of setting the destination
1457 // register to WZR/XZR if it ends up being unused.
1458 unsigned Opcode = AArch64ISD::SUBS;
1460 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
1461 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1462 // We'd like to combine a (CMP op1, (sub 0, op2) into a CMN instruction on
1463 // the grounds that "op1 - (-op2) == op1 + op2". However, the C and V flags
1464 // can be set differently by this operation. It comes down to whether
1465 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1466 // everything is fine. If not then the optimization is wrong. Thus general
1467 // comparisons are only valid if op2 != 0.
1469 // So, finally, the only LLVM-native comparisons that don't mention C and V
1470 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1471 // the absence of information about op2.
1472 Opcode = AArch64ISD::ADDS;
1473 RHS = RHS.getOperand(1);
1474 } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) &&
1475 !isUnsignedIntSetCC(CC)) {
1476 // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1477 // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1478 // of the signed comparisons.
1479 Opcode = AArch64ISD::ANDS;
1480 RHS = LHS.getOperand(1);
1481 LHS = LHS.getOperand(0);
1484 return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
1488 /// \defgroup AArch64CCMP CMP;CCMP matching
1490 /// These functions deal with the formation of CMP;CCMP;... sequences.
1491 /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1492 /// a comparison. They set the NZCV flags to a predefined value if their
1493 /// predicate is false. This allows to express arbitrary conjunctions, for
1494 /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B))))"
1497 /// ccmp B, inv(CB), CA
1498 /// check for CB flags
1500 /// In general we can create code for arbitrary "... (and (and A B) C)"
1501 /// sequences. We can also implement some "or" expressions, because "(or A B)"
1502 /// is equivalent to "not (and (not A) (not B))" and we can implement some
1503 /// negation operations:
1504 /// We can negate the results of a single comparison by inverting the flags
1505 /// used when the predicate fails and inverting the flags tested in the next
1506 /// instruction; We can also negate the results of the whole previous
1507 /// conditional compare sequence by inverting the flags tested in the next
1508 /// instruction. However there is no way to negate the result of a partial
1511 /// Therefore on encountering an "or" expression we can negate the subtree on
1512 /// one side and have to be able to push the negate to the leafs of the subtree
1513 /// on the other side (see also the comments in code). As complete example:
1514 /// "or (or (setCA (cmp A)) (setCB (cmp B)))
1515 /// (and (setCC (cmp C)) (setCD (cmp D)))"
1516 /// is transformed to
1517 /// "not (and (not (and (setCC (cmp C)) (setCC (cmp D))))
1518 /// (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1519 /// and implemented as:
1521 /// ccmp D, inv(CD), CC
1522 /// ccmp A, CA, inv(CD)
1523 /// ccmp B, CB, inv(CA)
1524 /// check for CB flags
1525 /// A counterexample is "or (and A B) (and C D)" which cannot be implemented
1526 /// by conditional compare sequences.
1529 /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
1530 static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1531 ISD::CondCode CC, SDValue CCOp,
1532 AArch64CC::CondCode Predicate,
1533 AArch64CC::CondCode OutCC,
1534 const SDLoc &DL, SelectionDAG &DAG) {
1535 unsigned Opcode = 0;
1536 const bool FullFP16 =
1537 static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
1539 if (LHS.getValueType().isFloatingPoint()) {
1540 assert(LHS.getValueType() != MVT::f128);
1541 if (LHS.getValueType() == MVT::f16 && !FullFP16) {
1542 LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS);
1543 RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS);
1545 Opcode = AArch64ISD::FCCMP;
1546 } else if (RHS.getOpcode() == ISD::SUB) {
1547 SDValue SubOp0 = RHS.getOperand(0);
1548 if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1549 // See emitComparison() on why we can only do this for SETEQ and SETNE.
1550 Opcode = AArch64ISD::CCMN;
1551 RHS = RHS.getOperand(1);
1555 Opcode = AArch64ISD::CCMP;
1557 SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC);
1558 AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1559 unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
1560 SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1561 return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1564 /// Returns true if @p Val is a tree of AND/OR/SETCC operations.
1565 /// CanPushNegate is set to true if we can push a negate operation through
1566 /// the tree in a was that we are left with AND operations and negate operations
1567 /// at the leafs only. i.e. "not (or (or x y) z)" can be changed to
1568 /// "and (and (not x) (not y)) (not z)"; "not (or (and x y) z)" cannot be
1569 /// brought into such a form.
1570 static bool isConjunctionDisjunctionTree(const SDValue Val, bool &CanNegate,
1571 unsigned Depth = 0) {
1572 if (!Val.hasOneUse())
1574 unsigned Opcode = Val->getOpcode();
1575 if (Opcode == ISD::SETCC) {
1576 if (Val->getOperand(0).getValueType() == MVT::f128)
1581 // Protect against exponential runtime and stack overflow.
1584 if (Opcode == ISD::AND || Opcode == ISD::OR) {
1585 SDValue O0 = Val->getOperand(0);
1586 SDValue O1 = Val->getOperand(1);
1588 if (!isConjunctionDisjunctionTree(O0, CanNegateL, Depth+1))
1591 if (!isConjunctionDisjunctionTree(O1, CanNegateR, Depth+1))
1594 if (Opcode == ISD::OR) {
1595 // For an OR expression we need to be able to negate at least one side or
1596 // we cannot do the transformation at all.
1597 if (!CanNegateL && !CanNegateR)
1599 // We can however change a (not (or x y)) to (and (not x) (not y)) if we
1600 // can negate the x and y subtrees.
1601 CanNegate = CanNegateL && CanNegateR;
1603 // If the operands are OR expressions then we finally need to negate their
1604 // outputs, we can only do that for the operand with emitted last by
1605 // negating OutCC, not for both operands.
1606 bool NeedsNegOutL = O0->getOpcode() == ISD::OR;
1607 bool NeedsNegOutR = O1->getOpcode() == ISD::OR;
1608 if (NeedsNegOutL && NeedsNegOutR)
1610 // We cannot negate an AND operation (it would become an OR),
1618 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1619 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1620 /// Tries to transform the given i1 producing node @p Val to a series compare
1621 /// and conditional compare operations. @returns an NZCV flags producing node
1622 /// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1623 /// transformation was not possible.
1624 /// On recursive invocations @p PushNegate may be set to true to have negation
1625 /// effects pushed to the tree leafs; @p Predicate is an NZCV flag predicate
1626 /// for the comparisons in the current subtree; @p Depth limits the search
1627 /// depth to avoid stack overflow.
1628 static SDValue emitConjunctionDisjunctionTreeRec(SelectionDAG &DAG, SDValue Val,
1629 AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp,
1630 AArch64CC::CondCode Predicate) {
1631 // We're at a tree leaf, produce a conditional comparison operation.
1632 unsigned Opcode = Val->getOpcode();
1633 if (Opcode == ISD::SETCC) {
1634 SDValue LHS = Val->getOperand(0);
1635 SDValue RHS = Val->getOperand(1);
1636 ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1637 bool isInteger = LHS.getValueType().isInteger();
1639 CC = getSetCCInverse(CC, isInteger);
1641 // Determine OutCC and handle FP special case.
1643 OutCC = changeIntCCToAArch64CC(CC);
1645 assert(LHS.getValueType().isFloatingPoint());
1646 AArch64CC::CondCode ExtraCC;
1647 changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
1648 // Some floating point conditions can't be tested with a single condition
1649 // code. Construct an additional comparison in this case.
1650 if (ExtraCC != AArch64CC::AL) {
1652 if (!CCOp.getNode())
1653 ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
1655 ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate,
1658 Predicate = ExtraCC;
1662 // Produce a normal comparison if we are first in the chain
1664 return emitComparison(LHS, RHS, CC, DL, DAG);
1665 // Otherwise produce a ccmp.
1666 return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL,
1669 assert((Opcode == ISD::AND || (Opcode == ISD::OR && Val->hasOneUse())) &&
1670 "Valid conjunction/disjunction tree");
1672 // Check if both sides can be transformed.
1673 SDValue LHS = Val->getOperand(0);
1674 SDValue RHS = Val->getOperand(1);
1676 // In case of an OR we need to negate our operands and the result.
1677 // (A v B) <=> not(not(A) ^ not(B))
1678 bool NegateOpsAndResult = Opcode == ISD::OR;
1679 // We can negate the results of all previous operations by inverting the
1680 // predicate flags giving us a free negation for one side. The other side
1681 // must be negatable by itself.
1682 if (NegateOpsAndResult) {
1683 // See which side we can negate.
1685 bool isValidL = isConjunctionDisjunctionTree(LHS, CanNegateL);
1686 assert(isValidL && "Valid conjunction/disjunction tree");
1691 bool isValidR = isConjunctionDisjunctionTree(RHS, CanNegateR);
1692 assert(isValidR && "Valid conjunction/disjunction tree");
1693 assert((CanNegateL || CanNegateR) && "Valid conjunction/disjunction tree");
1696 // Order the side which we cannot negate to RHS so we can emit it first.
1698 std::swap(LHS, RHS);
1700 bool NeedsNegOutL = LHS->getOpcode() == ISD::OR;
1701 assert((!NeedsNegOutL || RHS->getOpcode() != ISD::OR) &&
1702 "Valid conjunction/disjunction tree");
1703 // Order the side where we need to negate the output flags to RHS so it
1704 // gets emitted first.
1706 std::swap(LHS, RHS);
1709 // Emit RHS. If we want to negate the tree we only need to push a negate
1710 // through if we are already in a PushNegate case, otherwise we can negate
1711 // the "flags to test" afterwards.
1712 AArch64CC::CondCode RHSCC;
1713 SDValue CmpR = emitConjunctionDisjunctionTreeRec(DAG, RHS, RHSCC, Negate,
1715 if (NegateOpsAndResult && !Negate)
1716 RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
1717 // Emit LHS. We may need to negate it.
1718 SDValue CmpL = emitConjunctionDisjunctionTreeRec(DAG, LHS, OutCC,
1719 NegateOpsAndResult, CmpR,
1721 // If we transformed an OR to and AND then we have to negate the result
1722 // (or absorb the Negate parameter).
1723 if (NegateOpsAndResult && !Negate)
1724 OutCC = AArch64CC::getInvertedCondCode(OutCC);
1728 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1729 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1730 /// \see emitConjunctionDisjunctionTreeRec().
1731 static SDValue emitConjunctionDisjunctionTree(SelectionDAG &DAG, SDValue Val,
1732 AArch64CC::CondCode &OutCC) {
1734 if (!isConjunctionDisjunctionTree(Val, CanNegate))
1737 return emitConjunctionDisjunctionTreeRec(DAG, Val, OutCC, false, SDValue(),
1743 static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1744 SDValue &AArch64cc, SelectionDAG &DAG,
1746 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1747 EVT VT = RHS.getValueType();
1748 uint64_t C = RHSC->getZExtValue();
1749 if (!isLegalArithImmed(C)) {
1750 // Constant does not fit, try adjusting it by one?
1756 if ((VT == MVT::i32 && C != 0x80000000 &&
1757 isLegalArithImmed((uint32_t)(C - 1))) ||
1758 (VT == MVT::i64 && C != 0x80000000ULL &&
1759 isLegalArithImmed(C - 1ULL))) {
1760 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1761 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1762 RHS = DAG.getConstant(C, dl, VT);
1767 if ((VT == MVT::i32 && C != 0 &&
1768 isLegalArithImmed((uint32_t)(C - 1))) ||
1769 (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1770 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1771 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1772 RHS = DAG.getConstant(C, dl, VT);
1777 if ((VT == MVT::i32 && C != INT32_MAX &&
1778 isLegalArithImmed((uint32_t)(C + 1))) ||
1779 (VT == MVT::i64 && C != INT64_MAX &&
1780 isLegalArithImmed(C + 1ULL))) {
1781 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1782 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1783 RHS = DAG.getConstant(C, dl, VT);
1788 if ((VT == MVT::i32 && C != UINT32_MAX &&
1789 isLegalArithImmed((uint32_t)(C + 1))) ||
1790 (VT == MVT::i64 && C != UINT64_MAX &&
1791 isLegalArithImmed(C + 1ULL))) {
1792 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1793 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1794 RHS = DAG.getConstant(C, dl, VT);
1801 AArch64CC::CondCode AArch64CC;
1802 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
1803 const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
1805 // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
1806 // For the i8 operand, the largest immediate is 255, so this can be easily
1807 // encoded in the compare instruction. For the i16 operand, however, the
1808 // largest immediate cannot be encoded in the compare.
1809 // Therefore, use a sign extending load and cmn to avoid materializing the
1810 // -1 constant. For example,
1812 // ldrh w0, [x0, #0]
1815 // ldrsh w0, [x0, #0]
1817 // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
1818 // if and only if (sext LHS) == (sext RHS). The checks are in place to
1819 // ensure both the LHS and RHS are truly zero extended and to make sure the
1820 // transformation is profitable.
1821 if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
1822 cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
1823 cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
1824 LHS.getNode()->hasNUsesOfValue(1, 0)) {
1825 int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
1826 if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
1828 DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
1829 DAG.getValueType(MVT::i16));
1830 Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
1831 RHS.getValueType()),
1833 AArch64CC = changeIntCCToAArch64CC(CC);
1837 if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
1838 if ((Cmp = emitConjunctionDisjunctionTree(DAG, LHS, AArch64CC))) {
1839 if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
1840 AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
1846 Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
1847 AArch64CC = changeIntCCToAArch64CC(CC);
1849 AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
1853 static std::pair<SDValue, SDValue>
1854 getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
1855 assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
1856 "Unsupported value type");
1857 SDValue Value, Overflow;
1859 SDValue LHS = Op.getOperand(0);
1860 SDValue RHS = Op.getOperand(1);
1862 switch (Op.getOpcode()) {
1864 llvm_unreachable("Unknown overflow instruction!");
1866 Opc = AArch64ISD::ADDS;
1870 Opc = AArch64ISD::ADDS;
1874 Opc = AArch64ISD::SUBS;
1878 Opc = AArch64ISD::SUBS;
1881 // Multiply needs a little bit extra work.
1885 bool IsSigned = Op.getOpcode() == ISD::SMULO;
1886 if (Op.getValueType() == MVT::i32) {
1887 unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1888 // For a 32 bit multiply with overflow check we want the instruction
1889 // selector to generate a widening multiply (SMADDL/UMADDL). For that we
1890 // need to generate the following pattern:
1891 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
1892 LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
1893 RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
1894 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1895 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
1896 DAG.getConstant(0, DL, MVT::i64));
1897 // On AArch64 the upper 32 bits are always zero extended for a 32 bit
1898 // operation. We need to clear out the upper 32 bits, because we used a
1899 // widening multiply that wrote all 64 bits. In the end this should be a
1901 Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
1903 // The signed overflow check requires more than just a simple check for
1904 // any bit set in the upper 32 bits of the result. These bits could be
1905 // just the sign bits of a negative number. To perform the overflow
1906 // check we have to arithmetic shift right the 32nd bit of the result by
1907 // 31 bits. Then we compare the result to the upper 32 bits.
1908 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
1909 DAG.getConstant(32, DL, MVT::i64));
1910 UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
1911 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
1912 DAG.getConstant(31, DL, MVT::i64));
1913 // It is important that LowerBits is last, otherwise the arithmetic
1914 // shift will not be folded into the compare (SUBS).
1915 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
1916 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1919 // The overflow check for unsigned multiply is easy. We only need to
1920 // check if any of the upper 32 bits are set. This can be done with a
1921 // CMP (shifted register). For that we need to generate the following
1923 // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
1924 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
1925 DAG.getConstant(32, DL, MVT::i64));
1926 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1928 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1929 DAG.getConstant(0, DL, MVT::i64),
1930 UpperBits).getValue(1);
1934 assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
1935 // For the 64 bit multiply
1936 Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1938 SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
1939 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
1940 DAG.getConstant(63, DL, MVT::i64));
1941 // It is important that LowerBits is last, otherwise the arithmetic
1942 // shift will not be folded into the compare (SUBS).
1943 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1944 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1947 SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
1948 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1950 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1951 DAG.getConstant(0, DL, MVT::i64),
1952 UpperBits).getValue(1);
1959 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
1961 // Emit the AArch64 operation with overflow check.
1962 Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
1963 Overflow = Value.getValue(1);
1965 return std::make_pair(Value, Overflow);
1968 SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
1969 RTLIB::Libcall Call) const {
1970 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
1971 return makeLibCall(DAG, Call, MVT::f128, Ops, false, SDLoc(Op)).first;
1974 // Returns true if the given Op is the overflow flag result of an overflow
1975 // intrinsic operation.
1976 static bool isOverflowIntrOpRes(SDValue Op) {
1977 unsigned Opc = Op.getOpcode();
1978 return (Op.getResNo() == 1 &&
1979 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
1980 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO));
1983 static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
1984 SDValue Sel = Op.getOperand(0);
1985 SDValue Other = Op.getOperand(1);
1988 // If the operand is an overflow checking operation, invert the condition
1989 // code and kill the Not operation. I.e., transform:
1990 // (xor (overflow_op_bool, 1))
1992 // (csel 1, 0, invert(cc), overflow_op_bool)
1993 // ... which later gets transformed to just a cset instruction with an
1994 // inverted condition code, rather than a cset + eor sequence.
1995 if (isOneConstant(Other) && isOverflowIntrOpRes(Sel)) {
1996 // Only lower legal XALUO ops.
1997 if (!DAG.getTargetLoweringInfo().isTypeLegal(Sel->getValueType(0)))
2000 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2001 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
2002 AArch64CC::CondCode CC;
2003 SDValue Value, Overflow;
2004 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Sel.getValue(0), DAG);
2005 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2006 return DAG.getNode(AArch64ISD::CSEL, dl, Op.getValueType(), TVal, FVal,
2009 // If neither operand is a SELECT_CC, give up.
2010 if (Sel.getOpcode() != ISD::SELECT_CC)
2011 std::swap(Sel, Other);
2012 if (Sel.getOpcode() != ISD::SELECT_CC)
2015 // The folding we want to perform is:
2016 // (xor x, (select_cc a, b, cc, 0, -1) )
2018 // (csel x, (xor x, -1), cc ...)
2020 // The latter will get matched to a CSINV instruction.
2022 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
2023 SDValue LHS = Sel.getOperand(0);
2024 SDValue RHS = Sel.getOperand(1);
2025 SDValue TVal = Sel.getOperand(2);
2026 SDValue FVal = Sel.getOperand(3);
2028 // FIXME: This could be generalized to non-integer comparisons.
2029 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
2032 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
2033 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
2035 // The values aren't constants, this isn't the pattern we're looking for.
2036 if (!CFVal || !CTVal)
2039 // We can commute the SELECT_CC by inverting the condition. This
2040 // might be needed to make this fit into a CSINV pattern.
2041 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
2042 std::swap(TVal, FVal);
2043 std::swap(CTVal, CFVal);
2044 CC = ISD::getSetCCInverse(CC, true);
2047 // If the constants line up, perform the transform!
2048 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
2050 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
2053 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
2054 DAG.getConstant(-1ULL, dl, Other.getValueType()));
2056 return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
2063 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
2064 EVT VT = Op.getValueType();
2066 // Let legalize expand this if it isn't a legal type yet.
2067 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
2070 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
2073 bool ExtraOp = false;
2074 switch (Op.getOpcode()) {
2076 llvm_unreachable("Invalid code");
2078 Opc = AArch64ISD::ADDS;
2081 Opc = AArch64ISD::SUBS;
2084 Opc = AArch64ISD::ADCS;
2088 Opc = AArch64ISD::SBCS;
2094 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
2095 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
2099 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
2100 // Let legalize expand this if it isn't a legal type yet.
2101 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
2105 AArch64CC::CondCode CC;
2106 // The actual operation that sets the overflow or carry flag.
2107 SDValue Value, Overflow;
2108 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
2110 // We use 0 and 1 as false and true values.
2111 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2112 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
2114 // We use an inverted condition, because the conditional select is inverted
2115 // too. This will allow it to be selected to a single instruction:
2116 // CSINC Wd, WZR, WZR, invert(cond).
2117 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2118 Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
2121 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
2122 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
2125 // Prefetch operands are:
2126 // 1: Address to prefetch
2128 // 3: int locality (0 = no locality ... 3 = extreme locality)
2129 // 4: bool isDataCache
2130 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
2132 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2133 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
2134 unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2136 bool IsStream = !Locality;
2137 // When the locality number is set
2139 // The front-end should have filtered out the out-of-range values
2140 assert(Locality <= 3 && "Prefetch locality out-of-range");
2141 // The locality degree is the opposite of the cache speed.
2142 // Put the number the other way around.
2143 // The encoding starts at 0 for level 1
2144 Locality = 3 - Locality;
2147 // built the mask value encoding the expected behavior.
2148 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit
2149 (!IsData << 3) | // IsDataCache bit
2150 (Locality << 1) | // Cache level bits
2151 (unsigned)IsStream; // Stream bit
2152 return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
2153 DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
2156 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
2157 SelectionDAG &DAG) const {
2158 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
2161 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
2163 return LowerF128Call(Op, DAG, LC);
2166 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
2167 SelectionDAG &DAG) const {
2168 if (Op.getOperand(0).getValueType() != MVT::f128) {
2169 // It's legal except when f128 is involved
2174 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
2176 // FP_ROUND node has a second operand indicating whether it is known to be
2177 // precise. That doesn't take part in the LibCall so we can't directly use
2179 SDValue SrcVal = Op.getOperand(0);
2180 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
2184 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
2185 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2186 // Any additional optimization in this function should be recorded
2187 // in the cost tables.
2188 EVT InVT = Op.getOperand(0).getValueType();
2189 EVT VT = Op.getValueType();
2190 unsigned NumElts = InVT.getVectorNumElements();
2192 // f16 vectors are promoted to f32 before a conversion.
2193 if (InVT.getVectorElementType() == MVT::f16) {
2194 MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
2197 Op.getOpcode(), dl, Op.getValueType(),
2198 DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
2201 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2204 DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
2206 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
2209 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2212 MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
2213 VT.getVectorNumElements());
2214 SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
2215 return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
2218 // Type changing conversions are illegal.
2222 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
2223 SelectionDAG &DAG) const {
2224 if (Op.getOperand(0).getValueType().isVector())
2225 return LowerVectorFP_TO_INT(Op, DAG);
2227 // f16 conversions are promoted to f32 when full fp16 is not supported.
2228 if (Op.getOperand(0).getValueType() == MVT::f16 &&
2229 !Subtarget->hasFullFP16()) {
2232 Op.getOpcode(), dl, Op.getValueType(),
2233 DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
2236 if (Op.getOperand(0).getValueType() != MVT::f128) {
2237 // It's legal except when f128 is involved
2242 if (Op.getOpcode() == ISD::FP_TO_SINT)
2243 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
2245 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
2247 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
2248 return makeLibCall(DAG, LC, Op.getValueType(), Ops, false, SDLoc(Op)).first;
2251 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
2252 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2253 // Any additional optimization in this function should be recorded
2254 // in the cost tables.
2255 EVT VT = Op.getValueType();
2257 SDValue In = Op.getOperand(0);
2258 EVT InVT = In.getValueType();
2260 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2262 MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
2263 InVT.getVectorNumElements());
2264 In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
2265 return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
2268 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2270 Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2271 EVT CastVT = VT.changeVectorElementTypeToInteger();
2272 In = DAG.getNode(CastOpc, dl, CastVT, In);
2273 return DAG.getNode(Op.getOpcode(), dl, VT, In);
2279 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
2280 SelectionDAG &DAG) const {
2281 if (Op.getValueType().isVector())
2282 return LowerVectorINT_TO_FP(Op, DAG);
2284 // f16 conversions are promoted to f32 when full fp16 is not supported.
2285 if (Op.getValueType() == MVT::f16 &&
2286 !Subtarget->hasFullFP16()) {
2289 ISD::FP_ROUND, dl, MVT::f16,
2290 DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
2291 DAG.getIntPtrConstant(0, dl));
2294 // i128 conversions are libcalls.
2295 if (Op.getOperand(0).getValueType() == MVT::i128)
2298 // Other conversions are legal, unless it's to the completely software-based
2300 if (Op.getValueType() != MVT::f128)
2304 if (Op.getOpcode() == ISD::SINT_TO_FP)
2305 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2307 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2309 return LowerF128Call(Op, DAG, LC);
2312 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
2313 SelectionDAG &DAG) const {
2314 // For iOS, we want to call an alternative entry point: __sincos_stret,
2315 // which returns the values in two S / D registers.
2317 SDValue Arg = Op.getOperand(0);
2318 EVT ArgVT = Arg.getValueType();
2319 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2326 Entry.IsSExt = false;
2327 Entry.IsZExt = false;
2328 Args.push_back(Entry);
2330 RTLIB::Libcall LC = ArgVT == MVT::f64 ? RTLIB::SINCOS_STRET_F64
2331 : RTLIB::SINCOS_STRET_F32;
2332 const char *LibcallName = getLibcallName(LC);
2334 DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
2336 StructType *RetTy = StructType::get(ArgTy, ArgTy);
2337 TargetLowering::CallLoweringInfo CLI(DAG);
2339 .setChain(DAG.getEntryNode())
2340 .setLibCallee(CallingConv::Fast, RetTy, Callee, std::move(Args));
2342 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2343 return CallResult.first;
2346 static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
2347 if (Op.getValueType() != MVT::f16)
2350 assert(Op.getOperand(0).getValueType() == MVT::i16);
2353 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
2354 Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
2356 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
2357 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
2361 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
2362 if (OrigVT.getSizeInBits() >= 64)
2365 assert(OrigVT.isSimple() && "Expecting a simple value type");
2367 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
2368 switch (OrigSimpleTy) {
2369 default: llvm_unreachable("Unexpected Vector Type");
2378 static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2381 unsigned ExtOpcode) {
2382 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2383 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2384 // 64-bits we need to insert a new extension so that it will be 64-bits.
2385 assert(ExtTy.is128BitVector() && "Unexpected extension size");
2386 if (OrigTy.getSizeInBits() >= 64)
2389 // Must extend size to at least 64 bits to be used as an operand for VMULL.
2390 EVT NewVT = getExtensionTo64Bits(OrigTy);
2392 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2395 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2397 EVT VT = N->getValueType(0);
2399 if (N->getOpcode() != ISD::BUILD_VECTOR)
2402 for (const SDValue &Elt : N->op_values()) {
2403 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
2404 unsigned EltSize = VT.getScalarSizeInBits();
2405 unsigned HalfSize = EltSize / 2;
2407 if (!isIntN(HalfSize, C->getSExtValue()))
2410 if (!isUIntN(HalfSize, C->getZExtValue()))
2421 static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2422 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2423 return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2424 N->getOperand(0)->getValueType(0),
2428 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2429 EVT VT = N->getValueType(0);
2431 unsigned EltSize = VT.getScalarSizeInBits() / 2;
2432 unsigned NumElts = VT.getVectorNumElements();
2433 MVT TruncVT = MVT::getIntegerVT(EltSize);
2434 SmallVector<SDValue, 8> Ops;
2435 for (unsigned i = 0; i != NumElts; ++i) {
2436 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2437 const APInt &CInt = C->getAPIntValue();
2438 // Element types smaller than 32 bits are not legal, so use i32 elements.
2439 // The values are implicitly truncated so sext vs. zext doesn't matter.
2440 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
2442 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
2445 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
2446 return N->getOpcode() == ISD::SIGN_EXTEND ||
2447 isExtendedBUILD_VECTOR(N, DAG, true);
2450 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
2451 return N->getOpcode() == ISD::ZERO_EXTEND ||
2452 isExtendedBUILD_VECTOR(N, DAG, false);
2455 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2456 unsigned Opcode = N->getOpcode();
2457 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2458 SDNode *N0 = N->getOperand(0).getNode();
2459 SDNode *N1 = N->getOperand(1).getNode();
2460 return N0->hasOneUse() && N1->hasOneUse() &&
2461 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2466 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2467 unsigned Opcode = N->getOpcode();
2468 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2469 SDNode *N0 = N->getOperand(0).getNode();
2470 SDNode *N1 = N->getOperand(1).getNode();
2471 return N0->hasOneUse() && N1->hasOneUse() &&
2472 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2477 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2478 // Multiplications are only custom-lowered for 128-bit vectors so that
2479 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
2480 EVT VT = Op.getValueType();
2481 assert(VT.is128BitVector() && VT.isInteger() &&
2482 "unexpected type for custom-lowering ISD::MUL");
2483 SDNode *N0 = Op.getOperand(0).getNode();
2484 SDNode *N1 = Op.getOperand(1).getNode();
2485 unsigned NewOpc = 0;
2487 bool isN0SExt = isSignExtended(N0, DAG);
2488 bool isN1SExt = isSignExtended(N1, DAG);
2489 if (isN0SExt && isN1SExt)
2490 NewOpc = AArch64ISD::SMULL;
2492 bool isN0ZExt = isZeroExtended(N0, DAG);
2493 bool isN1ZExt = isZeroExtended(N1, DAG);
2494 if (isN0ZExt && isN1ZExt)
2495 NewOpc = AArch64ISD::UMULL;
2496 else if (isN1SExt || isN1ZExt) {
2497 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2498 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2499 if (isN1SExt && isAddSubSExt(N0, DAG)) {
2500 NewOpc = AArch64ISD::SMULL;
2502 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2503 NewOpc = AArch64ISD::UMULL;
2505 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2507 NewOpc = AArch64ISD::UMULL;
2513 if (VT == MVT::v2i64)
2514 // Fall through to expand this. It is not legal.
2517 // Other vector multiplications are legal.
2522 // Legalize to a S/UMULL instruction
2525 SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2527 Op0 = skipExtensionForVectorMULL(N0, DAG);
2528 assert(Op0.getValueType().is64BitVector() &&
2529 Op1.getValueType().is64BitVector() &&
2530 "unexpected types for extended operands to VMULL");
2531 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2533 // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2534 // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2535 // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2536 SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2537 SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2538 EVT Op1VT = Op1.getValueType();
2539 return DAG.getNode(N0->getOpcode(), DL, VT,
2540 DAG.getNode(NewOpc, DL, VT,
2541 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2542 DAG.getNode(NewOpc, DL, VT,
2543 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2546 SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2547 SelectionDAG &DAG) const {
2548 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2551 default: return SDValue(); // Don't custom lower most intrinsics.
2552 case Intrinsic::thread_pointer: {
2553 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2554 return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
2556 case Intrinsic::aarch64_neon_abs:
2557 return DAG.getNode(ISD::ABS, dl, Op.getValueType(),
2559 case Intrinsic::aarch64_neon_smax:
2560 return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
2561 Op.getOperand(1), Op.getOperand(2));
2562 case Intrinsic::aarch64_neon_umax:
2563 return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
2564 Op.getOperand(1), Op.getOperand(2));
2565 case Intrinsic::aarch64_neon_smin:
2566 return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
2567 Op.getOperand(1), Op.getOperand(2));
2568 case Intrinsic::aarch64_neon_umin:
2569 return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
2570 Op.getOperand(1), Op.getOperand(2));
2574 SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
2575 SelectionDAG &DAG) const {
2576 DEBUG(dbgs() << "Custom lowering: ");
2579 switch (Op.getOpcode()) {
2581 llvm_unreachable("unimplemented operand");
2584 return LowerBITCAST(Op, DAG);
2585 case ISD::GlobalAddress:
2586 return LowerGlobalAddress(Op, DAG);
2587 case ISD::GlobalTLSAddress:
2588 return LowerGlobalTLSAddress(Op, DAG);
2590 return LowerSETCC(Op, DAG);
2592 return LowerBR_CC(Op, DAG);
2594 return LowerSELECT(Op, DAG);
2595 case ISD::SELECT_CC:
2596 return LowerSELECT_CC(Op, DAG);
2597 case ISD::JumpTable:
2598 return LowerJumpTable(Op, DAG);
2599 case ISD::ConstantPool:
2600 return LowerConstantPool(Op, DAG);
2601 case ISD::BlockAddress:
2602 return LowerBlockAddress(Op, DAG);
2604 return LowerVASTART(Op, DAG);
2606 return LowerVACOPY(Op, DAG);
2608 return LowerVAARG(Op, DAG);
2613 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
2620 return LowerXALUO(Op, DAG);
2622 return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
2624 return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
2626 return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
2628 return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
2630 return LowerFP_ROUND(Op, DAG);
2631 case ISD::FP_EXTEND:
2632 return LowerFP_EXTEND(Op, DAG);
2633 case ISD::FRAMEADDR:
2634 return LowerFRAMEADDR(Op, DAG);
2635 case ISD::RETURNADDR:
2636 return LowerRETURNADDR(Op, DAG);
2637 case ISD::INSERT_VECTOR_ELT:
2638 return LowerINSERT_VECTOR_ELT(Op, DAG);
2639 case ISD::EXTRACT_VECTOR_ELT:
2640 return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2641 case ISD::BUILD_VECTOR:
2642 return LowerBUILD_VECTOR(Op, DAG);
2643 case ISD::VECTOR_SHUFFLE:
2644 return LowerVECTOR_SHUFFLE(Op, DAG);
2645 case ISD::EXTRACT_SUBVECTOR:
2646 return LowerEXTRACT_SUBVECTOR(Op, DAG);
2650 return LowerVectorSRA_SRL_SHL(Op, DAG);
2651 case ISD::SHL_PARTS:
2652 return LowerShiftLeftParts(Op, DAG);
2653 case ISD::SRL_PARTS:
2654 case ISD::SRA_PARTS:
2655 return LowerShiftRightParts(Op, DAG);
2657 return LowerCTPOP(Op, DAG);
2658 case ISD::FCOPYSIGN:
2659 return LowerFCOPYSIGN(Op, DAG);
2661 return LowerVectorAND(Op, DAG);
2663 return LowerVectorOR(Op, DAG);
2665 return LowerXOR(Op, DAG);
2667 return LowerPREFETCH(Op, DAG);
2668 case ISD::SINT_TO_FP:
2669 case ISD::UINT_TO_FP:
2670 return LowerINT_TO_FP(Op, DAG);
2671 case ISD::FP_TO_SINT:
2672 case ISD::FP_TO_UINT:
2673 return LowerFP_TO_INT(Op, DAG);
2675 return LowerFSINCOS(Op, DAG);
2677 return LowerMUL(Op, DAG);
2678 case ISD::INTRINSIC_WO_CHAIN:
2679 return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2680 case ISD::VECREDUCE_ADD:
2681 case ISD::VECREDUCE_SMAX:
2682 case ISD::VECREDUCE_SMIN:
2683 case ISD::VECREDUCE_UMAX:
2684 case ISD::VECREDUCE_UMIN:
2685 case ISD::VECREDUCE_FMAX:
2686 case ISD::VECREDUCE_FMIN:
2687 return LowerVECREDUCE(Op, DAG);
2691 //===----------------------------------------------------------------------===//
2692 // Calling Convention Implementation
2693 //===----------------------------------------------------------------------===//
2695 #include "AArch64GenCallingConv.inc"
2697 /// Selects the correct CCAssignFn for a given CallingConvention value.
2698 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2699 bool IsVarArg) const {
2702 report_fatal_error("Unsupported calling convention.");
2703 case CallingConv::WebKit_JS:
2704 return CC_AArch64_WebKit_JS;
2705 case CallingConv::GHC:
2706 return CC_AArch64_GHC;
2707 case CallingConv::C:
2708 case CallingConv::Fast:
2709 case CallingConv::PreserveMost:
2710 case CallingConv::CXX_FAST_TLS:
2711 case CallingConv::Swift:
2712 if (Subtarget->isTargetWindows() && IsVarArg)
2713 return CC_AArch64_Win64_VarArg;
2714 if (!Subtarget->isTargetDarwin())
2715 return CC_AArch64_AAPCS;
2716 return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
2717 case CallingConv::Win64:
2718 return IsVarArg ? CC_AArch64_Win64_VarArg : CC_AArch64_AAPCS;
2723 AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const {
2724 return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
2725 : RetCC_AArch64_AAPCS;
2728 SDValue AArch64TargetLowering::LowerFormalArguments(
2729 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2730 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2731 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2732 MachineFunction &MF = DAG.getMachineFunction();
2733 MachineFrameInfo &MFI = MF.getFrameInfo();
2734 bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
2736 // Assign locations to all of the incoming arguments.
2737 SmallVector<CCValAssign, 16> ArgLocs;
2738 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2741 // At this point, Ins[].VT may already be promoted to i32. To correctly
2742 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2743 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2744 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
2745 // we use a special version of AnalyzeFormalArguments to pass in ValVT and
2747 unsigned NumArgs = Ins.size();
2748 Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
2749 unsigned CurArgIdx = 0;
2750 for (unsigned i = 0; i != NumArgs; ++i) {
2751 MVT ValVT = Ins[i].VT;
2752 if (Ins[i].isOrigArg()) {
2753 std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
2754 CurArgIdx = Ins[i].getOrigArgIndex();
2756 // Get type of the original argument.
2757 EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
2758 /*AllowUnknown*/ true);
2759 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
2760 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2761 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2763 else if (ActualMVT == MVT::i16)
2766 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2768 AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
2769 assert(!Res && "Call operand has unhandled type");
2772 assert(ArgLocs.size() == Ins.size());
2773 SmallVector<SDValue, 16> ArgValues;
2774 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2775 CCValAssign &VA = ArgLocs[i];
2777 if (Ins[i].Flags.isByVal()) {
2778 // Byval is used for HFAs in the PCS, but the system should work in a
2779 // non-compliant manner for larger structs.
2780 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2781 int Size = Ins[i].Flags.getByValSize();
2782 unsigned NumRegs = (Size + 7) / 8;
2784 // FIXME: This works on big-endian for composite byvals, which are the common
2785 // case. It should also work for fundamental types too.
2787 MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
2788 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
2789 InVals.push_back(FrameIdxN);
2794 if (VA.isRegLoc()) {
2795 // Arguments stored in registers.
2796 EVT RegVT = VA.getLocVT();
2799 const TargetRegisterClass *RC;
2801 if (RegVT == MVT::i32)
2802 RC = &AArch64::GPR32RegClass;
2803 else if (RegVT == MVT::i64)
2804 RC = &AArch64::GPR64RegClass;
2805 else if (RegVT == MVT::f16)
2806 RC = &AArch64::FPR16RegClass;
2807 else if (RegVT == MVT::f32)
2808 RC = &AArch64::FPR32RegClass;
2809 else if (RegVT == MVT::f64 || RegVT.is64BitVector())
2810 RC = &AArch64::FPR64RegClass;
2811 else if (RegVT == MVT::f128 || RegVT.is128BitVector())
2812 RC = &AArch64::FPR128RegClass;
2814 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2816 // Transform the arguments in physical registers into virtual ones.
2817 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2818 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2820 // If this is an 8, 16 or 32-bit value, it is really passed promoted
2821 // to 64 bits. Insert an assert[sz]ext to capture this, then
2822 // truncate to the right size.
2823 switch (VA.getLocInfo()) {
2825 llvm_unreachable("Unknown loc info!");
2826 case CCValAssign::Full:
2828 case CCValAssign::BCvt:
2829 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
2831 case CCValAssign::AExt:
2832 case CCValAssign::SExt:
2833 case CCValAssign::ZExt:
2834 // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
2835 // nodes after our lowering.
2836 assert(RegVT == Ins[i].VT && "incorrect register location selected");
2840 InVals.push_back(ArgValue);
2842 } else { // VA.isRegLoc()
2843 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
2844 unsigned ArgOffset = VA.getLocMemOffset();
2845 unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
2847 uint32_t BEAlign = 0;
2848 if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
2849 !Ins[i].Flags.isInConsecutiveRegs())
2850 BEAlign = 8 - ArgSize;
2852 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
2854 // Create load nodes to retrieve arguments from the stack.
2855 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2858 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
2859 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
2860 MVT MemVT = VA.getValVT();
2862 switch (VA.getLocInfo()) {
2865 case CCValAssign::BCvt:
2866 MemVT = VA.getLocVT();
2868 case CCValAssign::SExt:
2869 ExtType = ISD::SEXTLOAD;
2871 case CCValAssign::ZExt:
2872 ExtType = ISD::ZEXTLOAD;
2874 case CCValAssign::AExt:
2875 ExtType = ISD::EXTLOAD;
2879 ArgValue = DAG.getExtLoad(
2880 ExtType, DL, VA.getLocVT(), Chain, FIN,
2881 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
2884 InVals.push_back(ArgValue);
2889 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2891 if (!Subtarget->isTargetDarwin() || IsWin64) {
2892 // The AAPCS variadic function ABI is identical to the non-variadic
2893 // one. As a result there may be more arguments in registers and we should
2894 // save them for future reference.
2895 // Win64 variadic functions also pass arguments in registers, but all float
2896 // arguments are passed in integer registers.
2897 saveVarArgRegisters(CCInfo, DAG, DL, Chain);
2900 // This will point to the next argument passed via stack.
2901 unsigned StackOffset = CCInfo.getNextStackOffset();
2902 // We currently pass all varargs at 8-byte alignment.
2903 StackOffset = ((StackOffset + 7) & ~7);
2904 FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true));
2907 unsigned StackArgSize = CCInfo.getNextStackOffset();
2908 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2909 if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
2910 // This is a non-standard ABI so by fiat I say we're allowed to make full
2911 // use of the stack area to be popped, which must be aligned to 16 bytes in
2913 StackArgSize = alignTo(StackArgSize, 16);
2915 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
2916 // a multiple of 16.
2917 FuncInfo->setArgumentStackToRestore(StackArgSize);
2919 // This realignment carries over to the available bytes below. Our own
2920 // callers will guarantee the space is free by giving an aligned value to
2923 // Even if we're not expected to free up the space, it's useful to know how
2924 // much is there while considering tail calls (because we can reuse it).
2925 FuncInfo->setBytesInStackArgArea(StackArgSize);
2930 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
2933 SDValue &Chain) const {
2934 MachineFunction &MF = DAG.getMachineFunction();
2935 MachineFrameInfo &MFI = MF.getFrameInfo();
2936 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2937 auto PtrVT = getPointerTy(DAG.getDataLayout());
2938 bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
2940 SmallVector<SDValue, 8> MemOps;
2942 static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
2943 AArch64::X3, AArch64::X4, AArch64::X5,
2944 AArch64::X6, AArch64::X7 };
2945 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
2946 unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
2948 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
2950 if (GPRSaveSize != 0) {
2952 GPRIdx = MFI.CreateFixedObject(GPRSaveSize, -(int)GPRSaveSize, false);
2953 if (GPRSaveSize & 15)
2954 // The extra size here, if triggered, will always be 8.
2955 MFI.CreateFixedObject(16 - (GPRSaveSize & 15), -(int)alignTo(GPRSaveSize, 16), false);
2957 GPRIdx = MFI.CreateStackObject(GPRSaveSize, 8, false);
2959 SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
2961 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
2962 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
2963 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
2964 SDValue Store = DAG.getStore(
2965 Val.getValue(1), DL, Val, FIN,
2967 ? MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
2969 (i - FirstVariadicGPR) * 8)
2970 : MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8));
2971 MemOps.push_back(Store);
2973 DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
2976 FuncInfo->setVarArgsGPRIndex(GPRIdx);
2977 FuncInfo->setVarArgsGPRSize(GPRSaveSize);
2979 if (Subtarget->hasFPARMv8() && !IsWin64) {
2980 static const MCPhysReg FPRArgRegs[] = {
2981 AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
2982 AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
2983 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
2984 unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
2986 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
2988 if (FPRSaveSize != 0) {
2989 FPRIdx = MFI.CreateStackObject(FPRSaveSize, 16, false);
2991 SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
2993 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
2994 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
2995 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
2997 SDValue Store = DAG.getStore(
2998 Val.getValue(1), DL, Val, FIN,
2999 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16));
3000 MemOps.push_back(Store);
3001 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
3002 DAG.getConstant(16, DL, PtrVT));
3005 FuncInfo->setVarArgsFPRIndex(FPRIdx);
3006 FuncInfo->setVarArgsFPRSize(FPRSaveSize);
3009 if (!MemOps.empty()) {
3010 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
3014 /// LowerCallResult - Lower the result values of a call into the
3015 /// appropriate copies out of appropriate physical registers.
3016 SDValue AArch64TargetLowering::LowerCallResult(
3017 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
3018 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3019 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
3020 SDValue ThisVal) const {
3021 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3022 ? RetCC_AArch64_WebKit_JS
3023 : RetCC_AArch64_AAPCS;
3024 // Assign locations to each value returned by this call.
3025 SmallVector<CCValAssign, 16> RVLocs;
3026 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3028 CCInfo.AnalyzeCallResult(Ins, RetCC);
3030 // Copy all of the result registers out of their specified physreg.
3031 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3032 CCValAssign VA = RVLocs[i];
3034 // Pass 'this' value directly from the argument to return value, to avoid
3035 // reg unit interference
3036 if (i == 0 && isThisReturn) {
3037 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
3038 "unexpected return calling convention register assignment");
3039 InVals.push_back(ThisVal);
3044 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
3045 Chain = Val.getValue(1);
3046 InFlag = Val.getValue(2);
3048 switch (VA.getLocInfo()) {
3050 llvm_unreachable("Unknown loc info!");
3051 case CCValAssign::Full:
3053 case CCValAssign::BCvt:
3054 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
3058 InVals.push_back(Val);
3064 /// Return true if the calling convention is one that we can guarantee TCO for.
3065 static bool canGuaranteeTCO(CallingConv::ID CC) {
3066 return CC == CallingConv::Fast;
3069 /// Return true if we might ever do TCO for calls with this calling convention.
3070 static bool mayTailCallThisCC(CallingConv::ID CC) {
3072 case CallingConv::C:
3073 case CallingConv::PreserveMost:
3074 case CallingConv::Swift:
3077 return canGuaranteeTCO(CC);
3081 bool AArch64TargetLowering::isEligibleForTailCallOptimization(
3082 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
3083 const SmallVectorImpl<ISD::OutputArg> &Outs,
3084 const SmallVectorImpl<SDValue> &OutVals,
3085 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
3086 if (!mayTailCallThisCC(CalleeCC))
3089 MachineFunction &MF = DAG.getMachineFunction();
3090 const Function &CallerF = MF.getFunction();
3091 CallingConv::ID CallerCC = CallerF.getCallingConv();
3092 bool CCMatch = CallerCC == CalleeCC;
3094 // Byval parameters hand the function a pointer directly into the stack area
3095 // we want to reuse during a tail call. Working around this *is* possible (see
3096 // X86) but less efficient and uglier in LowerCall.
3097 for (Function::const_arg_iterator i = CallerF.arg_begin(),
3098 e = CallerF.arg_end();
3100 if (i->hasByValAttr())
3103 if (getTargetMachine().Options.GuaranteedTailCallOpt)
3104 return canGuaranteeTCO(CalleeCC) && CCMatch;
3106 // Externally-defined functions with weak linkage should not be
3107 // tail-called on AArch64 when the OS does not support dynamic
3108 // pre-emption of symbols, as the AAELF spec requires normal calls
3109 // to undefined weak functions to be replaced with a NOP or jump to the
3110 // next instruction. The behaviour of branch instructions in this
3111 // situation (as used for tail calls) is implementation-defined, so we
3112 // cannot rely on the linker replacing the tail call with a return.
3113 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3114 const GlobalValue *GV = G->getGlobal();
3115 const Triple &TT = getTargetMachine().getTargetTriple();
3116 if (GV->hasExternalWeakLinkage() &&
3117 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
3121 // Now we search for cases where we can use a tail call without changing the
3122 // ABI. Sibcall is used in some places (particularly gcc) to refer to this
3125 // I want anyone implementing a new calling convention to think long and hard
3126 // about this assert.
3127 assert((!isVarArg || CalleeCC == CallingConv::C) &&
3128 "Unexpected variadic calling convention");
3130 LLVMContext &C = *DAG.getContext();
3131 if (isVarArg && !Outs.empty()) {
3132 // At least two cases here: if caller is fastcc then we can't have any
3133 // memory arguments (we'd be expected to clean up the stack afterwards). If
3134 // caller is C then we could potentially use its argument area.
3136 // FIXME: for now we take the most conservative of these in both cases:
3137 // disallow all variadic memory operands.
3138 SmallVector<CCValAssign, 16> ArgLocs;
3139 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
3141 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
3142 for (const CCValAssign &ArgLoc : ArgLocs)
3143 if (!ArgLoc.isRegLoc())
3147 // Check that the call results are passed in the same way.
3148 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
3149 CCAssignFnForCall(CalleeCC, isVarArg),
3150 CCAssignFnForCall(CallerCC, isVarArg)))
3152 // The callee has to preserve all registers the caller needs to preserve.
3153 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3154 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
3156 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
3157 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
3161 // Nothing more to check if the callee is taking no arguments
3165 SmallVector<CCValAssign, 16> ArgLocs;
3166 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
3168 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
3170 const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3172 // If the stack arguments for this call do not fit into our own save area then
3173 // the call cannot be made tail.
3174 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
3177 const MachineRegisterInfo &MRI = MF.getRegInfo();
3178 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
3184 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
3186 MachineFrameInfo &MFI,
3187 int ClobberedFI) const {
3188 SmallVector<SDValue, 8> ArgChains;
3189 int64_t FirstByte = MFI.getObjectOffset(ClobberedFI);
3190 int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1;
3192 // Include the original chain at the beginning of the list. When this is
3193 // used by target LowerCall hooks, this helps legalize find the
3194 // CALLSEQ_BEGIN node.
3195 ArgChains.push_back(Chain);
3197 // Add a chain value for each stack argument corresponding
3198 for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
3199 UE = DAG.getEntryNode().getNode()->use_end();
3201 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
3202 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
3203 if (FI->getIndex() < 0) {
3204 int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex());
3205 int64_t InLastByte = InFirstByte;
3206 InLastByte += MFI.getObjectSize(FI->getIndex()) - 1;
3208 if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
3209 (FirstByte <= InFirstByte && InFirstByte <= LastByte))
3210 ArgChains.push_back(SDValue(L, 1));
3213 // Build a tokenfactor for all the chains.
3214 return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
3217 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
3218 bool TailCallOpt) const {
3219 return CallCC == CallingConv::Fast && TailCallOpt;
3222 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
3223 /// and add input and output parameter nodes.
3225 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
3226 SmallVectorImpl<SDValue> &InVals) const {
3227 SelectionDAG &DAG = CLI.DAG;
3229 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
3230 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
3231 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
3232 SDValue Chain = CLI.Chain;
3233 SDValue Callee = CLI.Callee;
3234 bool &IsTailCall = CLI.IsTailCall;
3235 CallingConv::ID CallConv = CLI.CallConv;
3236 bool IsVarArg = CLI.IsVarArg;
3238 MachineFunction &MF = DAG.getMachineFunction();
3239 bool IsThisReturn = false;
3241 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3242 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3243 bool IsSibCall = false;
3246 // Check if it's really possible to do a tail call.
3247 IsTailCall = isEligibleForTailCallOptimization(
3248 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
3249 if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall())
3250 report_fatal_error("failed to perform tail call elimination on a call "
3251 "site marked musttail");
3253 // A sibling call is one where we're under the usual C ABI and not planning
3254 // to change that but can still do a tail call:
3255 if (!TailCallOpt && IsTailCall)
3262 // Analyze operands of the call, assigning locations to each operand.
3263 SmallVector<CCValAssign, 16> ArgLocs;
3264 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
3268 // Handle fixed and variable vector arguments differently.
3269 // Variable vector arguments always go into memory.
3270 unsigned NumArgs = Outs.size();
3272 for (unsigned i = 0; i != NumArgs; ++i) {
3273 MVT ArgVT = Outs[i].VT;
3274 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3275 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
3276 /*IsVarArg=*/ !Outs[i].IsFixed);
3277 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3278 assert(!Res && "Call operand has unhandled type");
3282 // At this point, Outs[].VT may already be promoted to i32. To correctly
3283 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
3284 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
3285 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
3286 // we use a special version of AnalyzeCallOperands to pass in ValVT and
3288 unsigned NumArgs = Outs.size();
3289 for (unsigned i = 0; i != NumArgs; ++i) {
3290 MVT ValVT = Outs[i].VT;
3291 // Get type of the original argument.
3292 EVT ActualVT = getValueType(DAG.getDataLayout(),
3293 CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
3294 /*AllowUnknown*/ true);
3295 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
3296 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3297 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
3298 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
3300 else if (ActualMVT == MVT::i16)
3303 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
3304 bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
3305 assert(!Res && "Call operand has unhandled type");
3310 // Get a count of how many bytes are to be pushed on the stack.
3311 unsigned NumBytes = CCInfo.getNextStackOffset();
3314 // Since we're not changing the ABI to make this a tail call, the memory
3315 // operands are already available in the caller's incoming argument space.
3319 // FPDiff is the byte offset of the call's argument area from the callee's.
3320 // Stores to callee stack arguments will be placed in FixedStackSlots offset
3321 // by this amount for a tail call. In a sibling call it must be 0 because the
3322 // caller will deallocate the entire stack and the callee still expects its
3323 // arguments to begin at SP+0. Completely unused for non-tail calls.
3326 if (IsTailCall && !IsSibCall) {
3327 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
3329 // Since callee will pop argument stack as a tail call, we must keep the
3330 // popped size 16-byte aligned.
3331 NumBytes = alignTo(NumBytes, 16);
3333 // FPDiff will be negative if this tail call requires more space than we
3334 // would automatically have in our incoming argument space. Positive if we
3335 // can actually shrink the stack.
3336 FPDiff = NumReusableBytes - NumBytes;
3338 // The stack pointer must be 16-byte aligned at all times it's used for a
3339 // memory operation, which in practice means at *all* times and in
3340 // particular across call boundaries. Therefore our own arguments started at
3341 // a 16-byte aligned SP and the delta applied for the tail call should
3342 // satisfy the same constraint.
3343 assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
3346 // Adjust the stack pointer for the new arguments...
3347 // These operations are automatically eliminated by the prolog/epilog pass
3349 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL);
3351 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
3352 getPointerTy(DAG.getDataLayout()));
3354 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3355 SmallVector<SDValue, 8> MemOpChains;
3356 auto PtrVT = getPointerTy(DAG.getDataLayout());
3358 // Walk the register/memloc assignments, inserting copies/loads.
3359 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
3360 ++i, ++realArgIdx) {
3361 CCValAssign &VA = ArgLocs[i];
3362 SDValue Arg = OutVals[realArgIdx];
3363 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
3365 // Promote the value if needed.
3366 switch (VA.getLocInfo()) {
3368 llvm_unreachable("Unknown loc info!");
3369 case CCValAssign::Full:
3371 case CCValAssign::SExt:
3372 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3374 case CCValAssign::ZExt:
3375 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3377 case CCValAssign::AExt:
3378 if (Outs[realArgIdx].ArgVT == MVT::i1) {
3379 // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
3380 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3381 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
3383 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3385 case CCValAssign::BCvt:
3386 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3388 case CCValAssign::FPExt:
3389 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3393 if (VA.isRegLoc()) {
3394 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
3395 Outs[0].VT == MVT::i64) {
3396 assert(VA.getLocVT() == MVT::i64 &&
3397 "unexpected calling convention register assignment");
3398 assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
3399 "unexpected use of 'returned'");
3400 IsThisReturn = true;
3402 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3404 assert(VA.isMemLoc());
3407 MachinePointerInfo DstInfo;
3409 // FIXME: This works on big-endian for composite byvals, which are the
3410 // common case. It should also work for fundamental types too.
3411 uint32_t BEAlign = 0;
3412 unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
3413 : VA.getValVT().getSizeInBits();
3414 OpSize = (OpSize + 7) / 8;
3415 if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
3416 !Flags.isInConsecutiveRegs()) {
3418 BEAlign = 8 - OpSize;
3420 unsigned LocMemOffset = VA.getLocMemOffset();
3421 int32_t Offset = LocMemOffset + BEAlign;
3422 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3423 PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3426 Offset = Offset + FPDiff;
3427 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
3429 DstAddr = DAG.getFrameIndex(FI, PtrVT);
3431 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
3433 // Make sure any stack arguments overlapping with where we're storing
3434 // are loaded before this eventual operation. Otherwise they'll be
3436 Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
3438 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3440 DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3441 DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
3445 if (Outs[i].Flags.isByVal()) {
3447 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
3448 SDValue Cpy = DAG.getMemcpy(
3449 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
3450 /*isVol = */ false, /*AlwaysInline = */ false,
3451 /*isTailCall = */ false,
3452 DstInfo, MachinePointerInfo());
3454 MemOpChains.push_back(Cpy);
3456 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
3457 // promoted to a legal register type i32, we should truncate Arg back to
3459 if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
3460 VA.getValVT() == MVT::i16)
3461 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
3463 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
3464 MemOpChains.push_back(Store);
3469 if (!MemOpChains.empty())
3470 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3472 // Build a sequence of copy-to-reg nodes chained together with token chain
3473 // and flag operands which copy the outgoing args into the appropriate regs.
3475 for (auto &RegToPass : RegsToPass) {
3476 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3477 RegToPass.second, InFlag);
3478 InFlag = Chain.getValue(1);
3481 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3482 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3483 // node so that legalize doesn't hack it.
3484 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3485 auto GV = G->getGlobal();
3486 if (Subtarget->classifyGlobalFunctionReference(GV, getTargetMachine()) ==
3487 AArch64II::MO_GOT) {
3488 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT);
3489 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3490 } else if (Subtarget->isTargetCOFF() && GV->hasDLLImportStorageClass()) {
3491 assert(Subtarget->isTargetWindows() &&
3492 "Windows is the only supported COFF target");
3493 Callee = getGOT(G, DAG, AArch64II::MO_DLLIMPORT);
3495 const GlobalValue *GV = G->getGlobal();
3496 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3498 } else if (auto *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3499 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3500 Subtarget->isTargetMachO()) {
3501 const char *Sym = S->getSymbol();
3502 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
3503 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3505 const char *Sym = S->getSymbol();
3506 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
3510 // We don't usually want to end the call-sequence here because we would tidy
3511 // the frame up *after* the call, however in the ABI-changing tail-call case
3512 // we've carefully laid out the parameters so that when sp is reset they'll be
3513 // in the correct location.
3514 if (IsTailCall && !IsSibCall) {
3515 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3516 DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
3517 InFlag = Chain.getValue(1);
3520 std::vector<SDValue> Ops;
3521 Ops.push_back(Chain);
3522 Ops.push_back(Callee);
3525 // Each tail call may have to adjust the stack by a different amount, so
3526 // this information must travel along with the operation for eventual
3527 // consumption by emitEpilogue.
3528 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3531 // Add argument registers to the end of the list so that they are known live
3533 for (auto &RegToPass : RegsToPass)
3534 Ops.push_back(DAG.getRegister(RegToPass.first,
3535 RegToPass.second.getValueType()));
3537 // Add a register mask operand representing the call-preserved registers.
3538 const uint32_t *Mask;
3539 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3541 // For 'this' returns, use the X0-preserving mask if applicable
3542 Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
3544 IsThisReturn = false;
3545 Mask = TRI->getCallPreservedMask(MF, CallConv);
3548 Mask = TRI->getCallPreservedMask(MF, CallConv);
3550 assert(Mask && "Missing call preserved mask for calling convention");
3551 Ops.push_back(DAG.getRegisterMask(Mask));
3553 if (InFlag.getNode())
3554 Ops.push_back(InFlag);
3556 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3558 // If we're doing a tall call, use a TC_RETURN here rather than an
3559 // actual call instruction.
3561 MF.getFrameInfo().setHasTailCall();
3562 return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
3565 // Returns a chain and a flag for retval copy to use.
3566 Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
3567 InFlag = Chain.getValue(1);
3569 uint64_t CalleePopBytes =
3570 DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
3572 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3573 DAG.getIntPtrConstant(CalleePopBytes, DL, true),
3576 InFlag = Chain.getValue(1);
3578 // Handle result values, copying them out of physregs into vregs that we
3580 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3581 InVals, IsThisReturn,
3582 IsThisReturn ? OutVals[0] : SDValue());
3585 bool AArch64TargetLowering::CanLowerReturn(
3586 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
3587 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
3588 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3589 ? RetCC_AArch64_WebKit_JS
3590 : RetCC_AArch64_AAPCS;
3591 SmallVector<CCValAssign, 16> RVLocs;
3592 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
3593 return CCInfo.CheckReturn(Outs, RetCC);
3597 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3599 const SmallVectorImpl<ISD::OutputArg> &Outs,
3600 const SmallVectorImpl<SDValue> &OutVals,
3601 const SDLoc &DL, SelectionDAG &DAG) const {
3602 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3603 ? RetCC_AArch64_WebKit_JS
3604 : RetCC_AArch64_AAPCS;
3605 SmallVector<CCValAssign, 16> RVLocs;
3606 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3608 CCInfo.AnalyzeReturn(Outs, RetCC);
3610 // Copy the result values into the output registers.
3612 SmallVector<SDValue, 4> RetOps(1, Chain);
3613 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
3614 ++i, ++realRVLocIdx) {
3615 CCValAssign &VA = RVLocs[i];
3616 assert(VA.isRegLoc() && "Can only return in registers!");
3617 SDValue Arg = OutVals[realRVLocIdx];
3619 switch (VA.getLocInfo()) {
3621 llvm_unreachable("Unknown loc info!");
3622 case CCValAssign::Full:
3623 if (Outs[i].ArgVT == MVT::i1) {
3624 // AAPCS requires i1 to be zero-extended to i8 by the producer of the
3625 // value. This is strictly redundant on Darwin (which uses "zeroext
3626 // i1"), but will be optimised out before ISel.
3627 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3628 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3631 case CCValAssign::BCvt:
3632 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3636 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
3637 Flag = Chain.getValue(1);
3638 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3640 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3641 const MCPhysReg *I =
3642 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
3645 if (AArch64::GPR64RegClass.contains(*I))
3646 RetOps.push_back(DAG.getRegister(*I, MVT::i64));
3647 else if (AArch64::FPR64RegClass.contains(*I))
3648 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
3650 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
3654 RetOps[0] = Chain; // Update chain.
3656 // Add the flag if we have it.
3658 RetOps.push_back(Flag);
3660 return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
3663 //===----------------------------------------------------------------------===//
3664 // Other Lowering Code
3665 //===----------------------------------------------------------------------===//
3667 SDValue AArch64TargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
3669 unsigned Flag) const {
3670 return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty, 0, Flag);
3673 SDValue AArch64TargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
3675 unsigned Flag) const {
3676 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
3679 SDValue AArch64TargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
3681 unsigned Flag) const {
3682 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
3683 N->getOffset(), Flag);
3686 SDValue AArch64TargetLowering::getTargetNode(BlockAddressSDNode* N, EVT Ty,
3688 unsigned Flag) const {
3689 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
3693 template <class NodeTy>
3694 SDValue AArch64TargetLowering::getGOT(NodeTy *N, SelectionDAG &DAG,
3695 unsigned Flags) const {
3696 DEBUG(dbgs() << "AArch64TargetLowering::getGOT\n");
3698 EVT Ty = getPointerTy(DAG.getDataLayout());
3699 SDValue GotAddr = getTargetNode(N, Ty, DAG, AArch64II::MO_GOT | Flags);
3700 // FIXME: Once remat is capable of dealing with instructions with register
3701 // operands, expand this into two nodes instead of using a wrapper node.
3702 return DAG.getNode(AArch64ISD::LOADgot, DL, Ty, GotAddr);
3705 // (wrapper %highest(sym), %higher(sym), %hi(sym), %lo(sym))
3706 template <class NodeTy>
3707 SDValue AArch64TargetLowering::getAddrLarge(NodeTy *N, SelectionDAG &DAG,
3708 unsigned Flags) const {
3709 DEBUG(dbgs() << "AArch64TargetLowering::getAddrLarge\n");
3711 EVT Ty = getPointerTy(DAG.getDataLayout());
3712 const unsigned char MO_NC = AArch64II::MO_NC;
3714 AArch64ISD::WrapperLarge, DL, Ty,
3715 getTargetNode(N, Ty, DAG, AArch64II::MO_G3 | Flags),
3716 getTargetNode(N, Ty, DAG, AArch64II::MO_G2 | MO_NC | Flags),
3717 getTargetNode(N, Ty, DAG, AArch64II::MO_G1 | MO_NC | Flags),
3718 getTargetNode(N, Ty, DAG, AArch64II::MO_G0 | MO_NC | Flags));
3721 // (addlow (adrp %hi(sym)) %lo(sym))
3722 template <class NodeTy>
3723 SDValue AArch64TargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
3724 unsigned Flags) const {
3725 DEBUG(dbgs() << "AArch64TargetLowering::getAddr\n");
3727 EVT Ty = getPointerTy(DAG.getDataLayout());
3728 SDValue Hi = getTargetNode(N, Ty, DAG, AArch64II::MO_PAGE | Flags);
3729 SDValue Lo = getTargetNode(N, Ty, DAG,
3730 AArch64II::MO_PAGEOFF | AArch64II::MO_NC | Flags);
3731 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, Ty, Hi);
3732 return DAG.getNode(AArch64ISD::ADDlow, DL, Ty, ADRP, Lo);
3735 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
3736 SelectionDAG &DAG) const {
3737 GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
3738 const GlobalValue *GV = GN->getGlobal();
3739 const AArch64II::TOF TargetFlags =
3740 (GV->hasDLLImportStorageClass() ? AArch64II::MO_DLLIMPORT
3741 : AArch64II::MO_NO_FLAG);
3742 unsigned char OpFlags =
3743 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
3745 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
3746 "unexpected offset in global node");
3748 // This also catches the large code model case for Darwin.
3749 if ((OpFlags & AArch64II::MO_GOT) != 0) {
3750 return getGOT(GN, DAG, TargetFlags);
3754 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
3755 Result = getAddrLarge(GN, DAG, TargetFlags);
3757 Result = getAddr(GN, DAG, TargetFlags);
3759 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3761 if (GV->hasDLLImportStorageClass())
3762 Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
3763 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3767 /// \brief Convert a TLS address reference into the correct sequence of loads
3768 /// and calls to compute the variable's address (for Darwin, currently) and
3769 /// return an SDValue containing the final node.
3771 /// Darwin only has one TLS scheme which must be capable of dealing with the
3772 /// fully general situation, in the worst case. This means:
3773 /// + "extern __thread" declaration.
3774 /// + Defined in a possibly unknown dynamic library.
3776 /// The general system is that each __thread variable has a [3 x i64] descriptor
3777 /// which contains information used by the runtime to calculate the address. The
3778 /// only part of this the compiler needs to know about is the first xword, which
3779 /// contains a function pointer that must be called with the address of the
3780 /// entire descriptor in "x0".
3782 /// Since this descriptor may be in a different unit, in general even the
3783 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
3785 /// adrp x0, _var@TLVPPAGE
3786 /// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor
3787 /// ldr x1, [x0] ; x1 contains 1st entry of descriptor,
3788 /// ; the function pointer
3789 /// blr x1 ; Uses descriptor address in x0
3790 /// ; Address of _var is now in x0.
3792 /// If the address of _var's descriptor *is* known to the linker, then it can
3793 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
3794 /// a slight efficiency gain.
3796 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
3797 SelectionDAG &DAG) const {
3798 assert(Subtarget->isTargetDarwin() &&
3799 "This function expects a Darwin target");
3802 MVT PtrVT = getPointerTy(DAG.getDataLayout());
3803 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3806 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3807 SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
3809 // The first entry in the descriptor is a function pointer that we must call
3810 // to obtain the address of the variable.
3811 SDValue Chain = DAG.getEntryNode();
3812 SDValue FuncTLVGet = DAG.getLoad(
3813 MVT::i64, DL, Chain, DescAddr,
3814 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
3815 /* Alignment = */ 8,
3816 MachineMemOperand::MONonTemporal | MachineMemOperand::MOInvariant |
3817 MachineMemOperand::MODereferenceable);
3818 Chain = FuncTLVGet.getValue(1);
3820 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
3821 MFI.setAdjustsStack(true);
3823 // TLS calls preserve all registers except those that absolutely must be
3824 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
3826 const uint32_t *Mask =
3827 Subtarget->getRegisterInfo()->getTLSCallPreservedMask();
3829 // Finally, we can make the call. This is just a degenerate version of a
3830 // normal AArch64 call node: x0 takes the address of the descriptor, and
3831 // returns the address of the variable in this thread.
3832 Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
3834 DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3835 Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
3836 DAG.getRegisterMask(Mask), Chain.getValue(1));
3837 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
3840 /// When accessing thread-local variables under either the general-dynamic or
3841 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
3842 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
3843 /// is a function pointer to carry out the resolution.
3845 /// The sequence is:
3846 /// adrp x0, :tlsdesc:var
3847 /// ldr x1, [x0, #:tlsdesc_lo12:var]
3848 /// add x0, x0, #:tlsdesc_lo12:var
3849 /// .tlsdesccall var
3851 /// (TPIDR_EL0 offset now in x0)
3853 /// The above sequence must be produced unscheduled, to enable the linker to
3854 /// optimize/relax this sequence.
3855 /// Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
3856 /// above sequence, and expanded really late in the compilation flow, to ensure
3857 /// the sequence is produced as per above.
3858 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr,
3860 SelectionDAG &DAG) const {
3861 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3863 SDValue Chain = DAG.getEntryNode();
3864 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3867 DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr});
3868 SDValue Glue = Chain.getValue(1);
3870 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
3874 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
3875 SelectionDAG &DAG) const {
3876 assert(Subtarget->isTargetELF() && "This function expects an ELF target");
3877 assert(Subtarget->useSmallAddressing() &&
3878 "ELF TLS only supported in small memory model");
3879 // Different choices can be made for the maximum size of the TLS area for a
3880 // module. For the small address model, the default TLS size is 16MiB and the
3881 // maximum TLS size is 4GiB.
3882 // FIXME: add -mtls-size command line option and make it control the 16MiB
3883 // vs. 4GiB code sequence generation.
3884 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3886 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
3888 if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
3889 if (Model == TLSModel::LocalDynamic)
3890 Model = TLSModel::GeneralDynamic;
3894 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3896 const GlobalValue *GV = GA->getGlobal();
3898 SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
3900 if (Model == TLSModel::LocalExec) {
3901 SDValue HiVar = DAG.getTargetGlobalAddress(
3902 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
3903 SDValue LoVar = DAG.getTargetGlobalAddress(
3905 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3907 SDValue TPWithOff_lo =
3908 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
3910 DAG.getTargetConstant(0, DL, MVT::i32)),
3913 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
3915 DAG.getTargetConstant(0, DL, MVT::i32)),
3918 } else if (Model == TLSModel::InitialExec) {
3919 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3920 TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
3921 } else if (Model == TLSModel::LocalDynamic) {
3922 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
3923 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
3924 // the beginning of the module's TLS region, followed by a DTPREL offset
3927 // These accesses will need deduplicating if there's more than one.
3928 AArch64FunctionInfo *MFI =
3929 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
3930 MFI->incNumLocalDynamicTLSAccesses();
3932 // The call needs a relocation too for linker relaxation. It doesn't make
3933 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3935 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
3938 // Now we can calculate the offset from TPIDR_EL0 to this module's
3939 // thread-local area.
3940 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
3942 // Now use :dtprel_whatever: operations to calculate this variable's offset
3943 // in its thread-storage area.
3944 SDValue HiVar = DAG.getTargetGlobalAddress(
3945 GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
3946 SDValue LoVar = DAG.getTargetGlobalAddress(
3947 GV, DL, MVT::i64, 0,
3948 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3950 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
3951 DAG.getTargetConstant(0, DL, MVT::i32)),
3953 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
3954 DAG.getTargetConstant(0, DL, MVT::i32)),
3956 } else if (Model == TLSModel::GeneralDynamic) {
3957 // The call needs a relocation too for linker relaxation. It doesn't make
3958 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3961 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3963 // Finally we can make a call to calculate the offset from tpidr_el0.
3964 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
3966 llvm_unreachable("Unsupported ELF TLS access model");
3968 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
3971 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
3972 SelectionDAG &DAG) const {
3973 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3974 if (DAG.getTarget().Options.EmulatedTLS)
3975 return LowerToTLSEmulatedModel(GA, DAG);
3977 if (Subtarget->isTargetDarwin())
3978 return LowerDarwinGlobalTLSAddress(Op, DAG);
3979 if (Subtarget->isTargetELF())
3980 return LowerELFGlobalTLSAddress(Op, DAG);
3982 llvm_unreachable("Unexpected platform trying to use TLS");
3985 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3986 SDValue Chain = Op.getOperand(0);
3987 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3988 SDValue LHS = Op.getOperand(2);
3989 SDValue RHS = Op.getOperand(3);
3990 SDValue Dest = Op.getOperand(4);
3993 // Handle f128 first, since lowering it will result in comparing the return
3994 // value of a libcall against zero, which is just what the rest of LowerBR_CC
3995 // is expecting to deal with.
3996 if (LHS.getValueType() == MVT::f128) {
3997 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3999 // If softenSetCCOperands returned a scalar, we need to compare the result
4000 // against zero to select between true and false values.
4001 if (!RHS.getNode()) {
4002 RHS = DAG.getConstant(0, dl, LHS.getValueType());
4007 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
4009 if (isOverflowIntrOpRes(LHS) && isOneConstant(RHS) &&
4010 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
4011 // Only lower legal XALUO ops.
4012 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
4015 // The actual operation with overflow check.
4016 AArch64CC::CondCode OFCC;
4017 SDValue Value, Overflow;
4018 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
4020 if (CC == ISD::SETNE)
4021 OFCC = getInvertedCondCode(OFCC);
4022 SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
4024 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
4028 if (LHS.getValueType().isInteger()) {
4029 assert((LHS.getValueType() == RHS.getValueType()) &&
4030 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
4032 // If the RHS of the comparison is zero, we can potentially fold this
4033 // to a specialized branch.
4034 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
4035 if (RHSC && RHSC->getZExtValue() == 0) {
4036 if (CC == ISD::SETEQ) {
4037 // See if we can use a TBZ to fold in an AND as well.
4038 // TBZ has a smaller branch displacement than CBZ. If the offset is
4039 // out of bounds, a late MI-layer pass rewrites branches.
4040 // 403.gcc is an example that hits this case.
4041 if (LHS.getOpcode() == ISD::AND &&
4042 isa<ConstantSDNode>(LHS.getOperand(1)) &&
4043 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
4044 SDValue Test = LHS.getOperand(0);
4045 uint64_t Mask = LHS.getConstantOperandVal(1);
4046 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
4047 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
4051 return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
4052 } else if (CC == ISD::SETNE) {
4053 // See if we can use a TBZ to fold in an AND as well.
4054 // TBZ has a smaller branch displacement than CBZ. If the offset is
4055 // out of bounds, a late MI-layer pass rewrites branches.
4056 // 403.gcc is an example that hits this case.
4057 if (LHS.getOpcode() == ISD::AND &&
4058 isa<ConstantSDNode>(LHS.getOperand(1)) &&
4059 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
4060 SDValue Test = LHS.getOperand(0);
4061 uint64_t Mask = LHS.getConstantOperandVal(1);
4062 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
4063 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
4067 return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
4068 } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
4069 // Don't combine AND since emitComparison converts the AND to an ANDS
4070 // (a.k.a. TST) and the test in the test bit and branch instruction
4071 // becomes redundant. This would also increase register pressure.
4072 uint64_t Mask = LHS.getValueSizeInBits() - 1;
4073 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
4074 DAG.getConstant(Mask, dl, MVT::i64), Dest);
4077 if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
4078 LHS.getOpcode() != ISD::AND) {
4079 // Don't combine AND since emitComparison converts the AND to an ANDS
4080 // (a.k.a. TST) and the test in the test bit and branch instruction
4081 // becomes redundant. This would also increase register pressure.
4082 uint64_t Mask = LHS.getValueSizeInBits() - 1;
4083 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
4084 DAG.getConstant(Mask, dl, MVT::i64), Dest);
4088 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
4089 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
4093 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
4094 LHS.getValueType() == MVT::f64);
4096 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4097 // clean. Some of them require two branches to implement.
4098 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
4099 AArch64CC::CondCode CC1, CC2;
4100 changeFPCCToAArch64CC(CC, CC1, CC2);
4101 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
4103 DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
4104 if (CC2 != AArch64CC::AL) {
4105 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
4106 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
4113 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
4114 SelectionDAG &DAG) const {
4115 EVT VT = Op.getValueType();
4118 SDValue In1 = Op.getOperand(0);
4119 SDValue In2 = Op.getOperand(1);
4120 EVT SrcVT = In2.getValueType();
4122 if (SrcVT.bitsLT(VT))
4123 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
4124 else if (SrcVT.bitsGT(VT))
4125 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
4129 SDValue VecVal1, VecVal2;
4131 auto setVecVal = [&] (int Idx) {
4132 if (!VT.isVector()) {
4133 VecVal1 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
4134 DAG.getUNDEF(VecVT), In1);
4135 VecVal2 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
4136 DAG.getUNDEF(VecVT), In2);
4138 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
4139 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
4143 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
4144 VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
4145 EltMask = 0x80000000ULL;
4146 setVecVal(AArch64::ssub);
4147 } else if (VT == MVT::f64 || VT == MVT::v2f64) {
4150 // We want to materialize a mask with the high bit set, but the AdvSIMD
4151 // immediate moves cannot materialize that in a single instruction for
4152 // 64-bit elements. Instead, materialize zero and then negate it.
4155 setVecVal(AArch64::dsub);
4156 } else if (VT == MVT::f16 || VT == MVT::v4f16 || VT == MVT::v8f16) {
4157 VecVT = (VT == MVT::v4f16 ? MVT::v4i16 : MVT::v8i16);
4158 EltMask = 0x8000ULL;
4159 setVecVal(AArch64::hsub);
4161 llvm_unreachable("Invalid type for copysign!");
4164 SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
4166 // If we couldn't materialize the mask above, then the mask vector will be
4167 // the zero vector, and we need to negate it here.
4168 if (VT == MVT::f64 || VT == MVT::v2f64) {
4169 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
4170 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
4171 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
4175 DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
4178 return DAG.getTargetExtractSubreg(AArch64::hsub, DL, VT, Sel);
4180 return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
4181 else if (VT == MVT::f64)
4182 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
4184 return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
4187 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
4188 if (DAG.getMachineFunction().getFunction().hasFnAttribute(
4189 Attribute::NoImplicitFloat))
4192 if (!Subtarget->hasNEON())
4195 // While there is no integer popcount instruction, it can
4196 // be more efficiently lowered to the following sequence that uses
4197 // AdvSIMD registers/instructions as long as the copies to/from
4198 // the AdvSIMD registers are cheap.
4199 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd
4200 // CNT V0.8B, V0.8B // 8xbyte pop-counts
4201 // ADDV B0, V0.8B // sum 8xbyte pop-counts
4202 // UMOV X0, V0.B[0] // copy byte result back to integer reg
4203 SDValue Val = Op.getOperand(0);
4205 EVT VT = Op.getValueType();
4208 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
4209 Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
4211 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
4212 SDValue UaddLV = DAG.getNode(
4213 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
4214 DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
4217 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
4221 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
4223 if (Op.getValueType().isVector())
4224 return LowerVSETCC(Op, DAG);
4226 SDValue LHS = Op.getOperand(0);
4227 SDValue RHS = Op.getOperand(1);
4228 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
4231 // We chose ZeroOrOneBooleanContents, so use zero and one.
4232 EVT VT = Op.getValueType();
4233 SDValue TVal = DAG.getConstant(1, dl, VT);
4234 SDValue FVal = DAG.getConstant(0, dl, VT);
4236 // Handle f128 first, since one possible outcome is a normal integer
4237 // comparison which gets picked up by the next if statement.
4238 if (LHS.getValueType() == MVT::f128) {
4239 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
4241 // If softenSetCCOperands returned a scalar, use it.
4242 if (!RHS.getNode()) {
4243 assert(LHS.getValueType() == Op.getValueType() &&
4244 "Unexpected setcc expansion!");
4249 if (LHS.getValueType().isInteger()) {
4252 getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
4254 // Note that we inverted the condition above, so we reverse the order of
4255 // the true and false operands here. This will allow the setcc to be
4256 // matched to a single CSINC instruction.
4257 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
4260 // Now we know we're dealing with FP values.
4261 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
4262 LHS.getValueType() == MVT::f64);
4264 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
4265 // and do the comparison.
4266 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
4268 AArch64CC::CondCode CC1, CC2;
4269 changeFPCCToAArch64CC(CC, CC1, CC2);
4270 if (CC2 == AArch64CC::AL) {
4271 changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
4272 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
4274 // Note that we inverted the condition above, so we reverse the order of
4275 // the true and false operands here. This will allow the setcc to be
4276 // matched to a single CSINC instruction.
4277 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
4279 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
4280 // totally clean. Some of them require two CSELs to implement. As is in
4281 // this case, we emit the first CSEL and then emit a second using the output
4282 // of the first as the RHS. We're effectively OR'ing the two CC's together.
4284 // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
4285 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
4287 DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4289 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
4290 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4294 SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
4295 SDValue RHS, SDValue TVal,
4296 SDValue FVal, const SDLoc &dl,
4297 SelectionDAG &DAG) const {
4298 // Handle f128 first, because it will result in a comparison of some RTLIB
4299 // call result against zero.
4300 if (LHS.getValueType() == MVT::f128) {
4301 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
4303 // If softenSetCCOperands returned a scalar, we need to compare the result
4304 // against zero to select between true and false values.
4305 if (!RHS.getNode()) {
4306 RHS = DAG.getConstant(0, dl, LHS.getValueType());
4311 // Also handle f16, for which we need to do a f32 comparison.
4312 if (LHS.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) {
4313 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
4314 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
4317 // Next, handle integers.
4318 if (LHS.getValueType().isInteger()) {
4319 assert((LHS.getValueType() == RHS.getValueType()) &&
4320 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
4322 unsigned Opcode = AArch64ISD::CSEL;
4324 // If both the TVal and the FVal are constants, see if we can swap them in
4325 // order to for a CSINV or CSINC out of them.
4326 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
4327 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
4329 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
4330 std::swap(TVal, FVal);
4331 std::swap(CTVal, CFVal);
4332 CC = ISD::getSetCCInverse(CC, true);
4333 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
4334 std::swap(TVal, FVal);
4335 std::swap(CTVal, CFVal);
4336 CC = ISD::getSetCCInverse(CC, true);
4337 } else if (TVal.getOpcode() == ISD::XOR) {
4338 // If TVal is a NOT we want to swap TVal and FVal so that we can match
4339 // with a CSINV rather than a CSEL.
4340 if (isAllOnesConstant(TVal.getOperand(1))) {
4341 std::swap(TVal, FVal);
4342 std::swap(CTVal, CFVal);
4343 CC = ISD::getSetCCInverse(CC, true);
4345 } else if (TVal.getOpcode() == ISD::SUB) {
4346 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
4347 // that we can match with a CSNEG rather than a CSEL.
4348 if (isNullConstant(TVal.getOperand(0))) {
4349 std::swap(TVal, FVal);
4350 std::swap(CTVal, CFVal);
4351 CC = ISD::getSetCCInverse(CC, true);
4353 } else if (CTVal && CFVal) {
4354 const int64_t TrueVal = CTVal->getSExtValue();
4355 const int64_t FalseVal = CFVal->getSExtValue();
4358 // If both TVal and FVal are constants, see if FVal is the
4359 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
4360 // instead of a CSEL in that case.
4361 if (TrueVal == ~FalseVal) {
4362 Opcode = AArch64ISD::CSINV;
4363 } else if (TrueVal == -FalseVal) {
4364 Opcode = AArch64ISD::CSNEG;
4365 } else if (TVal.getValueType() == MVT::i32) {
4366 // If our operands are only 32-bit wide, make sure we use 32-bit
4367 // arithmetic for the check whether we can use CSINC. This ensures that
4368 // the addition in the check will wrap around properly in case there is
4369 // an overflow (which would not be the case if we do the check with
4370 // 64-bit arithmetic).
4371 const uint32_t TrueVal32 = CTVal->getZExtValue();
4372 const uint32_t FalseVal32 = CFVal->getZExtValue();
4374 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
4375 Opcode = AArch64ISD::CSINC;
4377 if (TrueVal32 > FalseVal32) {
4381 // 64-bit check whether we can use CSINC.
4382 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
4383 Opcode = AArch64ISD::CSINC;
4385 if (TrueVal > FalseVal) {
4390 // Swap TVal and FVal if necessary.
4392 std::swap(TVal, FVal);
4393 std::swap(CTVal, CFVal);
4394 CC = ISD::getSetCCInverse(CC, true);
4397 if (Opcode != AArch64ISD::CSEL) {
4398 // Drop FVal since we can get its value by simply inverting/negating
4404 // Avoid materializing a constant when possible by reusing a known value in
4405 // a register. However, don't perform this optimization if the known value
4406 // is one, zero or negative one in the case of a CSEL. We can always
4407 // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the
4408 // FVal, respectively.
4409 ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS);
4410 if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() &&
4411 !RHSVal->isNullValue() && !RHSVal->isAllOnesValue()) {
4412 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
4413 // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to
4414 // "a != C ? x : a" to avoid materializing C.
4415 if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ)
4417 else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE)
4419 } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) {
4420 assert (CTVal && CFVal && "Expected constant operands for CSNEG.");
4421 // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to
4422 // avoid materializing C.
4423 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
4424 if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) {
4425 Opcode = AArch64ISD::CSINV;
4427 FVal = DAG.getConstant(0, dl, FVal.getValueType());
4432 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
4433 EVT VT = TVal.getValueType();
4434 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
4437 // Now we know we're dealing with FP values.
4438 assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
4439 LHS.getValueType() == MVT::f64);
4440 assert(LHS.getValueType() == RHS.getValueType());
4441 EVT VT = TVal.getValueType();
4442 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
4444 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4445 // clean. Some of them require two CSELs to implement.
4446 AArch64CC::CondCode CC1, CC2;
4447 changeFPCCToAArch64CC(CC, CC1, CC2);
4449 if (DAG.getTarget().Options.UnsafeFPMath) {
4450 // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and
4451 // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0.
4452 ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS);
4453 if (RHSVal && RHSVal->isZero()) {
4454 ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal);
4455 ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal);
4457 if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) &&
4458 CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType())
4460 else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) &&
4461 CFVal && CFVal->isZero() &&
4462 FVal.getValueType() == LHS.getValueType())
4467 // Emit first, and possibly only, CSEL.
4468 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
4469 SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4471 // If we need a second CSEL, emit it, using the output of the first as the
4472 // RHS. We're effectively OR'ing the two CC's together.
4473 if (CC2 != AArch64CC::AL) {
4474 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
4475 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4478 // Otherwise, return the output of the first CSEL.
4482 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
4483 SelectionDAG &DAG) const {
4484 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4485 SDValue LHS = Op.getOperand(0);
4486 SDValue RHS = Op.getOperand(1);
4487 SDValue TVal = Op.getOperand(2);
4488 SDValue FVal = Op.getOperand(3);
4490 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4493 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
4494 SelectionDAG &DAG) const {
4495 SDValue CCVal = Op->getOperand(0);
4496 SDValue TVal = Op->getOperand(1);
4497 SDValue FVal = Op->getOperand(2);
4500 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
4502 if (isOverflowIntrOpRes(CCVal)) {
4503 // Only lower legal XALUO ops.
4504 if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
4507 AArch64CC::CondCode OFCC;
4508 SDValue Value, Overflow;
4509 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
4510 SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
4512 return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
4516 // Lower it the same way as we would lower a SELECT_CC node.
4519 if (CCVal.getOpcode() == ISD::SETCC) {
4520 LHS = CCVal.getOperand(0);
4521 RHS = CCVal.getOperand(1);
4522 CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
4525 RHS = DAG.getConstant(0, DL, CCVal.getValueType());
4528 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4531 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
4532 SelectionDAG &DAG) const {
4533 // Jump table entries as PC relative offsets. No additional tweaking
4534 // is necessary here. Just get the address of the jump table.
4535 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4537 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4538 !Subtarget->isTargetMachO()) {
4539 return getAddrLarge(JT, DAG);
4541 return getAddr(JT, DAG);
4544 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
4545 SelectionDAG &DAG) const {
4546 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4548 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4549 // Use the GOT for the large code model on iOS.
4550 if (Subtarget->isTargetMachO()) {
4551 return getGOT(CP, DAG);
4553 return getAddrLarge(CP, DAG);
4555 return getAddr(CP, DAG);
4559 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
4560 SelectionDAG &DAG) const {
4561 BlockAddressSDNode *BA = cast<BlockAddressSDNode>(Op);
4562 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4563 !Subtarget->isTargetMachO()) {
4564 return getAddrLarge(BA, DAG);
4566 return getAddr(BA, DAG);
4570 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
4571 SelectionDAG &DAG) const {
4572 AArch64FunctionInfo *FuncInfo =
4573 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4576 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
4577 getPointerTy(DAG.getDataLayout()));
4578 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4579 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
4580 MachinePointerInfo(SV));
4583 SDValue AArch64TargetLowering::LowerWin64_VASTART(SDValue Op,
4584 SelectionDAG &DAG) const {
4585 AArch64FunctionInfo *FuncInfo =
4586 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4589 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsGPRSize() > 0
4590 ? FuncInfo->getVarArgsGPRIndex()
4591 : FuncInfo->getVarArgsStackIndex(),
4592 getPointerTy(DAG.getDataLayout()));
4593 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4594 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
4595 MachinePointerInfo(SV));
4598 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
4599 SelectionDAG &DAG) const {
4600 // The layout of the va_list struct is specified in the AArch64 Procedure Call
4601 // Standard, section B.3.
4602 MachineFunction &MF = DAG.getMachineFunction();
4603 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4604 auto PtrVT = getPointerTy(DAG.getDataLayout());
4607 SDValue Chain = Op.getOperand(0);
4608 SDValue VAList = Op.getOperand(1);
4609 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4610 SmallVector<SDValue, 4> MemOps;
4612 // void *__stack at offset 0
4613 SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
4614 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
4615 MachinePointerInfo(SV), /* Alignment = */ 8));
4617 // void *__gr_top at offset 8
4618 int GPRSize = FuncInfo->getVarArgsGPRSize();
4620 SDValue GRTop, GRTopAddr;
4623 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
4625 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
4626 GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
4627 DAG.getConstant(GPRSize, DL, PtrVT));
4629 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
4630 MachinePointerInfo(SV, 8),
4631 /* Alignment = */ 8));
4634 // void *__vr_top at offset 16
4635 int FPRSize = FuncInfo->getVarArgsFPRSize();
4637 SDValue VRTop, VRTopAddr;
4638 VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4639 DAG.getConstant(16, DL, PtrVT));
4641 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
4642 VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
4643 DAG.getConstant(FPRSize, DL, PtrVT));
4645 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
4646 MachinePointerInfo(SV, 16),
4647 /* Alignment = */ 8));
4650 // int __gr_offs at offset 24
4651 SDValue GROffsAddr =
4652 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
4653 MemOps.push_back(DAG.getStore(
4654 Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32), GROffsAddr,
4655 MachinePointerInfo(SV, 24), /* Alignment = */ 4));
4657 // int __vr_offs at offset 28
4658 SDValue VROffsAddr =
4659 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
4660 MemOps.push_back(DAG.getStore(
4661 Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32), VROffsAddr,
4662 MachinePointerInfo(SV, 28), /* Alignment = */ 4));
4664 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
4667 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
4668 SelectionDAG &DAG) const {
4669 MachineFunction &MF = DAG.getMachineFunction();
4671 if (Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv()))
4672 return LowerWin64_VASTART(Op, DAG);
4673 else if (Subtarget->isTargetDarwin())
4674 return LowerDarwin_VASTART(Op, DAG);
4676 return LowerAAPCS_VASTART(Op, DAG);
4679 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
4680 SelectionDAG &DAG) const {
4681 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
4684 unsigned VaListSize =
4685 Subtarget->isTargetDarwin() || Subtarget->isTargetWindows() ? 8 : 32;
4686 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4687 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4689 return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1),
4691 DAG.getConstant(VaListSize, DL, MVT::i32),
4692 8, false, false, false, MachinePointerInfo(DestSV),
4693 MachinePointerInfo(SrcSV));
4696 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
4697 assert(Subtarget->isTargetDarwin() &&
4698 "automatic va_arg instruction only works on Darwin");
4700 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4701 EVT VT = Op.getValueType();
4703 SDValue Chain = Op.getOperand(0);
4704 SDValue Addr = Op.getOperand(1);
4705 unsigned Align = Op.getConstantOperandVal(3);
4706 auto PtrVT = getPointerTy(DAG.getDataLayout());
4708 SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V));
4709 Chain = VAList.getValue(1);
4712 assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
4713 VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4714 DAG.getConstant(Align - 1, DL, PtrVT));
4715 VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
4716 DAG.getConstant(-(int64_t)Align, DL, PtrVT));
4719 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
4720 uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
4722 // Scalar integer and FP values smaller than 64 bits are implicitly extended
4723 // up to 64 bits. At the very least, we have to increase the striding of the
4724 // vaargs list to match this, and for FP values we need to introduce
4725 // FP_ROUND nodes as well.
4726 if (VT.isInteger() && !VT.isVector())
4728 bool NeedFPTrunc = false;
4729 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
4734 // Increment the pointer, VAList, to the next vaarg
4735 SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4736 DAG.getConstant(ArgSize, DL, PtrVT));
4737 // Store the incremented VAList to the legalized pointer
4739 DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V));
4741 // Load the actual argument out of the pointer VAList
4743 // Load the value as an f64.
4745 DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo());
4746 // Round the value down to an f32.
4747 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
4748 DAG.getIntPtrConstant(1, DL));
4749 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
4750 // Merge the rounded value with the chain output of the load.
4751 return DAG.getMergeValues(Ops, DL);
4754 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo());
4757 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
4758 SelectionDAG &DAG) const {
4759 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
4760 MFI.setFrameAddressIsTaken(true);
4762 EVT VT = Op.getValueType();
4764 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4766 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
4768 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
4769 MachinePointerInfo());
4773 // FIXME? Maybe this could be a TableGen attribute on some registers and
4774 // this table could be generated automatically from RegInfo.
4775 unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT,
4776 SelectionDAG &DAG) const {
4777 unsigned Reg = StringSwitch<unsigned>(RegName)
4778 .Case("sp", AArch64::SP)
4779 .Case("x18", AArch64::X18)
4780 .Case("w18", AArch64::W18)
4782 if ((Reg == AArch64::X18 || Reg == AArch64::W18) &&
4783 !Subtarget->isX18Reserved())
4787 report_fatal_error(Twine("Invalid register name \""
4788 + StringRef(RegName) + "\"."));
4791 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
4792 SelectionDAG &DAG) const {
4793 MachineFunction &MF = DAG.getMachineFunction();
4794 MachineFrameInfo &MFI = MF.getFrameInfo();
4795 MFI.setReturnAddressIsTaken(true);
4797 EVT VT = Op.getValueType();
4799 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4801 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4802 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
4803 return DAG.getLoad(VT, DL, DAG.getEntryNode(),
4804 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
4805 MachinePointerInfo());
4808 // Return LR, which contains the return address. Mark it an implicit live-in.
4809 unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
4810 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4813 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4814 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
4815 SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
4816 SelectionDAG &DAG) const {
4817 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4818 EVT VT = Op.getValueType();
4819 unsigned VTBits = VT.getSizeInBits();
4821 SDValue ShOpLo = Op.getOperand(0);
4822 SDValue ShOpHi = Op.getOperand(1);
4823 SDValue ShAmt = Op.getOperand(2);
4824 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4826 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4828 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
4829 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
4830 SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4832 // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
4833 // is "undef". We wanted 0, so CSEL it directly.
4834 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
4835 ISD::SETEQ, dl, DAG);
4836 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
4838 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
4839 HiBitsForLo, CCVal, Cmp);
4841 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
4842 DAG.getConstant(VTBits, dl, MVT::i64));
4844 SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4845 SDValue LoForNormalShift =
4846 DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
4848 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
4850 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4851 SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4852 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
4853 LoForNormalShift, CCVal, Cmp);
4855 // AArch64 shifts larger than the register width are wrapped rather than
4856 // clamped, so we can't just emit "hi >> x".
4857 SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4858 SDValue HiForBigShift =
4860 ? DAG.getNode(Opc, dl, VT, ShOpHi,
4861 DAG.getConstant(VTBits - 1, dl, MVT::i64))
4862 : DAG.getConstant(0, dl, VT);
4863 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
4864 HiForNormalShift, CCVal, Cmp);
4866 SDValue Ops[2] = { Lo, Hi };
4867 return DAG.getMergeValues(Ops, dl);
4870 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4871 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
4872 SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
4873 SelectionDAG &DAG) const {
4874 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4875 EVT VT = Op.getValueType();
4876 unsigned VTBits = VT.getSizeInBits();
4878 SDValue ShOpLo = Op.getOperand(0);
4879 SDValue ShOpHi = Op.getOperand(1);
4880 SDValue ShAmt = Op.getOperand(2);
4882 assert(Op.getOpcode() == ISD::SHL_PARTS);
4883 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
4884 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
4885 SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4887 // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
4888 // is "undef". We wanted 0, so CSEL it directly.
4889 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
4890 ISD::SETEQ, dl, DAG);
4891 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
4893 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
4894 LoBitsForHi, CCVal, Cmp);
4896 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
4897 DAG.getConstant(VTBits, dl, MVT::i64));
4898 SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4899 SDValue HiForNormalShift =
4900 DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
4902 SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4904 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
4906 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4907 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
4908 HiForNormalShift, CCVal, Cmp);
4910 // AArch64 shifts of larger than register sizes are wrapped rather than
4911 // clamped, so we can't just emit "lo << a" if a is too big.
4912 SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
4913 SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4914 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
4915 LoForNormalShift, CCVal, Cmp);
4917 SDValue Ops[2] = { Lo, Hi };
4918 return DAG.getMergeValues(Ops, dl);
4921 bool AArch64TargetLowering::isOffsetFoldingLegal(
4922 const GlobalAddressSDNode *GA) const {
4923 DEBUG(dbgs() << "Skipping offset folding global address: ");
4925 DEBUG(dbgs() << "AArch64 doesn't support folding offsets into global "
4930 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4931 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
4932 // FIXME: We should be able to handle f128 as well with a clever lowering.
4933 if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32 ||
4934 (VT == MVT::f16 && Subtarget->hasFullFP16()))) {
4935 DEBUG(dbgs() << "Legal fp imm: materialize 0 using the zero register\n");
4940 bool IsLegal = false;
4941 SmallString<128> ImmStrVal;
4942 Imm.toString(ImmStrVal);
4944 if (VT == MVT::f64) {
4946 IsLegal = AArch64_AM::getFP64Imm(Imm) != -1;
4947 } else if (VT == MVT::f32) {
4949 IsLegal = AArch64_AM::getFP32Imm(Imm) != -1;
4950 } else if (VT == MVT::f16 && Subtarget->hasFullFP16()) {
4952 IsLegal = AArch64_AM::getFP16Imm(Imm) != -1;
4956 DEBUG(dbgs() << "Legal " << FPType << " imm value: " << ImmStrVal << "\n");
4960 if (!FPType.empty())
4961 DEBUG(dbgs() << "Illegal " << FPType << " imm value: " << ImmStrVal << "\n");
4963 DEBUG(dbgs() << "Illegal fp imm " << ImmStrVal << ": unsupported fp type\n");
4968 //===----------------------------------------------------------------------===//
4969 // AArch64 Optimization Hooks
4970 //===----------------------------------------------------------------------===//
4972 static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode,
4973 SDValue Operand, SelectionDAG &DAG,
4975 EVT VT = Operand.getValueType();
4976 if (ST->hasNEON() &&
4977 (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 ||
4978 VT == MVT::f32 || VT == MVT::v1f32 ||
4979 VT == MVT::v2f32 || VT == MVT::v4f32)) {
4980 if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified)
4981 // For the reciprocal estimates, convergence is quadratic, so the number
4982 // of digits is doubled after each iteration. In ARMv8, the accuracy of
4983 // the initial estimate is 2^-8. Thus the number of extra steps to refine
4984 // the result for float (23 mantissa bits) is 2 and for double (52
4985 // mantissa bits) is 3.
4986 ExtraSteps = VT.getScalarType() == MVT::f64 ? 3 : 2;
4988 return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand);
4994 SDValue AArch64TargetLowering::getSqrtEstimate(SDValue Operand,
4995 SelectionDAG &DAG, int Enabled,
4998 bool Reciprocal) const {
4999 if (Enabled == ReciprocalEstimate::Enabled ||
5000 (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt()))
5001 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, Operand,
5004 EVT VT = Operand.getValueType();
5007 Flags.setUnsafeAlgebra(true);
5009 // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2)
5010 // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N)
5011 for (int i = ExtraSteps; i > 0; --i) {
5012 SDValue Step = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Estimate,
5014 Step = DAG.getNode(AArch64ISD::FRSQRTS, DL, VT, Operand, Step, Flags);
5015 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
5019 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
5021 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
5022 SDValue Eq = DAG.getSetCC(DL, CCVT, Operand, FPZero, ISD::SETEQ);
5024 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Operand, Estimate, Flags);
5025 // Correct the result if the operand is 0.0.
5026 Estimate = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL,
5027 VT, Eq, Operand, Estimate);
5037 SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand,
5038 SelectionDAG &DAG, int Enabled,
5039 int &ExtraSteps) const {
5040 if (Enabled == ReciprocalEstimate::Enabled)
5041 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand,
5044 EVT VT = Operand.getValueType();
5047 Flags.setUnsafeAlgebra(true);
5049 // Newton reciprocal iteration: E * (2 - X * E)
5050 // AArch64 reciprocal iteration instruction: (2 - M * N)
5051 for (int i = ExtraSteps; i > 0; --i) {
5052 SDValue Step = DAG.getNode(AArch64ISD::FRECPS, DL, VT, Operand,
5054 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
5064 //===----------------------------------------------------------------------===//
5065 // AArch64 Inline Assembly Support
5066 //===----------------------------------------------------------------------===//
5068 // Table of Constraints
5069 // TODO: This is the current set of constraints supported by ARM for the
5070 // compiler, not all of them may make sense.
5072 // r - A general register
5073 // w - An FP/SIMD register of some size in the range v0-v31
5074 // x - An FP/SIMD register of some size in the range v0-v15
5075 // I - Constant that can be used with an ADD instruction
5076 // J - Constant that can be used with a SUB instruction
5077 // K - Constant that can be used with a 32-bit logical instruction
5078 // L - Constant that can be used with a 64-bit logical instruction
5079 // M - Constant that can be used as a 32-bit MOV immediate
5080 // N - Constant that can be used as a 64-bit MOV immediate
5081 // Q - A memory reference with base register and no offset
5082 // S - A symbolic address
5083 // Y - Floating point constant zero
5084 // Z - Integer constant zero
5086 // Note that general register operands will be output using their 64-bit x
5087 // register name, whatever the size of the variable, unless the asm operand
5088 // is prefixed by the %w modifier. Floating-point and SIMD register operands
5089 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
5091 const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
5092 // At this point, we have to lower this constraint to something else, so we
5093 // lower it to an "r" or "w". However, by doing this we will force the result
5094 // to be in register, while the X constraint is much more permissive.
5096 // Although we are correct (we are free to emit anything, without
5097 // constraints), we might break use cases that would expect us to be more
5098 // efficient and emit something else.
5099 if (!Subtarget->hasFPARMv8())
5102 if (ConstraintVT.isFloatingPoint())
5105 if (ConstraintVT.isVector() &&
5106 (ConstraintVT.getSizeInBits() == 64 ||
5107 ConstraintVT.getSizeInBits() == 128))
5113 /// getConstraintType - Given a constraint letter, return the type of
5114 /// constraint it is for this target.
5115 AArch64TargetLowering::ConstraintType
5116 AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
5117 if (Constraint.size() == 1) {
5118 switch (Constraint[0]) {
5125 return C_RegisterClass;
5126 // An address with a single base register. Due to the way we
5127 // currently handle addresses it is the same as 'r'.
5130 case 'S': // A symbolic address
5134 return TargetLowering::getConstraintType(Constraint);
5137 /// Examine constraint type and operand type and determine a weight value.
5138 /// This object must already have been set up with the operand type
5139 /// and the current alternative constraint selected.
5140 TargetLowering::ConstraintWeight
5141 AArch64TargetLowering::getSingleConstraintMatchWeight(
5142 AsmOperandInfo &info, const char *constraint) const {
5143 ConstraintWeight weight = CW_Invalid;
5144 Value *CallOperandVal = info.CallOperandVal;
5145 // If we don't have a value, we can't do a match,
5146 // but allow it at the lowest weight.
5147 if (!CallOperandVal)
5149 Type *type = CallOperandVal->getType();
5150 // Look at the constraint type.
5151 switch (*constraint) {
5153 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
5157 if (type->isFloatingPointTy() || type->isVectorTy())
5158 weight = CW_Register;
5161 weight = CW_Constant;
5167 std::pair<unsigned, const TargetRegisterClass *>
5168 AArch64TargetLowering::getRegForInlineAsmConstraint(
5169 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
5170 if (Constraint.size() == 1) {
5171 switch (Constraint[0]) {
5173 if (VT.getSizeInBits() == 64)
5174 return std::make_pair(0U, &AArch64::GPR64commonRegClass);
5175 return std::make_pair(0U, &AArch64::GPR32commonRegClass);
5177 if (VT.getSizeInBits() == 16)
5178 return std::make_pair(0U, &AArch64::FPR16RegClass);
5179 if (VT.getSizeInBits() == 32)
5180 return std::make_pair(0U, &AArch64::FPR32RegClass);
5181 if (VT.getSizeInBits() == 64)
5182 return std::make_pair(0U, &AArch64::FPR64RegClass);
5183 if (VT.getSizeInBits() == 128)
5184 return std::make_pair(0U, &AArch64::FPR128RegClass);
5186 // The instructions that this constraint is designed for can
5187 // only take 128-bit registers so just use that regclass.
5189 if (VT.getSizeInBits() == 128)
5190 return std::make_pair(0U, &AArch64::FPR128_loRegClass);
5194 if (StringRef("{cc}").equals_lower(Constraint))
5195 return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
5197 // Use the default implementation in TargetLowering to convert the register
5198 // constraint into a member of a register class.
5199 std::pair<unsigned, const TargetRegisterClass *> Res;
5200 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
5202 // Not found as a standard register?
5204 unsigned Size = Constraint.size();
5205 if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
5206 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
5208 bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
5209 if (!Failed && RegNo >= 0 && RegNo <= 31) {
5210 // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size.
5211 // By default we'll emit v0-v31 for this unless there's a modifier where
5212 // we'll emit the correct register as well.
5213 if (VT != MVT::Other && VT.getSizeInBits() == 64) {
5214 Res.first = AArch64::FPR64RegClass.getRegister(RegNo);
5215 Res.second = &AArch64::FPR64RegClass;
5217 Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
5218 Res.second = &AArch64::FPR128RegClass;
5227 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
5228 /// vector. If it is invalid, don't add anything to Ops.
5229 void AArch64TargetLowering::LowerAsmOperandForConstraint(
5230 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
5231 SelectionDAG &DAG) const {
5234 // Currently only support length 1 constraints.
5235 if (Constraint.length() != 1)
5238 char ConstraintLetter = Constraint[0];
5239 switch (ConstraintLetter) {
5243 // This set of constraints deal with valid constants for various instructions.
5244 // Validate and return a target constant for them if we can.
5246 // 'z' maps to xzr or wzr so it needs an input of 0.
5247 if (!isNullConstant(Op))
5250 if (Op.getValueType() == MVT::i64)
5251 Result = DAG.getRegister(AArch64::XZR, MVT::i64);
5253 Result = DAG.getRegister(AArch64::WZR, MVT::i32);
5257 // An absolute symbolic address or label reference.
5258 if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
5259 Result = DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
5260 GA->getValueType(0));
5261 } else if (const BlockAddressSDNode *BA =
5262 dyn_cast<BlockAddressSDNode>(Op)) {
5264 DAG.getTargetBlockAddress(BA->getBlockAddress(), BA->getValueType(0));
5265 } else if (const ExternalSymbolSDNode *ES =
5266 dyn_cast<ExternalSymbolSDNode>(Op)) {
5268 DAG.getTargetExternalSymbol(ES->getSymbol(), ES->getValueType(0));
5280 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
5284 // Grab the value and do some validation.
5285 uint64_t CVal = C->getZExtValue();
5286 switch (ConstraintLetter) {
5287 // The I constraint applies only to simple ADD or SUB immediate operands:
5288 // i.e. 0 to 4095 with optional shift by 12
5289 // The J constraint applies only to ADD or SUB immediates that would be
5290 // valid when negated, i.e. if [an add pattern] were to be output as a SUB
5291 // instruction [or vice versa], in other words -1 to -4095 with optional
5292 // left shift by 12.
5294 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
5298 uint64_t NVal = -C->getSExtValue();
5299 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
5300 CVal = C->getSExtValue();
5305 // The K and L constraints apply *only* to logical immediates, including
5306 // what used to be the MOVI alias for ORR (though the MOVI alias has now
5307 // been removed and MOV should be used). So these constraints have to
5308 // distinguish between bit patterns that are valid 32-bit or 64-bit
5309 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
5310 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
5313 if (AArch64_AM::isLogicalImmediate(CVal, 32))
5317 if (AArch64_AM::isLogicalImmediate(CVal, 64))
5320 // The M and N constraints are a superset of K and L respectively, for use
5321 // with the MOV (immediate) alias. As well as the logical immediates they
5322 // also match 32 or 64-bit immediates that can be loaded either using a
5323 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
5324 // (M) or 64-bit 0x1234000000000000 (N) etc.
5325 // As a note some of this code is liberally stolen from the asm parser.
5327 if (!isUInt<32>(CVal))
5329 if (AArch64_AM::isLogicalImmediate(CVal, 32))
5331 if ((CVal & 0xFFFF) == CVal)
5333 if ((CVal & 0xFFFF0000ULL) == CVal)
5335 uint64_t NCVal = ~(uint32_t)CVal;
5336 if ((NCVal & 0xFFFFULL) == NCVal)
5338 if ((NCVal & 0xFFFF0000ULL) == NCVal)
5343 if (AArch64_AM::isLogicalImmediate(CVal, 64))
5345 if ((CVal & 0xFFFFULL) == CVal)
5347 if ((CVal & 0xFFFF0000ULL) == CVal)
5349 if ((CVal & 0xFFFF00000000ULL) == CVal)
5351 if ((CVal & 0xFFFF000000000000ULL) == CVal)
5353 uint64_t NCVal = ~CVal;
5354 if ((NCVal & 0xFFFFULL) == NCVal)
5356 if ((NCVal & 0xFFFF0000ULL) == NCVal)
5358 if ((NCVal & 0xFFFF00000000ULL) == NCVal)
5360 if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
5368 // All assembler immediates are 64-bit integers.
5369 Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
5373 if (Result.getNode()) {
5374 Ops.push_back(Result);
5378 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
5381 //===----------------------------------------------------------------------===//
5382 // AArch64 Advanced SIMD Support
5383 //===----------------------------------------------------------------------===//
5385 /// WidenVector - Given a value in the V64 register class, produce the
5386 /// equivalent value in the V128 register class.
5387 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
5388 EVT VT = V64Reg.getValueType();
5389 unsigned NarrowSize = VT.getVectorNumElements();
5390 MVT EltTy = VT.getVectorElementType().getSimpleVT();
5391 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
5394 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
5395 V64Reg, DAG.getConstant(0, DL, MVT::i32));
5398 /// getExtFactor - Determine the adjustment factor for the position when
5399 /// generating an "extract from vector registers" instruction.
5400 static unsigned getExtFactor(SDValue &V) {
5401 EVT EltType = V.getValueType().getVectorElementType();
5402 return EltType.getSizeInBits() / 8;
5405 /// NarrowVector - Given a value in the V128 register class, produce the
5406 /// equivalent value in the V64 register class.
5407 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
5408 EVT VT = V128Reg.getValueType();
5409 unsigned WideSize = VT.getVectorNumElements();
5410 MVT EltTy = VT.getVectorElementType().getSimpleVT();
5411 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
5414 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
5417 // Gather data to see if the operation can be modelled as a
5418 // shuffle in combination with VEXTs.
5419 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
5420 SelectionDAG &DAG) const {
5421 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
5422 DEBUG(dbgs() << "AArch64TargetLowering::ReconstructShuffle\n");
5424 EVT VT = Op.getValueType();
5425 unsigned NumElts = VT.getVectorNumElements();
5427 struct ShuffleSourceInfo {
5432 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
5433 // be compatible with the shuffle we intend to construct. As a result
5434 // ShuffleVec will be some sliding window into the original Vec.
5437 // Code should guarantee that element i in Vec starts at element "WindowBase
5438 // + i * WindowScale in ShuffleVec".
5442 ShuffleSourceInfo(SDValue Vec)
5443 : Vec(Vec), MinElt(std::numeric_limits<unsigned>::max()), MaxElt(0),
5444 ShuffleVec(Vec), WindowBase(0), WindowScale(1) {}
5446 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
5449 // First gather all vectors used as an immediate source for this BUILD_VECTOR
5451 SmallVector<ShuffleSourceInfo, 2> Sources;
5452 for (unsigned i = 0; i < NumElts; ++i) {
5453 SDValue V = Op.getOperand(i);
5456 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5457 !isa<ConstantSDNode>(V.getOperand(1))) {
5458 DEBUG(dbgs() << "Reshuffle failed: "
5459 "a shuffle can only come from building a vector from "
5460 "various elements of other vectors, provided their "
5461 "indices are constant\n");
5465 // Add this element source to the list if it's not already there.
5466 SDValue SourceVec = V.getOperand(0);
5467 auto Source = find(Sources, SourceVec);
5468 if (Source == Sources.end())
5469 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
5471 // Update the minimum and maximum lane number seen.
5472 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5473 Source->MinElt = std::min(Source->MinElt, EltNo);
5474 Source->MaxElt = std::max(Source->MaxElt, EltNo);
5477 if (Sources.size() > 2) {
5478 DEBUG(dbgs() << "Reshuffle failed: currently only do something sane when at "
5479 "most two source vectors are involved\n");
5483 // Find out the smallest element size among result and two sources, and use
5484 // it as element size to build the shuffle_vector.
5485 EVT SmallestEltTy = VT.getVectorElementType();
5486 for (auto &Source : Sources) {
5487 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
5488 if (SrcEltTy.bitsLT(SmallestEltTy)) {
5489 SmallestEltTy = SrcEltTy;
5492 unsigned ResMultiplier =
5493 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
5494 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
5495 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
5497 // If the source vector is too wide or too narrow, we may nevertheless be able
5498 // to construct a compatible shuffle either by concatenating it with UNDEF or
5499 // extracting a suitable range of elements.
5500 for (auto &Src : Sources) {
5501 EVT SrcVT = Src.ShuffleVec.getValueType();
5503 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
5506 // This stage of the search produces a source with the same element type as
5507 // the original, but with a total width matching the BUILD_VECTOR output.
5508 EVT EltVT = SrcVT.getVectorElementType();
5509 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
5510 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
5512 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
5513 assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
5514 // We can pad out the smaller vector for free, so if it's part of a
5517 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
5518 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
5522 assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
5524 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
5525 DEBUG(dbgs() << "Reshuffle failed: span too large for a VEXT to cope\n");
5529 if (Src.MinElt >= NumSrcElts) {
5530 // The extraction can just take the second half
5532 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5533 DAG.getConstant(NumSrcElts, dl, MVT::i64));
5534 Src.WindowBase = -NumSrcElts;
5535 } else if (Src.MaxElt < NumSrcElts) {
5536 // The extraction can just take the first half
5538 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5539 DAG.getConstant(0, dl, MVT::i64));
5541 // An actual VEXT is needed
5543 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5544 DAG.getConstant(0, dl, MVT::i64));
5546 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5547 DAG.getConstant(NumSrcElts, dl, MVT::i64));
5548 unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
5550 Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
5552 DAG.getConstant(Imm, dl, MVT::i32));
5553 Src.WindowBase = -Src.MinElt;
5557 // Another possible incompatibility occurs from the vector element types. We
5558 // can fix this by bitcasting the source vectors to the same type we intend
5560 for (auto &Src : Sources) {
5561 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
5562 if (SrcEltTy == SmallestEltTy)
5564 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
5565 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
5566 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
5567 Src.WindowBase *= Src.WindowScale;
5570 // Final sanity check before we try to actually produce a shuffle.
5572 for (auto Src : Sources)
5573 assert(Src.ShuffleVec.getValueType() == ShuffleVT);
5576 // The stars all align, our next step is to produce the mask for the shuffle.
5577 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
5578 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
5579 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
5580 SDValue Entry = Op.getOperand(i);
5581 if (Entry.isUndef())
5584 auto Src = find(Sources, Entry.getOperand(0));
5585 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
5587 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
5588 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
5590 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
5592 std::min(OrigEltTy.getSizeInBits(), VT.getScalarSizeInBits());
5593 int LanesDefined = BitsDefined / BitsPerShuffleLane;
5595 // This source is expected to fill ResMultiplier lanes of the final shuffle,
5596 // starting at the appropriate offset.
5597 int *LaneMask = &Mask[i * ResMultiplier];
5599 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
5600 ExtractBase += NumElts * (Src - Sources.begin());
5601 for (int j = 0; j < LanesDefined; ++j)
5602 LaneMask[j] = ExtractBase + j;
5605 // Final check before we try to produce nonsense...
5606 if (!isShuffleMaskLegal(Mask, ShuffleVT)) {
5607 DEBUG(dbgs() << "Reshuffle failed: illegal shuffle mask\n");
5611 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
5612 for (unsigned i = 0; i < Sources.size(); ++i)
5613 ShuffleOps[i] = Sources[i].ShuffleVec;
5615 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
5616 ShuffleOps[1], Mask);
5617 SDValue V = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
5620 dbgs() << "Reshuffle, creating node: ";
5622 dbgs() << "Reshuffle, creating node: ";
5629 // check if an EXT instruction can handle the shuffle mask when the
5630 // vector sources of the shuffle are the same.
5631 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
5632 unsigned NumElts = VT.getVectorNumElements();
5634 // Assume that the first shuffle index is not UNDEF. Fail if it is.
5640 // If this is a VEXT shuffle, the immediate value is the index of the first
5641 // element. The other shuffle indices must be the successive elements after
5643 unsigned ExpectedElt = Imm;
5644 for (unsigned i = 1; i < NumElts; ++i) {
5645 // Increment the expected index. If it wraps around, just follow it
5646 // back to index zero and keep going.
5648 if (ExpectedElt == NumElts)
5652 continue; // ignore UNDEF indices
5653 if (ExpectedElt != static_cast<unsigned>(M[i]))
5660 // check if an EXT instruction can handle the shuffle mask when the
5661 // vector sources of the shuffle are different.
5662 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
5664 // Look for the first non-undef element.
5665 const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; });
5667 // Benefit form APInt to handle overflow when calculating expected element.
5668 unsigned NumElts = VT.getVectorNumElements();
5669 unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
5670 APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
5671 // The following shuffle indices must be the successive elements after the
5672 // first real element.
5673 const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
5674 [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
5675 if (FirstWrongElt != M.end())
5678 // The index of an EXT is the first element if it is not UNDEF.
5679 // Watch out for the beginning UNDEFs. The EXT index should be the expected
5680 // value of the first element. E.g.
5681 // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
5682 // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
5683 // ExpectedElt is the last mask index plus 1.
5684 Imm = ExpectedElt.getZExtValue();
5686 // There are two difference cases requiring to reverse input vectors.
5687 // For example, for vector <4 x i32> we have the following cases,
5688 // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
5689 // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
5690 // For both cases, we finally use mask <5, 6, 7, 0>, which requires
5691 // to reverse two input vectors.
5700 /// isREVMask - Check if a vector shuffle corresponds to a REV
5701 /// instruction with the specified blocksize. (The order of the elements
5702 /// within each block of the vector is reversed.)
5703 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5704 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
5705 "Only possible block sizes for REV are: 16, 32, 64");
5707 unsigned EltSz = VT.getScalarSizeInBits();
5711 unsigned NumElts = VT.getVectorNumElements();
5712 unsigned BlockElts = M[0] + 1;
5713 // If the first shuffle index is UNDEF, be optimistic.
5715 BlockElts = BlockSize / EltSz;
5717 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5720 for (unsigned i = 0; i < NumElts; ++i) {
5722 continue; // ignore UNDEF indices
5723 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
5730 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5731 unsigned NumElts = VT.getVectorNumElements();
5732 WhichResult = (M[0] == 0 ? 0 : 1);
5733 unsigned Idx = WhichResult * NumElts / 2;
5734 for (unsigned i = 0; i != NumElts; i += 2) {
5735 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5736 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
5744 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5745 unsigned NumElts = VT.getVectorNumElements();
5746 WhichResult = (M[0] == 0 ? 0 : 1);
5747 for (unsigned i = 0; i != NumElts; ++i) {
5749 continue; // ignore UNDEF indices
5750 if ((unsigned)M[i] != 2 * i + WhichResult)
5757 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5758 unsigned NumElts = VT.getVectorNumElements();
5759 WhichResult = (M[0] == 0 ? 0 : 1);
5760 for (unsigned i = 0; i < NumElts; i += 2) {
5761 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5762 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
5768 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
5769 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5770 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5771 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5772 unsigned NumElts = VT.getVectorNumElements();
5773 WhichResult = (M[0] == 0 ? 0 : 1);
5774 unsigned Idx = WhichResult * NumElts / 2;
5775 for (unsigned i = 0; i != NumElts; i += 2) {
5776 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5777 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
5785 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
5786 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5787 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5788 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5789 unsigned Half = VT.getVectorNumElements() / 2;
5790 WhichResult = (M[0] == 0 ? 0 : 1);
5791 for (unsigned j = 0; j != 2; ++j) {
5792 unsigned Idx = WhichResult;
5793 for (unsigned i = 0; i != Half; ++i) {
5794 int MIdx = M[i + j * Half];
5795 if (MIdx >= 0 && (unsigned)MIdx != Idx)
5804 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
5805 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5806 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5807 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5808 unsigned NumElts = VT.getVectorNumElements();
5809 WhichResult = (M[0] == 0 ? 0 : 1);
5810 for (unsigned i = 0; i < NumElts; i += 2) {
5811 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5812 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
5818 static bool isINSMask(ArrayRef<int> M, int NumInputElements,
5819 bool &DstIsLeft, int &Anomaly) {
5820 if (M.size() != static_cast<size_t>(NumInputElements))
5823 int NumLHSMatch = 0, NumRHSMatch = 0;
5824 int LastLHSMismatch = -1, LastRHSMismatch = -1;
5826 for (int i = 0; i < NumInputElements; ++i) {
5836 LastLHSMismatch = i;
5838 if (M[i] == i + NumInputElements)
5841 LastRHSMismatch = i;
5844 if (NumLHSMatch == NumInputElements - 1) {
5846 Anomaly = LastLHSMismatch;
5848 } else if (NumRHSMatch == NumInputElements - 1) {
5850 Anomaly = LastRHSMismatch;
5857 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
5858 if (VT.getSizeInBits() != 128)
5861 unsigned NumElts = VT.getVectorNumElements();
5863 for (int I = 0, E = NumElts / 2; I != E; I++) {
5868 int Offset = NumElts / 2;
5869 for (int I = NumElts / 2, E = NumElts; I != E; I++) {
5870 if (Mask[I] != I + SplitLHS * Offset)
5877 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
5879 EVT VT = Op.getValueType();
5880 SDValue V0 = Op.getOperand(0);
5881 SDValue V1 = Op.getOperand(1);
5882 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
5884 if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
5885 VT.getVectorElementType() != V1.getValueType().getVectorElementType())
5888 bool SplitV0 = V0.getValueSizeInBits() == 128;
5890 if (!isConcatMask(Mask, VT, SplitV0))
5893 EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
5894 VT.getVectorNumElements() / 2);
5896 V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
5897 DAG.getConstant(0, DL, MVT::i64));
5899 if (V1.getValueSizeInBits() == 128) {
5900 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
5901 DAG.getConstant(0, DL, MVT::i64));
5903 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
5906 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5907 /// the specified operations to build the shuffle.
5908 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5909 SDValue RHS, SelectionDAG &DAG,
5911 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5912 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
5913 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
5916 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5925 OP_VUZPL, // VUZP, left result
5926 OP_VUZPR, // VUZP, right result
5927 OP_VZIPL, // VZIP, left result
5928 OP_VZIPR, // VZIP, right result
5929 OP_VTRNL, // VTRN, left result
5930 OP_VTRNR // VTRN, right result
5933 if (OpNum == OP_COPY) {
5934 if (LHSID == (1 * 9 + 2) * 9 + 3)
5936 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
5940 SDValue OpLHS, OpRHS;
5941 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5942 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5943 EVT VT = OpLHS.getValueType();
5947 llvm_unreachable("Unknown shuffle opcode!");
5949 // VREV divides the vector in half and swaps within the half.
5950 if (VT.getVectorElementType() == MVT::i32 ||
5951 VT.getVectorElementType() == MVT::f32)
5952 return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
5953 // vrev <4 x i16> -> REV32
5954 if (VT.getVectorElementType() == MVT::i16 ||
5955 VT.getVectorElementType() == MVT::f16)
5956 return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
5957 // vrev <4 x i8> -> REV16
5958 assert(VT.getVectorElementType() == MVT::i8);
5959 return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
5964 EVT EltTy = VT.getVectorElementType();
5966 if (EltTy == MVT::i8)
5967 Opcode = AArch64ISD::DUPLANE8;
5968 else if (EltTy == MVT::i16 || EltTy == MVT::f16)
5969 Opcode = AArch64ISD::DUPLANE16;
5970 else if (EltTy == MVT::i32 || EltTy == MVT::f32)
5971 Opcode = AArch64ISD::DUPLANE32;
5972 else if (EltTy == MVT::i64 || EltTy == MVT::f64)
5973 Opcode = AArch64ISD::DUPLANE64;
5975 llvm_unreachable("Invalid vector element type?");
5977 if (VT.getSizeInBits() == 64)
5978 OpLHS = WidenVector(OpLHS, DAG);
5979 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
5980 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
5985 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
5986 return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
5987 DAG.getConstant(Imm, dl, MVT::i32));
5990 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
5993 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
5996 return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
5999 return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
6002 return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
6005 return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
6010 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
6011 SelectionDAG &DAG) {
6012 // Check to see if we can use the TBL instruction.
6013 SDValue V1 = Op.getOperand(0);
6014 SDValue V2 = Op.getOperand(1);
6017 EVT EltVT = Op.getValueType().getVectorElementType();
6018 unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
6020 SmallVector<SDValue, 8> TBLMask;
6021 for (int Val : ShuffleMask) {
6022 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
6023 unsigned Offset = Byte + Val * BytesPerElt;
6024 TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
6028 MVT IndexVT = MVT::v8i8;
6029 unsigned IndexLen = 8;
6030 if (Op.getValueSizeInBits() == 128) {
6031 IndexVT = MVT::v16i8;
6035 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
6036 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
6039 if (V2.getNode()->isUndef()) {
6041 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
6042 Shuffle = DAG.getNode(
6043 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
6044 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
6045 DAG.getBuildVector(IndexVT, DL,
6046 makeArrayRef(TBLMask.data(), IndexLen)));
6048 if (IndexLen == 8) {
6049 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
6050 Shuffle = DAG.getNode(
6051 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
6052 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
6053 DAG.getBuildVector(IndexVT, DL,
6054 makeArrayRef(TBLMask.data(), IndexLen)));
6056 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
6057 // cannot currently represent the register constraints on the input
6059 // Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
6060 // DAG.getBuildVector(IndexVT, DL, &TBLMask[0],
6062 Shuffle = DAG.getNode(
6063 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
6064 DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst,
6065 V2Cst, DAG.getBuildVector(IndexVT, DL,
6066 makeArrayRef(TBLMask.data(), IndexLen)));
6069 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
6072 static unsigned getDUPLANEOp(EVT EltType) {
6073 if (EltType == MVT::i8)
6074 return AArch64ISD::DUPLANE8;
6075 if (EltType == MVT::i16 || EltType == MVT::f16)
6076 return AArch64ISD::DUPLANE16;
6077 if (EltType == MVT::i32 || EltType == MVT::f32)
6078 return AArch64ISD::DUPLANE32;
6079 if (EltType == MVT::i64 || EltType == MVT::f64)
6080 return AArch64ISD::DUPLANE64;
6082 llvm_unreachable("Invalid vector element type?");
6085 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
6086 SelectionDAG &DAG) const {
6088 EVT VT = Op.getValueType();
6090 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
6092 // Convert shuffles that are directly supported on NEON to target-specific
6093 // DAG nodes, instead of keeping them as shuffles and matching them again
6094 // during code selection. This is more efficient and avoids the possibility
6095 // of inconsistencies between legalization and selection.
6096 ArrayRef<int> ShuffleMask = SVN->getMask();
6098 SDValue V1 = Op.getOperand(0);
6099 SDValue V2 = Op.getOperand(1);
6101 if (SVN->isSplat()) {
6102 int Lane = SVN->getSplatIndex();
6103 // If this is undef splat, generate it via "just" vdup, if possible.
6107 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
6108 return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
6110 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
6111 // constant. If so, we can just reference the lane's definition directly.
6112 if (V1.getOpcode() == ISD::BUILD_VECTOR &&
6113 !isa<ConstantSDNode>(V1.getOperand(Lane)))
6114 return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
6116 // Otherwise, duplicate from the lane of the input vector.
6117 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
6119 // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
6120 // to make a vector of the same size as this SHUFFLE. We can ignore the
6121 // extract entirely, and canonicalise the concat using WidenVector.
6122 if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
6123 Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
6124 V1 = V1.getOperand(0);
6125 } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
6126 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
6127 Lane -= Idx * VT.getVectorNumElements() / 2;
6128 V1 = WidenVector(V1.getOperand(Idx), DAG);
6129 } else if (VT.getSizeInBits() == 64)
6130 V1 = WidenVector(V1, DAG);
6132 return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
6135 if (isREVMask(ShuffleMask, VT, 64))
6136 return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
6137 if (isREVMask(ShuffleMask, VT, 32))
6138 return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
6139 if (isREVMask(ShuffleMask, VT, 16))
6140 return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
6142 bool ReverseEXT = false;
6144 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
6147 Imm *= getExtFactor(V1);
6148 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
6149 DAG.getConstant(Imm, dl, MVT::i32));
6150 } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) {
6151 Imm *= getExtFactor(V1);
6152 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
6153 DAG.getConstant(Imm, dl, MVT::i32));
6156 unsigned WhichResult;
6157 if (isZIPMask(ShuffleMask, VT, WhichResult)) {
6158 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
6159 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6161 if (isUZPMask(ShuffleMask, VT, WhichResult)) {
6162 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
6163 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6165 if (isTRNMask(ShuffleMask, VT, WhichResult)) {
6166 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
6167 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6170 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6171 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
6172 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6174 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6175 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
6176 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6178 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6179 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
6180 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6183 if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG))
6188 int NumInputElements = V1.getValueType().getVectorNumElements();
6189 if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
6190 SDValue DstVec = DstIsLeft ? V1 : V2;
6191 SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
6193 SDValue SrcVec = V1;
6194 int SrcLane = ShuffleMask[Anomaly];
6195 if (SrcLane >= NumInputElements) {
6197 SrcLane -= VT.getVectorNumElements();
6199 SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
6201 EVT ScalarVT = VT.getVectorElementType();
6203 if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
6204 ScalarVT = MVT::i32;
6207 ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6208 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
6212 // If the shuffle is not directly supported and it has 4 elements, use
6213 // the PerfectShuffle-generated table to synthesize it from other shuffles.
6214 unsigned NumElts = VT.getVectorNumElements();
6216 unsigned PFIndexes[4];
6217 for (unsigned i = 0; i != 4; ++i) {
6218 if (ShuffleMask[i] < 0)
6221 PFIndexes[i] = ShuffleMask[i];
6224 // Compute the index in the perfect shuffle table.
6225 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6226 PFIndexes[2] * 9 + PFIndexes[3];
6227 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6228 unsigned Cost = (PFEntry >> 30);
6231 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6234 return GenerateTBL(Op, ShuffleMask, DAG);
6237 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
6239 EVT VT = BVN->getValueType(0);
6240 APInt SplatBits, SplatUndef;
6241 unsigned SplatBitSize;
6243 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
6244 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
6246 for (unsigned i = 0; i < NumSplats; ++i) {
6247 CnstBits <<= SplatBitSize;
6248 UndefBits <<= SplatBitSize;
6249 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
6250 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
6259 SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op,
6260 SelectionDAG &DAG) const {
6261 BuildVectorSDNode *BVN =
6262 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
6263 SDValue LHS = Op.getOperand(0);
6265 EVT VT = Op.getValueType();
6270 APInt CnstBits(VT.getSizeInBits(), 0);
6271 APInt UndefBits(VT.getSizeInBits(), 0);
6272 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
6273 // We only have BIC vector immediate instruction, which is and-not.
6274 CnstBits = ~CnstBits;
6276 // We make use of a little bit of goto ickiness in order to avoid having to
6277 // duplicate the immediate matching logic for the undef toggled case.
6278 bool SecondTry = false;
6281 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
6282 CnstBits = CnstBits.zextOrTrunc(64);
6283 uint64_t CnstVal = CnstBits.getZExtValue();
6285 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6286 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6287 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6288 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
6289 DAG.getConstant(CnstVal, dl, MVT::i32),
6290 DAG.getConstant(0, dl, MVT::i32));
6291 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6294 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6295 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6296 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6297 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
6298 DAG.getConstant(CnstVal, dl, MVT::i32),
6299 DAG.getConstant(8, dl, MVT::i32));
6300 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6303 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6304 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6305 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6306 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
6307 DAG.getConstant(CnstVal, dl, MVT::i32),
6308 DAG.getConstant(16, dl, MVT::i32));
6309 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6312 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6313 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6314 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6315 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
6316 DAG.getConstant(CnstVal, dl, MVT::i32),
6317 DAG.getConstant(24, dl, MVT::i32));
6318 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6321 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6322 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6323 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6324 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
6325 DAG.getConstant(CnstVal, dl, MVT::i32),
6326 DAG.getConstant(0, dl, MVT::i32));
6327 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6330 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6331 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6332 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6333 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
6334 DAG.getConstant(CnstVal, dl, MVT::i32),
6335 DAG.getConstant(8, dl, MVT::i32));
6336 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6343 CnstBits = ~UndefBits;
6347 // We can always fall back to a non-immediate AND.
6352 // Specialized code to quickly find if PotentialBVec is a BuildVector that
6353 // consists of only the same constant int value, returned in reference arg
6355 static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
6356 uint64_t &ConstVal) {
6357 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
6360 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
6363 EVT VT = Bvec->getValueType(0);
6364 unsigned NumElts = VT.getVectorNumElements();
6365 for (unsigned i = 1; i < NumElts; ++i)
6366 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
6368 ConstVal = FirstElt->getZExtValue();
6372 static unsigned getIntrinsicID(const SDNode *N) {
6373 unsigned Opcode = N->getOpcode();
6376 return Intrinsic::not_intrinsic;
6377 case ISD::INTRINSIC_WO_CHAIN: {
6378 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
6379 if (IID < Intrinsic::num_intrinsics)
6381 return Intrinsic::not_intrinsic;
6386 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
6387 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
6388 // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
6389 // Also, logical shift right -> sri, with the same structure.
6390 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
6391 EVT VT = N->getValueType(0);
6398 // Is the first op an AND?
6399 const SDValue And = N->getOperand(0);
6400 if (And.getOpcode() != ISD::AND)
6403 // Is the second op an shl or lshr?
6404 SDValue Shift = N->getOperand(1);
6405 // This will have been turned into: AArch64ISD::VSHL vector, #shift
6406 // or AArch64ISD::VLSHR vector, #shift
6407 unsigned ShiftOpc = Shift.getOpcode();
6408 if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
6410 bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
6412 // Is the shift amount constant?
6413 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
6417 // Is the and mask vector all constant?
6419 if (!isAllConstantBuildVector(And.getOperand(1), C1))
6422 // Is C1 == ~C2, taking into account how much one can shift elements of a
6424 uint64_t C2 = C2node->getZExtValue();
6425 unsigned ElemSizeInBits = VT.getScalarSizeInBits();
6426 if (C2 > ElemSizeInBits)
6428 unsigned ElemMask = (1 << ElemSizeInBits) - 1;
6429 if ((C1 & ElemMask) != (~C2 & ElemMask))
6432 SDValue X = And.getOperand(0);
6433 SDValue Y = Shift.getOperand(0);
6436 IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
6438 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
6439 DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
6440 Shift.getOperand(1));
6442 DEBUG(dbgs() << "aarch64-lower: transformed: \n");
6443 DEBUG(N->dump(&DAG));
6444 DEBUG(dbgs() << "into: \n");
6445 DEBUG(ResultSLI->dump(&DAG));
6451 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
6452 SelectionDAG &DAG) const {
6453 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
6454 if (EnableAArch64SlrGeneration) {
6455 if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG))
6459 BuildVectorSDNode *BVN =
6460 dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
6461 SDValue LHS = Op.getOperand(1);
6463 EVT VT = Op.getValueType();
6465 // OR commutes, so try swapping the operands.
6467 LHS = Op.getOperand(0);
6468 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
6473 APInt CnstBits(VT.getSizeInBits(), 0);
6474 APInt UndefBits(VT.getSizeInBits(), 0);
6475 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
6476 // We make use of a little bit of goto ickiness in order to avoid having to
6477 // duplicate the immediate matching logic for the undef toggled case.
6478 bool SecondTry = false;
6481 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
6482 CnstBits = CnstBits.zextOrTrunc(64);
6483 uint64_t CnstVal = CnstBits.getZExtValue();
6485 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6486 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6487 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6488 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6489 DAG.getConstant(CnstVal, dl, MVT::i32),
6490 DAG.getConstant(0, dl, MVT::i32));
6491 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6494 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6495 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6496 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6497 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6498 DAG.getConstant(CnstVal, dl, MVT::i32),
6499 DAG.getConstant(8, dl, MVT::i32));
6500 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6503 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6504 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6505 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6506 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6507 DAG.getConstant(CnstVal, dl, MVT::i32),
6508 DAG.getConstant(16, dl, MVT::i32));
6509 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6512 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6513 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6514 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6515 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6516 DAG.getConstant(CnstVal, dl, MVT::i32),
6517 DAG.getConstant(24, dl, MVT::i32));
6518 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6521 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6522 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6523 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6524 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6525 DAG.getConstant(CnstVal, dl, MVT::i32),
6526 DAG.getConstant(0, dl, MVT::i32));
6527 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6530 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6531 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6532 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6533 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6534 DAG.getConstant(CnstVal, dl, MVT::i32),
6535 DAG.getConstant(8, dl, MVT::i32));
6536 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6543 CnstBits = UndefBits;
6547 // We can always fall back to a non-immediate OR.
6552 // Normalize the operands of BUILD_VECTOR. The value of constant operands will
6553 // be truncated to fit element width.
6554 static SDValue NormalizeBuildVector(SDValue Op,
6555 SelectionDAG &DAG) {
6556 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
6558 EVT VT = Op.getValueType();
6559 EVT EltTy= VT.getVectorElementType();
6561 if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
6564 SmallVector<SDValue, 16> Ops;
6565 for (SDValue Lane : Op->ops()) {
6566 if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
6567 APInt LowBits(EltTy.getSizeInBits(),
6568 CstLane->getZExtValue());
6569 Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
6571 Ops.push_back(Lane);
6573 return DAG.getBuildVector(VT, dl, Ops);
6576 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
6577 SelectionDAG &DAG) const {
6579 EVT VT = Op.getValueType();
6580 Op = NormalizeBuildVector(Op, DAG);
6581 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
6583 APInt CnstBits(VT.getSizeInBits(), 0);
6584 APInt UndefBits(VT.getSizeInBits(), 0);
6585 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
6586 // We make use of a little bit of goto ickiness in order to avoid having to
6587 // duplicate the immediate matching logic for the undef toggled case.
6588 bool SecondTry = false;
6591 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
6592 CnstBits = CnstBits.zextOrTrunc(64);
6593 uint64_t CnstVal = CnstBits.getZExtValue();
6595 // Certain magic vector constants (used to express things like NOT
6596 // and NEG) are passed through unmodified. This allows codegen patterns
6597 // for these operations to match. Special-purpose patterns will lower
6598 // these immediates to MOVIs if it proves necessary.
6599 if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL))
6602 // The many faces of MOVI...
6603 if (AArch64_AM::isAdvSIMDModImmType10(CnstVal)) {
6604 CnstVal = AArch64_AM::encodeAdvSIMDModImmType10(CnstVal);
6605 if (VT.getSizeInBits() == 128) {
6606 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::v2i64,
6607 DAG.getConstant(CnstVal, dl, MVT::i32));
6608 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6611 // Support the V64 version via subregister insertion.
6612 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::f64,
6613 DAG.getConstant(CnstVal, dl, MVT::i32));
6614 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6617 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6618 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6619 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6620 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6621 DAG.getConstant(CnstVal, dl, MVT::i32),
6622 DAG.getConstant(0, dl, MVT::i32));
6623 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6626 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6627 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6628 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6629 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6630 DAG.getConstant(CnstVal, dl, MVT::i32),
6631 DAG.getConstant(8, dl, MVT::i32));
6632 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6635 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6636 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6637 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6638 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6639 DAG.getConstant(CnstVal, dl, MVT::i32),
6640 DAG.getConstant(16, dl, MVT::i32));
6641 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6644 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6645 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6646 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6647 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6648 DAG.getConstant(CnstVal, dl, MVT::i32),
6649 DAG.getConstant(24, dl, MVT::i32));
6650 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6653 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6654 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6655 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6656 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6657 DAG.getConstant(CnstVal, dl, MVT::i32),
6658 DAG.getConstant(0, dl, MVT::i32));
6659 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6662 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6663 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6664 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6665 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6666 DAG.getConstant(CnstVal, dl, MVT::i32),
6667 DAG.getConstant(8, dl, MVT::i32));
6668 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6671 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6672 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6673 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6674 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
6675 DAG.getConstant(CnstVal, dl, MVT::i32),
6676 DAG.getConstant(264, dl, MVT::i32));
6677 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6680 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6681 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6682 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6683 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
6684 DAG.getConstant(CnstVal, dl, MVT::i32),
6685 DAG.getConstant(272, dl, MVT::i32));
6686 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6689 if (AArch64_AM::isAdvSIMDModImmType9(CnstVal)) {
6690 CnstVal = AArch64_AM::encodeAdvSIMDModImmType9(CnstVal);
6691 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
6692 SDValue Mov = DAG.getNode(AArch64ISD::MOVI, dl, MovTy,
6693 DAG.getConstant(CnstVal, dl, MVT::i32));
6694 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6697 // The few faces of FMOV...
6698 if (AArch64_AM::isAdvSIMDModImmType11(CnstVal)) {
6699 CnstVal = AArch64_AM::encodeAdvSIMDModImmType11(CnstVal);
6700 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32;
6701 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MovTy,
6702 DAG.getConstant(CnstVal, dl, MVT::i32));
6703 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6706 if (AArch64_AM::isAdvSIMDModImmType12(CnstVal) &&
6707 VT.getSizeInBits() == 128) {
6708 CnstVal = AArch64_AM::encodeAdvSIMDModImmType12(CnstVal);
6709 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MVT::v2f64,
6710 DAG.getConstant(CnstVal, dl, MVT::i32));
6711 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6714 // The many faces of MVNI...
6716 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6717 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6718 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6719 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6720 DAG.getConstant(CnstVal, dl, MVT::i32),
6721 DAG.getConstant(0, dl, MVT::i32));
6722 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6725 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6726 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6727 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6728 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6729 DAG.getConstant(CnstVal, dl, MVT::i32),
6730 DAG.getConstant(8, dl, MVT::i32));
6731 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6734 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6735 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6736 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6737 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6738 DAG.getConstant(CnstVal, dl, MVT::i32),
6739 DAG.getConstant(16, dl, MVT::i32));
6740 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6743 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6744 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6745 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6746 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6747 DAG.getConstant(CnstVal, dl, MVT::i32),
6748 DAG.getConstant(24, dl, MVT::i32));
6749 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6752 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6753 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6754 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6755 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6756 DAG.getConstant(CnstVal, dl, MVT::i32),
6757 DAG.getConstant(0, dl, MVT::i32));
6758 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6761 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6762 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6763 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6764 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6765 DAG.getConstant(CnstVal, dl, MVT::i32),
6766 DAG.getConstant(8, dl, MVT::i32));
6767 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6770 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6771 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6772 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6773 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
6774 DAG.getConstant(CnstVal, dl, MVT::i32),
6775 DAG.getConstant(264, dl, MVT::i32));
6776 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6779 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6780 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6781 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6782 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
6783 DAG.getConstant(CnstVal, dl, MVT::i32),
6784 DAG.getConstant(272, dl, MVT::i32));
6785 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6792 CnstBits = UndefBits;
6797 // Scan through the operands to find some interesting properties we can
6799 // 1) If only one value is used, we can use a DUP, or
6800 // 2) if only the low element is not undef, we can just insert that, or
6801 // 3) if only one constant value is used (w/ some non-constant lanes),
6802 // we can splat the constant value into the whole vector then fill
6803 // in the non-constant lanes.
6804 // 4) FIXME: If different constant values are used, but we can intelligently
6805 // select the values we'll be overwriting for the non-constant
6806 // lanes such that we can directly materialize the vector
6807 // some other way (MOVI, e.g.), we can be sneaky.
6808 unsigned NumElts = VT.getVectorNumElements();
6809 bool isOnlyLowElement = true;
6810 bool usesOnlyOneValue = true;
6811 bool usesOnlyOneConstantValue = true;
6812 bool isConstant = true;
6813 unsigned NumConstantLanes = 0;
6815 SDValue ConstantValue;
6816 for (unsigned i = 0; i < NumElts; ++i) {
6817 SDValue V = Op.getOperand(i);
6821 isOnlyLowElement = false;
6822 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6825 if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
6827 if (!ConstantValue.getNode())
6829 else if (ConstantValue != V)
6830 usesOnlyOneConstantValue = false;
6833 if (!Value.getNode())
6835 else if (V != Value)
6836 usesOnlyOneValue = false;
6839 if (!Value.getNode()) {
6840 DEBUG(dbgs() << "LowerBUILD_VECTOR: value undefined, creating undef node\n");
6841 return DAG.getUNDEF(VT);
6844 if (isOnlyLowElement) {
6845 DEBUG(dbgs() << "LowerBUILD_VECTOR: only low element used, creating 1 "
6846 "SCALAR_TO_VECTOR node\n");
6847 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
6850 // Use DUP for non-constant splats. For f32 constant splats, reduce to
6851 // i32 and try again.
6852 if (usesOnlyOneValue) {
6854 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6855 Value.getValueType() != VT) {
6856 DEBUG(dbgs() << "LowerBUILD_VECTOR: use DUP for non-constant splats\n");
6857 return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
6860 // This is actually a DUPLANExx operation, which keeps everything vectory.
6862 SDValue Lane = Value.getOperand(1);
6863 Value = Value.getOperand(0);
6864 if (Value.getValueSizeInBits() == 64) {
6865 DEBUG(dbgs() << "LowerBUILD_VECTOR: DUPLANE works on 128-bit vectors, "
6867 Value = WidenVector(Value, DAG);
6870 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
6871 return DAG.getNode(Opcode, dl, VT, Value, Lane);
6874 if (VT.getVectorElementType().isFloatingPoint()) {
6875 SmallVector<SDValue, 8> Ops;
6876 EVT EltTy = VT.getVectorElementType();
6877 assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
6878 "Unsupported floating-point vector type");
6879 DEBUG(dbgs() << "LowerBUILD_VECTOR: float constant splats, creating int "
6880 "BITCASTS, and try again\n");
6881 MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
6882 for (unsigned i = 0; i < NumElts; ++i)
6883 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
6884 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
6885 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
6887 dbgs() << "LowerBUILD_VECTOR: trying to lower new vector: ";
6890 Val = LowerBUILD_VECTOR(Val, DAG);
6892 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6896 // If there was only one constant value used and for more than one lane,
6897 // start by splatting that value, then replace the non-constant lanes. This
6898 // is better than the default, which will perform a separate initialization
6900 if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
6901 SDValue Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
6902 // Now insert the non-constant lanes.
6903 for (unsigned i = 0; i < NumElts; ++i) {
6904 SDValue V = Op.getOperand(i);
6905 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
6906 if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) {
6907 // Note that type legalization likely mucked about with the VT of the
6908 // source operand, so we may have to convert it here before inserting.
6909 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
6915 // This will generate a load from the constant pool.
6917 DEBUG(dbgs() << "LowerBUILD_VECTOR: all elements are constant, use default "
6922 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6924 if (SDValue shuffle = ReconstructShuffle(Op, DAG))
6928 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6929 // know the default expansion would otherwise fall back on something even
6930 // worse. For a vector with one or two non-undef values, that's
6931 // scalar_to_vector for the elements followed by a shuffle (provided the
6932 // shuffle is valid for the target) and materialization element by element
6933 // on the stack followed by a load for everything else.
6934 if (!isConstant && !usesOnlyOneValue) {
6935 DEBUG(dbgs() << "LowerBUILD_VECTOR: alternatives failed, creating sequence "
6936 "of INSERT_VECTOR_ELT\n");
6938 SDValue Vec = DAG.getUNDEF(VT);
6939 SDValue Op0 = Op.getOperand(0);
6942 // Use SCALAR_TO_VECTOR for lane zero to
6943 // a) Avoid a RMW dependency on the full vector register, and
6944 // b) Allow the register coalescer to fold away the copy if the
6945 // value is already in an S or D register, and we're forced to emit an
6946 // INSERT_SUBREG that we can't fold anywhere.
6948 // We also allow types like i8 and i16 which are illegal scalar but legal
6949 // vector element types. After type-legalization the inserted value is
6950 // extended (i32) and it is safe to cast them to the vector type by ignoring
6951 // the upper bits of the lowest lane (e.g. v8i8, v4i16).
6952 if (!Op0.isUndef()) {
6953 DEBUG(dbgs() << "Creating node for op0, it is not undefined:\n");
6954 Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op0);
6959 dbgs() << "Creating nodes for the other vector elements:\n";
6961 for (; i < NumElts; ++i) {
6962 SDValue V = Op.getOperand(i);
6965 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
6966 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6971 DEBUG(dbgs() << "LowerBUILD_VECTOR: use default expansion, failed to find "
6972 "better alternative\n");
6976 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
6977 SelectionDAG &DAG) const {
6978 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
6980 // Check for non-constant or out of range lane.
6981 EVT VT = Op.getOperand(0).getValueType();
6982 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
6983 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
6987 // Insertion/extraction are legal for V128 types.
6988 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
6989 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6993 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
6994 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
6997 // For V64 types, we perform insertion by expanding the value
6998 // to a V128 type and perform the insertion on that.
7000 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
7001 EVT WideTy = WideVec.getValueType();
7003 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
7004 Op.getOperand(1), Op.getOperand(2));
7005 // Re-narrow the resultant vector.
7006 return NarrowVector(Node, DAG);
7010 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
7011 SelectionDAG &DAG) const {
7012 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
7014 // Check for non-constant or out of range lane.
7015 EVT VT = Op.getOperand(0).getValueType();
7016 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7017 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
7021 // Insertion/extraction are legal for V128 types.
7022 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
7023 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
7027 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
7028 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
7031 // For V64 types, we perform extraction by expanding the value
7032 // to a V128 type and perform the extraction on that.
7034 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
7035 EVT WideTy = WideVec.getValueType();
7037 EVT ExtrTy = WideTy.getVectorElementType();
7038 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
7041 // For extractions, we just return the result directly.
7042 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
7046 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
7047 SelectionDAG &DAG) const {
7048 EVT VT = Op.getOperand(0).getValueType();
7054 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7057 unsigned Val = Cst->getZExtValue();
7059 unsigned Size = Op.getValueSizeInBits();
7061 // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
7065 // If this is extracting the upper 64-bits of a 128-bit vector, we match
7067 if (Size == 64 && Val * VT.getScalarSizeInBits() == 64)
7073 bool AArch64TargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
7074 if (VT.getVectorNumElements() == 4 &&
7075 (VT.is128BitVector() || VT.is64BitVector())) {
7076 unsigned PFIndexes[4];
7077 for (unsigned i = 0; i != 4; ++i) {
7081 PFIndexes[i] = M[i];
7084 // Compute the index in the perfect shuffle table.
7085 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
7086 PFIndexes[2] * 9 + PFIndexes[3];
7087 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7088 unsigned Cost = (PFEntry >> 30);
7096 unsigned DummyUnsigned;
7098 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
7099 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
7100 isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
7101 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
7102 isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
7103 isZIPMask(M, VT, DummyUnsigned) ||
7104 isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
7105 isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
7106 isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
7107 isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
7108 isConcatMask(M, VT, VT.getSizeInBits() == 128));
7111 /// getVShiftImm - Check if this is a valid build_vector for the immediate
7112 /// operand of a vector shift operation, where all the elements of the
7113 /// build_vector must have the same constant integer value.
7114 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
7115 // Ignore bit_converts.
7116 while (Op.getOpcode() == ISD::BITCAST)
7117 Op = Op.getOperand(0);
7118 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
7119 APInt SplatBits, SplatUndef;
7120 unsigned SplatBitSize;
7122 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
7123 HasAnyUndefs, ElementBits) ||
7124 SplatBitSize > ElementBits)
7126 Cnt = SplatBits.getSExtValue();
7130 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
7131 /// operand of a vector shift left operation. That value must be in the range:
7132 /// 0 <= Value < ElementBits for a left shift; or
7133 /// 0 <= Value <= ElementBits for a long left shift.
7134 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
7135 assert(VT.isVector() && "vector shift count is not a vector type");
7136 int64_t ElementBits = VT.getScalarSizeInBits();
7137 if (!getVShiftImm(Op, ElementBits, Cnt))
7139 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
7142 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
7143 /// operand of a vector shift right operation. The value must be in the range:
7144 /// 1 <= Value <= ElementBits for a right shift; or
7145 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
7146 assert(VT.isVector() && "vector shift count is not a vector type");
7147 int64_t ElementBits = VT.getScalarSizeInBits();
7148 if (!getVShiftImm(Op, ElementBits, Cnt))
7150 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
7153 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
7154 SelectionDAG &DAG) const {
7155 EVT VT = Op.getValueType();
7159 if (!Op.getOperand(1).getValueType().isVector())
7161 unsigned EltSize = VT.getScalarSizeInBits();
7163 switch (Op.getOpcode()) {
7165 llvm_unreachable("unexpected shift opcode");
7168 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
7169 return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
7170 DAG.getConstant(Cnt, DL, MVT::i32));
7171 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
7172 DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
7174 Op.getOperand(0), Op.getOperand(1));
7177 // Right shift immediate
7178 if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
7180 (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
7181 return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
7182 DAG.getConstant(Cnt, DL, MVT::i32));
7185 // Right shift register. Note, there is not a shift right register
7186 // instruction, but the shift left register instruction takes a signed
7187 // value, where negative numbers specify a right shift.
7188 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
7189 : Intrinsic::aarch64_neon_ushl;
7190 // negate the shift amount
7191 SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
7192 SDValue NegShiftLeft =
7193 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
7194 DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
7196 return NegShiftLeft;
7202 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
7203 AArch64CC::CondCode CC, bool NoNans, EVT VT,
7204 const SDLoc &dl, SelectionDAG &DAG) {
7205 EVT SrcVT = LHS.getValueType();
7206 assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
7207 "function only supposed to emit natural comparisons");
7209 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
7210 APInt CnstBits(VT.getSizeInBits(), 0);
7211 APInt UndefBits(VT.getSizeInBits(), 0);
7212 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
7213 bool IsZero = IsCnst && (CnstBits == 0);
7215 if (SrcVT.getVectorElementType().isFloatingPoint()) {
7219 case AArch64CC::NE: {
7222 Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
7224 Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
7225 return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
7229 return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
7230 return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
7233 return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
7234 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
7237 return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
7238 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
7241 return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
7242 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
7246 // If we ignore NaNs then we can use to the MI implementation.
7250 return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
7251 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
7258 case AArch64CC::NE: {
7261 Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
7263 Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
7264 return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
7268 return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
7269 return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
7272 return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
7273 return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
7276 return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
7277 return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
7280 return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
7281 return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
7283 return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
7285 return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
7288 return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
7289 return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
7291 return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
7293 return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
7297 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
7298 SelectionDAG &DAG) const {
7299 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7300 SDValue LHS = Op.getOperand(0);
7301 SDValue RHS = Op.getOperand(1);
7302 EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
7305 if (LHS.getValueType().getVectorElementType().isInteger()) {
7306 assert(LHS.getValueType() == RHS.getValueType());
7307 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
7309 EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
7310 return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
7313 if (LHS.getValueType().getVectorElementType() == MVT::f16)
7316 assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
7317 LHS.getValueType().getVectorElementType() == MVT::f64);
7319 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
7320 // clean. Some of them require two branches to implement.
7321 AArch64CC::CondCode CC1, CC2;
7323 changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
7325 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
7327 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
7331 if (CC2 != AArch64CC::AL) {
7333 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
7334 if (!Cmp2.getNode())
7337 Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
7340 Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
7343 return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
7348 static SDValue getReductionSDNode(unsigned Op, SDLoc DL, SDValue ScalarOp,
7349 SelectionDAG &DAG) {
7350 SDValue VecOp = ScalarOp.getOperand(0);
7351 auto Rdx = DAG.getNode(Op, DL, VecOp.getSimpleValueType(), VecOp);
7352 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarOp.getValueType(), Rdx,
7353 DAG.getConstant(0, DL, MVT::i64));
7356 SDValue AArch64TargetLowering::LowerVECREDUCE(SDValue Op,
7357 SelectionDAG &DAG) const {
7359 switch (Op.getOpcode()) {
7360 case ISD::VECREDUCE_ADD:
7361 return getReductionSDNode(AArch64ISD::UADDV, dl, Op, DAG);
7362 case ISD::VECREDUCE_SMAX:
7363 return getReductionSDNode(AArch64ISD::SMAXV, dl, Op, DAG);
7364 case ISD::VECREDUCE_SMIN:
7365 return getReductionSDNode(AArch64ISD::SMINV, dl, Op, DAG);
7366 case ISD::VECREDUCE_UMAX:
7367 return getReductionSDNode(AArch64ISD::UMAXV, dl, Op, DAG);
7368 case ISD::VECREDUCE_UMIN:
7369 return getReductionSDNode(AArch64ISD::UMINV, dl, Op, DAG);
7370 case ISD::VECREDUCE_FMAX: {
7371 assert(Op->getFlags().hasNoNaNs() && "fmax vector reduction needs NoNaN flag");
7373 ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
7374 DAG.getConstant(Intrinsic::aarch64_neon_fmaxnmv, dl, MVT::i32),
7377 case ISD::VECREDUCE_FMIN: {
7378 assert(Op->getFlags().hasNoNaNs() && "fmin vector reduction needs NoNaN flag");
7380 ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
7381 DAG.getConstant(Intrinsic::aarch64_neon_fminnmv, dl, MVT::i32),
7385 llvm_unreachable("Unhandled reduction");
7389 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
7390 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
7391 /// specified in the intrinsic calls.
7392 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
7394 MachineFunction &MF,
7395 unsigned Intrinsic) const {
7396 auto &DL = I.getModule()->getDataLayout();
7397 switch (Intrinsic) {
7398 case Intrinsic::aarch64_neon_ld2:
7399 case Intrinsic::aarch64_neon_ld3:
7400 case Intrinsic::aarch64_neon_ld4:
7401 case Intrinsic::aarch64_neon_ld1x2:
7402 case Intrinsic::aarch64_neon_ld1x3:
7403 case Intrinsic::aarch64_neon_ld1x4:
7404 case Intrinsic::aarch64_neon_ld2lane:
7405 case Intrinsic::aarch64_neon_ld3lane:
7406 case Intrinsic::aarch64_neon_ld4lane:
7407 case Intrinsic::aarch64_neon_ld2r:
7408 case Intrinsic::aarch64_neon_ld3r:
7409 case Intrinsic::aarch64_neon_ld4r: {
7410 Info.opc = ISD::INTRINSIC_W_CHAIN;
7411 // Conservatively set memVT to the entire set of vectors loaded.
7412 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
7413 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
7414 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
7417 // volatile loads with NEON intrinsics not supported
7418 Info.flags = MachineMemOperand::MOLoad;
7421 case Intrinsic::aarch64_neon_st2:
7422 case Intrinsic::aarch64_neon_st3:
7423 case Intrinsic::aarch64_neon_st4:
7424 case Intrinsic::aarch64_neon_st1x2:
7425 case Intrinsic::aarch64_neon_st1x3:
7426 case Intrinsic::aarch64_neon_st1x4:
7427 case Intrinsic::aarch64_neon_st2lane:
7428 case Intrinsic::aarch64_neon_st3lane:
7429 case Intrinsic::aarch64_neon_st4lane: {
7430 Info.opc = ISD::INTRINSIC_VOID;
7431 // Conservatively set memVT to the entire set of vectors stored.
7432 unsigned NumElts = 0;
7433 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
7434 Type *ArgTy = I.getArgOperand(ArgI)->getType();
7435 if (!ArgTy->isVectorTy())
7437 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
7439 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
7440 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
7443 // volatile stores with NEON intrinsics not supported
7444 Info.flags = MachineMemOperand::MOStore;
7447 case Intrinsic::aarch64_ldaxr:
7448 case Intrinsic::aarch64_ldxr: {
7449 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
7450 Info.opc = ISD::INTRINSIC_W_CHAIN;
7451 Info.memVT = MVT::getVT(PtrTy->getElementType());
7452 Info.ptrVal = I.getArgOperand(0);
7454 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
7455 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
7458 case Intrinsic::aarch64_stlxr:
7459 case Intrinsic::aarch64_stxr: {
7460 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
7461 Info.opc = ISD::INTRINSIC_W_CHAIN;
7462 Info.memVT = MVT::getVT(PtrTy->getElementType());
7463 Info.ptrVal = I.getArgOperand(1);
7465 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
7466 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
7469 case Intrinsic::aarch64_ldaxp:
7470 case Intrinsic::aarch64_ldxp:
7471 Info.opc = ISD::INTRINSIC_W_CHAIN;
7472 Info.memVT = MVT::i128;
7473 Info.ptrVal = I.getArgOperand(0);
7476 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
7478 case Intrinsic::aarch64_stlxp:
7479 case Intrinsic::aarch64_stxp:
7480 Info.opc = ISD::INTRINSIC_W_CHAIN;
7481 Info.memVT = MVT::i128;
7482 Info.ptrVal = I.getArgOperand(2);
7485 Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
7494 // Truncations from 64-bit GPR to 32-bit GPR is free.
7495 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
7496 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
7498 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7499 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
7500 return NumBits1 > NumBits2;
7502 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
7503 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
7505 unsigned NumBits1 = VT1.getSizeInBits();
7506 unsigned NumBits2 = VT2.getSizeInBits();
7507 return NumBits1 > NumBits2;
7510 /// Check if it is profitable to hoist instruction in then/else to if.
7511 /// Not profitable if I and it's user can form a FMA instruction
7512 /// because we prefer FMSUB/FMADD.
7513 bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
7514 if (I->getOpcode() != Instruction::FMul)
7517 if (!I->hasOneUse())
7520 Instruction *User = I->user_back();
7523 !(User->getOpcode() == Instruction::FSub ||
7524 User->getOpcode() == Instruction::FAdd))
7527 const TargetOptions &Options = getTargetMachine().Options;
7528 const DataLayout &DL = I->getModule()->getDataLayout();
7529 EVT VT = getValueType(DL, User->getOperand(0)->getType());
7531 return !(isFMAFasterThanFMulAndFAdd(VT) &&
7532 isOperationLegalOrCustom(ISD::FMA, VT) &&
7533 (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7534 Options.UnsafeFPMath));
7537 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
7539 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
7540 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
7542 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7543 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
7544 return NumBits1 == 32 && NumBits2 == 64;
7546 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
7547 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
7549 unsigned NumBits1 = VT1.getSizeInBits();
7550 unsigned NumBits2 = VT2.getSizeInBits();
7551 return NumBits1 == 32 && NumBits2 == 64;
7554 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
7555 EVT VT1 = Val.getValueType();
7556 if (isZExtFree(VT1, VT2)) {
7560 if (Val.getOpcode() != ISD::LOAD)
7563 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
7564 return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
7565 VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
7566 VT1.getSizeInBits() <= 32);
7569 bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
7570 if (isa<FPExtInst>(Ext))
7573 // Vector types are not free.
7574 if (Ext->getType()->isVectorTy())
7577 for (const Use &U : Ext->uses()) {
7578 // The extension is free if we can fold it with a left shift in an
7579 // addressing mode or an arithmetic operation: add, sub, and cmp.
7581 // Is there a shift?
7582 const Instruction *Instr = cast<Instruction>(U.getUser());
7584 // Is this a constant shift?
7585 switch (Instr->getOpcode()) {
7586 case Instruction::Shl:
7587 if (!isa<ConstantInt>(Instr->getOperand(1)))
7590 case Instruction::GetElementPtr: {
7591 gep_type_iterator GTI = gep_type_begin(Instr);
7592 auto &DL = Ext->getModule()->getDataLayout();
7593 std::advance(GTI, U.getOperandNo()-1);
7594 Type *IdxTy = GTI.getIndexedType();
7595 // This extension will end up with a shift because of the scaling factor.
7596 // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
7597 // Get the shift amount based on the scaling factor:
7598 // log2(sizeof(IdxTy)) - log2(8).
7600 countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3;
7601 // Is the constant foldable in the shift of the addressing mode?
7602 // I.e., shift amount is between 1 and 4 inclusive.
7603 if (ShiftAmt == 0 || ShiftAmt > 4)
7607 case Instruction::Trunc:
7608 // Check if this is a noop.
7609 // trunc(sext ty1 to ty2) to ty1.
7610 if (Instr->getType() == Ext->getOperand(0)->getType())
7617 // At this point we can use the bfm family, so this extension is free
7623 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
7624 unsigned &RequiredAligment) const {
7625 if (!LoadedType.isSimple() ||
7626 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
7628 // Cyclone supports unaligned accesses.
7629 RequiredAligment = 0;
7630 unsigned NumBits = LoadedType.getSizeInBits();
7631 return NumBits == 32 || NumBits == 64;
7634 /// A helper function for determining the number of interleaved accesses we
7635 /// will generate when lowering accesses of the given type.
7637 AArch64TargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
7638 const DataLayout &DL) const {
7639 return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
7642 MachineMemOperand::Flags
7643 AArch64TargetLowering::getMMOFlags(const Instruction &I) const {
7644 if (Subtarget->getProcFamily() == AArch64Subtarget::Falkor &&
7645 I.getMetadata(FALKOR_STRIDED_ACCESS_MD) != nullptr)
7646 return MOStridedAccess;
7647 return MachineMemOperand::MONone;
7650 bool AArch64TargetLowering::isLegalInterleavedAccessType(
7651 VectorType *VecTy, const DataLayout &DL) const {
7653 unsigned VecSize = DL.getTypeSizeInBits(VecTy);
7654 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
7656 // Ensure the number of vector elements is greater than 1.
7657 if (VecTy->getNumElements() < 2)
7660 // Ensure the element type is legal.
7661 if (ElSize != 8 && ElSize != 16 && ElSize != 32 && ElSize != 64)
7664 // Ensure the total vector size is 64 or a multiple of 128. Types larger than
7665 // 128 will be split into multiple interleaved accesses.
7666 return VecSize == 64 || VecSize % 128 == 0;
7669 /// \brief Lower an interleaved load into a ldN intrinsic.
7671 /// E.g. Lower an interleaved load (Factor = 2):
7672 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr
7673 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
7674 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
7677 /// %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
7678 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
7679 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
7680 bool AArch64TargetLowering::lowerInterleavedLoad(
7681 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
7682 ArrayRef<unsigned> Indices, unsigned Factor) const {
7683 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7684 "Invalid interleave factor");
7685 assert(!Shuffles.empty() && "Empty shufflevector input");
7686 assert(Shuffles.size() == Indices.size() &&
7687 "Unmatched number of shufflevectors and indices");
7689 const DataLayout &DL = LI->getModule()->getDataLayout();
7691 VectorType *VecTy = Shuffles[0]->getType();
7693 // Skip if we do not have NEON and skip illegal vector types. We can
7694 // "legalize" wide vector types into multiple interleaved accesses as long as
7695 // the vector types are divisible by 128.
7696 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL))
7699 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
7701 // A pointer vector can not be the return type of the ldN intrinsics. Need to
7702 // load integer vectors first and then convert to pointer vectors.
7703 Type *EltTy = VecTy->getVectorElementType();
7704 if (EltTy->isPointerTy())
7706 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
7708 IRBuilder<> Builder(LI);
7710 // The base address of the load.
7711 Value *BaseAddr = LI->getPointerOperand();
7714 // If we're going to generate more than one load, reset the sub-vector type
7715 // to something legal.
7716 VecTy = VectorType::get(VecTy->getVectorElementType(),
7717 VecTy->getVectorNumElements() / NumLoads);
7719 // We will compute the pointer operand of each load from the original base
7720 // address using GEPs. Cast the base address to a pointer to the scalar
7722 BaseAddr = Builder.CreateBitCast(
7723 BaseAddr, VecTy->getVectorElementType()->getPointerTo(
7724 LI->getPointerAddressSpace()));
7727 Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
7728 Type *Tys[2] = {VecTy, PtrTy};
7729 static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
7730 Intrinsic::aarch64_neon_ld3,
7731 Intrinsic::aarch64_neon_ld4};
7733 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
7735 // Holds sub-vectors extracted from the load intrinsic return values. The
7736 // sub-vectors are associated with the shufflevector instructions they will
7738 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
7740 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
7742 // If we're generating more than one load, compute the base address of
7743 // subsequent loads as an offset from the previous.
7745 BaseAddr = Builder.CreateConstGEP1_32(
7746 BaseAddr, VecTy->getVectorNumElements() * Factor);
7748 CallInst *LdN = Builder.CreateCall(
7749 LdNFunc, Builder.CreateBitCast(BaseAddr, PtrTy), "ldN");
7751 // Extract and store the sub-vectors returned by the load intrinsic.
7752 for (unsigned i = 0; i < Shuffles.size(); i++) {
7753 ShuffleVectorInst *SVI = Shuffles[i];
7754 unsigned Index = Indices[i];
7756 Value *SubVec = Builder.CreateExtractValue(LdN, Index);
7758 // Convert the integer vector to pointer vector if the element is pointer.
7759 if (EltTy->isPointerTy())
7760 SubVec = Builder.CreateIntToPtr(
7761 SubVec, VectorType::get(SVI->getType()->getVectorElementType(),
7762 VecTy->getVectorNumElements()));
7763 SubVecs[SVI].push_back(SubVec);
7767 // Replace uses of the shufflevector instructions with the sub-vectors
7768 // returned by the load intrinsic. If a shufflevector instruction is
7769 // associated with more than one sub-vector, those sub-vectors will be
7770 // concatenated into a single wide vector.
7771 for (ShuffleVectorInst *SVI : Shuffles) {
7772 auto &SubVec = SubVecs[SVI];
7774 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
7775 SVI->replaceAllUsesWith(WideVec);
7781 /// \brief Lower an interleaved store into a stN intrinsic.
7783 /// E.g. Lower an interleaved store (Factor = 3):
7784 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
7785 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
7786 /// store <12 x i32> %i.vec, <12 x i32>* %ptr
7789 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
7790 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
7791 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
7792 /// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
7794 /// Note that the new shufflevectors will be removed and we'll only generate one
7795 /// st3 instruction in CodeGen.
7797 /// Example for a more general valid mask (Factor 3). Lower:
7798 /// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
7799 /// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
7800 /// store <12 x i32> %i.vec, <12 x i32>* %ptr
7803 /// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
7804 /// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
7805 /// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
7806 /// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
7807 bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
7808 ShuffleVectorInst *SVI,
7809 unsigned Factor) const {
7810 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7811 "Invalid interleave factor");
7813 VectorType *VecTy = SVI->getType();
7814 assert(VecTy->getVectorNumElements() % Factor == 0 &&
7815 "Invalid interleaved store");
7817 unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
7818 Type *EltTy = VecTy->getVectorElementType();
7819 VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
7821 const DataLayout &DL = SI->getModule()->getDataLayout();
7823 // Skip if we do not have NEON and skip illegal vector types. We can
7824 // "legalize" wide vector types into multiple interleaved accesses as long as
7825 // the vector types are divisible by 128.
7826 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
7829 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
7831 Value *Op0 = SVI->getOperand(0);
7832 Value *Op1 = SVI->getOperand(1);
7833 IRBuilder<> Builder(SI);
7835 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
7836 // vectors to integer vectors.
7837 if (EltTy->isPointerTy()) {
7838 Type *IntTy = DL.getIntPtrType(EltTy);
7839 unsigned NumOpElts =
7840 dyn_cast<VectorType>(Op0->getType())->getVectorNumElements();
7842 // Convert to the corresponding integer vector.
7843 Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
7844 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
7845 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
7847 SubVecTy = VectorType::get(IntTy, LaneLen);
7850 // The base address of the store.
7851 Value *BaseAddr = SI->getPointerOperand();
7853 if (NumStores > 1) {
7854 // If we're going to generate more than one store, reset the lane length
7855 // and sub-vector type to something legal.
7856 LaneLen /= NumStores;
7857 SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen);
7859 // We will compute the pointer operand of each store from the original base
7860 // address using GEPs. Cast the base address to a pointer to the scalar
7862 BaseAddr = Builder.CreateBitCast(
7863 BaseAddr, SubVecTy->getVectorElementType()->getPointerTo(
7864 SI->getPointerAddressSpace()));
7867 auto Mask = SVI->getShuffleMask();
7869 Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
7870 Type *Tys[2] = {SubVecTy, PtrTy};
7871 static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
7872 Intrinsic::aarch64_neon_st3,
7873 Intrinsic::aarch64_neon_st4};
7875 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
7877 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
7879 SmallVector<Value *, 5> Ops;
7881 // Split the shufflevector operands into sub vectors for the new stN call.
7882 for (unsigned i = 0; i < Factor; i++) {
7883 unsigned IdxI = StoreCount * LaneLen * Factor + i;
7884 if (Mask[IdxI] >= 0) {
7885 Ops.push_back(Builder.CreateShuffleVector(
7886 Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0)));
7888 unsigned StartMask = 0;
7889 for (unsigned j = 1; j < LaneLen; j++) {
7890 unsigned IdxJ = StoreCount * LaneLen * Factor + j;
7891 if (Mask[IdxJ * Factor + IdxI] >= 0) {
7892 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
7896 // Note: Filling undef gaps with random elements is ok, since
7897 // those elements were being written anyway (with undefs).
7898 // In the case of all undefs we're defaulting to using elems from 0
7899 // Note: StartMask cannot be negative, it's checked in
7900 // isReInterleaveMask
7901 Ops.push_back(Builder.CreateShuffleVector(
7902 Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0)));
7906 // If we generating more than one store, we compute the base address of
7907 // subsequent stores as an offset from the previous.
7909 BaseAddr = Builder.CreateConstGEP1_32(BaseAddr, LaneLen * Factor);
7911 Ops.push_back(Builder.CreateBitCast(BaseAddr, PtrTy));
7912 Builder.CreateCall(StNFunc, Ops);
7917 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
7918 unsigned AlignCheck) {
7919 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
7920 (DstAlign == 0 || DstAlign % AlignCheck == 0));
7923 EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
7924 unsigned SrcAlign, bool IsMemset,
7927 MachineFunction &MF) const {
7928 // Don't use AdvSIMD to implement 16-byte memset. It would have taken one
7929 // instruction to materialize the v2i64 zero and one store (with restrictive
7930 // addressing mode). Just do two i64 store of zero-registers.
7932 const Function &F = MF.getFunction();
7933 if (Subtarget->hasFPARMv8() && !IsMemset && Size >= 16 &&
7934 !F.hasFnAttribute(Attribute::NoImplicitFloat) &&
7935 (memOpAlign(SrcAlign, DstAlign, 16) ||
7936 (allowsMisalignedMemoryAccesses(MVT::f128, 0, 1, &Fast) && Fast)))
7940 (memOpAlign(SrcAlign, DstAlign, 8) ||
7941 (allowsMisalignedMemoryAccesses(MVT::i64, 0, 1, &Fast) && Fast)))
7945 (memOpAlign(SrcAlign, DstAlign, 4) ||
7946 (allowsMisalignedMemoryAccesses(MVT::i32, 0, 1, &Fast) && Fast)))
7952 // 12-bit optionally shifted immediates are legal for adds.
7953 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
7954 if (Immed == std::numeric_limits<int64_t>::min()) {
7955 DEBUG(dbgs() << "Illegal add imm " << Immed << ": avoid UB for INT64_MIN\n");
7958 // Same encoding for add/sub, just flip the sign.
7959 Immed = std::abs(Immed);
7960 bool IsLegal = ((Immed >> 12) == 0 ||
7961 ((Immed & 0xfff) == 0 && Immed >> 24 == 0));
7962 DEBUG(dbgs() << "Is " << Immed << " legal add imm: " <<
7963 (IsLegal ? "yes" : "no") << "\n");
7967 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
7968 // immediates is the same as for an add or a sub.
7969 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
7970 return isLegalAddImmediate(Immed);
7973 /// isLegalAddressingMode - Return true if the addressing mode represented
7974 /// by AM is legal for this target, for a load/store of the specified type.
7975 bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
7976 const AddrMode &AM, Type *Ty,
7977 unsigned AS, Instruction *I) const {
7978 // AArch64 has five basic addressing modes:
7980 // reg + 9-bit signed offset
7981 // reg + SIZE_IN_BYTES * 12-bit unsigned offset
7983 // reg + SIZE_IN_BYTES * reg
7985 // No global is ever allowed as a base.
7989 // No reg+reg+imm addressing.
7990 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
7993 // check reg + imm case:
7994 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
7995 uint64_t NumBytes = 0;
7996 if (Ty->isSized()) {
7997 uint64_t NumBits = DL.getTypeSizeInBits(Ty);
7998 NumBytes = NumBits / 8;
7999 if (!isPowerOf2_64(NumBits))
8004 int64_t Offset = AM.BaseOffs;
8006 // 9-bit signed offset
8007 if (isInt<9>(Offset))
8010 // 12-bit unsigned offset
8011 unsigned shift = Log2_64(NumBytes);
8012 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
8013 // Must be a multiple of NumBytes (NumBytes is a power of 2)
8014 (Offset >> shift) << shift == Offset)
8019 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
8021 return AM.Scale == 1 || (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes);
8024 int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
8025 const AddrMode &AM, Type *Ty,
8026 unsigned AS) const {
8027 // Scaling factors are not free at all.
8028 // Operands | Rt Latency
8029 // -------------------------------------------
8031 // -------------------------------------------
8032 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5
8033 // Rt, [Xn, Wm, <extend> #imm] |
8034 if (isLegalAddressingMode(DL, AM, Ty, AS))
8035 // Scale represents reg2 * scale, thus account for 1 if
8036 // it is not equal to 0 or 1.
8037 return AM.Scale != 0 && AM.Scale != 1;
8041 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
8042 VT = VT.getScalarType();
8047 switch (VT.getSimpleVT().SimpleTy) {
8059 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
8060 // LR is a callee-save register, but we must treat it as clobbered by any call
8061 // site. Hence we include LR in the scratch registers, which are in turn added
8062 // as implicit-defs for stackmaps and patchpoints.
8063 static const MCPhysReg ScratchRegs[] = {
8064 AArch64::X16, AArch64::X17, AArch64::LR, 0
8070 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N) const {
8071 EVT VT = N->getValueType(0);
8072 // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
8073 // it with shift to let it be lowered to UBFX.
8074 if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
8075 isa<ConstantSDNode>(N->getOperand(1))) {
8076 uint64_t TruncMask = N->getConstantOperandVal(1);
8077 if (isMask_64(TruncMask) &&
8078 N->getOperand(0).getOpcode() == ISD::SRL &&
8079 isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
8085 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
8087 assert(Ty->isIntegerTy());
8089 unsigned BitSize = Ty->getPrimitiveSizeInBits();
8093 int64_t Val = Imm.getSExtValue();
8094 if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
8097 if ((int64_t)Val < 0)
8100 Val &= (1LL << 32) - 1;
8102 unsigned LZ = countLeadingZeros((uint64_t)Val);
8103 unsigned Shift = (63 - LZ) / 16;
8104 // MOVZ is free so return true for one or fewer MOVK.
8108 /// Turn vector tests of the signbit in the form of:
8109 /// xor (sra X, elt_size(X)-1), -1
8112 static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
8113 const AArch64Subtarget *Subtarget) {
8114 EVT VT = N->getValueType(0);
8115 if (!Subtarget->hasNEON() || !VT.isVector())
8118 // There must be a shift right algebraic before the xor, and the xor must be a
8120 SDValue Shift = N->getOperand(0);
8121 SDValue Ones = N->getOperand(1);
8122 if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() ||
8123 !ISD::isBuildVectorAllOnes(Ones.getNode()))
8126 // The shift should be smearing the sign bit across each vector element.
8127 auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
8128 EVT ShiftEltTy = Shift.getValueType().getVectorElementType();
8129 if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1)
8132 return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0));
8135 // Generate SUBS and CSEL for integer abs.
8136 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
8137 EVT VT = N->getValueType(0);
8139 SDValue N0 = N->getOperand(0);
8140 SDValue N1 = N->getOperand(1);
8143 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
8144 // and change it to SUB and CSEL.
8145 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
8146 N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
8147 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
8148 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
8149 if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
8150 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
8152 // Generate SUBS & CSEL.
8154 DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
8155 N0.getOperand(0), DAG.getConstant(0, DL, VT));
8156 return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
8157 DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
8158 SDValue(Cmp.getNode(), 1));
8163 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
8164 TargetLowering::DAGCombinerInfo &DCI,
8165 const AArch64Subtarget *Subtarget) {
8166 if (DCI.isBeforeLegalizeOps())
8169 if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget))
8172 return performIntegerAbsCombine(N, DAG);
8176 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
8178 std::vector<SDNode *> *Created) const {
8179 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
8180 if (isIntDivCheap(N->getValueType(0), Attr))
8181 return SDValue(N,0); // Lower SDIV as SDIV
8183 // fold (sdiv X, pow2)
8184 EVT VT = N->getValueType(0);
8185 if ((VT != MVT::i32 && VT != MVT::i64) ||
8186 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
8190 SDValue N0 = N->getOperand(0);
8191 unsigned Lg2 = Divisor.countTrailingZeros();
8192 SDValue Zero = DAG.getConstant(0, DL, VT);
8193 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
8195 // Add (N0 < 0) ? Pow2 - 1 : 0;
8197 SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
8198 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
8199 SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
8202 Created->push_back(Cmp.getNode());
8203 Created->push_back(Add.getNode());
8204 Created->push_back(CSel.getNode());
8209 DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
8211 // If we're dividing by a positive value, we're done. Otherwise, we must
8212 // negate the result.
8213 if (Divisor.isNonNegative())
8217 Created->push_back(SRA.getNode());
8218 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
8221 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
8222 TargetLowering::DAGCombinerInfo &DCI,
8223 const AArch64Subtarget *Subtarget) {
8224 if (DCI.isBeforeLegalizeOps())
8227 // The below optimizations require a constant RHS.
8228 if (!isa<ConstantSDNode>(N->getOperand(1)))
8231 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1));
8232 const APInt &ConstValue = C->getAPIntValue();
8234 // Multiplication of a power of two plus/minus one can be done more
8235 // cheaply as as shift+add/sub. For now, this is true unilaterally. If
8236 // future CPUs have a cheaper MADD instruction, this may need to be
8237 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
8238 // 64-bit is 5 cycles, so this is always a win.
8239 // More aggressively, some multiplications N0 * C can be lowered to
8240 // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M,
8241 // e.g. 6=3*2=(2+1)*2.
8242 // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45
8243 // which equals to (1+2)*16-(1+2).
8244 SDValue N0 = N->getOperand(0);
8245 // TrailingZeroes is used to test if the mul can be lowered to
8247 unsigned TrailingZeroes = ConstValue.countTrailingZeros();
8248 if (TrailingZeroes) {
8249 // Conservatively do not lower to shift+add+shift if the mul might be
8250 // folded into smul or umul.
8251 if (N0->hasOneUse() && (isSignExtended(N0.getNode(), DAG) ||
8252 isZeroExtended(N0.getNode(), DAG)))
8254 // Conservatively do not lower to shift+add+shift if the mul might be
8255 // folded into madd or msub.
8256 if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ADD ||
8257 N->use_begin()->getOpcode() == ISD::SUB))
8260 // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub
8261 // and shift+add+shift.
8262 APInt ShiftedConstValue = ConstValue.ashr(TrailingZeroes);
8264 unsigned ShiftAmt, AddSubOpc;
8265 // Is the shifted value the LHS operand of the add/sub?
8266 bool ShiftValUseIsN0 = true;
8267 // Do we need to negate the result?
8268 bool NegateResult = false;
8270 if (ConstValue.isNonNegative()) {
8271 // (mul x, 2^N + 1) => (add (shl x, N), x)
8272 // (mul x, 2^N - 1) => (sub (shl x, N), x)
8273 // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M)
8274 APInt SCVMinus1 = ShiftedConstValue - 1;
8275 APInt CVPlus1 = ConstValue + 1;
8276 if (SCVMinus1.isPowerOf2()) {
8277 ShiftAmt = SCVMinus1.logBase2();
8278 AddSubOpc = ISD::ADD;
8279 } else if (CVPlus1.isPowerOf2()) {
8280 ShiftAmt = CVPlus1.logBase2();
8281 AddSubOpc = ISD::SUB;
8285 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8286 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8287 APInt CVNegPlus1 = -ConstValue + 1;
8288 APInt CVNegMinus1 = -ConstValue - 1;
8289 if (CVNegPlus1.isPowerOf2()) {
8290 ShiftAmt = CVNegPlus1.logBase2();
8291 AddSubOpc = ISD::SUB;
8292 ShiftValUseIsN0 = false;
8293 } else if (CVNegMinus1.isPowerOf2()) {
8294 ShiftAmt = CVNegMinus1.logBase2();
8295 AddSubOpc = ISD::ADD;
8296 NegateResult = true;
8302 EVT VT = N->getValueType(0);
8303 SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, VT, N0,
8304 DAG.getConstant(ShiftAmt, DL, MVT::i64));
8306 SDValue AddSubN0 = ShiftValUseIsN0 ? ShiftedVal : N0;
8307 SDValue AddSubN1 = ShiftValUseIsN0 ? N0 : ShiftedVal;
8308 SDValue Res = DAG.getNode(AddSubOpc, DL, VT, AddSubN0, AddSubN1);
8309 assert(!(NegateResult && TrailingZeroes) &&
8310 "NegateResult and TrailingZeroes cannot both be true for now.");
8311 // Negate the result.
8313 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
8314 // Shift the result.
8316 return DAG.getNode(ISD::SHL, DL, VT, Res,
8317 DAG.getConstant(TrailingZeroes, DL, MVT::i64));
8321 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
8322 SelectionDAG &DAG) {
8323 // Take advantage of vector comparisons producing 0 or -1 in each lane to
8324 // optimize away operation when it's from a constant.
8326 // The general transformation is:
8327 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
8328 // AND(VECTOR_CMP(x,y), constant2)
8329 // constant2 = UNARYOP(constant)
8331 // Early exit if this isn't a vector operation, the operand of the
8332 // unary operation isn't a bitwise AND, or if the sizes of the operations
8334 EVT VT = N->getValueType(0);
8335 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
8336 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
8337 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
8340 // Now check that the other operand of the AND is a constant. We could
8341 // make the transformation for non-constant splats as well, but it's unclear
8342 // that would be a benefit as it would not eliminate any operations, just
8343 // perform one more step in scalar code before moving to the vector unit.
8344 if (BuildVectorSDNode *BV =
8345 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
8346 // Bail out if the vector isn't a constant.
8347 if (!BV->isConstant())
8350 // Everything checks out. Build up the new and improved node.
8352 EVT IntVT = BV->getValueType(0);
8353 // Create a new constant of the appropriate type for the transformed
8355 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
8356 // The AND node needs bitcasts to/from an integer vector type around it.
8357 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
8358 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
8359 N->getOperand(0)->getOperand(0), MaskConst);
8360 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
8367 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
8368 const AArch64Subtarget *Subtarget) {
8369 // First try to optimize away the conversion when it's conditionally from
8370 // a constant. Vectors only.
8371 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
8374 EVT VT = N->getValueType(0);
8375 if (VT != MVT::f32 && VT != MVT::f64)
8378 // Only optimize when the source and destination types have the same width.
8379 if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits())
8382 // If the result of an integer load is only used by an integer-to-float
8383 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
8384 // This eliminates an "integer-to-vector-move" UOP and improves throughput.
8385 SDValue N0 = N->getOperand(0);
8386 if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8387 // Do not change the width of a volatile load.
8388 !cast<LoadSDNode>(N0)->isVolatile()) {
8389 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8390 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
8391 LN0->getPointerInfo(), LN0->getAlignment(),
8392 LN0->getMemOperand()->getFlags());
8394 // Make sure successors of the original load stay after it by updating them
8395 // to use the new Chain.
8396 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
8399 (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
8400 return DAG.getNode(Opcode, SDLoc(N), VT, Load);
8406 /// Fold a floating-point multiply by power of two into floating-point to
8407 /// fixed-point conversion.
8408 static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
8409 TargetLowering::DAGCombinerInfo &DCI,
8410 const AArch64Subtarget *Subtarget) {
8411 if (!Subtarget->hasNEON())
8414 SDValue Op = N->getOperand(0);
8415 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
8416 Op.getOpcode() != ISD::FMUL)
8419 SDValue ConstVec = Op->getOperand(1);
8420 if (!isa<BuildVectorSDNode>(ConstVec))
8423 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
8424 uint32_t FloatBits = FloatTy.getSizeInBits();
8425 if (FloatBits != 32 && FloatBits != 64)
8428 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
8429 uint32_t IntBits = IntTy.getSizeInBits();
8430 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
8433 // Avoid conversions where iN is larger than the float (e.g., float -> i64).
8434 if (IntBits > FloatBits)
8437 BitVector UndefElements;
8438 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
8439 int32_t Bits = IntBits == 64 ? 64 : 32;
8440 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
8441 if (C == -1 || C == 0 || C > Bits)
8445 unsigned NumLanes = Op.getValueType().getVectorNumElements();
8450 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
8453 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
8457 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
8460 assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) &&
8461 "Illegal vector type after legalization");
8464 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
8465 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
8466 : Intrinsic::aarch64_neon_vcvtfp2fxu;
8468 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
8469 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
8470 Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
8471 // We can handle smaller integers by generating an extra trunc.
8472 if (IntBits < FloatBits)
8473 FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
8478 /// Fold a floating-point divide by power of two into fixed-point to
8479 /// floating-point conversion.
8480 static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
8481 TargetLowering::DAGCombinerInfo &DCI,
8482 const AArch64Subtarget *Subtarget) {
8483 if (!Subtarget->hasNEON())
8486 SDValue Op = N->getOperand(0);
8487 unsigned Opc = Op->getOpcode();
8488 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
8489 !Op.getOperand(0).getValueType().isSimple() ||
8490 (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
8493 SDValue ConstVec = N->getOperand(1);
8494 if (!isa<BuildVectorSDNode>(ConstVec))
8497 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
8498 int32_t IntBits = IntTy.getSizeInBits();
8499 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
8502 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
8503 int32_t FloatBits = FloatTy.getSizeInBits();
8504 if (FloatBits != 32 && FloatBits != 64)
8507 // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
8508 if (IntBits > FloatBits)
8511 BitVector UndefElements;
8512 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
8513 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
8514 if (C == -1 || C == 0 || C > FloatBits)
8518 unsigned NumLanes = Op.getValueType().getVectorNumElements();
8523 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
8526 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
8530 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
8534 SDValue ConvInput = Op.getOperand(0);
8535 bool IsSigned = Opc == ISD::SINT_TO_FP;
8536 if (IntBits < FloatBits)
8537 ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
8540 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
8541 : Intrinsic::aarch64_neon_vcvtfxu2fp;
8542 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
8543 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
8544 DAG.getConstant(C, DL, MVT::i32));
8547 /// An EXTR instruction is made up of two shifts, ORed together. This helper
8548 /// searches for and classifies those shifts.
8549 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
8551 if (N.getOpcode() == ISD::SHL)
8553 else if (N.getOpcode() == ISD::SRL)
8558 if (!isa<ConstantSDNode>(N.getOperand(1)))
8561 ShiftAmount = N->getConstantOperandVal(1);
8562 Src = N->getOperand(0);
8566 /// EXTR instruction extracts a contiguous chunk of bits from two existing
8567 /// registers viewed as a high/low pair. This function looks for the pattern:
8568 /// <tt>(or (shl VAL1, \#N), (srl VAL2, \#RegWidth-N))</tt> and replaces it
8569 /// with an EXTR. Can't quite be done in TableGen because the two immediates
8570 /// aren't independent.
8571 static SDValue tryCombineToEXTR(SDNode *N,
8572 TargetLowering::DAGCombinerInfo &DCI) {
8573 SelectionDAG &DAG = DCI.DAG;
8575 EVT VT = N->getValueType(0);
8577 assert(N->getOpcode() == ISD::OR && "Unexpected root");
8579 if (VT != MVT::i32 && VT != MVT::i64)
8583 uint32_t ShiftLHS = 0;
8584 bool LHSFromHi = false;
8585 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
8589 uint32_t ShiftRHS = 0;
8590 bool RHSFromHi = false;
8591 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
8594 // If they're both trying to come from the high part of the register, they're
8595 // not really an EXTR.
8596 if (LHSFromHi == RHSFromHi)
8599 if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
8603 std::swap(LHS, RHS);
8604 std::swap(ShiftLHS, ShiftRHS);
8607 return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
8608 DAG.getConstant(ShiftRHS, DL, MVT::i64));
8611 static SDValue tryCombineToBSL(SDNode *N,
8612 TargetLowering::DAGCombinerInfo &DCI) {
8613 EVT VT = N->getValueType(0);
8614 SelectionDAG &DAG = DCI.DAG;
8620 SDValue N0 = N->getOperand(0);
8621 if (N0.getOpcode() != ISD::AND)
8624 SDValue N1 = N->getOperand(1);
8625 if (N1.getOpcode() != ISD::AND)
8628 // We only have to look for constant vectors here since the general, variable
8629 // case can be handled in TableGen.
8630 unsigned Bits = VT.getScalarSizeInBits();
8631 uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
8632 for (int i = 1; i >= 0; --i)
8633 for (int j = 1; j >= 0; --j) {
8634 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
8635 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
8639 bool FoundMatch = true;
8640 for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
8641 ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
8642 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
8644 CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
8651 return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
8652 N0->getOperand(1 - i), N1->getOperand(1 - j));
8658 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
8659 const AArch64Subtarget *Subtarget) {
8660 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
8661 SelectionDAG &DAG = DCI.DAG;
8662 EVT VT = N->getValueType(0);
8664 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8667 if (SDValue Res = tryCombineToEXTR(N, DCI))
8670 if (SDValue Res = tryCombineToBSL(N, DCI))
8676 static SDValue performSRLCombine(SDNode *N,
8677 TargetLowering::DAGCombinerInfo &DCI) {
8678 SelectionDAG &DAG = DCI.DAG;
8679 EVT VT = N->getValueType(0);
8680 if (VT != MVT::i32 && VT != MVT::i64)
8683 // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the
8684 // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32)
8685 // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero.
8686 SDValue N0 = N->getOperand(0);
8687 if (N0.getOpcode() == ISD::BSWAP) {
8689 SDValue N1 = N->getOperand(1);
8690 SDValue N00 = N0.getOperand(0);
8691 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
8692 uint64_t ShiftAmt = C->getZExtValue();
8693 if (VT == MVT::i32 && ShiftAmt == 16 &&
8694 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16)))
8695 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
8696 if (VT == MVT::i64 && ShiftAmt == 32 &&
8697 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32)))
8698 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
8704 static SDValue performBitcastCombine(SDNode *N,
8705 TargetLowering::DAGCombinerInfo &DCI,
8706 SelectionDAG &DAG) {
8707 // Wait 'til after everything is legalized to try this. That way we have
8708 // legal vector types and such.
8709 if (DCI.isBeforeLegalizeOps())
8712 // Remove extraneous bitcasts around an extract_subvector.
8714 // (v4i16 (bitconvert
8715 // (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
8717 // (extract_subvector ((v8i16 ...), (i64 4)))
8719 // Only interested in 64-bit vectors as the ultimate result.
8720 EVT VT = N->getValueType(0);
8723 if (VT.getSimpleVT().getSizeInBits() != 64)
8725 // Is the operand an extract_subvector starting at the beginning or halfway
8726 // point of the vector? A low half may also come through as an
8727 // EXTRACT_SUBREG, so look for that, too.
8728 SDValue Op0 = N->getOperand(0);
8729 if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
8730 !(Op0->isMachineOpcode() &&
8731 Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
8733 uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
8734 if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
8735 if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
8737 } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
8738 if (idx != AArch64::dsub)
8740 // The dsub reference is equivalent to a lane zero subvector reference.
8743 // Look through the bitcast of the input to the extract.
8744 if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
8746 SDValue Source = Op0->getOperand(0)->getOperand(0);
8747 // If the source type has twice the number of elements as our destination
8748 // type, we know this is an extract of the high or low half of the vector.
8749 EVT SVT = Source->getValueType(0);
8750 if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
8753 DEBUG(dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
8755 // Create the simplified form to just extract the low or high half of the
8756 // vector directly rather than bothering with the bitcasts.
8758 unsigned NumElements = VT.getVectorNumElements();
8760 SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
8761 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
8763 SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
8764 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
8770 static SDValue performConcatVectorsCombine(SDNode *N,
8771 TargetLowering::DAGCombinerInfo &DCI,
8772 SelectionDAG &DAG) {
8774 EVT VT = N->getValueType(0);
8775 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
8777 // Optimize concat_vectors of truncated vectors, where the intermediate
8778 // type is illegal, to avoid said illegality, e.g.,
8779 // (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
8780 // (v2i16 (truncate (v2i64)))))
8782 // (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
8783 // (v4i32 (bitcast (v2i64))),
8785 // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
8786 // on both input and result type, so we might generate worse code.
8787 // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
8788 if (N->getNumOperands() == 2 &&
8789 N0->getOpcode() == ISD::TRUNCATE &&
8790 N1->getOpcode() == ISD::TRUNCATE) {
8791 SDValue N00 = N0->getOperand(0);
8792 SDValue N10 = N1->getOperand(0);
8793 EVT N00VT = N00.getValueType();
8795 if (N00VT == N10.getValueType() &&
8796 (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
8797 N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
8798 MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
8799 SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
8800 for (size_t i = 0; i < Mask.size(); ++i)
8802 return DAG.getNode(ISD::TRUNCATE, dl, VT,
8803 DAG.getVectorShuffle(
8805 DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
8806 DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
8810 // Wait 'til after everything is legalized to try this. That way we have
8811 // legal vector types and such.
8812 if (DCI.isBeforeLegalizeOps())
8815 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
8816 // splat. The indexed instructions are going to be expecting a DUPLANE64, so
8817 // canonicalise to that.
8818 if (N0 == N1 && VT.getVectorNumElements() == 2) {
8819 assert(VT.getScalarSizeInBits() == 64);
8820 return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
8821 DAG.getConstant(0, dl, MVT::i64));
8824 // Canonicalise concat_vectors so that the right-hand vector has as few
8825 // bit-casts as possible before its real operation. The primary matching
8826 // destination for these operations will be the narrowing "2" instructions,
8827 // which depend on the operation being performed on this right-hand vector.
8829 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS))))
8831 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
8833 if (N1->getOpcode() != ISD::BITCAST)
8835 SDValue RHS = N1->getOperand(0);
8836 MVT RHSTy = RHS.getValueType().getSimpleVT();
8837 // If the RHS is not a vector, this is not the pattern we're looking for.
8838 if (!RHSTy.isVector())
8841 DEBUG(dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
8843 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
8844 RHSTy.getVectorNumElements() * 2);
8845 return DAG.getNode(ISD::BITCAST, dl, VT,
8846 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
8847 DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
8851 static SDValue tryCombineFixedPointConvert(SDNode *N,
8852 TargetLowering::DAGCombinerInfo &DCI,
8853 SelectionDAG &DAG) {
8854 // Wait 'til after everything is legalized to try this. That way we have
8855 // legal vector types and such.
8856 if (DCI.isBeforeLegalizeOps())
8858 // Transform a scalar conversion of a value from a lane extract into a
8859 // lane extract of a vector conversion. E.g., from foo1 to foo2:
8860 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
8861 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
8863 // The second form interacts better with instruction selection and the
8864 // register allocator to avoid cross-class register copies that aren't
8865 // coalescable due to a lane reference.
8867 // Check the operand and see if it originates from a lane extract.
8868 SDValue Op1 = N->getOperand(1);
8869 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8870 // Yep, no additional predication needed. Perform the transform.
8871 SDValue IID = N->getOperand(0);
8872 SDValue Shift = N->getOperand(2);
8873 SDValue Vec = Op1.getOperand(0);
8874 SDValue Lane = Op1.getOperand(1);
8875 EVT ResTy = N->getValueType(0);
8879 // The vector width should be 128 bits by the time we get here, even
8880 // if it started as 64 bits (the extract_vector handling will have
8882 assert(Vec.getValueSizeInBits() == 128 &&
8883 "unexpected vector size on extract_vector_elt!");
8884 if (Vec.getValueType() == MVT::v4i32)
8885 VecResTy = MVT::v4f32;
8886 else if (Vec.getValueType() == MVT::v2i64)
8887 VecResTy = MVT::v2f64;
8889 llvm_unreachable("unexpected vector type!");
8892 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
8893 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
8898 // AArch64 high-vector "long" operations are formed by performing the non-high
8899 // version on an extract_subvector of each operand which gets the high half:
8901 // (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
8903 // However, there are cases which don't have an extract_high explicitly, but
8904 // have another operation that can be made compatible with one for free. For
8907 // (dupv64 scalar) --> (extract_high (dup128 scalar))
8909 // This routine does the actual conversion of such DUPs, once outer routines
8910 // have determined that everything else is in order.
8911 // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
8913 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
8914 switch (N.getOpcode()) {
8915 case AArch64ISD::DUP:
8916 case AArch64ISD::DUPLANE8:
8917 case AArch64ISD::DUPLANE16:
8918 case AArch64ISD::DUPLANE32:
8919 case AArch64ISD::DUPLANE64:
8920 case AArch64ISD::MOVI:
8921 case AArch64ISD::MOVIshift:
8922 case AArch64ISD::MOVIedit:
8923 case AArch64ISD::MOVImsl:
8924 case AArch64ISD::MVNIshift:
8925 case AArch64ISD::MVNImsl:
8928 // FMOV could be supported, but isn't very useful, as it would only occur
8929 // if you passed a bitcast' floating point immediate to an eligible long
8930 // integer op (addl, smull, ...).
8934 MVT NarrowTy = N.getSimpleValueType();
8935 if (!NarrowTy.is64BitVector())
8938 MVT ElementTy = NarrowTy.getVectorElementType();
8939 unsigned NumElems = NarrowTy.getVectorNumElements();
8940 MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
8943 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
8944 DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
8945 DAG.getConstant(NumElems, dl, MVT::i64));
8948 static bool isEssentiallyExtractSubvector(SDValue N) {
8949 if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
8952 return N.getOpcode() == ISD::BITCAST &&
8953 N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
8956 /// \brief Helper structure to keep track of ISD::SET_CC operands.
8957 struct GenericSetCCInfo {
8958 const SDValue *Opnd0;
8959 const SDValue *Opnd1;
8963 /// \brief Helper structure to keep track of a SET_CC lowered into AArch64 code.
8964 struct AArch64SetCCInfo {
8966 AArch64CC::CondCode CC;
8969 /// \brief Helper structure to keep track of SetCC information.
8971 GenericSetCCInfo Generic;
8972 AArch64SetCCInfo AArch64;
8975 /// \brief Helper structure to be able to read SetCC information. If set to
8976 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
8977 /// GenericSetCCInfo.
8978 struct SetCCInfoAndKind {
8983 /// \brief Check whether or not \p Op is a SET_CC operation, either a generic or
8985 /// AArch64 lowered one.
8986 /// \p SetCCInfo is filled accordingly.
8987 /// \post SetCCInfo is meanginfull only when this function returns true.
8988 /// \return True when Op is a kind of SET_CC operation.
8989 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
8990 // If this is a setcc, this is straight forward.
8991 if (Op.getOpcode() == ISD::SETCC) {
8992 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
8993 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
8994 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8995 SetCCInfo.IsAArch64 = false;
8998 // Otherwise, check if this is a matching csel instruction.
9002 if (Op.getOpcode() != AArch64ISD::CSEL)
9004 // Set the information about the operands.
9005 // TODO: we want the operands of the Cmp not the csel
9006 SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
9007 SetCCInfo.IsAArch64 = true;
9008 SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
9009 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
9011 // Check that the operands matches the constraints:
9012 // (1) Both operands must be constants.
9013 // (2) One must be 1 and the other must be 0.
9014 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
9015 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9018 if (!TValue || !FValue)
9022 if (!TValue->isOne()) {
9023 // Update the comparison when we are interested in !cc.
9024 std::swap(TValue, FValue);
9025 SetCCInfo.Info.AArch64.CC =
9026 AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
9028 return TValue->isOne() && FValue->isNullValue();
9031 // Returns true if Op is setcc or zext of setcc.
9032 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
9033 if (isSetCC(Op, Info))
9035 return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
9036 isSetCC(Op->getOperand(0), Info));
9039 // The folding we want to perform is:
9040 // (add x, [zext] (setcc cc ...) )
9042 // (csel x, (add x, 1), !cc ...)
9044 // The latter will get matched to a CSINC instruction.
9045 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
9046 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
9047 SDValue LHS = Op->getOperand(0);
9048 SDValue RHS = Op->getOperand(1);
9049 SetCCInfoAndKind InfoAndKind;
9051 // If neither operand is a SET_CC, give up.
9052 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
9053 std::swap(LHS, RHS);
9054 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
9058 // FIXME: This could be generatized to work for FP comparisons.
9059 EVT CmpVT = InfoAndKind.IsAArch64
9060 ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
9061 : InfoAndKind.Info.Generic.Opnd0->getValueType();
9062 if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
9068 if (InfoAndKind.IsAArch64) {
9069 CCVal = DAG.getConstant(
9070 AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
9072 Cmp = *InfoAndKind.Info.AArch64.Cmp;
9074 Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
9075 *InfoAndKind.Info.Generic.Opnd1,
9076 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
9079 EVT VT = Op->getValueType(0);
9080 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
9081 return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
9084 // The basic add/sub long vector instructions have variants with "2" on the end
9085 // which act on the high-half of their inputs. They are normally matched by
9088 // (add (zeroext (extract_high LHS)),
9089 // (zeroext (extract_high RHS)))
9090 // -> uaddl2 vD, vN, vM
9092 // However, if one of the extracts is something like a duplicate, this
9093 // instruction can still be used profitably. This function puts the DAG into a
9094 // more appropriate form for those patterns to trigger.
9095 static SDValue performAddSubLongCombine(SDNode *N,
9096 TargetLowering::DAGCombinerInfo &DCI,
9097 SelectionDAG &DAG) {
9098 if (DCI.isBeforeLegalizeOps())
9101 MVT VT = N->getSimpleValueType(0);
9102 if (!VT.is128BitVector()) {
9103 if (N->getOpcode() == ISD::ADD)
9104 return performSetccAddFolding(N, DAG);
9108 // Make sure both branches are extended in the same way.
9109 SDValue LHS = N->getOperand(0);
9110 SDValue RHS = N->getOperand(1);
9111 if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
9112 LHS.getOpcode() != ISD::SIGN_EXTEND) ||
9113 LHS.getOpcode() != RHS.getOpcode())
9116 unsigned ExtType = LHS.getOpcode();
9118 // It's not worth doing if at least one of the inputs isn't already an
9119 // extract, but we don't know which it'll be so we have to try both.
9120 if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
9121 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
9125 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
9126 } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
9127 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
9131 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
9134 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
9137 // Massage DAGs which we can use the high-half "long" operations on into
9138 // something isel will recognize better. E.g.
9140 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
9141 // (aarch64_neon_umull (extract_high (v2i64 vec)))
9142 // (extract_high (v2i64 (dup128 scalar)))))
9144 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
9145 TargetLowering::DAGCombinerInfo &DCI,
9146 SelectionDAG &DAG) {
9147 if (DCI.isBeforeLegalizeOps())
9150 SDValue LHS = N->getOperand(1);
9151 SDValue RHS = N->getOperand(2);
9152 assert(LHS.getValueType().is64BitVector() &&
9153 RHS.getValueType().is64BitVector() &&
9154 "unexpected shape for long operation");
9156 // Either node could be a DUP, but it's not worth doing both of them (you'd
9157 // just as well use the non-high version) so look for a corresponding extract
9158 // operation on the other "wing".
9159 if (isEssentiallyExtractSubvector(LHS)) {
9160 RHS = tryExtendDUPToExtractHigh(RHS, DAG);
9163 } else if (isEssentiallyExtractSubvector(RHS)) {
9164 LHS = tryExtendDUPToExtractHigh(LHS, DAG);
9169 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
9170 N->getOperand(0), LHS, RHS);
9173 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
9174 MVT ElemTy = N->getSimpleValueType(0).getScalarType();
9175 unsigned ElemBits = ElemTy.getSizeInBits();
9177 int64_t ShiftAmount;
9178 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
9179 APInt SplatValue, SplatUndef;
9180 unsigned SplatBitSize;
9182 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
9183 HasAnyUndefs, ElemBits) ||
9184 SplatBitSize != ElemBits)
9187 ShiftAmount = SplatValue.getSExtValue();
9188 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
9189 ShiftAmount = CVN->getSExtValue();
9197 llvm_unreachable("Unknown shift intrinsic");
9198 case Intrinsic::aarch64_neon_sqshl:
9199 Opcode = AArch64ISD::SQSHL_I;
9200 IsRightShift = false;
9202 case Intrinsic::aarch64_neon_uqshl:
9203 Opcode = AArch64ISD::UQSHL_I;
9204 IsRightShift = false;
9206 case Intrinsic::aarch64_neon_srshl:
9207 Opcode = AArch64ISD::SRSHR_I;
9208 IsRightShift = true;
9210 case Intrinsic::aarch64_neon_urshl:
9211 Opcode = AArch64ISD::URSHR_I;
9212 IsRightShift = true;
9214 case Intrinsic::aarch64_neon_sqshlu:
9215 Opcode = AArch64ISD::SQSHLU_I;
9216 IsRightShift = false;
9220 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
9222 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
9223 DAG.getConstant(-ShiftAmount, dl, MVT::i32));
9224 } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
9226 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
9227 DAG.getConstant(ShiftAmount, dl, MVT::i32));
9233 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
9234 // the intrinsics must be legal and take an i32, this means there's almost
9235 // certainly going to be a zext in the DAG which we can eliminate.
9236 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
9237 SDValue AndN = N->getOperand(2);
9238 if (AndN.getOpcode() != ISD::AND)
9241 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
9242 if (!CMask || CMask->getZExtValue() != Mask)
9245 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
9246 N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
9249 static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
9250 SelectionDAG &DAG) {
9252 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
9253 DAG.getNode(Opc, dl,
9254 N->getOperand(1).getSimpleValueType(),
9256 DAG.getConstant(0, dl, MVT::i64));
9259 static SDValue performIntrinsicCombine(SDNode *N,
9260 TargetLowering::DAGCombinerInfo &DCI,
9261 const AArch64Subtarget *Subtarget) {
9262 SelectionDAG &DAG = DCI.DAG;
9263 unsigned IID = getIntrinsicID(N);
9267 case Intrinsic::aarch64_neon_vcvtfxs2fp:
9268 case Intrinsic::aarch64_neon_vcvtfxu2fp:
9269 return tryCombineFixedPointConvert(N, DCI, DAG);
9270 case Intrinsic::aarch64_neon_saddv:
9271 return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
9272 case Intrinsic::aarch64_neon_uaddv:
9273 return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
9274 case Intrinsic::aarch64_neon_sminv:
9275 return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
9276 case Intrinsic::aarch64_neon_uminv:
9277 return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
9278 case Intrinsic::aarch64_neon_smaxv:
9279 return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
9280 case Intrinsic::aarch64_neon_umaxv:
9281 return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
9282 case Intrinsic::aarch64_neon_fmax:
9283 return DAG.getNode(ISD::FMAXNAN, SDLoc(N), N->getValueType(0),
9284 N->getOperand(1), N->getOperand(2));
9285 case Intrinsic::aarch64_neon_fmin:
9286 return DAG.getNode(ISD::FMINNAN, SDLoc(N), N->getValueType(0),
9287 N->getOperand(1), N->getOperand(2));
9288 case Intrinsic::aarch64_neon_fmaxnm:
9289 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
9290 N->getOperand(1), N->getOperand(2));
9291 case Intrinsic::aarch64_neon_fminnm:
9292 return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
9293 N->getOperand(1), N->getOperand(2));
9294 case Intrinsic::aarch64_neon_smull:
9295 case Intrinsic::aarch64_neon_umull:
9296 case Intrinsic::aarch64_neon_pmull:
9297 case Intrinsic::aarch64_neon_sqdmull:
9298 return tryCombineLongOpWithDup(IID, N, DCI, DAG);
9299 case Intrinsic::aarch64_neon_sqshl:
9300 case Intrinsic::aarch64_neon_uqshl:
9301 case Intrinsic::aarch64_neon_sqshlu:
9302 case Intrinsic::aarch64_neon_srshl:
9303 case Intrinsic::aarch64_neon_urshl:
9304 return tryCombineShiftImm(IID, N, DAG);
9305 case Intrinsic::aarch64_crc32b:
9306 case Intrinsic::aarch64_crc32cb:
9307 return tryCombineCRC32(0xff, N, DAG);
9308 case Intrinsic::aarch64_crc32h:
9309 case Intrinsic::aarch64_crc32ch:
9310 return tryCombineCRC32(0xffff, N, DAG);
9315 static SDValue performExtendCombine(SDNode *N,
9316 TargetLowering::DAGCombinerInfo &DCI,
9317 SelectionDAG &DAG) {
9318 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
9319 // we can convert that DUP into another extract_high (of a bigger DUP), which
9320 // helps the backend to decide that an sabdl2 would be useful, saving a real
9321 // extract_high operation.
9322 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
9323 N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
9324 SDNode *ABDNode = N->getOperand(0).getNode();
9325 unsigned IID = getIntrinsicID(ABDNode);
9326 if (IID == Intrinsic::aarch64_neon_sabd ||
9327 IID == Intrinsic::aarch64_neon_uabd) {
9328 SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
9329 if (!NewABD.getNode())
9332 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
9337 // This is effectively a custom type legalization for AArch64.
9339 // Type legalization will split an extend of a small, legal, type to a larger
9340 // illegal type by first splitting the destination type, often creating
9341 // illegal source types, which then get legalized in isel-confusing ways,
9342 // leading to really terrible codegen. E.g.,
9343 // %result = v8i32 sext v8i8 %value
9345 // %losrc = extract_subreg %value, ...
9346 // %hisrc = extract_subreg %value, ...
9347 // %lo = v4i32 sext v4i8 %losrc
9348 // %hi = v4i32 sext v4i8 %hisrc
9349 // Things go rapidly downhill from there.
9351 // For AArch64, the [sz]ext vector instructions can only go up one element
9352 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
9353 // take two instructions.
9355 // This implies that the most efficient way to do the extend from v8i8
9356 // to two v4i32 values is to first extend the v8i8 to v8i16, then do
9357 // the normal splitting to happen for the v8i16->v8i32.
9359 // This is pre-legalization to catch some cases where the default
9360 // type legalization will create ill-tempered code.
9361 if (!DCI.isBeforeLegalizeOps())
9364 // We're only interested in cleaning things up for non-legal vector types
9365 // here. If both the source and destination are legal, things will just
9366 // work naturally without any fiddling.
9367 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9368 EVT ResVT = N->getValueType(0);
9369 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
9371 // If the vector type isn't a simple VT, it's beyond the scope of what
9372 // we're worried about here. Let legalization do its thing and hope for
9374 SDValue Src = N->getOperand(0);
9375 EVT SrcVT = Src->getValueType(0);
9376 if (!ResVT.isSimple() || !SrcVT.isSimple())
9379 // If the source VT is a 64-bit vector, we can play games and get the
9380 // better results we want.
9381 if (SrcVT.getSizeInBits() != 64)
9384 unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
9385 unsigned ElementCount = SrcVT.getVectorNumElements();
9386 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
9388 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
9390 // Now split the rest of the operation into two halves, each with a 64
9394 unsigned NumElements = ResVT.getVectorNumElements();
9395 assert(!(NumElements & 1) && "Splitting vector, but not in half!");
9396 LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
9397 ResVT.getVectorElementType(), NumElements / 2);
9399 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
9400 LoVT.getVectorNumElements());
9401 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
9402 DAG.getConstant(0, DL, MVT::i64));
9403 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
9404 DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
9405 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
9406 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
9408 // Now combine the parts back together so we still have a single result
9409 // like the combiner expects.
9410 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
9413 static SDValue splitStoreSplat(SelectionDAG &DAG, StoreSDNode &St,
9414 SDValue SplatVal, unsigned NumVecElts) {
9415 unsigned OrigAlignment = St.getAlignment();
9416 unsigned EltOffset = SplatVal.getValueType().getSizeInBits() / 8;
9418 // Create scalar stores. This is at least as good as the code sequence for a
9419 // split unaligned store which is a dup.s, ext.b, and two stores.
9420 // Most of the time the three stores should be replaced by store pair
9421 // instructions (stp).
9423 SDValue BasePtr = St.getBasePtr();
9424 uint64_t BaseOffset = 0;
9426 const MachinePointerInfo &PtrInfo = St.getPointerInfo();
9428 DAG.getStore(St.getChain(), DL, SplatVal, BasePtr, PtrInfo,
9429 OrigAlignment, St.getMemOperand()->getFlags());
9431 // As this in ISel, we will not merge this add which may degrade results.
9432 if (BasePtr->getOpcode() == ISD::ADD &&
9433 isa<ConstantSDNode>(BasePtr->getOperand(1))) {
9434 BaseOffset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue();
9435 BasePtr = BasePtr->getOperand(0);
9438 unsigned Offset = EltOffset;
9439 while (--NumVecElts) {
9440 unsigned Alignment = MinAlign(OrigAlignment, Offset);
9442 DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
9443 DAG.getConstant(BaseOffset + Offset, DL, MVT::i64));
9444 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
9445 PtrInfo.getWithOffset(Offset), Alignment,
9446 St.getMemOperand()->getFlags());
9447 Offset += EltOffset;
9452 /// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR. The
9453 /// load store optimizer pass will merge them to store pair stores. This should
9454 /// be better than a movi to create the vector zero followed by a vector store
9455 /// if the zero constant is not re-used, since one instructions and one register
9456 /// live range will be removed.
9458 /// For example, the final generated code should be:
9460 /// stp xzr, xzr, [x0]
9467 static SDValue replaceZeroVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
9468 SDValue StVal = St.getValue();
9469 EVT VT = StVal.getValueType();
9471 // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or
9472 // 2, 3 or 4 i32 elements.
9473 int NumVecElts = VT.getVectorNumElements();
9474 if (!(((NumVecElts == 2 || NumVecElts == 3) &&
9475 VT.getVectorElementType().getSizeInBits() == 64) ||
9476 ((NumVecElts == 2 || NumVecElts == 3 || NumVecElts == 4) &&
9477 VT.getVectorElementType().getSizeInBits() == 32)))
9480 if (StVal.getOpcode() != ISD::BUILD_VECTOR)
9483 // If the zero constant has more than one use then the vector store could be
9484 // better since the constant mov will be amortized and stp q instructions
9485 // should be able to be formed.
9486 if (!StVal.hasOneUse())
9489 // If the immediate offset of the address operand is too large for the stp
9490 // instruction, then bail out.
9491 if (DAG.isBaseWithConstantOffset(St.getBasePtr())) {
9492 int64_t Offset = St.getBasePtr()->getConstantOperandVal(1);
9493 if (Offset < -512 || Offset > 504)
9497 for (int I = 0; I < NumVecElts; ++I) {
9498 SDValue EltVal = StVal.getOperand(I);
9499 if (!isNullConstant(EltVal) && !isNullFPConstant(EltVal))
9503 // Use a CopyFromReg WZR/XZR here to prevent
9504 // DAGCombiner::MergeConsecutiveStores from undoing this transformation.
9508 if (VT.getVectorElementType().getSizeInBits() == 32) {
9509 ZeroReg = AArch64::WZR;
9512 ZeroReg = AArch64::XZR;
9516 DAG.getCopyFromReg(DAG.getEntryNode(), DL, ZeroReg, ZeroVT);
9517 return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
9520 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
9521 /// value. The load store optimizer pass will merge them to store pair stores.
9522 /// This has better performance than a splat of the scalar followed by a split
9523 /// vector store. Even if the stores are not merged it is four stores vs a dup,
9524 /// followed by an ext.b and two stores.
9525 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
9526 SDValue StVal = St.getValue();
9527 EVT VT = StVal.getValueType();
9529 // Don't replace floating point stores, they possibly won't be transformed to
9530 // stp because of the store pair suppress pass.
9531 if (VT.isFloatingPoint())
9534 // We can express a splat as store pair(s) for 2 or 4 elements.
9535 unsigned NumVecElts = VT.getVectorNumElements();
9536 if (NumVecElts != 4 && NumVecElts != 2)
9539 // Check that this is a splat.
9540 // Make sure that each of the relevant vector element locations are inserted
9541 // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32.
9542 std::bitset<4> IndexNotInserted((1 << NumVecElts) - 1);
9544 for (unsigned I = 0; I < NumVecElts; ++I) {
9545 // Check for insert vector elements.
9546 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
9549 // Check that same value is inserted at each vector element.
9551 SplatVal = StVal.getOperand(1);
9552 else if (StVal.getOperand(1) != SplatVal)
9555 // Check insert element index.
9556 ConstantSDNode *CIndex = dyn_cast<ConstantSDNode>(StVal.getOperand(2));
9559 uint64_t IndexVal = CIndex->getZExtValue();
9560 if (IndexVal >= NumVecElts)
9562 IndexNotInserted.reset(IndexVal);
9564 StVal = StVal.getOperand(0);
9566 // Check that all vector element locations were inserted to.
9567 if (IndexNotInserted.any())
9570 return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
9573 static SDValue splitStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
9575 const AArch64Subtarget *Subtarget) {
9577 StoreSDNode *S = cast<StoreSDNode>(N);
9578 if (S->isVolatile() || S->isIndexed())
9581 SDValue StVal = S->getValue();
9582 EVT VT = StVal.getValueType();
9586 // If we get a splat of zeros, convert this vector store to a store of
9587 // scalars. They will be merged into store pairs of xzr thereby removing one
9588 // instruction and one register.
9589 if (SDValue ReplacedZeroSplat = replaceZeroVectorStore(DAG, *S))
9590 return ReplacedZeroSplat;
9592 // FIXME: The logic for deciding if an unaligned store should be split should
9593 // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
9594 // a call to that function here.
9596 if (!Subtarget->isMisaligned128StoreSlow())
9599 // Don't split at -Oz.
9600 if (DAG.getMachineFunction().getFunction().optForMinSize())
9603 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
9604 // those up regresses performance on micro-benchmarks and olden/bh.
9605 if (VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
9608 // Split unaligned 16B stores. They are terrible for performance.
9609 // Don't split stores with alignment of 1 or 2. Code that uses clang vector
9610 // extensions can use this to mark that it does not want splitting to happen
9611 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
9612 // eliminating alignment hazards is only 1 in 8 for alignment of 2.
9613 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
9614 S->getAlignment() <= 2)
9617 // If we get a splat of a scalar convert this vector store to a store of
9618 // scalars. They will be merged into store pairs thereby removing two
9620 if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, *S))
9621 return ReplacedSplat;
9624 unsigned NumElts = VT.getVectorNumElements() / 2;
9625 // Split VT into two.
9627 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
9628 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
9629 DAG.getConstant(0, DL, MVT::i64));
9630 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
9631 DAG.getConstant(NumElts, DL, MVT::i64));
9632 SDValue BasePtr = S->getBasePtr();
9634 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
9635 S->getAlignment(), S->getMemOperand()->getFlags());
9636 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
9637 DAG.getConstant(8, DL, MVT::i64));
9638 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
9639 S->getPointerInfo(), S->getAlignment(),
9640 S->getMemOperand()->getFlags());
9643 /// Target-specific DAG combine function for post-increment LD1 (lane) and
9644 /// post-increment LD1R.
9645 static SDValue performPostLD1Combine(SDNode *N,
9646 TargetLowering::DAGCombinerInfo &DCI,
9648 if (DCI.isBeforeLegalizeOps())
9651 SelectionDAG &DAG = DCI.DAG;
9652 EVT VT = N->getValueType(0);
9654 unsigned LoadIdx = IsLaneOp ? 1 : 0;
9655 SDNode *LD = N->getOperand(LoadIdx).getNode();
9656 // If it is not LOAD, can not do such combine.
9657 if (LD->getOpcode() != ISD::LOAD)
9660 // The vector lane must be a constant in the LD1LANE opcode.
9663 Lane = N->getOperand(2);
9664 auto *LaneC = dyn_cast<ConstantSDNode>(Lane);
9665 if (!LaneC || LaneC->getZExtValue() >= VT.getVectorNumElements())
9669 LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
9670 EVT MemVT = LoadSDN->getMemoryVT();
9671 // Check if memory operand is the same type as the vector element.
9672 if (MemVT != VT.getVectorElementType())
9675 // Check if there are other uses. If so, do not combine as it will introduce
9677 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
9679 if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
9685 SDValue Addr = LD->getOperand(1);
9686 SDValue Vector = N->getOperand(0);
9687 // Search for a use of the address operand that is an increment.
9688 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
9689 Addr.getNode()->use_end(); UI != UE; ++UI) {
9691 if (User->getOpcode() != ISD::ADD
9692 || UI.getUse().getResNo() != Addr.getResNo())
9695 // Check that the add is independent of the load. Otherwise, folding it
9696 // would create a cycle.
9697 if (User->isPredecessorOf(LD) || LD->isPredecessorOf(User))
9699 // Also check that add is not used in the vector operand. This would also
9701 if (User->isPredecessorOf(Vector.getNode()))
9704 // If the increment is a constant, it must match the memory ref size.
9705 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9706 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9707 uint32_t IncVal = CInc->getZExtValue();
9708 unsigned NumBytes = VT.getScalarSizeInBits() / 8;
9709 if (IncVal != NumBytes)
9711 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
9714 // Finally, check that the vector doesn't depend on the load.
9715 // Again, this would create a cycle.
9716 // The load depending on the vector is fine, as that's the case for the
9717 // LD1*post we'll eventually generate anyway.
9718 if (LoadSDN->isPredecessorOf(Vector.getNode()))
9721 SmallVector<SDValue, 8> Ops;
9722 Ops.push_back(LD->getOperand(0)); // Chain
9724 Ops.push_back(Vector); // The vector to be inserted
9725 Ops.push_back(Lane); // The lane to be inserted in the vector
9727 Ops.push_back(Addr);
9730 EVT Tys[3] = { VT, MVT::i64, MVT::Other };
9731 SDVTList SDTys = DAG.getVTList(Tys);
9732 unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
9733 SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
9735 LoadSDN->getMemOperand());
9738 SDValue NewResults[] = {
9739 SDValue(LD, 0), // The result of load
9740 SDValue(UpdN.getNode(), 2) // Chain
9742 DCI.CombineTo(LD, NewResults);
9743 DCI.CombineTo(N, SDValue(UpdN.getNode(), 0)); // Dup/Inserted Result
9744 DCI.CombineTo(User, SDValue(UpdN.getNode(), 1)); // Write back register
9751 /// Simplify ``Addr`` given that the top byte of it is ignored by HW during
9752 /// address translation.
9753 static bool performTBISimplification(SDValue Addr,
9754 TargetLowering::DAGCombinerInfo &DCI,
9755 SelectionDAG &DAG) {
9756 APInt DemandedMask = APInt::getLowBitsSet(64, 56);
9758 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
9759 !DCI.isBeforeLegalizeOps());
9760 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9761 if (TLI.SimplifyDemandedBits(Addr, DemandedMask, Known, TLO)) {
9762 DCI.CommitTargetLoweringOpt(TLO);
9768 static SDValue performSTORECombine(SDNode *N,
9769 TargetLowering::DAGCombinerInfo &DCI,
9771 const AArch64Subtarget *Subtarget) {
9772 if (SDValue Split = splitStores(N, DCI, DAG, Subtarget))
9775 if (Subtarget->supportsAddressTopByteIgnored() &&
9776 performTBISimplification(N->getOperand(2), DCI, DAG))
9777 return SDValue(N, 0);
9783 /// Target-specific DAG combine function for NEON load/store intrinsics
9784 /// to merge base address updates.
9785 static SDValue performNEONPostLDSTCombine(SDNode *N,
9786 TargetLowering::DAGCombinerInfo &DCI,
9787 SelectionDAG &DAG) {
9788 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9791 unsigned AddrOpIdx = N->getNumOperands() - 1;
9792 SDValue Addr = N->getOperand(AddrOpIdx);
9794 // Search for a use of the address operand that is an increment.
9795 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9796 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9798 if (User->getOpcode() != ISD::ADD ||
9799 UI.getUse().getResNo() != Addr.getResNo())
9802 // Check that the add is independent of the load/store. Otherwise, folding
9803 // it would create a cycle.
9804 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9807 // Find the new opcode for the updating load/store.
9808 bool IsStore = false;
9809 bool IsLaneOp = false;
9810 bool IsDupOp = false;
9811 unsigned NewOpc = 0;
9812 unsigned NumVecs = 0;
9813 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9815 default: llvm_unreachable("unexpected intrinsic for Neon base update");
9816 case Intrinsic::aarch64_neon_ld2: NewOpc = AArch64ISD::LD2post;
9818 case Intrinsic::aarch64_neon_ld3: NewOpc = AArch64ISD::LD3post;
9820 case Intrinsic::aarch64_neon_ld4: NewOpc = AArch64ISD::LD4post;
9822 case Intrinsic::aarch64_neon_st2: NewOpc = AArch64ISD::ST2post;
9823 NumVecs = 2; IsStore = true; break;
9824 case Intrinsic::aarch64_neon_st3: NewOpc = AArch64ISD::ST3post;
9825 NumVecs = 3; IsStore = true; break;
9826 case Intrinsic::aarch64_neon_st4: NewOpc = AArch64ISD::ST4post;
9827 NumVecs = 4; IsStore = true; break;
9828 case Intrinsic::aarch64_neon_ld1x2: NewOpc = AArch64ISD::LD1x2post;
9830 case Intrinsic::aarch64_neon_ld1x3: NewOpc = AArch64ISD::LD1x3post;
9832 case Intrinsic::aarch64_neon_ld1x4: NewOpc = AArch64ISD::LD1x4post;
9834 case Intrinsic::aarch64_neon_st1x2: NewOpc = AArch64ISD::ST1x2post;
9835 NumVecs = 2; IsStore = true; break;
9836 case Intrinsic::aarch64_neon_st1x3: NewOpc = AArch64ISD::ST1x3post;
9837 NumVecs = 3; IsStore = true; break;
9838 case Intrinsic::aarch64_neon_st1x4: NewOpc = AArch64ISD::ST1x4post;
9839 NumVecs = 4; IsStore = true; break;
9840 case Intrinsic::aarch64_neon_ld2r: NewOpc = AArch64ISD::LD2DUPpost;
9841 NumVecs = 2; IsDupOp = true; break;
9842 case Intrinsic::aarch64_neon_ld3r: NewOpc = AArch64ISD::LD3DUPpost;
9843 NumVecs = 3; IsDupOp = true; break;
9844 case Intrinsic::aarch64_neon_ld4r: NewOpc = AArch64ISD::LD4DUPpost;
9845 NumVecs = 4; IsDupOp = true; break;
9846 case Intrinsic::aarch64_neon_ld2lane: NewOpc = AArch64ISD::LD2LANEpost;
9847 NumVecs = 2; IsLaneOp = true; break;
9848 case Intrinsic::aarch64_neon_ld3lane: NewOpc = AArch64ISD::LD3LANEpost;
9849 NumVecs = 3; IsLaneOp = true; break;
9850 case Intrinsic::aarch64_neon_ld4lane: NewOpc = AArch64ISD::LD4LANEpost;
9851 NumVecs = 4; IsLaneOp = true; break;
9852 case Intrinsic::aarch64_neon_st2lane: NewOpc = AArch64ISD::ST2LANEpost;
9853 NumVecs = 2; IsStore = true; IsLaneOp = true; break;
9854 case Intrinsic::aarch64_neon_st3lane: NewOpc = AArch64ISD::ST3LANEpost;
9855 NumVecs = 3; IsStore = true; IsLaneOp = true; break;
9856 case Intrinsic::aarch64_neon_st4lane: NewOpc = AArch64ISD::ST4LANEpost;
9857 NumVecs = 4; IsStore = true; IsLaneOp = true; break;
9862 VecTy = N->getOperand(2).getValueType();
9864 VecTy = N->getValueType(0);
9866 // If the increment is a constant, it must match the memory ref size.
9867 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9868 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9869 uint32_t IncVal = CInc->getZExtValue();
9870 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9871 if (IsLaneOp || IsDupOp)
9872 NumBytes /= VecTy.getVectorNumElements();
9873 if (IncVal != NumBytes)
9875 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
9877 SmallVector<SDValue, 8> Ops;
9878 Ops.push_back(N->getOperand(0)); // Incoming chain
9879 // Load lane and store have vector list as input.
9880 if (IsLaneOp || IsStore)
9881 for (unsigned i = 2; i < AddrOpIdx; ++i)
9882 Ops.push_back(N->getOperand(i));
9883 Ops.push_back(Addr); // Base register
9888 unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
9890 for (n = 0; n < NumResultVecs; ++n)
9892 Tys[n++] = MVT::i64; // Type of write back register
9893 Tys[n] = MVT::Other; // Type of the chain
9894 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
9896 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9897 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
9898 MemInt->getMemoryVT(),
9899 MemInt->getMemOperand());
9902 std::vector<SDValue> NewResults;
9903 for (unsigned i = 0; i < NumResultVecs; ++i) {
9904 NewResults.push_back(SDValue(UpdN.getNode(), i));
9906 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
9907 DCI.CombineTo(N, NewResults);
9908 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9915 // Checks to see if the value is the prescribed width and returns information
9916 // about its extension mode.
9918 bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
9919 ExtType = ISD::NON_EXTLOAD;
9920 switch(V.getNode()->getOpcode()) {
9924 LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
9925 if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
9926 || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
9927 ExtType = LoadNode->getExtensionType();
9932 case ISD::AssertSext: {
9933 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9934 if ((TypeNode->getVT() == MVT::i8 && width == 8)
9935 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9936 ExtType = ISD::SEXTLOAD;
9941 case ISD::AssertZext: {
9942 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9943 if ((TypeNode->getVT() == MVT::i8 && width == 8)
9944 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9945 ExtType = ISD::ZEXTLOAD;
9951 case ISD::TargetConstant: {
9952 return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
9960 // This function does a whole lot of voodoo to determine if the tests are
9961 // equivalent without and with a mask. Essentially what happens is that given a
9964 // +-------------+ +-------------+ +-------------+ +-------------+
9965 // | Input | | AddConstant | | CompConstant| | CC |
9966 // +-------------+ +-------------+ +-------------+ +-------------+
9968 // V V | +----------+
9969 // +-------------+ +----+ | |
9970 // | ADD | |0xff| | |
9971 // +-------------+ +----+ | |
9974 // +-------------+ | |
9976 // +-------------+ | |
9985 // The AND node may be safely removed for some combinations of inputs. In
9986 // particular we need to take into account the extension type of the Input,
9987 // the exact values of AddConstant, CompConstant, and CC, along with the nominal
9988 // width of the input (this can work for any width inputs, the above graph is
9989 // specific to 8 bits.
9991 // The specific equations were worked out by generating output tables for each
9992 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
9993 // problem was simplified by working with 4 bit inputs, which means we only
9994 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
9995 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
9996 // patterns present in both extensions (0,7). For every distinct set of
9997 // AddConstant and CompConstants bit patterns we can consider the masked and
9998 // unmasked versions to be equivalent if the result of this function is true for
9999 // all 16 distinct bit patterns of for the current extension type of Input (w0).
10002 // and w10, w8, #0x0f
10004 // cset w9, AArch64CC
10006 // cset w11, AArch64CC
10011 // Since the above function shows when the outputs are equivalent it defines
10012 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
10013 // would be expensive to run during compiles. The equations below were written
10014 // in a test harness that confirmed they gave equivalent outputs to the above
10015 // for all inputs function, so they can be used determine if the removal is
10018 // isEquivalentMaskless() is the code for testing if the AND can be removed
10019 // factored out of the DAG recognition as the DAG can take several forms.
10021 static bool isEquivalentMaskless(unsigned CC, unsigned width,
10022 ISD::LoadExtType ExtType, int AddConstant,
10023 int CompConstant) {
10024 // By being careful about our equations and only writing the in term
10025 // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
10026 // make them generally applicable to all bit widths.
10027 int MaxUInt = (1 << width);
10029 // For the purposes of these comparisons sign extending the type is
10030 // equivalent to zero extending the add and displacing it by half the integer
10031 // width. Provided we are careful and make sure our equations are valid over
10032 // the whole range we can just adjust the input and avoid writing equations
10033 // for sign extended inputs.
10034 if (ExtType == ISD::SEXTLOAD)
10035 AddConstant -= (1 << (width-1));
10038 case AArch64CC::LE:
10039 case AArch64CC::GT:
10040 if ((AddConstant == 0) ||
10041 (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
10042 (AddConstant >= 0 && CompConstant < 0) ||
10043 (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
10046 case AArch64CC::LT:
10047 case AArch64CC::GE:
10048 if ((AddConstant == 0) ||
10049 (AddConstant >= 0 && CompConstant <= 0) ||
10050 (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
10053 case AArch64CC::HI:
10054 case AArch64CC::LS:
10055 if ((AddConstant >= 0 && CompConstant < 0) ||
10056 (AddConstant <= 0 && CompConstant >= -1 &&
10057 CompConstant < AddConstant + MaxUInt))
10060 case AArch64CC::PL:
10061 case AArch64CC::MI:
10062 if ((AddConstant == 0) ||
10063 (AddConstant > 0 && CompConstant <= 0) ||
10064 (AddConstant < 0 && CompConstant <= AddConstant))
10067 case AArch64CC::LO:
10068 case AArch64CC::HS:
10069 if ((AddConstant >= 0 && CompConstant <= 0) ||
10070 (AddConstant <= 0 && CompConstant >= 0 &&
10071 CompConstant <= AddConstant + MaxUInt))
10074 case AArch64CC::EQ:
10075 case AArch64CC::NE:
10076 if ((AddConstant > 0 && CompConstant < 0) ||
10077 (AddConstant < 0 && CompConstant >= 0 &&
10078 CompConstant < AddConstant + MaxUInt) ||
10079 (AddConstant >= 0 && CompConstant >= 0 &&
10080 CompConstant >= AddConstant) ||
10081 (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
10084 case AArch64CC::VS:
10085 case AArch64CC::VC:
10086 case AArch64CC::AL:
10087 case AArch64CC::NV:
10089 case AArch64CC::Invalid:
10097 SDValue performCONDCombine(SDNode *N,
10098 TargetLowering::DAGCombinerInfo &DCI,
10099 SelectionDAG &DAG, unsigned CCIndex,
10100 unsigned CmpIndex) {
10101 unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
10102 SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
10103 unsigned CondOpcode = SubsNode->getOpcode();
10105 if (CondOpcode != AArch64ISD::SUBS)
10108 // There is a SUBS feeding this condition. Is it fed by a mask we can
10111 SDNode *AndNode = SubsNode->getOperand(0).getNode();
10112 unsigned MaskBits = 0;
10114 if (AndNode->getOpcode() != ISD::AND)
10117 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
10118 uint32_t CNV = CN->getZExtValue();
10121 else if (CNV == 65535)
10128 SDValue AddValue = AndNode->getOperand(0);
10130 if (AddValue.getOpcode() != ISD::ADD)
10133 // The basic dag structure is correct, grab the inputs and validate them.
10135 SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
10136 SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
10137 SDValue SubsInputValue = SubsNode->getOperand(1);
10139 // The mask is present and the provenance of all the values is a smaller type,
10140 // lets see if the mask is superfluous.
10142 if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
10143 !isa<ConstantSDNode>(SubsInputValue.getNode()))
10146 ISD::LoadExtType ExtType;
10148 if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
10149 !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
10150 !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
10153 if(!isEquivalentMaskless(CC, MaskBits, ExtType,
10154 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
10155 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
10158 // The AND is not necessary, remove it.
10160 SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
10161 SubsNode->getValueType(1));
10162 SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
10164 SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
10165 DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
10167 return SDValue(N, 0);
10170 // Optimize compare with zero and branch.
10171 static SDValue performBRCONDCombine(SDNode *N,
10172 TargetLowering::DAGCombinerInfo &DCI,
10173 SelectionDAG &DAG) {
10174 if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3))
10176 SDValue Chain = N->getOperand(0);
10177 SDValue Dest = N->getOperand(1);
10178 SDValue CCVal = N->getOperand(2);
10179 SDValue Cmp = N->getOperand(3);
10181 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
10182 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
10183 if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
10186 unsigned CmpOpc = Cmp.getOpcode();
10187 if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
10190 // Only attempt folding if there is only one use of the flag and no use of the
10192 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
10195 SDValue LHS = Cmp.getOperand(0);
10196 SDValue RHS = Cmp.getOperand(1);
10198 assert(LHS.getValueType() == RHS.getValueType() &&
10199 "Expected the value type to be the same for both operands!");
10200 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
10203 if (isNullConstant(LHS))
10204 std::swap(LHS, RHS);
10206 if (!isNullConstant(RHS))
10209 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
10210 LHS.getOpcode() == ISD::SRL)
10213 // Fold the compare into the branch instruction.
10215 if (CC == AArch64CC::EQ)
10216 BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
10218 BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
10220 // Do not add new nodes to DAG combiner worklist.
10221 DCI.CombineTo(N, BR, false);
10226 // Optimize some simple tbz/tbnz cases. Returns the new operand and bit to test
10227 // as well as whether the test should be inverted. This code is required to
10228 // catch these cases (as opposed to standard dag combines) because
10229 // AArch64ISD::TBZ is matched during legalization.
10230 static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert,
10231 SelectionDAG &DAG) {
10233 if (!Op->hasOneUse())
10236 // We don't handle undef/constant-fold cases below, as they should have
10237 // already been taken care of (e.g. and of 0, test of undefined shifted bits,
10240 // (tbz (trunc x), b) -> (tbz x, b)
10241 // This case is just here to enable more of the below cases to be caught.
10242 if (Op->getOpcode() == ISD::TRUNCATE &&
10243 Bit < Op->getValueType(0).getSizeInBits()) {
10244 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10247 if (Op->getNumOperands() != 2)
10250 auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
10254 switch (Op->getOpcode()) {
10258 // (tbz (and x, m), b) -> (tbz x, b)
10260 if ((C->getZExtValue() >> Bit) & 1)
10261 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10264 // (tbz (shl x, c), b) -> (tbz x, b-c)
10266 if (C->getZExtValue() <= Bit &&
10267 (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
10268 Bit = Bit - C->getZExtValue();
10269 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10273 // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
10275 Bit = Bit + C->getZExtValue();
10276 if (Bit >= Op->getValueType(0).getSizeInBits())
10277 Bit = Op->getValueType(0).getSizeInBits() - 1;
10278 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10280 // (tbz (srl x, c), b) -> (tbz x, b+c)
10282 if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
10283 Bit = Bit + C->getZExtValue();
10284 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10288 // (tbz (xor x, -1), b) -> (tbnz x, b)
10290 if ((C->getZExtValue() >> Bit) & 1)
10292 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10296 // Optimize test single bit zero/non-zero and branch.
10297 static SDValue performTBZCombine(SDNode *N,
10298 TargetLowering::DAGCombinerInfo &DCI,
10299 SelectionDAG &DAG) {
10300 unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
10301 bool Invert = false;
10302 SDValue TestSrc = N->getOperand(1);
10303 SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG);
10305 if (TestSrc == NewTestSrc)
10308 unsigned NewOpc = N->getOpcode();
10310 if (NewOpc == AArch64ISD::TBZ)
10311 NewOpc = AArch64ISD::TBNZ;
10313 assert(NewOpc == AArch64ISD::TBNZ);
10314 NewOpc = AArch64ISD::TBZ;
10319 return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc,
10320 DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3));
10323 // vselect (v1i1 setcc) ->
10324 // vselect (v1iXX setcc) (XX is the size of the compared operand type)
10325 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
10326 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
10328 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
10329 SDValue N0 = N->getOperand(0);
10330 EVT CCVT = N0.getValueType();
10332 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
10333 CCVT.getVectorElementType() != MVT::i1)
10336 EVT ResVT = N->getValueType(0);
10337 EVT CmpVT = N0.getOperand(0).getValueType();
10338 // Only combine when the result type is of the same size as the compared
10340 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
10343 SDValue IfTrue = N->getOperand(1);
10344 SDValue IfFalse = N->getOperand(2);
10346 DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
10347 N0.getOperand(0), N0.getOperand(1),
10348 cast<CondCodeSDNode>(N0.getOperand(2))->get());
10349 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
10353 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
10354 /// the compare-mask instructions rather than going via NZCV, even if LHS and
10355 /// RHS are really scalar. This replaces any scalar setcc in the above pattern
10356 /// with a vector one followed by a DUP shuffle on the result.
10357 static SDValue performSelectCombine(SDNode *N,
10358 TargetLowering::DAGCombinerInfo &DCI) {
10359 SelectionDAG &DAG = DCI.DAG;
10360 SDValue N0 = N->getOperand(0);
10361 EVT ResVT = N->getValueType(0);
10363 if (N0.getOpcode() != ISD::SETCC)
10366 // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
10367 // scalar SetCCResultType. We also don't expect vectors, because we assume
10368 // that selects fed by vector SETCCs are canonicalized to VSELECT.
10369 assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
10370 "Scalar-SETCC feeding SELECT has unexpected result type!");
10372 // If NumMaskElts == 0, the comparison is larger than select result. The
10373 // largest real NEON comparison is 64-bits per lane, which means the result is
10374 // at most 32-bits and an illegal vector. Just bail out for now.
10375 EVT SrcVT = N0.getOperand(0).getValueType();
10377 // Don't try to do this optimization when the setcc itself has i1 operands.
10378 // There are no legal vectors of i1, so this would be pointless.
10379 if (SrcVT == MVT::i1)
10382 int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
10383 if (!ResVT.isVector() || NumMaskElts == 0)
10386 SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
10387 EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
10389 // Also bail out if the vector CCVT isn't the same size as ResVT.
10390 // This can happen if the SETCC operand size doesn't divide the ResVT size
10391 // (e.g., f64 vs v3f32).
10392 if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
10395 // Make sure we didn't create illegal types, if we're not supposed to.
10396 assert(DCI.isBeforeLegalize() ||
10397 DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
10399 // First perform a vector comparison, where lane 0 is the one we're interested
10403 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
10405 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
10406 SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
10408 // Now duplicate the comparison mask we want across all other lanes.
10409 SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
10410 SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask);
10411 Mask = DAG.getNode(ISD::BITCAST, DL,
10412 ResVT.changeVectorElementTypeToInteger(), Mask);
10414 return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
10417 /// Get rid of unnecessary NVCASTs (that don't change the type).
10418 static SDValue performNVCASTCombine(SDNode *N) {
10419 if (N->getValueType(0) == N->getOperand(0).getValueType())
10420 return N->getOperand(0);
10425 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
10426 DAGCombinerInfo &DCI) const {
10427 SelectionDAG &DAG = DCI.DAG;
10428 switch (N->getOpcode()) {
10430 DEBUG(dbgs() << "Custom combining: skipping\n");
10434 return performAddSubLongCombine(N, DCI, DAG);
10436 return performXorCombine(N, DAG, DCI, Subtarget);
10438 return performMulCombine(N, DAG, DCI, Subtarget);
10439 case ISD::SINT_TO_FP:
10440 case ISD::UINT_TO_FP:
10441 return performIntToFpCombine(N, DAG, Subtarget);
10442 case ISD::FP_TO_SINT:
10443 case ISD::FP_TO_UINT:
10444 return performFpToIntCombine(N, DAG, DCI, Subtarget);
10446 return performFDivCombine(N, DAG, DCI, Subtarget);
10448 return performORCombine(N, DCI, Subtarget);
10450 return performSRLCombine(N, DCI);
10451 case ISD::INTRINSIC_WO_CHAIN:
10452 return performIntrinsicCombine(N, DCI, Subtarget);
10453 case ISD::ANY_EXTEND:
10454 case ISD::ZERO_EXTEND:
10455 case ISD::SIGN_EXTEND:
10456 return performExtendCombine(N, DCI, DAG);
10458 return performBitcastCombine(N, DCI, DAG);
10459 case ISD::CONCAT_VECTORS:
10460 return performConcatVectorsCombine(N, DCI, DAG);
10462 return performSelectCombine(N, DCI);
10464 return performVSelectCombine(N, DCI.DAG);
10466 if (performTBISimplification(N->getOperand(1), DCI, DAG))
10467 return SDValue(N, 0);
10470 return performSTORECombine(N, DCI, DAG, Subtarget);
10471 case AArch64ISD::BRCOND:
10472 return performBRCONDCombine(N, DCI, DAG);
10473 case AArch64ISD::TBNZ:
10474 case AArch64ISD::TBZ:
10475 return performTBZCombine(N, DCI, DAG);
10476 case AArch64ISD::CSEL:
10477 return performCONDCombine(N, DCI, DAG, 2, 3);
10478 case AArch64ISD::DUP:
10479 return performPostLD1Combine(N, DCI, false);
10480 case AArch64ISD::NVCAST:
10481 return performNVCASTCombine(N);
10482 case ISD::INSERT_VECTOR_ELT:
10483 return performPostLD1Combine(N, DCI, true);
10484 case ISD::INTRINSIC_VOID:
10485 case ISD::INTRINSIC_W_CHAIN:
10486 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10487 case Intrinsic::aarch64_neon_ld2:
10488 case Intrinsic::aarch64_neon_ld3:
10489 case Intrinsic::aarch64_neon_ld4:
10490 case Intrinsic::aarch64_neon_ld1x2:
10491 case Intrinsic::aarch64_neon_ld1x3:
10492 case Intrinsic::aarch64_neon_ld1x4:
10493 case Intrinsic::aarch64_neon_ld2lane:
10494 case Intrinsic::aarch64_neon_ld3lane:
10495 case Intrinsic::aarch64_neon_ld4lane:
10496 case Intrinsic::aarch64_neon_ld2r:
10497 case Intrinsic::aarch64_neon_ld3r:
10498 case Intrinsic::aarch64_neon_ld4r:
10499 case Intrinsic::aarch64_neon_st2:
10500 case Intrinsic::aarch64_neon_st3:
10501 case Intrinsic::aarch64_neon_st4:
10502 case Intrinsic::aarch64_neon_st1x2:
10503 case Intrinsic::aarch64_neon_st1x3:
10504 case Intrinsic::aarch64_neon_st1x4:
10505 case Intrinsic::aarch64_neon_st2lane:
10506 case Intrinsic::aarch64_neon_st3lane:
10507 case Intrinsic::aarch64_neon_st4lane:
10508 return performNEONPostLDSTCombine(N, DCI, DAG);
10516 // Check if the return value is used as only a return value, as otherwise
10517 // we can't perform a tail-call. In particular, we need to check for
10518 // target ISD nodes that are returns and any other "odd" constructs
10519 // that the generic analysis code won't necessarily catch.
10520 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
10521 SDValue &Chain) const {
10522 if (N->getNumValues() != 1)
10524 if (!N->hasNUsesOfValue(1, 0))
10527 SDValue TCChain = Chain;
10528 SDNode *Copy = *N->use_begin();
10529 if (Copy->getOpcode() == ISD::CopyToReg) {
10530 // If the copy has a glue operand, we conservatively assume it isn't safe to
10531 // perform a tail call.
10532 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
10535 TCChain = Copy->getOperand(0);
10536 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
10539 bool HasRet = false;
10540 for (SDNode *Node : Copy->uses()) {
10541 if (Node->getOpcode() != AArch64ISD::RET_FLAG)
10553 // Return whether the an instruction can potentially be optimized to a tail
10554 // call. This will cause the optimizers to attempt to move, or duplicate,
10555 // return instructions to help enable tail call optimizations for this
10557 bool AArch64TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
10558 return CI->isTailCall();
10561 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
10563 ISD::MemIndexedMode &AM,
10565 SelectionDAG &DAG) const {
10566 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
10569 Base = Op->getOperand(0);
10570 // All of the indexed addressing mode instructions take a signed
10571 // 9 bit immediate offset.
10572 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
10573 int64_t RHSC = RHS->getSExtValue();
10574 if (Op->getOpcode() == ISD::SUB)
10575 RHSC = -(uint64_t)RHSC;
10576 if (!isInt<9>(RHSC))
10578 IsInc = (Op->getOpcode() == ISD::ADD);
10579 Offset = Op->getOperand(1);
10585 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10587 ISD::MemIndexedMode &AM,
10588 SelectionDAG &DAG) const {
10591 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10592 VT = LD->getMemoryVT();
10593 Ptr = LD->getBasePtr();
10594 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10595 VT = ST->getMemoryVT();
10596 Ptr = ST->getBasePtr();
10601 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
10603 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
10607 bool AArch64TargetLowering::getPostIndexedAddressParts(
10608 SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
10609 ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
10612 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10613 VT = LD->getMemoryVT();
10614 Ptr = LD->getBasePtr();
10615 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10616 VT = ST->getMemoryVT();
10617 Ptr = ST->getBasePtr();
10622 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
10624 // Post-indexing updates the base, so it's not a valid transform
10625 // if that's not the same as the load's pointer.
10628 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
10632 static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
10633 SelectionDAG &DAG) {
10635 SDValue Op = N->getOperand(0);
10637 if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
10641 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
10642 DAG.getUNDEF(MVT::i32), Op,
10643 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
10645 Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
10646 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
10649 static void ReplaceReductionResults(SDNode *N,
10650 SmallVectorImpl<SDValue> &Results,
10651 SelectionDAG &DAG, unsigned InterOp,
10652 unsigned AcrossOp) {
10656 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
10657 std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
10658 SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
10659 SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
10660 Results.push_back(SplitVal);
10663 static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) {
10665 SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N);
10666 SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64,
10667 DAG.getNode(ISD::SRL, DL, MVT::i128, N,
10668 DAG.getConstant(64, DL, MVT::i64)));
10669 return std::make_pair(Lo, Hi);
10672 static void ReplaceCMP_SWAP_128Results(SDNode *N,
10673 SmallVectorImpl<SDValue> & Results,
10674 SelectionDAG &DAG) {
10675 assert(N->getValueType(0) == MVT::i128 &&
10676 "AtomicCmpSwap on types less than 128 should be legal");
10677 auto Desired = splitInt128(N->getOperand(2), DAG);
10678 auto New = splitInt128(N->getOperand(3), DAG);
10679 SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second,
10680 New.first, New.second, N->getOperand(0)};
10681 SDNode *CmpSwap = DAG.getMachineNode(
10682 AArch64::CMP_SWAP_128, SDLoc(N),
10683 DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops);
10685 MachineFunction &MF = DAG.getMachineFunction();
10686 MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1);
10687 MemOp[0] = cast<MemSDNode>(N)->getMemOperand();
10688 cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1);
10690 Results.push_back(SDValue(CmpSwap, 0));
10691 Results.push_back(SDValue(CmpSwap, 1));
10692 Results.push_back(SDValue(CmpSwap, 3));
10695 void AArch64TargetLowering::ReplaceNodeResults(
10696 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
10697 switch (N->getOpcode()) {
10699 llvm_unreachable("Don't know how to custom expand this");
10701 ReplaceBITCASTResults(N, Results, DAG);
10703 case ISD::VECREDUCE_ADD:
10704 case ISD::VECREDUCE_SMAX:
10705 case ISD::VECREDUCE_SMIN:
10706 case ISD::VECREDUCE_UMAX:
10707 case ISD::VECREDUCE_UMIN:
10708 Results.push_back(LowerVECREDUCE(SDValue(N, 0), DAG));
10711 case AArch64ISD::SADDV:
10712 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
10714 case AArch64ISD::UADDV:
10715 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
10717 case AArch64ISD::SMINV:
10718 ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
10720 case AArch64ISD::UMINV:
10721 ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
10723 case AArch64ISD::SMAXV:
10724 ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
10726 case AArch64ISD::UMAXV:
10727 ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
10729 case ISD::FP_TO_UINT:
10730 case ISD::FP_TO_SINT:
10731 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
10732 // Let normal code take care of it by not adding anything to Results.
10734 case ISD::ATOMIC_CMP_SWAP:
10735 ReplaceCMP_SWAP_128Results(N, Results, DAG);
10740 bool AArch64TargetLowering::useLoadStackGuardNode() const {
10741 if (Subtarget->isTargetAndroid() || Subtarget->isTargetFuchsia())
10742 return TargetLowering::useLoadStackGuardNode();
10746 unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
10747 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
10748 // reciprocal if there are three or more FDIVs.
10752 TargetLoweringBase::LegalizeTypeAction
10753 AArch64TargetLowering::getPreferredVectorAction(EVT VT) const {
10754 MVT SVT = VT.getSimpleVT();
10755 // During type legalization, we prefer to widen v1i8, v1i16, v1i32 to v8i8,
10756 // v4i16, v2i32 instead of to promote.
10757 if (SVT == MVT::v1i8 || SVT == MVT::v1i16 || SVT == MVT::v1i32
10758 || SVT == MVT::v1f32)
10759 return TypeWidenVector;
10761 return TargetLoweringBase::getPreferredVectorAction(VT);
10764 // Loads and stores less than 128-bits are already atomic; ones above that
10765 // are doomed anyway, so defer to the default libcall and blame the OS when
10766 // things go wrong.
10767 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
10768 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
10769 return Size == 128;
10772 // Loads and stores less than 128-bits are already atomic; ones above that
10773 // are doomed anyway, so defer to the default libcall and blame the OS when
10774 // things go wrong.
10775 TargetLowering::AtomicExpansionKind
10776 AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
10777 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
10778 return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
10781 // For the real atomic operations, we have ldxr/stxr up to 128 bits,
10782 TargetLowering::AtomicExpansionKind
10783 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
10784 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
10785 if (Size > 128) return AtomicExpansionKind::None;
10786 // Nand not supported in LSE.
10787 if (AI->getOperation() == AtomicRMWInst::Nand) return AtomicExpansionKind::LLSC;
10788 // Leave 128 bits to LLSC.
10789 return (Subtarget->hasLSE() && Size < 128) ? AtomicExpansionKind::None : AtomicExpansionKind::LLSC;
10792 bool AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
10793 AtomicCmpXchgInst *AI) const {
10794 // If subtarget has LSE, leave cmpxchg intact for codegen.
10795 if (Subtarget->hasLSE()) return false;
10796 // At -O0, fast-regalloc cannot cope with the live vregs necessary to
10797 // implement cmpxchg without spilling. If the address being exchanged is also
10798 // on the stack and close enough to the spill slot, this can lead to a
10799 // situation where the monitor always gets cleared and the atomic operation
10800 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
10801 return getTargetMachine().getOptLevel() != 0;
10804 Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
10805 AtomicOrdering Ord) const {
10806 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10807 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
10808 bool IsAcquire = isAcquireOrStronger(Ord);
10810 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
10811 // intrinsic must return {i64, i64} and we have to recombine them into a
10812 // single i128 here.
10813 if (ValTy->getPrimitiveSizeInBits() == 128) {
10814 Intrinsic::ID Int =
10815 IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
10816 Function *Ldxr = Intrinsic::getDeclaration(M, Int);
10818 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10819 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
10821 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
10822 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
10823 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
10824 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
10825 return Builder.CreateOr(
10826 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
10829 Type *Tys[] = { Addr->getType() };
10830 Intrinsic::ID Int =
10831 IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
10832 Function *Ldxr = Intrinsic::getDeclaration(M, Int, Tys);
10834 return Builder.CreateTruncOrBitCast(
10835 Builder.CreateCall(Ldxr, Addr),
10836 cast<PointerType>(Addr->getType())->getElementType());
10839 void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
10840 IRBuilder<> &Builder) const {
10841 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10842 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
10845 Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
10846 Value *Val, Value *Addr,
10847 AtomicOrdering Ord) const {
10848 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10849 bool IsRelease = isReleaseOrStronger(Ord);
10851 // Since the intrinsics must have legal type, the i128 intrinsics take two
10852 // parameters: "i64, i64". We must marshal Val into the appropriate form
10853 // before the call.
10854 if (Val->getType()->getPrimitiveSizeInBits() == 128) {
10855 Intrinsic::ID Int =
10856 IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
10857 Function *Stxr = Intrinsic::getDeclaration(M, Int);
10858 Type *Int64Ty = Type::getInt64Ty(M->getContext());
10860 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
10861 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
10862 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10863 return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
10866 Intrinsic::ID Int =
10867 IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
10868 Type *Tys[] = { Addr->getType() };
10869 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
10871 return Builder.CreateCall(Stxr,
10872 {Builder.CreateZExtOrBitCast(
10873 Val, Stxr->getFunctionType()->getParamType(0)),
10877 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
10878 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
10879 return Ty->isArrayTy();
10882 bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
10887 static Value *UseTlsOffset(IRBuilder<> &IRB, unsigned Offset) {
10888 Module *M = IRB.GetInsertBlock()->getParent()->getParent();
10889 Function *ThreadPointerFunc =
10890 Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
10891 return IRB.CreatePointerCast(
10892 IRB.CreateConstGEP1_32(IRB.CreateCall(ThreadPointerFunc), Offset),
10893 Type::getInt8PtrTy(IRB.getContext())->getPointerTo(0));
10896 Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const {
10897 // Android provides a fixed TLS slot for the stack cookie. See the definition
10898 // of TLS_SLOT_STACK_GUARD in
10899 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
10900 if (Subtarget->isTargetAndroid())
10901 return UseTlsOffset(IRB, 0x28);
10903 // Fuchsia is similar.
10904 // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value.
10905 if (Subtarget->isTargetFuchsia())
10906 return UseTlsOffset(IRB, -0x10);
10908 return TargetLowering::getIRStackGuard(IRB);
10911 Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
10912 // Android provides a fixed TLS slot for the SafeStack pointer. See the
10913 // definition of TLS_SLOT_SAFESTACK in
10914 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
10915 if (Subtarget->isTargetAndroid())
10916 return UseTlsOffset(IRB, 0x48);
10918 // Fuchsia is similar.
10919 // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value.
10920 if (Subtarget->isTargetFuchsia())
10921 return UseTlsOffset(IRB, -0x8);
10923 return TargetLowering::getSafeStackPointerLocation(IRB);
10926 bool AArch64TargetLowering::isMaskAndCmp0FoldingBeneficial(
10927 const Instruction &AndI) const {
10928 // Only sink 'and' mask to cmp use block if it is masking a single bit, since
10929 // this is likely to be fold the and/cmp/br into a single tbz instruction. It
10930 // may be beneficial to sink in other cases, but we would have to check that
10931 // the cmp would not get folded into the br to form a cbz for these to be
10933 ConstantInt* Mask = dyn_cast<ConstantInt>(AndI.getOperand(1));
10936 return Mask->getValue().isPowerOf2();
10939 void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
10940 // Update IsSplitCSR in AArch64unctionInfo.
10941 AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>();
10942 AFI->setIsSplitCSR(true);
10945 void AArch64TargetLowering::insertCopiesSplitCSR(
10946 MachineBasicBlock *Entry,
10947 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
10948 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
10949 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
10953 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10954 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
10955 MachineBasicBlock::iterator MBBI = Entry->begin();
10956 for (const MCPhysReg *I = IStart; *I; ++I) {
10957 const TargetRegisterClass *RC = nullptr;
10958 if (AArch64::GPR64RegClass.contains(*I))
10959 RC = &AArch64::GPR64RegClass;
10960 else if (AArch64::FPR64RegClass.contains(*I))
10961 RC = &AArch64::FPR64RegClass;
10963 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
10965 unsigned NewVR = MRI->createVirtualRegister(RC);
10966 // Create copy from CSR to a virtual register.
10967 // FIXME: this currently does not emit CFI pseudo-instructions, it works
10968 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
10969 // nounwind. If we want to generalize this later, we may need to emit
10970 // CFI pseudo-instructions.
10971 assert(Entry->getParent()->getFunction().hasFnAttribute(
10972 Attribute::NoUnwind) &&
10973 "Function should be nounwind in insertCopiesSplitCSR!");
10974 Entry->addLiveIn(*I);
10975 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
10978 // Insert the copy-back instructions right before the terminator.
10979 for (auto *Exit : Exits)
10980 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
10981 TII->get(TargetOpcode::COPY), *I)
10986 bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const {
10987 // Integer division on AArch64 is expensive. However, when aggressively
10988 // optimizing for code size, we prefer to use a div instruction, as it is
10989 // usually smaller than the alternative sequence.
10990 // The exception to this is vector division. Since AArch64 doesn't have vector
10991 // integer division, leaving the division as-is is a loss even in terms of
10992 // size, because it will have to be scalarized, while the alternative code
10993 // sequence can be performed in vector form.
10995 Attr.hasAttribute(AttributeList::FunctionIndex, Attribute::MinSize);
10996 return OptSize && !VT.isVector();
11000 AArch64TargetLowering::getVaListSizeInBits(const DataLayout &DL) const {
11001 if (Subtarget->isTargetDarwin() || Subtarget->isTargetWindows())
11002 return getPointerTy(DL).getSizeInBits();
11004 return 3 * getPointerTy(DL).getSizeInBits() + 2 * 32;