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/ValueTypes.h"
46 #include "llvm/IR/Attributes.h"
47 #include "llvm/IR/Constants.h"
48 #include "llvm/IR/DataLayout.h"
49 #include "llvm/IR/DebugLoc.h"
50 #include "llvm/IR/DerivedTypes.h"
51 #include "llvm/IR/Function.h"
52 #include "llvm/IR/GetElementPtrTypeIterator.h"
53 #include "llvm/IR/GlobalValue.h"
54 #include "llvm/IR/IRBuilder.h"
55 #include "llvm/IR/Instruction.h"
56 #include "llvm/IR/Instructions.h"
57 #include "llvm/IR/Intrinsics.h"
58 #include "llvm/IR/Module.h"
59 #include "llvm/IR/OperandTraits.h"
60 #include "llvm/IR/Type.h"
61 #include "llvm/IR/Use.h"
62 #include "llvm/IR/Value.h"
63 #include "llvm/MC/MCRegisterInfo.h"
64 #include "llvm/Support/Casting.h"
65 #include "llvm/Support/CodeGen.h"
66 #include "llvm/Support/CommandLine.h"
67 #include "llvm/Support/Compiler.h"
68 #include "llvm/Support/Debug.h"
69 #include "llvm/Support/ErrorHandling.h"
70 #include "llvm/Support/KnownBits.h"
71 #include "llvm/Support/MathExtras.h"
72 #include "llvm/Support/raw_ostream.h"
73 #include "llvm/Target/TargetCallingConv.h"
74 #include "llvm/Target/TargetInstrInfo.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::f32, Custom);
170 setOperationAction(ISD::SETCC, MVT::f64, Custom);
171 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
172 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
173 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
174 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
175 setOperationAction(ISD::BR_CC, MVT::i64, Custom);
176 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
177 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
178 setOperationAction(ISD::SELECT, MVT::i32, Custom);
179 setOperationAction(ISD::SELECT, MVT::i64, Custom);
180 setOperationAction(ISD::SELECT, MVT::f32, Custom);
181 setOperationAction(ISD::SELECT, MVT::f64, Custom);
182 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
183 setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
184 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
185 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
186 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
187 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
189 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
190 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
191 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
193 setOperationAction(ISD::FREM, MVT::f32, Expand);
194 setOperationAction(ISD::FREM, MVT::f64, Expand);
195 setOperationAction(ISD::FREM, MVT::f80, Expand);
197 // Custom lowering hooks are needed for XOR
198 // to fold it into CSINC/CSINV.
199 setOperationAction(ISD::XOR, MVT::i32, Custom);
200 setOperationAction(ISD::XOR, MVT::i64, Custom);
202 // Virtually no operation on f128 is legal, but LLVM can't expand them when
203 // there's a valid register class, so we need custom operations in most cases.
204 setOperationAction(ISD::FABS, MVT::f128, Expand);
205 setOperationAction(ISD::FADD, MVT::f128, Custom);
206 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
207 setOperationAction(ISD::FCOS, MVT::f128, Expand);
208 setOperationAction(ISD::FDIV, MVT::f128, Custom);
209 setOperationAction(ISD::FMA, MVT::f128, Expand);
210 setOperationAction(ISD::FMUL, MVT::f128, Custom);
211 setOperationAction(ISD::FNEG, MVT::f128, Expand);
212 setOperationAction(ISD::FPOW, MVT::f128, Expand);
213 setOperationAction(ISD::FREM, MVT::f128, Expand);
214 setOperationAction(ISD::FRINT, MVT::f128, Expand);
215 setOperationAction(ISD::FSIN, MVT::f128, Expand);
216 setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
217 setOperationAction(ISD::FSQRT, MVT::f128, Expand);
218 setOperationAction(ISD::FSUB, MVT::f128, Custom);
219 setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
220 setOperationAction(ISD::SETCC, MVT::f128, Custom);
221 setOperationAction(ISD::BR_CC, MVT::f128, Custom);
222 setOperationAction(ISD::SELECT, MVT::f128, Custom);
223 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
224 setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
226 // Lowering for many of the conversions is actually specified by the non-f128
227 // type. The LowerXXX function will be trivial when f128 isn't involved.
228 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
229 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
230 setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
231 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
232 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
233 setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
234 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
235 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
236 setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
237 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
238 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
239 setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
240 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
241 setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
243 // Variable arguments.
244 setOperationAction(ISD::VASTART, MVT::Other, Custom);
245 setOperationAction(ISD::VAARG, MVT::Other, Custom);
246 setOperationAction(ISD::VACOPY, MVT::Other, Custom);
247 setOperationAction(ISD::VAEND, MVT::Other, Expand);
249 // Variable-sized objects.
250 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
251 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
252 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
254 // Constant pool entries
255 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
258 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
260 // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
261 setOperationAction(ISD::ADDC, MVT::i32, Custom);
262 setOperationAction(ISD::ADDE, MVT::i32, Custom);
263 setOperationAction(ISD::SUBC, MVT::i32, Custom);
264 setOperationAction(ISD::SUBE, MVT::i32, Custom);
265 setOperationAction(ISD::ADDC, MVT::i64, Custom);
266 setOperationAction(ISD::ADDE, MVT::i64, Custom);
267 setOperationAction(ISD::SUBC, MVT::i64, Custom);
268 setOperationAction(ISD::SUBE, MVT::i64, Custom);
270 // AArch64 lacks both left-rotate and popcount instructions.
271 setOperationAction(ISD::ROTL, MVT::i32, Expand);
272 setOperationAction(ISD::ROTL, MVT::i64, Expand);
273 for (MVT VT : MVT::vector_valuetypes()) {
274 setOperationAction(ISD::ROTL, VT, Expand);
275 setOperationAction(ISD::ROTR, VT, Expand);
278 // AArch64 doesn't have {U|S}MUL_LOHI.
279 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
280 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
282 setOperationAction(ISD::CTPOP, MVT::i32, Custom);
283 setOperationAction(ISD::CTPOP, MVT::i64, Custom);
285 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
286 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
287 for (MVT VT : MVT::vector_valuetypes()) {
288 setOperationAction(ISD::SDIVREM, VT, Expand);
289 setOperationAction(ISD::UDIVREM, VT, Expand);
291 setOperationAction(ISD::SREM, MVT::i32, Expand);
292 setOperationAction(ISD::SREM, MVT::i64, Expand);
293 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
294 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
295 setOperationAction(ISD::UREM, MVT::i32, Expand);
296 setOperationAction(ISD::UREM, MVT::i64, Expand);
298 // Custom lower Add/Sub/Mul with overflow.
299 setOperationAction(ISD::SADDO, MVT::i32, Custom);
300 setOperationAction(ISD::SADDO, MVT::i64, Custom);
301 setOperationAction(ISD::UADDO, MVT::i32, Custom);
302 setOperationAction(ISD::UADDO, MVT::i64, Custom);
303 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
304 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
305 setOperationAction(ISD::USUBO, MVT::i32, Custom);
306 setOperationAction(ISD::USUBO, MVT::i64, Custom);
307 setOperationAction(ISD::SMULO, MVT::i32, Custom);
308 setOperationAction(ISD::SMULO, MVT::i64, Custom);
309 setOperationAction(ISD::UMULO, MVT::i32, Custom);
310 setOperationAction(ISD::UMULO, MVT::i64, Custom);
312 setOperationAction(ISD::FSIN, MVT::f32, Expand);
313 setOperationAction(ISD::FSIN, MVT::f64, Expand);
314 setOperationAction(ISD::FCOS, MVT::f32, Expand);
315 setOperationAction(ISD::FCOS, MVT::f64, Expand);
316 setOperationAction(ISD::FPOW, MVT::f32, Expand);
317 setOperationAction(ISD::FPOW, MVT::f64, Expand);
318 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
319 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
321 // f16 is a storage-only type, always promote it to f32.
322 setOperationAction(ISD::SETCC, MVT::f16, Promote);
323 setOperationAction(ISD::BR_CC, MVT::f16, Promote);
324 setOperationAction(ISD::SELECT_CC, MVT::f16, Promote);
325 setOperationAction(ISD::SELECT, MVT::f16, Promote);
326 setOperationAction(ISD::FADD, MVT::f16, Promote);
327 setOperationAction(ISD::FSUB, MVT::f16, Promote);
328 setOperationAction(ISD::FMUL, MVT::f16, Promote);
329 setOperationAction(ISD::FDIV, MVT::f16, Promote);
330 setOperationAction(ISD::FREM, MVT::f16, Promote);
331 setOperationAction(ISD::FMA, MVT::f16, Promote);
332 setOperationAction(ISD::FNEG, MVT::f16, Promote);
333 setOperationAction(ISD::FABS, MVT::f16, Promote);
334 setOperationAction(ISD::FCEIL, MVT::f16, Promote);
335 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote);
336 setOperationAction(ISD::FCOS, MVT::f16, Promote);
337 setOperationAction(ISD::FFLOOR, MVT::f16, Promote);
338 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote);
339 setOperationAction(ISD::FPOW, MVT::f16, Promote);
340 setOperationAction(ISD::FPOWI, MVT::f16, Promote);
341 setOperationAction(ISD::FRINT, MVT::f16, Promote);
342 setOperationAction(ISD::FSIN, MVT::f16, Promote);
343 setOperationAction(ISD::FSINCOS, MVT::f16, Promote);
344 setOperationAction(ISD::FSQRT, MVT::f16, Promote);
345 setOperationAction(ISD::FEXP, MVT::f16, Promote);
346 setOperationAction(ISD::FEXP2, MVT::f16, Promote);
347 setOperationAction(ISD::FLOG, MVT::f16, Promote);
348 setOperationAction(ISD::FLOG2, MVT::f16, Promote);
349 setOperationAction(ISD::FLOG10, MVT::f16, Promote);
350 setOperationAction(ISD::FROUND, MVT::f16, Promote);
351 setOperationAction(ISD::FTRUNC, MVT::f16, Promote);
352 setOperationAction(ISD::FMINNUM, MVT::f16, Promote);
353 setOperationAction(ISD::FMAXNUM, MVT::f16, Promote);
354 setOperationAction(ISD::FMINNAN, MVT::f16, Promote);
355 setOperationAction(ISD::FMAXNAN, MVT::f16, Promote);
357 // v4f16 is also a storage-only type, so promote it to v4f32 when that is
359 setOperationAction(ISD::FADD, MVT::v4f16, Promote);
360 setOperationAction(ISD::FSUB, MVT::v4f16, Promote);
361 setOperationAction(ISD::FMUL, MVT::v4f16, Promote);
362 setOperationAction(ISD::FDIV, MVT::v4f16, Promote);
363 setOperationAction(ISD::FP_EXTEND, MVT::v4f16, Promote);
364 setOperationAction(ISD::FP_ROUND, MVT::v4f16, Promote);
365 AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32);
366 AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32);
367 AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32);
368 AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32);
369 AddPromotedToType(ISD::FP_EXTEND, MVT::v4f16, MVT::v4f32);
370 AddPromotedToType(ISD::FP_ROUND, MVT::v4f16, MVT::v4f32);
372 // Expand all other v4f16 operations.
373 // FIXME: We could generate better code by promoting some operations to
375 setOperationAction(ISD::FABS, MVT::v4f16, Expand);
376 setOperationAction(ISD::FCEIL, MVT::v4f16, Expand);
377 setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand);
378 setOperationAction(ISD::FCOS, MVT::v4f16, Expand);
379 setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand);
380 setOperationAction(ISD::FMA, MVT::v4f16, Expand);
381 setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand);
382 setOperationAction(ISD::FNEG, MVT::v4f16, Expand);
383 setOperationAction(ISD::FPOW, MVT::v4f16, Expand);
384 setOperationAction(ISD::FREM, MVT::v4f16, Expand);
385 setOperationAction(ISD::FROUND, MVT::v4f16, Expand);
386 setOperationAction(ISD::FRINT, MVT::v4f16, Expand);
387 setOperationAction(ISD::FSIN, MVT::v4f16, Expand);
388 setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand);
389 setOperationAction(ISD::FSQRT, MVT::v4f16, Expand);
390 setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand);
391 setOperationAction(ISD::SETCC, MVT::v4f16, Expand);
392 setOperationAction(ISD::BR_CC, MVT::v4f16, Expand);
393 setOperationAction(ISD::SELECT, MVT::v4f16, Expand);
394 setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand);
395 setOperationAction(ISD::FEXP, MVT::v4f16, Expand);
396 setOperationAction(ISD::FEXP2, MVT::v4f16, Expand);
397 setOperationAction(ISD::FLOG, MVT::v4f16, Expand);
398 setOperationAction(ISD::FLOG2, MVT::v4f16, Expand);
399 setOperationAction(ISD::FLOG10, MVT::v4f16, Expand);
402 // v8f16 is also a storage-only type, so expand it.
403 setOperationAction(ISD::FABS, MVT::v8f16, Expand);
404 setOperationAction(ISD::FADD, MVT::v8f16, Expand);
405 setOperationAction(ISD::FCEIL, MVT::v8f16, Expand);
406 setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand);
407 setOperationAction(ISD::FCOS, MVT::v8f16, Expand);
408 setOperationAction(ISD::FDIV, MVT::v8f16, Expand);
409 setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand);
410 setOperationAction(ISD::FMA, MVT::v8f16, Expand);
411 setOperationAction(ISD::FMUL, MVT::v8f16, Expand);
412 setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand);
413 setOperationAction(ISD::FNEG, MVT::v8f16, Expand);
414 setOperationAction(ISD::FPOW, MVT::v8f16, Expand);
415 setOperationAction(ISD::FREM, MVT::v8f16, Expand);
416 setOperationAction(ISD::FROUND, MVT::v8f16, Expand);
417 setOperationAction(ISD::FRINT, MVT::v8f16, Expand);
418 setOperationAction(ISD::FSIN, MVT::v8f16, Expand);
419 setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
420 setOperationAction(ISD::FSQRT, MVT::v8f16, Expand);
421 setOperationAction(ISD::FSUB, MVT::v8f16, Expand);
422 setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand);
423 setOperationAction(ISD::SETCC, MVT::v8f16, Expand);
424 setOperationAction(ISD::BR_CC, MVT::v8f16, Expand);
425 setOperationAction(ISD::SELECT, MVT::v8f16, Expand);
426 setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand);
427 setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand);
428 setOperationAction(ISD::FEXP, MVT::v8f16, Expand);
429 setOperationAction(ISD::FEXP2, MVT::v8f16, Expand);
430 setOperationAction(ISD::FLOG, MVT::v8f16, Expand);
431 setOperationAction(ISD::FLOG2, MVT::v8f16, Expand);
432 setOperationAction(ISD::FLOG10, MVT::v8f16, Expand);
434 // AArch64 has implementations of a lot of rounding-like FP operations.
435 for (MVT Ty : {MVT::f32, MVT::f64}) {
436 setOperationAction(ISD::FFLOOR, Ty, Legal);
437 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
438 setOperationAction(ISD::FCEIL, Ty, Legal);
439 setOperationAction(ISD::FRINT, Ty, Legal);
440 setOperationAction(ISD::FTRUNC, Ty, Legal);
441 setOperationAction(ISD::FROUND, Ty, Legal);
442 setOperationAction(ISD::FMINNUM, Ty, Legal);
443 setOperationAction(ISD::FMAXNUM, Ty, Legal);
444 setOperationAction(ISD::FMINNAN, Ty, Legal);
445 setOperationAction(ISD::FMAXNAN, Ty, Legal);
448 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
450 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
452 // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
453 // This requires the Performance Monitors extension.
454 if (Subtarget->hasPerfMon())
455 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
457 if (Subtarget->isTargetMachO()) {
458 // For iOS, we don't want to the normal expansion of a libcall to
459 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
461 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
462 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
464 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
465 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
468 // Make floating-point constants legal for the large code model, so they don't
469 // become loads from the constant pool.
470 if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
471 setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
472 setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
475 // AArch64 does not have floating-point extending loads, i1 sign-extending
476 // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
477 for (MVT VT : MVT::fp_valuetypes()) {
478 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
479 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
480 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
481 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
483 for (MVT VT : MVT::integer_valuetypes())
484 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
486 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
487 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
488 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
489 setTruncStoreAction(MVT::f128, MVT::f80, Expand);
490 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
491 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
492 setTruncStoreAction(MVT::f128, MVT::f16, Expand);
494 setOperationAction(ISD::BITCAST, MVT::i16, Custom);
495 setOperationAction(ISD::BITCAST, MVT::f16, Custom);
497 // Indexed loads and stores are supported.
498 for (unsigned im = (unsigned)ISD::PRE_INC;
499 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
500 setIndexedLoadAction(im, MVT::i8, Legal);
501 setIndexedLoadAction(im, MVT::i16, Legal);
502 setIndexedLoadAction(im, MVT::i32, Legal);
503 setIndexedLoadAction(im, MVT::i64, Legal);
504 setIndexedLoadAction(im, MVT::f64, Legal);
505 setIndexedLoadAction(im, MVT::f32, Legal);
506 setIndexedLoadAction(im, MVT::f16, Legal);
507 setIndexedStoreAction(im, MVT::i8, Legal);
508 setIndexedStoreAction(im, MVT::i16, Legal);
509 setIndexedStoreAction(im, MVT::i32, Legal);
510 setIndexedStoreAction(im, MVT::i64, Legal);
511 setIndexedStoreAction(im, MVT::f64, Legal);
512 setIndexedStoreAction(im, MVT::f32, Legal);
513 setIndexedStoreAction(im, MVT::f16, Legal);
517 setOperationAction(ISD::TRAP, MVT::Other, Legal);
519 // We combine OR nodes for bitfield operations.
520 setTargetDAGCombine(ISD::OR);
522 // Vector add and sub nodes may conceal a high-half opportunity.
523 // Also, try to fold ADD into CSINC/CSINV..
524 setTargetDAGCombine(ISD::ADD);
525 setTargetDAGCombine(ISD::SUB);
526 setTargetDAGCombine(ISD::SRL);
527 setTargetDAGCombine(ISD::XOR);
528 setTargetDAGCombine(ISD::SINT_TO_FP);
529 setTargetDAGCombine(ISD::UINT_TO_FP);
531 setTargetDAGCombine(ISD::FP_TO_SINT);
532 setTargetDAGCombine(ISD::FP_TO_UINT);
533 setTargetDAGCombine(ISD::FDIV);
535 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
537 setTargetDAGCombine(ISD::ANY_EXTEND);
538 setTargetDAGCombine(ISD::ZERO_EXTEND);
539 setTargetDAGCombine(ISD::SIGN_EXTEND);
540 setTargetDAGCombine(ISD::BITCAST);
541 setTargetDAGCombine(ISD::CONCAT_VECTORS);
542 setTargetDAGCombine(ISD::STORE);
543 if (Subtarget->supportsAddressTopByteIgnored())
544 setTargetDAGCombine(ISD::LOAD);
546 setTargetDAGCombine(ISD::MUL);
548 setTargetDAGCombine(ISD::SELECT);
549 setTargetDAGCombine(ISD::VSELECT);
551 setTargetDAGCombine(ISD::INTRINSIC_VOID);
552 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
553 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
555 MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 8;
556 MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 4;
557 MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = 4;
559 setStackPointerRegisterToSaveRestore(AArch64::SP);
561 setSchedulingPreference(Sched::Hybrid);
563 EnableExtLdPromotion = true;
565 // Set required alignment.
566 setMinFunctionAlignment(2);
567 // Set preferred alignments.
568 setPrefFunctionAlignment(STI.getPrefFunctionAlignment());
569 setPrefLoopAlignment(STI.getPrefLoopAlignment());
571 // Only change the limit for entries in a jump table if specified by
572 // the subtarget, but not at the command line.
573 unsigned MaxJT = STI.getMaximumJumpTableSize();
574 if (MaxJT && getMaximumJumpTableSize() == 0)
575 setMaximumJumpTableSize(MaxJT);
577 setHasExtractBitsInsn(true);
579 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
581 if (Subtarget->hasNEON()) {
582 // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
583 // silliness like this:
584 setOperationAction(ISD::FABS, MVT::v1f64, Expand);
585 setOperationAction(ISD::FADD, MVT::v1f64, Expand);
586 setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
587 setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
588 setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
589 setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
590 setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
591 setOperationAction(ISD::FMA, MVT::v1f64, Expand);
592 setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
593 setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
594 setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
595 setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
596 setOperationAction(ISD::FREM, MVT::v1f64, Expand);
597 setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
598 setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
599 setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
600 setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
601 setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
602 setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
603 setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
604 setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
605 setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
606 setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
607 setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
608 setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
610 setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
611 setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
612 setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
613 setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
614 setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
616 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
618 // AArch64 doesn't have a direct vector ->f32 conversion instructions for
619 // elements smaller than i32, so promote the input to i32 first.
620 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Promote);
621 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Promote);
622 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Promote);
623 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Promote);
624 // i8 and i16 vector elements also need promotion to i32 for v8i8 or v8i16
625 // -> v8f16 conversions.
626 setOperationAction(ISD::SINT_TO_FP, MVT::v8i8, Promote);
627 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Promote);
628 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
629 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Promote);
630 // Similarly, there is no direct i32 -> f64 vector conversion instruction.
631 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
632 setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
633 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
634 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
635 // Or, direct i32 -> f16 vector conversion. Set it so custom, so the
636 // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
637 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
638 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
640 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand);
641 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand);
643 setOperationAction(ISD::CTTZ, MVT::v2i8, Expand);
644 setOperationAction(ISD::CTTZ, MVT::v4i16, Expand);
645 setOperationAction(ISD::CTTZ, MVT::v2i32, Expand);
646 setOperationAction(ISD::CTTZ, MVT::v1i64, Expand);
647 setOperationAction(ISD::CTTZ, MVT::v16i8, Expand);
648 setOperationAction(ISD::CTTZ, MVT::v8i16, Expand);
649 setOperationAction(ISD::CTTZ, MVT::v4i32, Expand);
650 setOperationAction(ISD::CTTZ, MVT::v2i64, Expand);
652 // AArch64 doesn't have MUL.2d:
653 setOperationAction(ISD::MUL, MVT::v2i64, Expand);
654 // Custom handling for some quad-vector types to detect MULL.
655 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
656 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
657 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
660 for (MVT VT : MVT::integer_valuetypes()) {
661 setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
662 setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
663 setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
664 setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
665 setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
667 for (MVT VT : MVT::fp_valuetypes()) {
668 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
669 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
672 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
673 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
674 // Likewise, narrowing and extending vector loads/stores aren't handled
676 for (MVT VT : MVT::vector_valuetypes()) {
677 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
679 setOperationAction(ISD::MULHS, VT, Expand);
680 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
681 setOperationAction(ISD::MULHU, VT, Expand);
682 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
684 setOperationAction(ISD::BSWAP, VT, Expand);
686 for (MVT InnerVT : MVT::vector_valuetypes()) {
687 setTruncStoreAction(VT, InnerVT, Expand);
688 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
689 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
690 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
694 // AArch64 has implementations of a lot of rounding-like FP operations.
695 for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
696 setOperationAction(ISD::FFLOOR, Ty, Legal);
697 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
698 setOperationAction(ISD::FCEIL, Ty, Legal);
699 setOperationAction(ISD::FRINT, Ty, Legal);
700 setOperationAction(ISD::FTRUNC, Ty, Legal);
701 setOperationAction(ISD::FROUND, Ty, Legal);
705 PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive();
708 void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) {
709 if (VT == MVT::v2f32 || VT == MVT::v4f16) {
710 setOperationAction(ISD::LOAD, VT, Promote);
711 AddPromotedToType(ISD::LOAD, VT, MVT::v2i32);
713 setOperationAction(ISD::STORE, VT, Promote);
714 AddPromotedToType(ISD::STORE, VT, MVT::v2i32);
715 } else if (VT == MVT::v2f64 || VT == MVT::v4f32 || VT == MVT::v8f16) {
716 setOperationAction(ISD::LOAD, VT, Promote);
717 AddPromotedToType(ISD::LOAD, VT, MVT::v2i64);
719 setOperationAction(ISD::STORE, VT, Promote);
720 AddPromotedToType(ISD::STORE, VT, MVT::v2i64);
723 // Mark vector float intrinsics as expand.
724 if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
725 setOperationAction(ISD::FSIN, VT, Expand);
726 setOperationAction(ISD::FCOS, VT, Expand);
727 setOperationAction(ISD::FPOW, VT, Expand);
728 setOperationAction(ISD::FLOG, VT, Expand);
729 setOperationAction(ISD::FLOG2, VT, Expand);
730 setOperationAction(ISD::FLOG10, VT, Expand);
731 setOperationAction(ISD::FEXP, VT, Expand);
732 setOperationAction(ISD::FEXP2, VT, Expand);
734 // But we do support custom-lowering for FCOPYSIGN.
735 setOperationAction(ISD::FCOPYSIGN, VT, Custom);
738 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
739 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
740 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
741 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
742 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
743 setOperationAction(ISD::SRA, VT, Custom);
744 setOperationAction(ISD::SRL, VT, Custom);
745 setOperationAction(ISD::SHL, VT, Custom);
746 setOperationAction(ISD::AND, VT, Custom);
747 setOperationAction(ISD::OR, VT, Custom);
748 setOperationAction(ISD::SETCC, VT, Custom);
749 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
751 setOperationAction(ISD::SELECT, VT, Expand);
752 setOperationAction(ISD::SELECT_CC, VT, Expand);
753 setOperationAction(ISD::VSELECT, VT, Expand);
754 for (MVT InnerVT : MVT::all_valuetypes())
755 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
757 // CNT supports only B element sizes.
758 if (VT != MVT::v8i8 && VT != MVT::v16i8)
759 setOperationAction(ISD::CTPOP, VT, Expand);
761 setOperationAction(ISD::UDIV, VT, Expand);
762 setOperationAction(ISD::SDIV, VT, Expand);
763 setOperationAction(ISD::UREM, VT, Expand);
764 setOperationAction(ISD::SREM, VT, Expand);
765 setOperationAction(ISD::FREM, VT, Expand);
767 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
768 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
770 if (!VT.isFloatingPoint())
771 setOperationAction(ISD::ABS, VT, Legal);
773 // [SU][MIN|MAX] are available for all NEON types apart from i64.
774 if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64)
775 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
776 setOperationAction(Opcode, VT, Legal);
778 // F[MIN|MAX][NUM|NAN] are available for all FP NEON types (not f16 though!).
779 if (VT.isFloatingPoint() && VT.getVectorElementType() != MVT::f16)
780 for (unsigned Opcode : {ISD::FMINNAN, ISD::FMAXNAN,
781 ISD::FMINNUM, ISD::FMAXNUM})
782 setOperationAction(Opcode, VT, Legal);
784 if (Subtarget->isLittleEndian()) {
785 for (unsigned im = (unsigned)ISD::PRE_INC;
786 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
787 setIndexedLoadAction(im, VT, Legal);
788 setIndexedStoreAction(im, VT, Legal);
793 void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
794 addRegisterClass(VT, &AArch64::FPR64RegClass);
795 addTypeForNEON(VT, MVT::v2i32);
798 void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
799 addRegisterClass(VT, &AArch64::FPR128RegClass);
800 addTypeForNEON(VT, MVT::v4i32);
803 EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
807 return VT.changeVectorElementTypeToInteger();
810 static bool optimizeLogicalImm(SDValue Op, unsigned Size, uint64_t Imm,
811 const APInt &Demanded,
812 TargetLowering::TargetLoweringOpt &TLO,
814 uint64_t OldImm = Imm, NewImm, Enc;
815 uint64_t Mask = ((uint64_t)(-1LL) >> (64 - Size)), OrigMask = Mask;
817 // Return if the immediate is already all zeros, all ones, a bimm32 or a
819 if (Imm == 0 || Imm == Mask ||
820 AArch64_AM::isLogicalImmediate(Imm & Mask, Size))
823 unsigned EltSize = Size;
824 uint64_t DemandedBits = Demanded.getZExtValue();
826 // Clear bits that are not demanded.
830 // The goal here is to set the non-demanded bits in a way that minimizes
831 // the number of switching between 0 and 1. In order to achieve this goal,
832 // we set the non-demanded bits to the value of the preceding demanded bits.
833 // For example, if we have an immediate 0bx10xx0x1 ('x' indicates a
834 // non-demanded bit), we copy bit0 (1) to the least significant 'x',
835 // bit2 (0) to 'xx', and bit6 (1) to the most significant 'x'.
836 // The final result is 0b11000011.
837 uint64_t NonDemandedBits = ~DemandedBits;
838 uint64_t InvertedImm = ~Imm & DemandedBits;
839 uint64_t RotatedImm =
840 ((InvertedImm << 1) | (InvertedImm >> (EltSize - 1) & 1)) &
842 uint64_t Sum = RotatedImm + NonDemandedBits;
843 bool Carry = NonDemandedBits & ~Sum & (1ULL << (EltSize - 1));
844 uint64_t Ones = (Sum + Carry) & NonDemandedBits;
845 NewImm = (Imm | Ones) & Mask;
847 // If NewImm or its bitwise NOT is a shifted mask, it is a bitmask immediate
848 // or all-ones or all-zeros, in which case we can stop searching. Otherwise,
849 // we halve the element size and continue the search.
850 if (isShiftedMask_64(NewImm) || isShiftedMask_64(~(NewImm | ~Mask)))
853 // We cannot shrink the element size any further if it is 2-bits.
859 uint64_t Hi = Imm >> EltSize, DemandedBitsHi = DemandedBits >> EltSize;
861 // Return if there is mismatch in any of the demanded bits of Imm and Hi.
862 if (((Imm ^ Hi) & (DemandedBits & DemandedBitsHi) & Mask) != 0)
865 // Merge the upper and lower halves of Imm and DemandedBits.
867 DemandedBits |= DemandedBitsHi;
872 // Replicate the element across the register width.
873 while (EltSize < Size) {
874 NewImm |= NewImm << EltSize;
879 assert(((OldImm ^ NewImm) & Demanded.getZExtValue()) == 0 &&
880 "demanded bits should never be altered");
881 assert(OldImm != NewImm && "the new imm shouldn't be equal to the old imm");
883 // Create the new constant immediate node.
884 EVT VT = Op.getValueType();
888 // If the new constant immediate is all-zeros or all-ones, let the target
889 // independent DAG combine optimize this node.
890 if (NewImm == 0 || NewImm == OrigMask) {
891 New = TLO.DAG.getNode(Op.getOpcode(), DL, VT, Op.getOperand(0),
892 TLO.DAG.getConstant(NewImm, DL, VT));
893 // Otherwise, create a machine node so that target independent DAG combine
894 // doesn't undo this optimization.
896 Enc = AArch64_AM::encodeLogicalImmediate(NewImm, Size);
897 SDValue EncConst = TLO.DAG.getTargetConstant(Enc, DL, VT);
899 TLO.DAG.getMachineNode(NewOpc, DL, VT, Op.getOperand(0), EncConst), 0);
902 return TLO.CombineTo(Op, New);
905 bool AArch64TargetLowering::targetShrinkDemandedConstant(
906 SDValue Op, const APInt &Demanded, TargetLoweringOpt &TLO) const {
907 // Delay this optimization to as late as possible.
911 if (!EnableOptimizeLogicalImm)
914 EVT VT = Op.getValueType();
918 unsigned Size = VT.getSizeInBits();
919 assert((Size == 32 || Size == 64) &&
920 "i32 or i64 is expected after legalization.");
922 // Exit early if we demand all bits.
923 if (Demanded.countPopulation() == Size)
927 switch (Op.getOpcode()) {
931 NewOpc = Size == 32 ? AArch64::ANDWri : AArch64::ANDXri;
934 NewOpc = Size == 32 ? AArch64::ORRWri : AArch64::ORRXri;
937 NewOpc = Size == 32 ? AArch64::EORWri : AArch64::EORXri;
940 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
943 uint64_t Imm = C->getZExtValue();
944 return optimizeLogicalImm(Op, Size, Imm, Demanded, TLO, NewOpc);
947 /// computeKnownBitsForTargetNode - Determine which of the bits specified in
948 /// Mask are known to be either zero or one and return them Known.
949 void AArch64TargetLowering::computeKnownBitsForTargetNode(
950 const SDValue Op, KnownBits &Known,
951 const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const {
952 switch (Op.getOpcode()) {
955 case AArch64ISD::CSEL: {
957 DAG.computeKnownBits(Op->getOperand(0), Known, Depth + 1);
958 DAG.computeKnownBits(Op->getOperand(1), Known2, Depth + 1);
959 Known.Zero &= Known2.Zero;
960 Known.One &= Known2.One;
963 case ISD::INTRINSIC_W_CHAIN: {
964 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
965 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
968 case Intrinsic::aarch64_ldaxr:
969 case Intrinsic::aarch64_ldxr: {
970 unsigned BitWidth = Known.getBitWidth();
971 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
972 unsigned MemBits = VT.getScalarSizeInBits();
973 Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
979 case ISD::INTRINSIC_WO_CHAIN:
980 case ISD::INTRINSIC_VOID: {
981 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
985 case Intrinsic::aarch64_neon_umaxv:
986 case Intrinsic::aarch64_neon_uminv: {
987 // Figure out the datatype of the vector operand. The UMINV instruction
988 // will zero extend the result, so we can mark as known zero all the
989 // bits larger than the element datatype. 32-bit or larget doesn't need
990 // this as those are legal types and will be handled by isel directly.
991 MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
992 unsigned BitWidth = Known.getBitWidth();
993 if (VT == MVT::v8i8 || VT == MVT::v16i8) {
994 assert(BitWidth >= 8 && "Unexpected width!");
995 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
997 } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
998 assert(BitWidth >= 16 && "Unexpected width!");
999 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
1009 MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
1014 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1018 if (Subtarget->requiresStrictAlign())
1022 // Some CPUs are fine with unaligned stores except for 128-bit ones.
1023 *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 ||
1024 // See comments in performSTORECombine() for more details about
1025 // these conditions.
1027 // Code that uses clang vector extensions can mark that it
1028 // wants unaligned accesses to be treated as fast by
1029 // underspecifying alignment to be 1 or 2.
1032 // Disregard v2i64. Memcpy lowering produces those and splitting
1033 // them regresses performance on micro-benchmarks and olden/bh.
1040 AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1041 const TargetLibraryInfo *libInfo) const {
1042 return AArch64::createFastISel(funcInfo, libInfo);
1045 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
1046 switch ((AArch64ISD::NodeType)Opcode) {
1047 case AArch64ISD::FIRST_NUMBER: break;
1048 case AArch64ISD::CALL: return "AArch64ISD::CALL";
1049 case AArch64ISD::ADRP: return "AArch64ISD::ADRP";
1050 case AArch64ISD::ADDlow: return "AArch64ISD::ADDlow";
1051 case AArch64ISD::LOADgot: return "AArch64ISD::LOADgot";
1052 case AArch64ISD::RET_FLAG: return "AArch64ISD::RET_FLAG";
1053 case AArch64ISD::BRCOND: return "AArch64ISD::BRCOND";
1054 case AArch64ISD::CSEL: return "AArch64ISD::CSEL";
1055 case AArch64ISD::FCSEL: return "AArch64ISD::FCSEL";
1056 case AArch64ISD::CSINV: return "AArch64ISD::CSINV";
1057 case AArch64ISD::CSNEG: return "AArch64ISD::CSNEG";
1058 case AArch64ISD::CSINC: return "AArch64ISD::CSINC";
1059 case AArch64ISD::THREAD_POINTER: return "AArch64ISD::THREAD_POINTER";
1060 case AArch64ISD::TLSDESC_CALLSEQ: return "AArch64ISD::TLSDESC_CALLSEQ";
1061 case AArch64ISD::ADC: return "AArch64ISD::ADC";
1062 case AArch64ISD::SBC: return "AArch64ISD::SBC";
1063 case AArch64ISD::ADDS: return "AArch64ISD::ADDS";
1064 case AArch64ISD::SUBS: return "AArch64ISD::SUBS";
1065 case AArch64ISD::ADCS: return "AArch64ISD::ADCS";
1066 case AArch64ISD::SBCS: return "AArch64ISD::SBCS";
1067 case AArch64ISD::ANDS: return "AArch64ISD::ANDS";
1068 case AArch64ISD::CCMP: return "AArch64ISD::CCMP";
1069 case AArch64ISD::CCMN: return "AArch64ISD::CCMN";
1070 case AArch64ISD::FCCMP: return "AArch64ISD::FCCMP";
1071 case AArch64ISD::FCMP: return "AArch64ISD::FCMP";
1072 case AArch64ISD::DUP: return "AArch64ISD::DUP";
1073 case AArch64ISD::DUPLANE8: return "AArch64ISD::DUPLANE8";
1074 case AArch64ISD::DUPLANE16: return "AArch64ISD::DUPLANE16";
1075 case AArch64ISD::DUPLANE32: return "AArch64ISD::DUPLANE32";
1076 case AArch64ISD::DUPLANE64: return "AArch64ISD::DUPLANE64";
1077 case AArch64ISD::MOVI: return "AArch64ISD::MOVI";
1078 case AArch64ISD::MOVIshift: return "AArch64ISD::MOVIshift";
1079 case AArch64ISD::MOVIedit: return "AArch64ISD::MOVIedit";
1080 case AArch64ISD::MOVImsl: return "AArch64ISD::MOVImsl";
1081 case AArch64ISD::FMOV: return "AArch64ISD::FMOV";
1082 case AArch64ISD::MVNIshift: return "AArch64ISD::MVNIshift";
1083 case AArch64ISD::MVNImsl: return "AArch64ISD::MVNImsl";
1084 case AArch64ISD::BICi: return "AArch64ISD::BICi";
1085 case AArch64ISD::ORRi: return "AArch64ISD::ORRi";
1086 case AArch64ISD::BSL: return "AArch64ISD::BSL";
1087 case AArch64ISD::NEG: return "AArch64ISD::NEG";
1088 case AArch64ISD::EXTR: return "AArch64ISD::EXTR";
1089 case AArch64ISD::ZIP1: return "AArch64ISD::ZIP1";
1090 case AArch64ISD::ZIP2: return "AArch64ISD::ZIP2";
1091 case AArch64ISD::UZP1: return "AArch64ISD::UZP1";
1092 case AArch64ISD::UZP2: return "AArch64ISD::UZP2";
1093 case AArch64ISD::TRN1: return "AArch64ISD::TRN1";
1094 case AArch64ISD::TRN2: return "AArch64ISD::TRN2";
1095 case AArch64ISD::REV16: return "AArch64ISD::REV16";
1096 case AArch64ISD::REV32: return "AArch64ISD::REV32";
1097 case AArch64ISD::REV64: return "AArch64ISD::REV64";
1098 case AArch64ISD::EXT: return "AArch64ISD::EXT";
1099 case AArch64ISD::VSHL: return "AArch64ISD::VSHL";
1100 case AArch64ISD::VLSHR: return "AArch64ISD::VLSHR";
1101 case AArch64ISD::VASHR: return "AArch64ISD::VASHR";
1102 case AArch64ISD::CMEQ: return "AArch64ISD::CMEQ";
1103 case AArch64ISD::CMGE: return "AArch64ISD::CMGE";
1104 case AArch64ISD::CMGT: return "AArch64ISD::CMGT";
1105 case AArch64ISD::CMHI: return "AArch64ISD::CMHI";
1106 case AArch64ISD::CMHS: return "AArch64ISD::CMHS";
1107 case AArch64ISD::FCMEQ: return "AArch64ISD::FCMEQ";
1108 case AArch64ISD::FCMGE: return "AArch64ISD::FCMGE";
1109 case AArch64ISD::FCMGT: return "AArch64ISD::FCMGT";
1110 case AArch64ISD::CMEQz: return "AArch64ISD::CMEQz";
1111 case AArch64ISD::CMGEz: return "AArch64ISD::CMGEz";
1112 case AArch64ISD::CMGTz: return "AArch64ISD::CMGTz";
1113 case AArch64ISD::CMLEz: return "AArch64ISD::CMLEz";
1114 case AArch64ISD::CMLTz: return "AArch64ISD::CMLTz";
1115 case AArch64ISD::FCMEQz: return "AArch64ISD::FCMEQz";
1116 case AArch64ISD::FCMGEz: return "AArch64ISD::FCMGEz";
1117 case AArch64ISD::FCMGTz: return "AArch64ISD::FCMGTz";
1118 case AArch64ISD::FCMLEz: return "AArch64ISD::FCMLEz";
1119 case AArch64ISD::FCMLTz: return "AArch64ISD::FCMLTz";
1120 case AArch64ISD::SADDV: return "AArch64ISD::SADDV";
1121 case AArch64ISD::UADDV: return "AArch64ISD::UADDV";
1122 case AArch64ISD::SMINV: return "AArch64ISD::SMINV";
1123 case AArch64ISD::UMINV: return "AArch64ISD::UMINV";
1124 case AArch64ISD::SMAXV: return "AArch64ISD::SMAXV";
1125 case AArch64ISD::UMAXV: return "AArch64ISD::UMAXV";
1126 case AArch64ISD::NOT: return "AArch64ISD::NOT";
1127 case AArch64ISD::BIT: return "AArch64ISD::BIT";
1128 case AArch64ISD::CBZ: return "AArch64ISD::CBZ";
1129 case AArch64ISD::CBNZ: return "AArch64ISD::CBNZ";
1130 case AArch64ISD::TBZ: return "AArch64ISD::TBZ";
1131 case AArch64ISD::TBNZ: return "AArch64ISD::TBNZ";
1132 case AArch64ISD::TC_RETURN: return "AArch64ISD::TC_RETURN";
1133 case AArch64ISD::PREFETCH: return "AArch64ISD::PREFETCH";
1134 case AArch64ISD::SITOF: return "AArch64ISD::SITOF";
1135 case AArch64ISD::UITOF: return "AArch64ISD::UITOF";
1136 case AArch64ISD::NVCAST: return "AArch64ISD::NVCAST";
1137 case AArch64ISD::SQSHL_I: return "AArch64ISD::SQSHL_I";
1138 case AArch64ISD::UQSHL_I: return "AArch64ISD::UQSHL_I";
1139 case AArch64ISD::SRSHR_I: return "AArch64ISD::SRSHR_I";
1140 case AArch64ISD::URSHR_I: return "AArch64ISD::URSHR_I";
1141 case AArch64ISD::SQSHLU_I: return "AArch64ISD::SQSHLU_I";
1142 case AArch64ISD::WrapperLarge: return "AArch64ISD::WrapperLarge";
1143 case AArch64ISD::LD2post: return "AArch64ISD::LD2post";
1144 case AArch64ISD::LD3post: return "AArch64ISD::LD3post";
1145 case AArch64ISD::LD4post: return "AArch64ISD::LD4post";
1146 case AArch64ISD::ST2post: return "AArch64ISD::ST2post";
1147 case AArch64ISD::ST3post: return "AArch64ISD::ST3post";
1148 case AArch64ISD::ST4post: return "AArch64ISD::ST4post";
1149 case AArch64ISD::LD1x2post: return "AArch64ISD::LD1x2post";
1150 case AArch64ISD::LD1x3post: return "AArch64ISD::LD1x3post";
1151 case AArch64ISD::LD1x4post: return "AArch64ISD::LD1x4post";
1152 case AArch64ISD::ST1x2post: return "AArch64ISD::ST1x2post";
1153 case AArch64ISD::ST1x3post: return "AArch64ISD::ST1x3post";
1154 case AArch64ISD::ST1x4post: return "AArch64ISD::ST1x4post";
1155 case AArch64ISD::LD1DUPpost: return "AArch64ISD::LD1DUPpost";
1156 case AArch64ISD::LD2DUPpost: return "AArch64ISD::LD2DUPpost";
1157 case AArch64ISD::LD3DUPpost: return "AArch64ISD::LD3DUPpost";
1158 case AArch64ISD::LD4DUPpost: return "AArch64ISD::LD4DUPpost";
1159 case AArch64ISD::LD1LANEpost: return "AArch64ISD::LD1LANEpost";
1160 case AArch64ISD::LD2LANEpost: return "AArch64ISD::LD2LANEpost";
1161 case AArch64ISD::LD3LANEpost: return "AArch64ISD::LD3LANEpost";
1162 case AArch64ISD::LD4LANEpost: return "AArch64ISD::LD4LANEpost";
1163 case AArch64ISD::ST2LANEpost: return "AArch64ISD::ST2LANEpost";
1164 case AArch64ISD::ST3LANEpost: return "AArch64ISD::ST3LANEpost";
1165 case AArch64ISD::ST4LANEpost: return "AArch64ISD::ST4LANEpost";
1166 case AArch64ISD::SMULL: return "AArch64ISD::SMULL";
1167 case AArch64ISD::UMULL: return "AArch64ISD::UMULL";
1168 case AArch64ISD::FRECPE: return "AArch64ISD::FRECPE";
1169 case AArch64ISD::FRECPS: return "AArch64ISD::FRECPS";
1170 case AArch64ISD::FRSQRTE: return "AArch64ISD::FRSQRTE";
1171 case AArch64ISD::FRSQRTS: return "AArch64ISD::FRSQRTS";
1177 AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI,
1178 MachineBasicBlock *MBB) const {
1179 // We materialise the F128CSEL pseudo-instruction as some control flow and a
1183 // [... previous instrs leading to comparison ...]
1189 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
1191 MachineFunction *MF = MBB->getParent();
1192 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1193 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
1194 DebugLoc DL = MI.getDebugLoc();
1195 MachineFunction::iterator It = ++MBB->getIterator();
1197 unsigned DestReg = MI.getOperand(0).getReg();
1198 unsigned IfTrueReg = MI.getOperand(1).getReg();
1199 unsigned IfFalseReg = MI.getOperand(2).getReg();
1200 unsigned CondCode = MI.getOperand(3).getImm();
1201 bool NZCVKilled = MI.getOperand(4).isKill();
1203 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
1204 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
1205 MF->insert(It, TrueBB);
1206 MF->insert(It, EndBB);
1208 // Transfer rest of current basic-block to EndBB
1209 EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
1211 EndBB->transferSuccessorsAndUpdatePHIs(MBB);
1213 BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
1214 BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
1215 MBB->addSuccessor(TrueBB);
1216 MBB->addSuccessor(EndBB);
1218 // TrueBB falls through to the end.
1219 TrueBB->addSuccessor(EndBB);
1222 TrueBB->addLiveIn(AArch64::NZCV);
1223 EndBB->addLiveIn(AArch64::NZCV);
1226 BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
1232 MI.eraseFromParent();
1236 MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter(
1237 MachineInstr &MI, MachineBasicBlock *BB) const {
1238 switch (MI.getOpcode()) {
1243 llvm_unreachable("Unexpected instruction for custom inserter!");
1245 case AArch64::F128CSEL:
1246 return EmitF128CSEL(MI, BB);
1248 case TargetOpcode::STACKMAP:
1249 case TargetOpcode::PATCHPOINT:
1250 return emitPatchPoint(MI, BB);
1254 //===----------------------------------------------------------------------===//
1255 // AArch64 Lowering private implementation.
1256 //===----------------------------------------------------------------------===//
1258 //===----------------------------------------------------------------------===//
1260 //===----------------------------------------------------------------------===//
1262 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1264 static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1267 llvm_unreachable("Unknown condition code!");
1269 return AArch64CC::NE;
1271 return AArch64CC::EQ;
1273 return AArch64CC::GT;
1275 return AArch64CC::GE;
1277 return AArch64CC::LT;
1279 return AArch64CC::LE;
1281 return AArch64CC::HI;
1283 return AArch64CC::HS;
1285 return AArch64CC::LO;
1287 return AArch64CC::LS;
1291 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1292 static void changeFPCCToAArch64CC(ISD::CondCode CC,
1293 AArch64CC::CondCode &CondCode,
1294 AArch64CC::CondCode &CondCode2) {
1295 CondCode2 = AArch64CC::AL;
1298 llvm_unreachable("Unknown FP condition!");
1301 CondCode = AArch64CC::EQ;
1305 CondCode = AArch64CC::GT;
1309 CondCode = AArch64CC::GE;
1312 CondCode = AArch64CC::MI;
1315 CondCode = AArch64CC::LS;
1318 CondCode = AArch64CC::MI;
1319 CondCode2 = AArch64CC::GT;
1322 CondCode = AArch64CC::VC;
1325 CondCode = AArch64CC::VS;
1328 CondCode = AArch64CC::EQ;
1329 CondCode2 = AArch64CC::VS;
1332 CondCode = AArch64CC::HI;
1335 CondCode = AArch64CC::PL;
1339 CondCode = AArch64CC::LT;
1343 CondCode = AArch64CC::LE;
1347 CondCode = AArch64CC::NE;
1352 /// Convert a DAG fp condition code to an AArch64 CC.
1353 /// This differs from changeFPCCToAArch64CC in that it returns cond codes that
1354 /// should be AND'ed instead of OR'ed.
1355 static void changeFPCCToANDAArch64CC(ISD::CondCode CC,
1356 AArch64CC::CondCode &CondCode,
1357 AArch64CC::CondCode &CondCode2) {
1358 CondCode2 = AArch64CC::AL;
1361 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1362 assert(CondCode2 == AArch64CC::AL);
1366 // == ((a olt b) || (a ogt b))
1367 // == ((a ord b) && (a une b))
1368 CondCode = AArch64CC::VC;
1369 CondCode2 = AArch64CC::NE;
1373 // == ((a uno b) || (a oeq b))
1374 // == ((a ule b) && (a uge b))
1375 CondCode = AArch64CC::PL;
1376 CondCode2 = AArch64CC::LE;
1381 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1382 /// CC usable with the vector instructions. Fewer operations are available
1383 /// without a real NZCV register, so we have to use less efficient combinations
1384 /// to get the same effect.
1385 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1386 AArch64CC::CondCode &CondCode,
1387 AArch64CC::CondCode &CondCode2,
1392 // Mostly the scalar mappings work fine.
1393 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1399 CondCode = AArch64CC::MI;
1400 CondCode2 = AArch64CC::GE;
1407 // All of the compare-mask comparisons are ordered, but we can switch
1408 // between the two by a double inversion. E.g. ULE == !OGT.
1410 changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1415 static bool isLegalArithImmed(uint64_t C) {
1416 // Matches AArch64DAGToDAGISel::SelectArithImmed().
1417 return (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1420 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1421 const SDLoc &dl, SelectionDAG &DAG) {
1422 EVT VT = LHS.getValueType();
1424 if (VT.isFloatingPoint()) {
1425 assert(VT != MVT::f128);
1426 if (VT == MVT::f16) {
1427 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
1428 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
1431 return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
1434 // The CMP instruction is just an alias for SUBS, and representing it as
1435 // SUBS means that it's possible to get CSE with subtract operations.
1436 // A later phase can perform the optimization of setting the destination
1437 // register to WZR/XZR if it ends up being unused.
1438 unsigned Opcode = AArch64ISD::SUBS;
1440 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
1441 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1442 // We'd like to combine a (CMP op1, (sub 0, op2) into a CMN instruction on
1443 // the grounds that "op1 - (-op2) == op1 + op2". However, the C and V flags
1444 // can be set differently by this operation. It comes down to whether
1445 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1446 // everything is fine. If not then the optimization is wrong. Thus general
1447 // comparisons are only valid if op2 != 0.
1449 // So, finally, the only LLVM-native comparisons that don't mention C and V
1450 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1451 // the absence of information about op2.
1452 Opcode = AArch64ISD::ADDS;
1453 RHS = RHS.getOperand(1);
1454 } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) &&
1455 !isUnsignedIntSetCC(CC)) {
1456 // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1457 // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1458 // of the signed comparisons.
1459 Opcode = AArch64ISD::ANDS;
1460 RHS = LHS.getOperand(1);
1461 LHS = LHS.getOperand(0);
1464 return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
1468 /// \defgroup AArch64CCMP CMP;CCMP matching
1470 /// These functions deal with the formation of CMP;CCMP;... sequences.
1471 /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1472 /// a comparison. They set the NZCV flags to a predefined value if their
1473 /// predicate is false. This allows to express arbitrary conjunctions, for
1474 /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B))))"
1477 /// ccmp B, inv(CB), CA
1478 /// check for CB flags
1480 /// In general we can create code for arbitrary "... (and (and A B) C)"
1481 /// sequences. We can also implement some "or" expressions, because "(or A B)"
1482 /// is equivalent to "not (and (not A) (not B))" and we can implement some
1483 /// negation operations:
1484 /// We can negate the results of a single comparison by inverting the flags
1485 /// used when the predicate fails and inverting the flags tested in the next
1486 /// instruction; We can also negate the results of the whole previous
1487 /// conditional compare sequence by inverting the flags tested in the next
1488 /// instruction. However there is no way to negate the result of a partial
1491 /// Therefore on encountering an "or" expression we can negate the subtree on
1492 /// one side and have to be able to push the negate to the leafs of the subtree
1493 /// on the other side (see also the comments in code). As complete example:
1494 /// "or (or (setCA (cmp A)) (setCB (cmp B)))
1495 /// (and (setCC (cmp C)) (setCD (cmp D)))"
1496 /// is transformed to
1497 /// "not (and (not (and (setCC (cmp C)) (setCC (cmp D))))
1498 /// (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1499 /// and implemented as:
1501 /// ccmp D, inv(CD), CC
1502 /// ccmp A, CA, inv(CD)
1503 /// ccmp B, CB, inv(CA)
1504 /// check for CB flags
1505 /// A counterexample is "or (and A B) (and C D)" which cannot be implemented
1506 /// by conditional compare sequences.
1509 /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
1510 static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1511 ISD::CondCode CC, SDValue CCOp,
1512 AArch64CC::CondCode Predicate,
1513 AArch64CC::CondCode OutCC,
1514 const SDLoc &DL, SelectionDAG &DAG) {
1515 unsigned Opcode = 0;
1516 if (LHS.getValueType().isFloatingPoint()) {
1517 assert(LHS.getValueType() != MVT::f128);
1518 if (LHS.getValueType() == MVT::f16) {
1519 LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS);
1520 RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS);
1522 Opcode = AArch64ISD::FCCMP;
1523 } else if (RHS.getOpcode() == ISD::SUB) {
1524 SDValue SubOp0 = RHS.getOperand(0);
1525 if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1526 // See emitComparison() on why we can only do this for SETEQ and SETNE.
1527 Opcode = AArch64ISD::CCMN;
1528 RHS = RHS.getOperand(1);
1532 Opcode = AArch64ISD::CCMP;
1534 SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC);
1535 AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1536 unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
1537 SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1538 return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1541 /// Returns true if @p Val is a tree of AND/OR/SETCC operations.
1542 /// CanPushNegate is set to true if we can push a negate operation through
1543 /// the tree in a was that we are left with AND operations and negate operations
1544 /// at the leafs only. i.e. "not (or (or x y) z)" can be changed to
1545 /// "and (and (not x) (not y)) (not z)"; "not (or (and x y) z)" cannot be
1546 /// brought into such a form.
1547 static bool isConjunctionDisjunctionTree(const SDValue Val, bool &CanNegate,
1548 unsigned Depth = 0) {
1549 if (!Val.hasOneUse())
1551 unsigned Opcode = Val->getOpcode();
1552 if (Opcode == ISD::SETCC) {
1553 if (Val->getOperand(0).getValueType() == MVT::f128)
1558 // Protect against exponential runtime and stack overflow.
1561 if (Opcode == ISD::AND || Opcode == ISD::OR) {
1562 SDValue O0 = Val->getOperand(0);
1563 SDValue O1 = Val->getOperand(1);
1565 if (!isConjunctionDisjunctionTree(O0, CanNegateL, Depth+1))
1568 if (!isConjunctionDisjunctionTree(O1, CanNegateR, Depth+1))
1571 if (Opcode == ISD::OR) {
1572 // For an OR expression we need to be able to negate at least one side or
1573 // we cannot do the transformation at all.
1574 if (!CanNegateL && !CanNegateR)
1576 // We can however change a (not (or x y)) to (and (not x) (not y)) if we
1577 // can negate the x and y subtrees.
1578 CanNegate = CanNegateL && CanNegateR;
1580 // If the operands are OR expressions then we finally need to negate their
1581 // outputs, we can only do that for the operand with emitted last by
1582 // negating OutCC, not for both operands.
1583 bool NeedsNegOutL = O0->getOpcode() == ISD::OR;
1584 bool NeedsNegOutR = O1->getOpcode() == ISD::OR;
1585 if (NeedsNegOutL && NeedsNegOutR)
1587 // We cannot negate an AND operation (it would become an OR),
1595 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1596 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1597 /// Tries to transform the given i1 producing node @p Val to a series compare
1598 /// and conditional compare operations. @returns an NZCV flags producing node
1599 /// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1600 /// transformation was not possible.
1601 /// On recursive invocations @p PushNegate may be set to true to have negation
1602 /// effects pushed to the tree leafs; @p Predicate is an NZCV flag predicate
1603 /// for the comparisons in the current subtree; @p Depth limits the search
1604 /// depth to avoid stack overflow.
1605 static SDValue emitConjunctionDisjunctionTreeRec(SelectionDAG &DAG, SDValue Val,
1606 AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp,
1607 AArch64CC::CondCode Predicate) {
1608 // We're at a tree leaf, produce a conditional comparison operation.
1609 unsigned Opcode = Val->getOpcode();
1610 if (Opcode == ISD::SETCC) {
1611 SDValue LHS = Val->getOperand(0);
1612 SDValue RHS = Val->getOperand(1);
1613 ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1614 bool isInteger = LHS.getValueType().isInteger();
1616 CC = getSetCCInverse(CC, isInteger);
1618 // Determine OutCC and handle FP special case.
1620 OutCC = changeIntCCToAArch64CC(CC);
1622 assert(LHS.getValueType().isFloatingPoint());
1623 AArch64CC::CondCode ExtraCC;
1624 changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
1625 // Some floating point conditions can't be tested with a single condition
1626 // code. Construct an additional comparison in this case.
1627 if (ExtraCC != AArch64CC::AL) {
1629 if (!CCOp.getNode())
1630 ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
1632 ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate,
1635 Predicate = ExtraCC;
1639 // Produce a normal comparison if we are first in the chain
1641 return emitComparison(LHS, RHS, CC, DL, DAG);
1642 // Otherwise produce a ccmp.
1643 return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL,
1646 assert((Opcode == ISD::AND || (Opcode == ISD::OR && Val->hasOneUse())) &&
1647 "Valid conjunction/disjunction tree");
1649 // Check if both sides can be transformed.
1650 SDValue LHS = Val->getOperand(0);
1651 SDValue RHS = Val->getOperand(1);
1653 // In case of an OR we need to negate our operands and the result.
1654 // (A v B) <=> not(not(A) ^ not(B))
1655 bool NegateOpsAndResult = Opcode == ISD::OR;
1656 // We can negate the results of all previous operations by inverting the
1657 // predicate flags giving us a free negation for one side. The other side
1658 // must be negatable by itself.
1659 if (NegateOpsAndResult) {
1660 // See which side we can negate.
1662 bool isValidL = isConjunctionDisjunctionTree(LHS, CanNegateL);
1663 assert(isValidL && "Valid conjunction/disjunction tree");
1668 bool isValidR = isConjunctionDisjunctionTree(RHS, CanNegateR);
1669 assert(isValidR && "Valid conjunction/disjunction tree");
1670 assert((CanNegateL || CanNegateR) && "Valid conjunction/disjunction tree");
1673 // Order the side which we cannot negate to RHS so we can emit it first.
1675 std::swap(LHS, RHS);
1677 bool NeedsNegOutL = LHS->getOpcode() == ISD::OR;
1678 assert((!NeedsNegOutL || RHS->getOpcode() != ISD::OR) &&
1679 "Valid conjunction/disjunction tree");
1680 // Order the side where we need to negate the output flags to RHS so it
1681 // gets emitted first.
1683 std::swap(LHS, RHS);
1686 // Emit RHS. If we want to negate the tree we only need to push a negate
1687 // through if we are already in a PushNegate case, otherwise we can negate
1688 // the "flags to test" afterwards.
1689 AArch64CC::CondCode RHSCC;
1690 SDValue CmpR = emitConjunctionDisjunctionTreeRec(DAG, RHS, RHSCC, Negate,
1692 if (NegateOpsAndResult && !Negate)
1693 RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
1694 // Emit LHS. We may need to negate it.
1695 SDValue CmpL = emitConjunctionDisjunctionTreeRec(DAG, LHS, OutCC,
1696 NegateOpsAndResult, CmpR,
1698 // If we transformed an OR to and AND then we have to negate the result
1699 // (or absorb the Negate parameter).
1700 if (NegateOpsAndResult && !Negate)
1701 OutCC = AArch64CC::getInvertedCondCode(OutCC);
1705 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1706 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1707 /// \see emitConjunctionDisjunctionTreeRec().
1708 static SDValue emitConjunctionDisjunctionTree(SelectionDAG &DAG, SDValue Val,
1709 AArch64CC::CondCode &OutCC) {
1711 if (!isConjunctionDisjunctionTree(Val, CanNegate))
1714 return emitConjunctionDisjunctionTreeRec(DAG, Val, OutCC, false, SDValue(),
1720 static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1721 SDValue &AArch64cc, SelectionDAG &DAG,
1723 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1724 EVT VT = RHS.getValueType();
1725 uint64_t C = RHSC->getZExtValue();
1726 if (!isLegalArithImmed(C)) {
1727 // Constant does not fit, try adjusting it by one?
1733 if ((VT == MVT::i32 && C != 0x80000000 &&
1734 isLegalArithImmed((uint32_t)(C - 1))) ||
1735 (VT == MVT::i64 && C != 0x80000000ULL &&
1736 isLegalArithImmed(C - 1ULL))) {
1737 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1738 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1739 RHS = DAG.getConstant(C, dl, VT);
1744 if ((VT == MVT::i32 && C != 0 &&
1745 isLegalArithImmed((uint32_t)(C - 1))) ||
1746 (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1747 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1748 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1749 RHS = DAG.getConstant(C, dl, VT);
1754 if ((VT == MVT::i32 && C != INT32_MAX &&
1755 isLegalArithImmed((uint32_t)(C + 1))) ||
1756 (VT == MVT::i64 && C != INT64_MAX &&
1757 isLegalArithImmed(C + 1ULL))) {
1758 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1759 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1760 RHS = DAG.getConstant(C, dl, VT);
1765 if ((VT == MVT::i32 && C != UINT32_MAX &&
1766 isLegalArithImmed((uint32_t)(C + 1))) ||
1767 (VT == MVT::i64 && C != UINT64_MAX &&
1768 isLegalArithImmed(C + 1ULL))) {
1769 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1770 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1771 RHS = DAG.getConstant(C, dl, VT);
1778 AArch64CC::CondCode AArch64CC;
1779 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
1780 const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
1782 // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
1783 // For the i8 operand, the largest immediate is 255, so this can be easily
1784 // encoded in the compare instruction. For the i16 operand, however, the
1785 // largest immediate cannot be encoded in the compare.
1786 // Therefore, use a sign extending load and cmn to avoid materializing the
1787 // -1 constant. For example,
1789 // ldrh w0, [x0, #0]
1792 // ldrsh w0, [x0, #0]
1794 // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
1795 // if and only if (sext LHS) == (sext RHS). The checks are in place to
1796 // ensure both the LHS and RHS are truly zero extended and to make sure the
1797 // transformation is profitable.
1798 if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
1799 cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
1800 cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
1801 LHS.getNode()->hasNUsesOfValue(1, 0)) {
1802 int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
1803 if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
1805 DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
1806 DAG.getValueType(MVT::i16));
1807 Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
1808 RHS.getValueType()),
1810 AArch64CC = changeIntCCToAArch64CC(CC);
1814 if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
1815 if ((Cmp = emitConjunctionDisjunctionTree(DAG, LHS, AArch64CC))) {
1816 if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
1817 AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
1823 Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
1824 AArch64CC = changeIntCCToAArch64CC(CC);
1826 AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
1830 static std::pair<SDValue, SDValue>
1831 getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
1832 assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
1833 "Unsupported value type");
1834 SDValue Value, Overflow;
1836 SDValue LHS = Op.getOperand(0);
1837 SDValue RHS = Op.getOperand(1);
1839 switch (Op.getOpcode()) {
1841 llvm_unreachable("Unknown overflow instruction!");
1843 Opc = AArch64ISD::ADDS;
1847 Opc = AArch64ISD::ADDS;
1851 Opc = AArch64ISD::SUBS;
1855 Opc = AArch64ISD::SUBS;
1858 // Multiply needs a little bit extra work.
1862 bool IsSigned = Op.getOpcode() == ISD::SMULO;
1863 if (Op.getValueType() == MVT::i32) {
1864 unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1865 // For a 32 bit multiply with overflow check we want the instruction
1866 // selector to generate a widening multiply (SMADDL/UMADDL). For that we
1867 // need to generate the following pattern:
1868 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
1869 LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
1870 RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
1871 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1872 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
1873 DAG.getConstant(0, DL, MVT::i64));
1874 // On AArch64 the upper 32 bits are always zero extended for a 32 bit
1875 // operation. We need to clear out the upper 32 bits, because we used a
1876 // widening multiply that wrote all 64 bits. In the end this should be a
1878 Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
1880 // The signed overflow check requires more than just a simple check for
1881 // any bit set in the upper 32 bits of the result. These bits could be
1882 // just the sign bits of a negative number. To perform the overflow
1883 // check we have to arithmetic shift right the 32nd bit of the result by
1884 // 31 bits. Then we compare the result to the upper 32 bits.
1885 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
1886 DAG.getConstant(32, DL, MVT::i64));
1887 UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
1888 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
1889 DAG.getConstant(31, DL, MVT::i64));
1890 // It is important that LowerBits is last, otherwise the arithmetic
1891 // shift will not be folded into the compare (SUBS).
1892 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
1893 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1896 // The overflow check for unsigned multiply is easy. We only need to
1897 // check if any of the upper 32 bits are set. This can be done with a
1898 // CMP (shifted register). For that we need to generate the following
1900 // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
1901 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
1902 DAG.getConstant(32, DL, MVT::i64));
1903 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1905 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1906 DAG.getConstant(0, DL, MVT::i64),
1907 UpperBits).getValue(1);
1911 assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
1912 // For the 64 bit multiply
1913 Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1915 SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
1916 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
1917 DAG.getConstant(63, DL, MVT::i64));
1918 // It is important that LowerBits is last, otherwise the arithmetic
1919 // shift will not be folded into the compare (SUBS).
1920 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1921 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1924 SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
1925 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1927 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1928 DAG.getConstant(0, DL, MVT::i64),
1929 UpperBits).getValue(1);
1936 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
1938 // Emit the AArch64 operation with overflow check.
1939 Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
1940 Overflow = Value.getValue(1);
1942 return std::make_pair(Value, Overflow);
1945 SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
1946 RTLIB::Libcall Call) const {
1947 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
1948 return makeLibCall(DAG, Call, MVT::f128, Ops, false, SDLoc(Op)).first;
1951 static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
1952 SDValue Sel = Op.getOperand(0);
1953 SDValue Other = Op.getOperand(1);
1955 // If neither operand is a SELECT_CC, give up.
1956 if (Sel.getOpcode() != ISD::SELECT_CC)
1957 std::swap(Sel, Other);
1958 if (Sel.getOpcode() != ISD::SELECT_CC)
1961 // The folding we want to perform is:
1962 // (xor x, (select_cc a, b, cc, 0, -1) )
1964 // (csel x, (xor x, -1), cc ...)
1966 // The latter will get matched to a CSINV instruction.
1968 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
1969 SDValue LHS = Sel.getOperand(0);
1970 SDValue RHS = Sel.getOperand(1);
1971 SDValue TVal = Sel.getOperand(2);
1972 SDValue FVal = Sel.getOperand(3);
1975 // FIXME: This could be generalized to non-integer comparisons.
1976 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
1979 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
1980 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
1982 // The values aren't constants, this isn't the pattern we're looking for.
1983 if (!CFVal || !CTVal)
1986 // We can commute the SELECT_CC by inverting the condition. This
1987 // might be needed to make this fit into a CSINV pattern.
1988 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
1989 std::swap(TVal, FVal);
1990 std::swap(CTVal, CFVal);
1991 CC = ISD::getSetCCInverse(CC, true);
1994 // If the constants line up, perform the transform!
1995 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
1997 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
2000 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
2001 DAG.getConstant(-1ULL, dl, Other.getValueType()));
2003 return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
2010 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
2011 EVT VT = Op.getValueType();
2013 // Let legalize expand this if it isn't a legal type yet.
2014 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
2017 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
2020 bool ExtraOp = false;
2021 switch (Op.getOpcode()) {
2023 llvm_unreachable("Invalid code");
2025 Opc = AArch64ISD::ADDS;
2028 Opc = AArch64ISD::SUBS;
2031 Opc = AArch64ISD::ADCS;
2035 Opc = AArch64ISD::SBCS;
2041 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
2042 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
2046 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
2047 // Let legalize expand this if it isn't a legal type yet.
2048 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
2052 AArch64CC::CondCode CC;
2053 // The actual operation that sets the overflow or carry flag.
2054 SDValue Value, Overflow;
2055 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
2057 // We use 0 and 1 as false and true values.
2058 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
2059 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
2061 // We use an inverted condition, because the conditional select is inverted
2062 // too. This will allow it to be selected to a single instruction:
2063 // CSINC Wd, WZR, WZR, invert(cond).
2064 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
2065 Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
2068 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
2069 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
2072 // Prefetch operands are:
2073 // 1: Address to prefetch
2075 // 3: int locality (0 = no locality ... 3 = extreme locality)
2076 // 4: bool isDataCache
2077 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
2079 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
2080 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
2081 unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
2083 bool IsStream = !Locality;
2084 // When the locality number is set
2086 // The front-end should have filtered out the out-of-range values
2087 assert(Locality <= 3 && "Prefetch locality out-of-range");
2088 // The locality degree is the opposite of the cache speed.
2089 // Put the number the other way around.
2090 // The encoding starts at 0 for level 1
2091 Locality = 3 - Locality;
2094 // built the mask value encoding the expected behavior.
2095 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit
2096 (!IsData << 3) | // IsDataCache bit
2097 (Locality << 1) | // Cache level bits
2098 (unsigned)IsStream; // Stream bit
2099 return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
2100 DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
2103 SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
2104 SelectionDAG &DAG) const {
2105 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
2108 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
2110 return LowerF128Call(Op, DAG, LC);
2113 SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
2114 SelectionDAG &DAG) const {
2115 if (Op.getOperand(0).getValueType() != MVT::f128) {
2116 // It's legal except when f128 is involved
2121 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
2123 // FP_ROUND node has a second operand indicating whether it is known to be
2124 // precise. That doesn't take part in the LibCall so we can't directly use
2126 SDValue SrcVal = Op.getOperand(0);
2127 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
2131 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
2132 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2133 // Any additional optimization in this function should be recorded
2134 // in the cost tables.
2135 EVT InVT = Op.getOperand(0).getValueType();
2136 EVT VT = Op.getValueType();
2137 unsigned NumElts = InVT.getVectorNumElements();
2139 // f16 vectors are promoted to f32 before a conversion.
2140 if (InVT.getVectorElementType() == MVT::f16) {
2141 MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
2144 Op.getOpcode(), dl, Op.getValueType(),
2145 DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
2148 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2151 DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
2153 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
2156 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2159 MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
2160 VT.getVectorNumElements());
2161 SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
2162 return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
2165 // Type changing conversions are illegal.
2169 SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
2170 SelectionDAG &DAG) const {
2171 if (Op.getOperand(0).getValueType().isVector())
2172 return LowerVectorFP_TO_INT(Op, DAG);
2174 // f16 conversions are promoted to f32.
2175 if (Op.getOperand(0).getValueType() == MVT::f16) {
2178 Op.getOpcode(), dl, Op.getValueType(),
2179 DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
2182 if (Op.getOperand(0).getValueType() != MVT::f128) {
2183 // It's legal except when f128 is involved
2188 if (Op.getOpcode() == ISD::FP_TO_SINT)
2189 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
2191 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
2193 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
2194 return makeLibCall(DAG, LC, Op.getValueType(), Ops, false, SDLoc(Op)).first;
2197 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
2198 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2199 // Any additional optimization in this function should be recorded
2200 // in the cost tables.
2201 EVT VT = Op.getValueType();
2203 SDValue In = Op.getOperand(0);
2204 EVT InVT = In.getValueType();
2206 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2208 MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
2209 InVT.getVectorNumElements());
2210 In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
2211 return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
2214 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2216 Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2217 EVT CastVT = VT.changeVectorElementTypeToInteger();
2218 In = DAG.getNode(CastOpc, dl, CastVT, In);
2219 return DAG.getNode(Op.getOpcode(), dl, VT, In);
2225 SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
2226 SelectionDAG &DAG) const {
2227 if (Op.getValueType().isVector())
2228 return LowerVectorINT_TO_FP(Op, DAG);
2230 // f16 conversions are promoted to f32.
2231 if (Op.getValueType() == MVT::f16) {
2234 ISD::FP_ROUND, dl, MVT::f16,
2235 DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
2236 DAG.getIntPtrConstant(0, dl));
2239 // i128 conversions are libcalls.
2240 if (Op.getOperand(0).getValueType() == MVT::i128)
2243 // Other conversions are legal, unless it's to the completely software-based
2245 if (Op.getValueType() != MVT::f128)
2249 if (Op.getOpcode() == ISD::SINT_TO_FP)
2250 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2252 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2254 return LowerF128Call(Op, DAG, LC);
2257 SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
2258 SelectionDAG &DAG) const {
2259 // For iOS, we want to call an alternative entry point: __sincos_stret,
2260 // which returns the values in two S / D registers.
2262 SDValue Arg = Op.getOperand(0);
2263 EVT ArgVT = Arg.getValueType();
2264 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2271 Entry.IsSExt = false;
2272 Entry.IsZExt = false;
2273 Args.push_back(Entry);
2275 const char *LibcallName =
2276 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
2278 DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
2280 StructType *RetTy = StructType::get(ArgTy, ArgTy);
2281 TargetLowering::CallLoweringInfo CLI(DAG);
2283 .setChain(DAG.getEntryNode())
2284 .setLibCallee(CallingConv::Fast, RetTy, Callee, std::move(Args));
2286 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2287 return CallResult.first;
2290 static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
2291 if (Op.getValueType() != MVT::f16)
2294 assert(Op.getOperand(0).getValueType() == MVT::i16);
2297 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
2298 Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
2300 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
2301 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
2305 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
2306 if (OrigVT.getSizeInBits() >= 64)
2309 assert(OrigVT.isSimple() && "Expecting a simple value type");
2311 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
2312 switch (OrigSimpleTy) {
2313 default: llvm_unreachable("Unexpected Vector Type");
2322 static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2325 unsigned ExtOpcode) {
2326 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2327 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2328 // 64-bits we need to insert a new extension so that it will be 64-bits.
2329 assert(ExtTy.is128BitVector() && "Unexpected extension size");
2330 if (OrigTy.getSizeInBits() >= 64)
2333 // Must extend size to at least 64 bits to be used as an operand for VMULL.
2334 EVT NewVT = getExtensionTo64Bits(OrigTy);
2336 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2339 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2341 EVT VT = N->getValueType(0);
2343 if (N->getOpcode() != ISD::BUILD_VECTOR)
2346 for (const SDValue &Elt : N->op_values()) {
2347 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
2348 unsigned EltSize = VT.getScalarSizeInBits();
2349 unsigned HalfSize = EltSize / 2;
2351 if (!isIntN(HalfSize, C->getSExtValue()))
2354 if (!isUIntN(HalfSize, C->getZExtValue()))
2365 static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2366 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2367 return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2368 N->getOperand(0)->getValueType(0),
2372 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2373 EVT VT = N->getValueType(0);
2375 unsigned EltSize = VT.getScalarSizeInBits() / 2;
2376 unsigned NumElts = VT.getVectorNumElements();
2377 MVT TruncVT = MVT::getIntegerVT(EltSize);
2378 SmallVector<SDValue, 8> Ops;
2379 for (unsigned i = 0; i != NumElts; ++i) {
2380 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2381 const APInt &CInt = C->getAPIntValue();
2382 // Element types smaller than 32 bits are not legal, so use i32 elements.
2383 // The values are implicitly truncated so sext vs. zext doesn't matter.
2384 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
2386 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
2389 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
2390 return N->getOpcode() == ISD::SIGN_EXTEND ||
2391 isExtendedBUILD_VECTOR(N, DAG, true);
2394 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
2395 return N->getOpcode() == ISD::ZERO_EXTEND ||
2396 isExtendedBUILD_VECTOR(N, DAG, false);
2399 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2400 unsigned Opcode = N->getOpcode();
2401 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2402 SDNode *N0 = N->getOperand(0).getNode();
2403 SDNode *N1 = N->getOperand(1).getNode();
2404 return N0->hasOneUse() && N1->hasOneUse() &&
2405 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2410 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2411 unsigned Opcode = N->getOpcode();
2412 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2413 SDNode *N0 = N->getOperand(0).getNode();
2414 SDNode *N1 = N->getOperand(1).getNode();
2415 return N0->hasOneUse() && N1->hasOneUse() &&
2416 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2421 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2422 // Multiplications are only custom-lowered for 128-bit vectors so that
2423 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
2424 EVT VT = Op.getValueType();
2425 assert(VT.is128BitVector() && VT.isInteger() &&
2426 "unexpected type for custom-lowering ISD::MUL");
2427 SDNode *N0 = Op.getOperand(0).getNode();
2428 SDNode *N1 = Op.getOperand(1).getNode();
2429 unsigned NewOpc = 0;
2431 bool isN0SExt = isSignExtended(N0, DAG);
2432 bool isN1SExt = isSignExtended(N1, DAG);
2433 if (isN0SExt && isN1SExt)
2434 NewOpc = AArch64ISD::SMULL;
2436 bool isN0ZExt = isZeroExtended(N0, DAG);
2437 bool isN1ZExt = isZeroExtended(N1, DAG);
2438 if (isN0ZExt && isN1ZExt)
2439 NewOpc = AArch64ISD::UMULL;
2440 else if (isN1SExt || isN1ZExt) {
2441 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2442 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2443 if (isN1SExt && isAddSubSExt(N0, DAG)) {
2444 NewOpc = AArch64ISD::SMULL;
2446 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2447 NewOpc = AArch64ISD::UMULL;
2449 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2451 NewOpc = AArch64ISD::UMULL;
2457 if (VT == MVT::v2i64)
2458 // Fall through to expand this. It is not legal.
2461 // Other vector multiplications are legal.
2466 // Legalize to a S/UMULL instruction
2469 SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2471 Op0 = skipExtensionForVectorMULL(N0, DAG);
2472 assert(Op0.getValueType().is64BitVector() &&
2473 Op1.getValueType().is64BitVector() &&
2474 "unexpected types for extended operands to VMULL");
2475 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2477 // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2478 // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2479 // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2480 SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2481 SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2482 EVT Op1VT = Op1.getValueType();
2483 return DAG.getNode(N0->getOpcode(), DL, VT,
2484 DAG.getNode(NewOpc, DL, VT,
2485 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2486 DAG.getNode(NewOpc, DL, VT,
2487 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2490 SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2491 SelectionDAG &DAG) const {
2492 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2495 default: return SDValue(); // Don't custom lower most intrinsics.
2496 case Intrinsic::thread_pointer: {
2497 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2498 return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
2500 case Intrinsic::aarch64_neon_abs:
2501 return DAG.getNode(ISD::ABS, dl, Op.getValueType(),
2503 case Intrinsic::aarch64_neon_smax:
2504 return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
2505 Op.getOperand(1), Op.getOperand(2));
2506 case Intrinsic::aarch64_neon_umax:
2507 return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
2508 Op.getOperand(1), Op.getOperand(2));
2509 case Intrinsic::aarch64_neon_smin:
2510 return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
2511 Op.getOperand(1), Op.getOperand(2));
2512 case Intrinsic::aarch64_neon_umin:
2513 return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
2514 Op.getOperand(1), Op.getOperand(2));
2518 SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
2519 SelectionDAG &DAG) const {
2520 switch (Op.getOpcode()) {
2522 llvm_unreachable("unimplemented operand");
2525 return LowerBITCAST(Op, DAG);
2526 case ISD::GlobalAddress:
2527 return LowerGlobalAddress(Op, DAG);
2528 case ISD::GlobalTLSAddress:
2529 return LowerGlobalTLSAddress(Op, DAG);
2531 return LowerSETCC(Op, DAG);
2533 return LowerBR_CC(Op, DAG);
2535 return LowerSELECT(Op, DAG);
2536 case ISD::SELECT_CC:
2537 return LowerSELECT_CC(Op, DAG);
2538 case ISD::JumpTable:
2539 return LowerJumpTable(Op, DAG);
2540 case ISD::ConstantPool:
2541 return LowerConstantPool(Op, DAG);
2542 case ISD::BlockAddress:
2543 return LowerBlockAddress(Op, DAG);
2545 return LowerVASTART(Op, DAG);
2547 return LowerVACOPY(Op, DAG);
2549 return LowerVAARG(Op, DAG);
2554 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
2561 return LowerXALUO(Op, DAG);
2563 return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
2565 return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
2567 return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
2569 return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
2571 return LowerFP_ROUND(Op, DAG);
2572 case ISD::FP_EXTEND:
2573 return LowerFP_EXTEND(Op, DAG);
2574 case ISD::FRAMEADDR:
2575 return LowerFRAMEADDR(Op, DAG);
2576 case ISD::RETURNADDR:
2577 return LowerRETURNADDR(Op, DAG);
2578 case ISD::INSERT_VECTOR_ELT:
2579 return LowerINSERT_VECTOR_ELT(Op, DAG);
2580 case ISD::EXTRACT_VECTOR_ELT:
2581 return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2582 case ISD::BUILD_VECTOR:
2583 return LowerBUILD_VECTOR(Op, DAG);
2584 case ISD::VECTOR_SHUFFLE:
2585 return LowerVECTOR_SHUFFLE(Op, DAG);
2586 case ISD::EXTRACT_SUBVECTOR:
2587 return LowerEXTRACT_SUBVECTOR(Op, DAG);
2591 return LowerVectorSRA_SRL_SHL(Op, DAG);
2592 case ISD::SHL_PARTS:
2593 return LowerShiftLeftParts(Op, DAG);
2594 case ISD::SRL_PARTS:
2595 case ISD::SRA_PARTS:
2596 return LowerShiftRightParts(Op, DAG);
2598 return LowerCTPOP(Op, DAG);
2599 case ISD::FCOPYSIGN:
2600 return LowerFCOPYSIGN(Op, DAG);
2602 return LowerVectorAND(Op, DAG);
2604 return LowerVectorOR(Op, DAG);
2606 return LowerXOR(Op, DAG);
2608 return LowerPREFETCH(Op, DAG);
2609 case ISD::SINT_TO_FP:
2610 case ISD::UINT_TO_FP:
2611 return LowerINT_TO_FP(Op, DAG);
2612 case ISD::FP_TO_SINT:
2613 case ISD::FP_TO_UINT:
2614 return LowerFP_TO_INT(Op, DAG);
2616 return LowerFSINCOS(Op, DAG);
2618 return LowerMUL(Op, DAG);
2619 case ISD::INTRINSIC_WO_CHAIN:
2620 return LowerINTRINSIC_WO_CHAIN(Op, DAG);
2621 case ISD::VECREDUCE_ADD:
2622 case ISD::VECREDUCE_SMAX:
2623 case ISD::VECREDUCE_SMIN:
2624 case ISD::VECREDUCE_UMAX:
2625 case ISD::VECREDUCE_UMIN:
2626 case ISD::VECREDUCE_FMAX:
2627 case ISD::VECREDUCE_FMIN:
2628 return LowerVECREDUCE(Op, DAG);
2632 //===----------------------------------------------------------------------===//
2633 // Calling Convention Implementation
2634 //===----------------------------------------------------------------------===//
2636 #include "AArch64GenCallingConv.inc"
2638 /// Selects the correct CCAssignFn for a given CallingConvention value.
2639 CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2640 bool IsVarArg) const {
2643 llvm_unreachable("Unsupported calling convention.");
2644 case CallingConv::WebKit_JS:
2645 return CC_AArch64_WebKit_JS;
2646 case CallingConv::GHC:
2647 return CC_AArch64_GHC;
2648 case CallingConv::C:
2649 case CallingConv::Fast:
2650 case CallingConv::PreserveMost:
2651 case CallingConv::CXX_FAST_TLS:
2652 case CallingConv::Swift:
2653 if (Subtarget->isTargetWindows() && IsVarArg)
2654 return CC_AArch64_Win64_VarArg;
2655 if (!Subtarget->isTargetDarwin())
2656 return CC_AArch64_AAPCS;
2657 return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
2658 case CallingConv::Win64:
2659 return IsVarArg ? CC_AArch64_Win64_VarArg : CC_AArch64_AAPCS;
2664 AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const {
2665 return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
2666 : RetCC_AArch64_AAPCS;
2669 SDValue AArch64TargetLowering::LowerFormalArguments(
2670 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2671 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2672 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2673 MachineFunction &MF = DAG.getMachineFunction();
2674 MachineFrameInfo &MFI = MF.getFrameInfo();
2675 bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv());
2677 // Assign locations to all of the incoming arguments.
2678 SmallVector<CCValAssign, 16> ArgLocs;
2679 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2682 // At this point, Ins[].VT may already be promoted to i32. To correctly
2683 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2684 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2685 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
2686 // we use a special version of AnalyzeFormalArguments to pass in ValVT and
2688 unsigned NumArgs = Ins.size();
2689 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2690 unsigned CurArgIdx = 0;
2691 for (unsigned i = 0; i != NumArgs; ++i) {
2692 MVT ValVT = Ins[i].VT;
2693 if (Ins[i].isOrigArg()) {
2694 std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
2695 CurArgIdx = Ins[i].getOrigArgIndex();
2697 // Get type of the original argument.
2698 EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
2699 /*AllowUnknown*/ true);
2700 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
2701 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2702 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2704 else if (ActualMVT == MVT::i16)
2707 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2709 AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
2710 assert(!Res && "Call operand has unhandled type");
2713 assert(ArgLocs.size() == Ins.size());
2714 SmallVector<SDValue, 16> ArgValues;
2715 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2716 CCValAssign &VA = ArgLocs[i];
2718 if (Ins[i].Flags.isByVal()) {
2719 // Byval is used for HFAs in the PCS, but the system should work in a
2720 // non-compliant manner for larger structs.
2721 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2722 int Size = Ins[i].Flags.getByValSize();
2723 unsigned NumRegs = (Size + 7) / 8;
2725 // FIXME: This works on big-endian for composite byvals, which are the common
2726 // case. It should also work for fundamental types too.
2728 MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
2729 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
2730 InVals.push_back(FrameIdxN);
2735 if (VA.isRegLoc()) {
2736 // Arguments stored in registers.
2737 EVT RegVT = VA.getLocVT();
2740 const TargetRegisterClass *RC;
2742 if (RegVT == MVT::i32)
2743 RC = &AArch64::GPR32RegClass;
2744 else if (RegVT == MVT::i64)
2745 RC = &AArch64::GPR64RegClass;
2746 else if (RegVT == MVT::f16)
2747 RC = &AArch64::FPR16RegClass;
2748 else if (RegVT == MVT::f32)
2749 RC = &AArch64::FPR32RegClass;
2750 else if (RegVT == MVT::f64 || RegVT.is64BitVector())
2751 RC = &AArch64::FPR64RegClass;
2752 else if (RegVT == MVT::f128 || RegVT.is128BitVector())
2753 RC = &AArch64::FPR128RegClass;
2755 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2757 // Transform the arguments in physical registers into virtual ones.
2758 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2759 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2761 // If this is an 8, 16 or 32-bit value, it is really passed promoted
2762 // to 64 bits. Insert an assert[sz]ext to capture this, then
2763 // truncate to the right size.
2764 switch (VA.getLocInfo()) {
2766 llvm_unreachable("Unknown loc info!");
2767 case CCValAssign::Full:
2769 case CCValAssign::BCvt:
2770 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
2772 case CCValAssign::AExt:
2773 case CCValAssign::SExt:
2774 case CCValAssign::ZExt:
2775 // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
2776 // nodes after our lowering.
2777 assert(RegVT == Ins[i].VT && "incorrect register location selected");
2781 InVals.push_back(ArgValue);
2783 } else { // VA.isRegLoc()
2784 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
2785 unsigned ArgOffset = VA.getLocMemOffset();
2786 unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
2788 uint32_t BEAlign = 0;
2789 if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
2790 !Ins[i].Flags.isInConsecutiveRegs())
2791 BEAlign = 8 - ArgSize;
2793 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
2795 // Create load nodes to retrieve arguments from the stack.
2796 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2799 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
2800 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
2801 MVT MemVT = VA.getValVT();
2803 switch (VA.getLocInfo()) {
2806 case CCValAssign::BCvt:
2807 MemVT = VA.getLocVT();
2809 case CCValAssign::SExt:
2810 ExtType = ISD::SEXTLOAD;
2812 case CCValAssign::ZExt:
2813 ExtType = ISD::ZEXTLOAD;
2815 case CCValAssign::AExt:
2816 ExtType = ISD::EXTLOAD;
2820 ArgValue = DAG.getExtLoad(
2821 ExtType, DL, VA.getLocVT(), Chain, FIN,
2822 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
2825 InVals.push_back(ArgValue);
2830 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2832 if (!Subtarget->isTargetDarwin() || IsWin64) {
2833 // The AAPCS variadic function ABI is identical to the non-variadic
2834 // one. As a result there may be more arguments in registers and we should
2835 // save them for future reference.
2836 // Win64 variadic functions also pass arguments in registers, but all float
2837 // arguments are passed in integer registers.
2838 saveVarArgRegisters(CCInfo, DAG, DL, Chain);
2841 // This will point to the next argument passed via stack.
2842 unsigned StackOffset = CCInfo.getNextStackOffset();
2843 // We currently pass all varargs at 8-byte alignment.
2844 StackOffset = ((StackOffset + 7) & ~7);
2845 FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true));
2848 unsigned StackArgSize = CCInfo.getNextStackOffset();
2849 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2850 if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
2851 // This is a non-standard ABI so by fiat I say we're allowed to make full
2852 // use of the stack area to be popped, which must be aligned to 16 bytes in
2854 StackArgSize = alignTo(StackArgSize, 16);
2856 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
2857 // a multiple of 16.
2858 FuncInfo->setArgumentStackToRestore(StackArgSize);
2860 // This realignment carries over to the available bytes below. Our own
2861 // callers will guarantee the space is free by giving an aligned value to
2864 // Even if we're not expected to free up the space, it's useful to know how
2865 // much is there while considering tail calls (because we can reuse it).
2866 FuncInfo->setBytesInStackArgArea(StackArgSize);
2871 void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
2874 SDValue &Chain) const {
2875 MachineFunction &MF = DAG.getMachineFunction();
2876 MachineFrameInfo &MFI = MF.getFrameInfo();
2877 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2878 auto PtrVT = getPointerTy(DAG.getDataLayout());
2879 bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv());
2881 SmallVector<SDValue, 8> MemOps;
2883 static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
2884 AArch64::X3, AArch64::X4, AArch64::X5,
2885 AArch64::X6, AArch64::X7 };
2886 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
2887 unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
2889 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
2891 if (GPRSaveSize != 0) {
2893 GPRIdx = MFI.CreateFixedObject(GPRSaveSize, -(int)GPRSaveSize, false);
2894 if (GPRSaveSize & 15)
2895 // The extra size here, if triggered, will always be 8.
2896 MFI.CreateFixedObject(16 - (GPRSaveSize & 15), -(int)alignTo(GPRSaveSize, 16), false);
2898 GPRIdx = MFI.CreateStackObject(GPRSaveSize, 8, false);
2900 SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
2902 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
2903 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
2904 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
2905 SDValue Store = DAG.getStore(
2906 Val.getValue(1), DL, Val, FIN,
2908 ? MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
2910 (i - FirstVariadicGPR) * 8)
2911 : MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8));
2912 MemOps.push_back(Store);
2914 DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
2917 FuncInfo->setVarArgsGPRIndex(GPRIdx);
2918 FuncInfo->setVarArgsGPRSize(GPRSaveSize);
2920 if (Subtarget->hasFPARMv8() && !IsWin64) {
2921 static const MCPhysReg FPRArgRegs[] = {
2922 AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
2923 AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
2924 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
2925 unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
2927 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
2929 if (FPRSaveSize != 0) {
2930 FPRIdx = MFI.CreateStackObject(FPRSaveSize, 16, false);
2932 SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
2934 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
2935 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
2936 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
2938 SDValue Store = DAG.getStore(
2939 Val.getValue(1), DL, Val, FIN,
2940 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16));
2941 MemOps.push_back(Store);
2942 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
2943 DAG.getConstant(16, DL, PtrVT));
2946 FuncInfo->setVarArgsFPRIndex(FPRIdx);
2947 FuncInfo->setVarArgsFPRSize(FPRSaveSize);
2950 if (!MemOps.empty()) {
2951 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
2955 /// LowerCallResult - Lower the result values of a call into the
2956 /// appropriate copies out of appropriate physical registers.
2957 SDValue AArch64TargetLowering::LowerCallResult(
2958 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
2959 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2960 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
2961 SDValue ThisVal) const {
2962 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
2963 ? RetCC_AArch64_WebKit_JS
2964 : RetCC_AArch64_AAPCS;
2965 // Assign locations to each value returned by this call.
2966 SmallVector<CCValAssign, 16> RVLocs;
2967 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2969 CCInfo.AnalyzeCallResult(Ins, RetCC);
2971 // Copy all of the result registers out of their specified physreg.
2972 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2973 CCValAssign VA = RVLocs[i];
2975 // Pass 'this' value directly from the argument to return value, to avoid
2976 // reg unit interference
2977 if (i == 0 && isThisReturn) {
2978 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
2979 "unexpected return calling convention register assignment");
2980 InVals.push_back(ThisVal);
2985 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2986 Chain = Val.getValue(1);
2987 InFlag = Val.getValue(2);
2989 switch (VA.getLocInfo()) {
2991 llvm_unreachable("Unknown loc info!");
2992 case CCValAssign::Full:
2994 case CCValAssign::BCvt:
2995 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2999 InVals.push_back(Val);
3005 /// Return true if the calling convention is one that we can guarantee TCO for.
3006 static bool canGuaranteeTCO(CallingConv::ID CC) {
3007 return CC == CallingConv::Fast;
3010 /// Return true if we might ever do TCO for calls with this calling convention.
3011 static bool mayTailCallThisCC(CallingConv::ID CC) {
3013 case CallingConv::C:
3014 case CallingConv::PreserveMost:
3015 case CallingConv::Swift:
3018 return canGuaranteeTCO(CC);
3022 bool AArch64TargetLowering::isEligibleForTailCallOptimization(
3023 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
3024 const SmallVectorImpl<ISD::OutputArg> &Outs,
3025 const SmallVectorImpl<SDValue> &OutVals,
3026 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
3027 if (!mayTailCallThisCC(CalleeCC))
3030 MachineFunction &MF = DAG.getMachineFunction();
3031 const Function *CallerF = MF.getFunction();
3032 CallingConv::ID CallerCC = CallerF->getCallingConv();
3033 bool CCMatch = CallerCC == CalleeCC;
3035 // Byval parameters hand the function a pointer directly into the stack area
3036 // we want to reuse during a tail call. Working around this *is* possible (see
3037 // X86) but less efficient and uglier in LowerCall.
3038 for (Function::const_arg_iterator i = CallerF->arg_begin(),
3039 e = CallerF->arg_end();
3041 if (i->hasByValAttr())
3044 if (getTargetMachine().Options.GuaranteedTailCallOpt)
3045 return canGuaranteeTCO(CalleeCC) && CCMatch;
3047 // Externally-defined functions with weak linkage should not be
3048 // tail-called on AArch64 when the OS does not support dynamic
3049 // pre-emption of symbols, as the AAELF spec requires normal calls
3050 // to undefined weak functions to be replaced with a NOP or jump to the
3051 // next instruction. The behaviour of branch instructions in this
3052 // situation (as used for tail calls) is implementation-defined, so we
3053 // cannot rely on the linker replacing the tail call with a return.
3054 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3055 const GlobalValue *GV = G->getGlobal();
3056 const Triple &TT = getTargetMachine().getTargetTriple();
3057 if (GV->hasExternalWeakLinkage() &&
3058 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
3062 // Now we search for cases where we can use a tail call without changing the
3063 // ABI. Sibcall is used in some places (particularly gcc) to refer to this
3066 // I want anyone implementing a new calling convention to think long and hard
3067 // about this assert.
3068 assert((!isVarArg || CalleeCC == CallingConv::C) &&
3069 "Unexpected variadic calling convention");
3071 LLVMContext &C = *DAG.getContext();
3072 if (isVarArg && !Outs.empty()) {
3073 // At least two cases here: if caller is fastcc then we can't have any
3074 // memory arguments (we'd be expected to clean up the stack afterwards). If
3075 // caller is C then we could potentially use its argument area.
3077 // FIXME: for now we take the most conservative of these in both cases:
3078 // disallow all variadic memory operands.
3079 SmallVector<CCValAssign, 16> ArgLocs;
3080 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
3082 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
3083 for (const CCValAssign &ArgLoc : ArgLocs)
3084 if (!ArgLoc.isRegLoc())
3088 // Check that the call results are passed in the same way.
3089 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
3090 CCAssignFnForCall(CalleeCC, isVarArg),
3091 CCAssignFnForCall(CallerCC, isVarArg)))
3093 // The callee has to preserve all registers the caller needs to preserve.
3094 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3095 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
3097 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
3098 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
3102 // Nothing more to check if the callee is taking no arguments
3106 SmallVector<CCValAssign, 16> ArgLocs;
3107 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
3109 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
3111 const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3113 // If the stack arguments for this call do not fit into our own save area then
3114 // the call cannot be made tail.
3115 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
3118 const MachineRegisterInfo &MRI = MF.getRegInfo();
3119 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
3125 SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
3127 MachineFrameInfo &MFI,
3128 int ClobberedFI) const {
3129 SmallVector<SDValue, 8> ArgChains;
3130 int64_t FirstByte = MFI.getObjectOffset(ClobberedFI);
3131 int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1;
3133 // Include the original chain at the beginning of the list. When this is
3134 // used by target LowerCall hooks, this helps legalize find the
3135 // CALLSEQ_BEGIN node.
3136 ArgChains.push_back(Chain);
3138 // Add a chain value for each stack argument corresponding
3139 for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
3140 UE = DAG.getEntryNode().getNode()->use_end();
3142 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
3143 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
3144 if (FI->getIndex() < 0) {
3145 int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex());
3146 int64_t InLastByte = InFirstByte;
3147 InLastByte += MFI.getObjectSize(FI->getIndex()) - 1;
3149 if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
3150 (FirstByte <= InFirstByte && InFirstByte <= LastByte))
3151 ArgChains.push_back(SDValue(L, 1));
3154 // Build a tokenfactor for all the chains.
3155 return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
3158 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
3159 bool TailCallOpt) const {
3160 return CallCC == CallingConv::Fast && TailCallOpt;
3163 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
3164 /// and add input and output parameter nodes.
3166 AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
3167 SmallVectorImpl<SDValue> &InVals) const {
3168 SelectionDAG &DAG = CLI.DAG;
3170 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
3171 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
3172 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
3173 SDValue Chain = CLI.Chain;
3174 SDValue Callee = CLI.Callee;
3175 bool &IsTailCall = CLI.IsTailCall;
3176 CallingConv::ID CallConv = CLI.CallConv;
3177 bool IsVarArg = CLI.IsVarArg;
3179 MachineFunction &MF = DAG.getMachineFunction();
3180 bool IsThisReturn = false;
3182 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
3183 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
3184 bool IsSibCall = false;
3187 // Check if it's really possible to do a tail call.
3188 IsTailCall = isEligibleForTailCallOptimization(
3189 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
3190 if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
3191 report_fatal_error("failed to perform tail call elimination on a call "
3192 "site marked musttail");
3194 // A sibling call is one where we're under the usual C ABI and not planning
3195 // to change that but can still do a tail call:
3196 if (!TailCallOpt && IsTailCall)
3203 // Analyze operands of the call, assigning locations to each operand.
3204 SmallVector<CCValAssign, 16> ArgLocs;
3205 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
3209 // Handle fixed and variable vector arguments differently.
3210 // Variable vector arguments always go into memory.
3211 unsigned NumArgs = Outs.size();
3213 for (unsigned i = 0; i != NumArgs; ++i) {
3214 MVT ArgVT = Outs[i].VT;
3215 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3216 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
3217 /*IsVarArg=*/ !Outs[i].IsFixed);
3218 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3219 assert(!Res && "Call operand has unhandled type");
3223 // At this point, Outs[].VT may already be promoted to i32. To correctly
3224 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
3225 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
3226 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
3227 // we use a special version of AnalyzeCallOperands to pass in ValVT and
3229 unsigned NumArgs = Outs.size();
3230 for (unsigned i = 0; i != NumArgs; ++i) {
3231 MVT ValVT = Outs[i].VT;
3232 // Get type of the original argument.
3233 EVT ActualVT = getValueType(DAG.getDataLayout(),
3234 CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
3235 /*AllowUnknown*/ true);
3236 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
3237 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3238 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
3239 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
3241 else if (ActualMVT == MVT::i16)
3244 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
3245 bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
3246 assert(!Res && "Call operand has unhandled type");
3251 // Get a count of how many bytes are to be pushed on the stack.
3252 unsigned NumBytes = CCInfo.getNextStackOffset();
3255 // Since we're not changing the ABI to make this a tail call, the memory
3256 // operands are already available in the caller's incoming argument space.
3260 // FPDiff is the byte offset of the call's argument area from the callee's.
3261 // Stores to callee stack arguments will be placed in FixedStackSlots offset
3262 // by this amount for a tail call. In a sibling call it must be 0 because the
3263 // caller will deallocate the entire stack and the callee still expects its
3264 // arguments to begin at SP+0. Completely unused for non-tail calls.
3267 if (IsTailCall && !IsSibCall) {
3268 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
3270 // Since callee will pop argument stack as a tail call, we must keep the
3271 // popped size 16-byte aligned.
3272 NumBytes = alignTo(NumBytes, 16);
3274 // FPDiff will be negative if this tail call requires more space than we
3275 // would automatically have in our incoming argument space. Positive if we
3276 // can actually shrink the stack.
3277 FPDiff = NumReusableBytes - NumBytes;
3279 // The stack pointer must be 16-byte aligned at all times it's used for a
3280 // memory operation, which in practice means at *all* times and in
3281 // particular across call boundaries. Therefore our own arguments started at
3282 // a 16-byte aligned SP and the delta applied for the tail call should
3283 // satisfy the same constraint.
3284 assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
3287 // Adjust the stack pointer for the new arguments...
3288 // These operations are automatically eliminated by the prolog/epilog pass
3290 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL);
3292 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
3293 getPointerTy(DAG.getDataLayout()));
3295 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3296 SmallVector<SDValue, 8> MemOpChains;
3297 auto PtrVT = getPointerTy(DAG.getDataLayout());
3299 // Walk the register/memloc assignments, inserting copies/loads.
3300 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
3301 ++i, ++realArgIdx) {
3302 CCValAssign &VA = ArgLocs[i];
3303 SDValue Arg = OutVals[realArgIdx];
3304 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
3306 // Promote the value if needed.
3307 switch (VA.getLocInfo()) {
3309 llvm_unreachable("Unknown loc info!");
3310 case CCValAssign::Full:
3312 case CCValAssign::SExt:
3313 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3315 case CCValAssign::ZExt:
3316 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3318 case CCValAssign::AExt:
3319 if (Outs[realArgIdx].ArgVT == MVT::i1) {
3320 // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
3321 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3322 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
3324 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3326 case CCValAssign::BCvt:
3327 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3329 case CCValAssign::FPExt:
3330 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3334 if (VA.isRegLoc()) {
3335 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
3336 Outs[0].VT == MVT::i64) {
3337 assert(VA.getLocVT() == MVT::i64 &&
3338 "unexpected calling convention register assignment");
3339 assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
3340 "unexpected use of 'returned'");
3341 IsThisReturn = true;
3343 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3345 assert(VA.isMemLoc());
3348 MachinePointerInfo DstInfo;
3350 // FIXME: This works on big-endian for composite byvals, which are the
3351 // common case. It should also work for fundamental types too.
3352 uint32_t BEAlign = 0;
3353 unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
3354 : VA.getValVT().getSizeInBits();
3355 OpSize = (OpSize + 7) / 8;
3356 if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
3357 !Flags.isInConsecutiveRegs()) {
3359 BEAlign = 8 - OpSize;
3361 unsigned LocMemOffset = VA.getLocMemOffset();
3362 int32_t Offset = LocMemOffset + BEAlign;
3363 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3364 PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3367 Offset = Offset + FPDiff;
3368 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
3370 DstAddr = DAG.getFrameIndex(FI, PtrVT);
3372 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
3374 // Make sure any stack arguments overlapping with where we're storing
3375 // are loaded before this eventual operation. Otherwise they'll be
3377 Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
3379 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
3381 DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
3382 DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
3386 if (Outs[i].Flags.isByVal()) {
3388 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
3389 SDValue Cpy = DAG.getMemcpy(
3390 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
3391 /*isVol = */ false, /*AlwaysInline = */ false,
3392 /*isTailCall = */ false,
3393 DstInfo, MachinePointerInfo());
3395 MemOpChains.push_back(Cpy);
3397 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
3398 // promoted to a legal register type i32, we should truncate Arg back to
3400 if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
3401 VA.getValVT() == MVT::i16)
3402 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
3404 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
3405 MemOpChains.push_back(Store);
3410 if (!MemOpChains.empty())
3411 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3413 // Build a sequence of copy-to-reg nodes chained together with token chain
3414 // and flag operands which copy the outgoing args into the appropriate regs.
3416 for (auto &RegToPass : RegsToPass) {
3417 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3418 RegToPass.second, InFlag);
3419 InFlag = Chain.getValue(1);
3422 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3423 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3424 // node so that legalize doesn't hack it.
3425 if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3426 auto GV = G->getGlobal();
3427 if (Subtarget->classifyGlobalFunctionReference(GV, getTargetMachine()) ==
3428 AArch64II::MO_GOT) {
3429 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT);
3430 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3432 const GlobalValue *GV = G->getGlobal();
3433 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
3435 } else if (auto *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3436 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3437 Subtarget->isTargetMachO()) {
3438 const char *Sym = S->getSymbol();
3439 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
3440 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
3442 const char *Sym = S->getSymbol();
3443 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
3447 // We don't usually want to end the call-sequence here because we would tidy
3448 // the frame up *after* the call, however in the ABI-changing tail-call case
3449 // we've carefully laid out the parameters so that when sp is reset they'll be
3450 // in the correct location.
3451 if (IsTailCall && !IsSibCall) {
3452 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3453 DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
3454 InFlag = Chain.getValue(1);
3457 std::vector<SDValue> Ops;
3458 Ops.push_back(Chain);
3459 Ops.push_back(Callee);
3462 // Each tail call may have to adjust the stack by a different amount, so
3463 // this information must travel along with the operation for eventual
3464 // consumption by emitEpilogue.
3465 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3468 // Add argument registers to the end of the list so that they are known live
3470 for (auto &RegToPass : RegsToPass)
3471 Ops.push_back(DAG.getRegister(RegToPass.first,
3472 RegToPass.second.getValueType()));
3474 // Add a register mask operand representing the call-preserved registers.
3475 const uint32_t *Mask;
3476 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3478 // For 'this' returns, use the X0-preserving mask if applicable
3479 Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
3481 IsThisReturn = false;
3482 Mask = TRI->getCallPreservedMask(MF, CallConv);
3485 Mask = TRI->getCallPreservedMask(MF, CallConv);
3487 assert(Mask && "Missing call preserved mask for calling convention");
3488 Ops.push_back(DAG.getRegisterMask(Mask));
3490 if (InFlag.getNode())
3491 Ops.push_back(InFlag);
3493 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3495 // If we're doing a tall call, use a TC_RETURN here rather than an
3496 // actual call instruction.
3498 MF.getFrameInfo().setHasTailCall();
3499 return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
3502 // Returns a chain and a flag for retval copy to use.
3503 Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
3504 InFlag = Chain.getValue(1);
3506 uint64_t CalleePopBytes =
3507 DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
3509 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3510 DAG.getIntPtrConstant(CalleePopBytes, DL, true),
3513 InFlag = Chain.getValue(1);
3515 // Handle result values, copying them out of physregs into vregs that we
3517 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3518 InVals, IsThisReturn,
3519 IsThisReturn ? OutVals[0] : SDValue());
3522 bool AArch64TargetLowering::CanLowerReturn(
3523 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
3524 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
3525 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3526 ? RetCC_AArch64_WebKit_JS
3527 : RetCC_AArch64_AAPCS;
3528 SmallVector<CCValAssign, 16> RVLocs;
3529 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
3530 return CCInfo.CheckReturn(Outs, RetCC);
3534 AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3536 const SmallVectorImpl<ISD::OutputArg> &Outs,
3537 const SmallVectorImpl<SDValue> &OutVals,
3538 const SDLoc &DL, SelectionDAG &DAG) const {
3539 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3540 ? RetCC_AArch64_WebKit_JS
3541 : RetCC_AArch64_AAPCS;
3542 SmallVector<CCValAssign, 16> RVLocs;
3543 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3545 CCInfo.AnalyzeReturn(Outs, RetCC);
3547 // Copy the result values into the output registers.
3549 SmallVector<SDValue, 4> RetOps(1, Chain);
3550 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
3551 ++i, ++realRVLocIdx) {
3552 CCValAssign &VA = RVLocs[i];
3553 assert(VA.isRegLoc() && "Can only return in registers!");
3554 SDValue Arg = OutVals[realRVLocIdx];
3556 switch (VA.getLocInfo()) {
3558 llvm_unreachable("Unknown loc info!");
3559 case CCValAssign::Full:
3560 if (Outs[i].ArgVT == MVT::i1) {
3561 // AAPCS requires i1 to be zero-extended to i8 by the producer of the
3562 // value. This is strictly redundant on Darwin (which uses "zeroext
3563 // i1"), but will be optimised out before ISel.
3564 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3565 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3568 case CCValAssign::BCvt:
3569 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3573 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
3574 Flag = Chain.getValue(1);
3575 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3577 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3578 const MCPhysReg *I =
3579 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
3582 if (AArch64::GPR64RegClass.contains(*I))
3583 RetOps.push_back(DAG.getRegister(*I, MVT::i64));
3584 else if (AArch64::FPR64RegClass.contains(*I))
3585 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
3587 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
3591 RetOps[0] = Chain; // Update chain.
3593 // Add the flag if we have it.
3595 RetOps.push_back(Flag);
3597 return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
3600 //===----------------------------------------------------------------------===//
3601 // Other Lowering Code
3602 //===----------------------------------------------------------------------===//
3604 SDValue AArch64TargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
3606 unsigned Flag) const {
3607 return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty, 0, Flag);
3610 SDValue AArch64TargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
3612 unsigned Flag) const {
3613 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
3616 SDValue AArch64TargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
3618 unsigned Flag) const {
3619 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
3620 N->getOffset(), Flag);
3623 SDValue AArch64TargetLowering::getTargetNode(BlockAddressSDNode* N, EVT Ty,
3625 unsigned Flag) const {
3626 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
3630 template <class NodeTy>
3631 SDValue AArch64TargetLowering::getGOT(NodeTy *N, SelectionDAG &DAG) const {
3632 DEBUG(dbgs() << "AArch64TargetLowering::getGOT\n");
3634 EVT Ty = getPointerTy(DAG.getDataLayout());
3635 SDValue GotAddr = getTargetNode(N, Ty, DAG, AArch64II::MO_GOT);
3636 // FIXME: Once remat is capable of dealing with instructions with register
3637 // operands, expand this into two nodes instead of using a wrapper node.
3638 return DAG.getNode(AArch64ISD::LOADgot, DL, Ty, GotAddr);
3641 // (wrapper %highest(sym), %higher(sym), %hi(sym), %lo(sym))
3642 template <class NodeTy>
3643 SDValue AArch64TargetLowering::getAddrLarge(NodeTy *N, SelectionDAG &DAG)
3645 DEBUG(dbgs() << "AArch64TargetLowering::getAddrLarge\n");
3647 EVT Ty = getPointerTy(DAG.getDataLayout());
3648 const unsigned char MO_NC = AArch64II::MO_NC;
3650 AArch64ISD::WrapperLarge, DL, Ty,
3651 getTargetNode(N, Ty, DAG, AArch64II::MO_G3),
3652 getTargetNode(N, Ty, DAG, AArch64II::MO_G2 | MO_NC),
3653 getTargetNode(N, Ty, DAG, AArch64II::MO_G1 | MO_NC),
3654 getTargetNode(N, Ty, DAG, AArch64II::MO_G0 | MO_NC));
3657 // (addlow (adrp %hi(sym)) %lo(sym))
3658 template <class NodeTy>
3659 SDValue AArch64TargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG) const {
3660 DEBUG(dbgs() << "AArch64TargetLowering::getAddr\n");
3662 EVT Ty = getPointerTy(DAG.getDataLayout());
3663 SDValue Hi = getTargetNode(N, Ty, DAG, AArch64II::MO_PAGE);
3664 SDValue Lo = getTargetNode(N, Ty, DAG,
3665 AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3666 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, Ty, Hi);
3667 return DAG.getNode(AArch64ISD::ADDlow, DL, Ty, ADRP, Lo);
3670 SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
3671 SelectionDAG &DAG) const {
3672 GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
3673 const GlobalValue *GV = GN->getGlobal();
3674 unsigned char OpFlags =
3675 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
3677 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
3678 "unexpected offset in global node");
3680 // This also catches the large code model case for Darwin.
3681 if ((OpFlags & AArch64II::MO_GOT) != 0) {
3682 return getGOT(GN, DAG);
3685 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
3686 return getAddrLarge(GN, DAG);
3688 return getAddr(GN, DAG);
3692 /// \brief Convert a TLS address reference into the correct sequence of loads
3693 /// and calls to compute the variable's address (for Darwin, currently) and
3694 /// return an SDValue containing the final node.
3696 /// Darwin only has one TLS scheme which must be capable of dealing with the
3697 /// fully general situation, in the worst case. This means:
3698 /// + "extern __thread" declaration.
3699 /// + Defined in a possibly unknown dynamic library.
3701 /// The general system is that each __thread variable has a [3 x i64] descriptor
3702 /// which contains information used by the runtime to calculate the address. The
3703 /// only part of this the compiler needs to know about is the first xword, which
3704 /// contains a function pointer that must be called with the address of the
3705 /// entire descriptor in "x0".
3707 /// Since this descriptor may be in a different unit, in general even the
3708 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
3710 /// adrp x0, _var@TLVPPAGE
3711 /// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor
3712 /// ldr x1, [x0] ; x1 contains 1st entry of descriptor,
3713 /// ; the function pointer
3714 /// blr x1 ; Uses descriptor address in x0
3715 /// ; Address of _var is now in x0.
3717 /// If the address of _var's descriptor *is* known to the linker, then it can
3718 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
3719 /// a slight efficiency gain.
3721 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
3722 SelectionDAG &DAG) const {
3723 assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
3726 MVT PtrVT = getPointerTy(DAG.getDataLayout());
3727 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3730 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3731 SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
3733 // The first entry in the descriptor is a function pointer that we must call
3734 // to obtain the address of the variable.
3735 SDValue Chain = DAG.getEntryNode();
3736 SDValue FuncTLVGet = DAG.getLoad(
3737 MVT::i64, DL, Chain, DescAddr,
3738 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
3739 /* Alignment = */ 8,
3740 MachineMemOperand::MONonTemporal | MachineMemOperand::MOInvariant |
3741 MachineMemOperand::MODereferenceable);
3742 Chain = FuncTLVGet.getValue(1);
3744 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
3745 MFI.setAdjustsStack(true);
3747 // TLS calls preserve all registers except those that absolutely must be
3748 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
3750 const uint32_t *Mask =
3751 Subtarget->getRegisterInfo()->getTLSCallPreservedMask();
3753 // Finally, we can make the call. This is just a degenerate version of a
3754 // normal AArch64 call node: x0 takes the address of the descriptor, and
3755 // returns the address of the variable in this thread.
3756 Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
3758 DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3759 Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
3760 DAG.getRegisterMask(Mask), Chain.getValue(1));
3761 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
3764 /// When accessing thread-local variables under either the general-dynamic or
3765 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
3766 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
3767 /// is a function pointer to carry out the resolution.
3769 /// The sequence is:
3770 /// adrp x0, :tlsdesc:var
3771 /// ldr x1, [x0, #:tlsdesc_lo12:var]
3772 /// add x0, x0, #:tlsdesc_lo12:var
3773 /// .tlsdesccall var
3775 /// (TPIDR_EL0 offset now in x0)
3777 /// The above sequence must be produced unscheduled, to enable the linker to
3778 /// optimize/relax this sequence.
3779 /// Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
3780 /// above sequence, and expanded really late in the compilation flow, to ensure
3781 /// the sequence is produced as per above.
3782 SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr,
3784 SelectionDAG &DAG) const {
3785 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3787 SDValue Chain = DAG.getEntryNode();
3788 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3791 DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr});
3792 SDValue Glue = Chain.getValue(1);
3794 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
3798 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
3799 SelectionDAG &DAG) const {
3800 assert(Subtarget->isTargetELF() && "This function expects an ELF target");
3801 assert(Subtarget->useSmallAddressing() &&
3802 "ELF TLS only supported in small memory model");
3803 // Different choices can be made for the maximum size of the TLS area for a
3804 // module. For the small address model, the default TLS size is 16MiB and the
3805 // maximum TLS size is 4GiB.
3806 // FIXME: add -mtls-size command line option and make it control the 16MiB
3807 // vs. 4GiB code sequence generation.
3808 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3810 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
3812 if (DAG.getTarget().Options.EmulatedTLS)
3813 return LowerToTLSEmulatedModel(GA, DAG);
3815 if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
3816 if (Model == TLSModel::LocalDynamic)
3817 Model = TLSModel::GeneralDynamic;
3821 EVT PtrVT = getPointerTy(DAG.getDataLayout());
3823 const GlobalValue *GV = GA->getGlobal();
3825 SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
3827 if (Model == TLSModel::LocalExec) {
3828 SDValue HiVar = DAG.getTargetGlobalAddress(
3829 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
3830 SDValue LoVar = DAG.getTargetGlobalAddress(
3832 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3834 SDValue TPWithOff_lo =
3835 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
3837 DAG.getTargetConstant(0, DL, MVT::i32)),
3840 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
3842 DAG.getTargetConstant(0, DL, MVT::i32)),
3845 } else if (Model == TLSModel::InitialExec) {
3846 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3847 TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
3848 } else if (Model == TLSModel::LocalDynamic) {
3849 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
3850 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
3851 // the beginning of the module's TLS region, followed by a DTPREL offset
3854 // These accesses will need deduplicating if there's more than one.
3855 AArch64FunctionInfo *MFI =
3856 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
3857 MFI->incNumLocalDynamicTLSAccesses();
3859 // The call needs a relocation too for linker relaxation. It doesn't make
3860 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3862 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
3865 // Now we can calculate the offset from TPIDR_EL0 to this module's
3866 // thread-local area.
3867 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
3869 // Now use :dtprel_whatever: operations to calculate this variable's offset
3870 // in its thread-storage area.
3871 SDValue HiVar = DAG.getTargetGlobalAddress(
3872 GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
3873 SDValue LoVar = DAG.getTargetGlobalAddress(
3874 GV, DL, MVT::i64, 0,
3875 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3877 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
3878 DAG.getTargetConstant(0, DL, MVT::i32)),
3880 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
3881 DAG.getTargetConstant(0, DL, MVT::i32)),
3883 } else if (Model == TLSModel::GeneralDynamic) {
3884 // The call needs a relocation too for linker relaxation. It doesn't make
3885 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3888 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3890 // Finally we can make a call to calculate the offset from tpidr_el0.
3891 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
3893 llvm_unreachable("Unsupported ELF TLS access model");
3895 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
3898 SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
3899 SelectionDAG &DAG) const {
3900 if (Subtarget->isTargetDarwin())
3901 return LowerDarwinGlobalTLSAddress(Op, DAG);
3902 if (Subtarget->isTargetELF())
3903 return LowerELFGlobalTLSAddress(Op, DAG);
3905 llvm_unreachable("Unexpected platform trying to use TLS");
3908 SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3909 SDValue Chain = Op.getOperand(0);
3910 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3911 SDValue LHS = Op.getOperand(2);
3912 SDValue RHS = Op.getOperand(3);
3913 SDValue Dest = Op.getOperand(4);
3916 // Handle f128 first, since lowering it will result in comparing the return
3917 // value of a libcall against zero, which is just what the rest of LowerBR_CC
3918 // is expecting to deal with.
3919 if (LHS.getValueType() == MVT::f128) {
3920 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3922 // If softenSetCCOperands returned a scalar, we need to compare the result
3923 // against zero to select between true and false values.
3924 if (!RHS.getNode()) {
3925 RHS = DAG.getConstant(0, dl, LHS.getValueType());
3930 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
3932 unsigned Opc = LHS.getOpcode();
3933 if (LHS.getResNo() == 1 && isOneConstant(RHS) &&
3934 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3935 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
3936 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
3937 "Unexpected condition code.");
3938 // Only lower legal XALUO ops.
3939 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
3942 // The actual operation with overflow check.
3943 AArch64CC::CondCode OFCC;
3944 SDValue Value, Overflow;
3945 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
3947 if (CC == ISD::SETNE)
3948 OFCC = getInvertedCondCode(OFCC);
3949 SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
3951 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3955 if (LHS.getValueType().isInteger()) {
3956 assert((LHS.getValueType() == RHS.getValueType()) &&
3957 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3959 // If the RHS of the comparison is zero, we can potentially fold this
3960 // to a specialized branch.
3961 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
3962 if (RHSC && RHSC->getZExtValue() == 0) {
3963 if (CC == ISD::SETEQ) {
3964 // See if we can use a TBZ to fold in an AND as well.
3965 // TBZ has a smaller branch displacement than CBZ. If the offset is
3966 // out of bounds, a late MI-layer pass rewrites branches.
3967 // 403.gcc is an example that hits this case.
3968 if (LHS.getOpcode() == ISD::AND &&
3969 isa<ConstantSDNode>(LHS.getOperand(1)) &&
3970 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3971 SDValue Test = LHS.getOperand(0);
3972 uint64_t Mask = LHS.getConstantOperandVal(1);
3973 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
3974 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3978 return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
3979 } else if (CC == ISD::SETNE) {
3980 // See if we can use a TBZ to fold in an AND as well.
3981 // TBZ has a smaller branch displacement than CBZ. If the offset is
3982 // out of bounds, a late MI-layer pass rewrites branches.
3983 // 403.gcc is an example that hits this case.
3984 if (LHS.getOpcode() == ISD::AND &&
3985 isa<ConstantSDNode>(LHS.getOperand(1)) &&
3986 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3987 SDValue Test = LHS.getOperand(0);
3988 uint64_t Mask = LHS.getConstantOperandVal(1);
3989 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
3990 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3994 return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
3995 } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
3996 // Don't combine AND since emitComparison converts the AND to an ANDS
3997 // (a.k.a. TST) and the test in the test bit and branch instruction
3998 // becomes redundant. This would also increase register pressure.
3999 uint64_t Mask = LHS.getValueSizeInBits() - 1;
4000 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
4001 DAG.getConstant(Mask, dl, MVT::i64), Dest);
4004 if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
4005 LHS.getOpcode() != ISD::AND) {
4006 // Don't combine AND since emitComparison converts the AND to an ANDS
4007 // (a.k.a. TST) and the test in the test bit and branch instruction
4008 // becomes redundant. This would also increase register pressure.
4009 uint64_t Mask = LHS.getValueSizeInBits() - 1;
4010 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
4011 DAG.getConstant(Mask, dl, MVT::i64), Dest);
4015 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
4016 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
4020 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
4022 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4023 // clean. Some of them require two branches to implement.
4024 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
4025 AArch64CC::CondCode CC1, CC2;
4026 changeFPCCToAArch64CC(CC, CC1, CC2);
4027 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
4029 DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
4030 if (CC2 != AArch64CC::AL) {
4031 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
4032 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
4039 SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
4040 SelectionDAG &DAG) const {
4041 EVT VT = Op.getValueType();
4044 SDValue In1 = Op.getOperand(0);
4045 SDValue In2 = Op.getOperand(1);
4046 EVT SrcVT = In2.getValueType();
4048 if (SrcVT.bitsLT(VT))
4049 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
4050 else if (SrcVT.bitsGT(VT))
4051 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
4056 SDValue VecVal1, VecVal2;
4057 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
4059 VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
4060 EltMask = 0x80000000ULL;
4062 if (!VT.isVector()) {
4063 VecVal1 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
4064 DAG.getUNDEF(VecVT), In1);
4065 VecVal2 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
4066 DAG.getUNDEF(VecVT), In2);
4068 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
4069 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
4071 } else if (VT == MVT::f64 || VT == MVT::v2f64) {
4075 // We want to materialize a mask with the high bit set, but the AdvSIMD
4076 // immediate moves cannot materialize that in a single instruction for
4077 // 64-bit elements. Instead, materialize zero and then negate it.
4080 if (!VT.isVector()) {
4081 VecVal1 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
4082 DAG.getUNDEF(VecVT), In1);
4083 VecVal2 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
4084 DAG.getUNDEF(VecVT), In2);
4086 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
4087 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
4090 llvm_unreachable("Invalid type for copysign!");
4093 SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
4095 // If we couldn't materialize the mask above, then the mask vector will be
4096 // the zero vector, and we need to negate it here.
4097 if (VT == MVT::f64 || VT == MVT::v2f64) {
4098 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
4099 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
4100 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
4104 DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
4107 return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
4108 else if (VT == MVT::f64)
4109 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
4111 return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
4114 SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
4115 if (DAG.getMachineFunction().getFunction()->hasFnAttribute(
4116 Attribute::NoImplicitFloat))
4119 if (!Subtarget->hasNEON())
4122 // While there is no integer popcount instruction, it can
4123 // be more efficiently lowered to the following sequence that uses
4124 // AdvSIMD registers/instructions as long as the copies to/from
4125 // the AdvSIMD registers are cheap.
4126 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd
4127 // CNT V0.8B, V0.8B // 8xbyte pop-counts
4128 // ADDV B0, V0.8B // sum 8xbyte pop-counts
4129 // UMOV X0, V0.B[0] // copy byte result back to integer reg
4130 SDValue Val = Op.getOperand(0);
4132 EVT VT = Op.getValueType();
4135 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
4136 Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
4138 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
4139 SDValue UaddLV = DAG.getNode(
4140 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
4141 DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
4144 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
4148 SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
4150 if (Op.getValueType().isVector())
4151 return LowerVSETCC(Op, DAG);
4153 SDValue LHS = Op.getOperand(0);
4154 SDValue RHS = Op.getOperand(1);
4155 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
4158 // We chose ZeroOrOneBooleanContents, so use zero and one.
4159 EVT VT = Op.getValueType();
4160 SDValue TVal = DAG.getConstant(1, dl, VT);
4161 SDValue FVal = DAG.getConstant(0, dl, VT);
4163 // Handle f128 first, since one possible outcome is a normal integer
4164 // comparison which gets picked up by the next if statement.
4165 if (LHS.getValueType() == MVT::f128) {
4166 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
4168 // If softenSetCCOperands returned a scalar, use it.
4169 if (!RHS.getNode()) {
4170 assert(LHS.getValueType() == Op.getValueType() &&
4171 "Unexpected setcc expansion!");
4176 if (LHS.getValueType().isInteger()) {
4179 getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
4181 // Note that we inverted the condition above, so we reverse the order of
4182 // the true and false operands here. This will allow the setcc to be
4183 // matched to a single CSINC instruction.
4184 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
4187 // Now we know we're dealing with FP values.
4188 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
4190 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
4191 // and do the comparison.
4192 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
4194 AArch64CC::CondCode CC1, CC2;
4195 changeFPCCToAArch64CC(CC, CC1, CC2);
4196 if (CC2 == AArch64CC::AL) {
4197 changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
4198 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
4200 // Note that we inverted the condition above, so we reverse the order of
4201 // the true and false operands here. This will allow the setcc to be
4202 // matched to a single CSINC instruction.
4203 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
4205 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
4206 // totally clean. Some of them require two CSELs to implement. As is in
4207 // this case, we emit the first CSEL and then emit a second using the output
4208 // of the first as the RHS. We're effectively OR'ing the two CC's together.
4210 // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
4211 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
4213 DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4215 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
4216 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4220 SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
4221 SDValue RHS, SDValue TVal,
4222 SDValue FVal, const SDLoc &dl,
4223 SelectionDAG &DAG) const {
4224 // Handle f128 first, because it will result in a comparison of some RTLIB
4225 // call result against zero.
4226 if (LHS.getValueType() == MVT::f128) {
4227 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
4229 // If softenSetCCOperands returned a scalar, we need to compare the result
4230 // against zero to select between true and false values.
4231 if (!RHS.getNode()) {
4232 RHS = DAG.getConstant(0, dl, LHS.getValueType());
4237 // Also handle f16, for which we need to do a f32 comparison.
4238 if (LHS.getValueType() == MVT::f16) {
4239 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
4240 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
4243 // Next, handle integers.
4244 if (LHS.getValueType().isInteger()) {
4245 assert((LHS.getValueType() == RHS.getValueType()) &&
4246 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
4248 unsigned Opcode = AArch64ISD::CSEL;
4250 // If both the TVal and the FVal are constants, see if we can swap them in
4251 // order to for a CSINV or CSINC out of them.
4252 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
4253 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
4255 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
4256 std::swap(TVal, FVal);
4257 std::swap(CTVal, CFVal);
4258 CC = ISD::getSetCCInverse(CC, true);
4259 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
4260 std::swap(TVal, FVal);
4261 std::swap(CTVal, CFVal);
4262 CC = ISD::getSetCCInverse(CC, true);
4263 } else if (TVal.getOpcode() == ISD::XOR) {
4264 // If TVal is a NOT we want to swap TVal and FVal so that we can match
4265 // with a CSINV rather than a CSEL.
4266 if (isAllOnesConstant(TVal.getOperand(1))) {
4267 std::swap(TVal, FVal);
4268 std::swap(CTVal, CFVal);
4269 CC = ISD::getSetCCInverse(CC, true);
4271 } else if (TVal.getOpcode() == ISD::SUB) {
4272 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
4273 // that we can match with a CSNEG rather than a CSEL.
4274 if (isNullConstant(TVal.getOperand(0))) {
4275 std::swap(TVal, FVal);
4276 std::swap(CTVal, CFVal);
4277 CC = ISD::getSetCCInverse(CC, true);
4279 } else if (CTVal && CFVal) {
4280 const int64_t TrueVal = CTVal->getSExtValue();
4281 const int64_t FalseVal = CFVal->getSExtValue();
4284 // If both TVal and FVal are constants, see if FVal is the
4285 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
4286 // instead of a CSEL in that case.
4287 if (TrueVal == ~FalseVal) {
4288 Opcode = AArch64ISD::CSINV;
4289 } else if (TrueVal == -FalseVal) {
4290 Opcode = AArch64ISD::CSNEG;
4291 } else if (TVal.getValueType() == MVT::i32) {
4292 // If our operands are only 32-bit wide, make sure we use 32-bit
4293 // arithmetic for the check whether we can use CSINC. This ensures that
4294 // the addition in the check will wrap around properly in case there is
4295 // an overflow (which would not be the case if we do the check with
4296 // 64-bit arithmetic).
4297 const uint32_t TrueVal32 = CTVal->getZExtValue();
4298 const uint32_t FalseVal32 = CFVal->getZExtValue();
4300 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
4301 Opcode = AArch64ISD::CSINC;
4303 if (TrueVal32 > FalseVal32) {
4307 // 64-bit check whether we can use CSINC.
4308 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
4309 Opcode = AArch64ISD::CSINC;
4311 if (TrueVal > FalseVal) {
4316 // Swap TVal and FVal if necessary.
4318 std::swap(TVal, FVal);
4319 std::swap(CTVal, CFVal);
4320 CC = ISD::getSetCCInverse(CC, true);
4323 if (Opcode != AArch64ISD::CSEL) {
4324 // Drop FVal since we can get its value by simply inverting/negating
4330 // Avoid materializing a constant when possible by reusing a known value in
4331 // a register. However, don't perform this optimization if the known value
4332 // is one, zero or negative one in the case of a CSEL. We can always
4333 // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the
4334 // FVal, respectively.
4335 ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS);
4336 if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() &&
4337 !RHSVal->isNullValue() && !RHSVal->isAllOnesValue()) {
4338 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
4339 // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to
4340 // "a != C ? x : a" to avoid materializing C.
4341 if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ)
4343 else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE)
4345 } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) {
4346 assert (CTVal && CFVal && "Expected constant operands for CSNEG.");
4347 // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to
4348 // avoid materializing C.
4349 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
4350 if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) {
4351 Opcode = AArch64ISD::CSINV;
4353 FVal = DAG.getConstant(0, dl, FVal.getValueType());
4358 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
4360 EVT VT = TVal.getValueType();
4361 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
4364 // Now we know we're dealing with FP values.
4365 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
4366 assert(LHS.getValueType() == RHS.getValueType());
4367 EVT VT = TVal.getValueType();
4368 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
4370 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4371 // clean. Some of them require two CSELs to implement.
4372 AArch64CC::CondCode CC1, CC2;
4373 changeFPCCToAArch64CC(CC, CC1, CC2);
4375 if (DAG.getTarget().Options.UnsafeFPMath) {
4376 // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and
4377 // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0.
4378 ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS);
4379 if (RHSVal && RHSVal->isZero()) {
4380 ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal);
4381 ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal);
4383 if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) &&
4384 CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType())
4386 else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) &&
4387 CFVal && CFVal->isZero() &&
4388 FVal.getValueType() == LHS.getValueType())
4393 // Emit first, and possibly only, CSEL.
4394 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
4395 SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4397 // If we need a second CSEL, emit it, using the output of the first as the
4398 // RHS. We're effectively OR'ing the two CC's together.
4399 if (CC2 != AArch64CC::AL) {
4400 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
4401 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4404 // Otherwise, return the output of the first CSEL.
4408 SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
4409 SelectionDAG &DAG) const {
4410 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4411 SDValue LHS = Op.getOperand(0);
4412 SDValue RHS = Op.getOperand(1);
4413 SDValue TVal = Op.getOperand(2);
4414 SDValue FVal = Op.getOperand(3);
4416 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4419 SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
4420 SelectionDAG &DAG) const {
4421 SDValue CCVal = Op->getOperand(0);
4422 SDValue TVal = Op->getOperand(1);
4423 SDValue FVal = Op->getOperand(2);
4426 unsigned Opc = CCVal.getOpcode();
4427 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
4429 if (CCVal.getResNo() == 1 &&
4430 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4431 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
4432 // Only lower legal XALUO ops.
4433 if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
4436 AArch64CC::CondCode OFCC;
4437 SDValue Value, Overflow;
4438 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
4439 SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
4441 return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
4445 // Lower it the same way as we would lower a SELECT_CC node.
4448 if (CCVal.getOpcode() == ISD::SETCC) {
4449 LHS = CCVal.getOperand(0);
4450 RHS = CCVal.getOperand(1);
4451 CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
4454 RHS = DAG.getConstant(0, DL, CCVal.getValueType());
4457 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4460 SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
4461 SelectionDAG &DAG) const {
4462 // Jump table entries as PC relative offsets. No additional tweaking
4463 // is necessary here. Just get the address of the jump table.
4464 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
4466 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4467 !Subtarget->isTargetMachO()) {
4468 return getAddrLarge(JT, DAG);
4470 return getAddr(JT, DAG);
4473 SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
4474 SelectionDAG &DAG) const {
4475 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
4477 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4478 // Use the GOT for the large code model on iOS.
4479 if (Subtarget->isTargetMachO()) {
4480 return getGOT(CP, DAG);
4482 return getAddrLarge(CP, DAG);
4484 return getAddr(CP, DAG);
4488 SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
4489 SelectionDAG &DAG) const {
4490 BlockAddressSDNode *BA = cast<BlockAddressSDNode>(Op);
4491 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4492 !Subtarget->isTargetMachO()) {
4493 return getAddrLarge(BA, DAG);
4495 return getAddr(BA, DAG);
4499 SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
4500 SelectionDAG &DAG) const {
4501 AArch64FunctionInfo *FuncInfo =
4502 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4505 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
4506 getPointerTy(DAG.getDataLayout()));
4507 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4508 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
4509 MachinePointerInfo(SV));
4512 SDValue AArch64TargetLowering::LowerWin64_VASTART(SDValue Op,
4513 SelectionDAG &DAG) const {
4514 AArch64FunctionInfo *FuncInfo =
4515 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4518 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsGPRSize() > 0
4519 ? FuncInfo->getVarArgsGPRIndex()
4520 : FuncInfo->getVarArgsStackIndex(),
4521 getPointerTy(DAG.getDataLayout()));
4522 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4523 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
4524 MachinePointerInfo(SV));
4527 SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
4528 SelectionDAG &DAG) const {
4529 // The layout of the va_list struct is specified in the AArch64 Procedure Call
4530 // Standard, section B.3.
4531 MachineFunction &MF = DAG.getMachineFunction();
4532 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
4533 auto PtrVT = getPointerTy(DAG.getDataLayout());
4536 SDValue Chain = Op.getOperand(0);
4537 SDValue VAList = Op.getOperand(1);
4538 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4539 SmallVector<SDValue, 4> MemOps;
4541 // void *__stack at offset 0
4542 SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
4543 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
4544 MachinePointerInfo(SV), /* Alignment = */ 8));
4546 // void *__gr_top at offset 8
4547 int GPRSize = FuncInfo->getVarArgsGPRSize();
4549 SDValue GRTop, GRTopAddr;
4552 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
4554 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
4555 GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
4556 DAG.getConstant(GPRSize, DL, PtrVT));
4558 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
4559 MachinePointerInfo(SV, 8),
4560 /* Alignment = */ 8));
4563 // void *__vr_top at offset 16
4564 int FPRSize = FuncInfo->getVarArgsFPRSize();
4566 SDValue VRTop, VRTopAddr;
4567 VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4568 DAG.getConstant(16, DL, PtrVT));
4570 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
4571 VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
4572 DAG.getConstant(FPRSize, DL, PtrVT));
4574 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
4575 MachinePointerInfo(SV, 16),
4576 /* Alignment = */ 8));
4579 // int __gr_offs at offset 24
4580 SDValue GROffsAddr =
4581 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
4582 MemOps.push_back(DAG.getStore(
4583 Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32), GROffsAddr,
4584 MachinePointerInfo(SV, 24), /* Alignment = */ 4));
4586 // int __vr_offs at offset 28
4587 SDValue VROffsAddr =
4588 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
4589 MemOps.push_back(DAG.getStore(
4590 Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32), VROffsAddr,
4591 MachinePointerInfo(SV, 28), /* Alignment = */ 4));
4593 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
4596 SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
4597 SelectionDAG &DAG) const {
4598 MachineFunction &MF = DAG.getMachineFunction();
4600 if (Subtarget->isCallingConvWin64(MF.getFunction()->getCallingConv()))
4601 return LowerWin64_VASTART(Op, DAG);
4602 else if (Subtarget->isTargetDarwin())
4603 return LowerDarwin_VASTART(Op, DAG);
4605 return LowerAAPCS_VASTART(Op, DAG);
4608 SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
4609 SelectionDAG &DAG) const {
4610 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
4613 unsigned VaListSize =
4614 Subtarget->isTargetDarwin() || Subtarget->isTargetWindows() ? 8 : 32;
4615 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4616 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4618 return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1),
4620 DAG.getConstant(VaListSize, DL, MVT::i32),
4621 8, false, false, false, MachinePointerInfo(DestSV),
4622 MachinePointerInfo(SrcSV));
4625 SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
4626 assert(Subtarget->isTargetDarwin() &&
4627 "automatic va_arg instruction only works on Darwin");
4629 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4630 EVT VT = Op.getValueType();
4632 SDValue Chain = Op.getOperand(0);
4633 SDValue Addr = Op.getOperand(1);
4634 unsigned Align = Op.getConstantOperandVal(3);
4635 auto PtrVT = getPointerTy(DAG.getDataLayout());
4637 SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V));
4638 Chain = VAList.getValue(1);
4641 assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
4642 VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4643 DAG.getConstant(Align - 1, DL, PtrVT));
4644 VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
4645 DAG.getConstant(-(int64_t)Align, DL, PtrVT));
4648 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
4649 uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
4651 // Scalar integer and FP values smaller than 64 bits are implicitly extended
4652 // up to 64 bits. At the very least, we have to increase the striding of the
4653 // vaargs list to match this, and for FP values we need to introduce
4654 // FP_ROUND nodes as well.
4655 if (VT.isInteger() && !VT.isVector())
4657 bool NeedFPTrunc = false;
4658 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
4663 // Increment the pointer, VAList, to the next vaarg
4664 SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4665 DAG.getConstant(ArgSize, DL, PtrVT));
4666 // Store the incremented VAList to the legalized pointer
4668 DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V));
4670 // Load the actual argument out of the pointer VAList
4672 // Load the value as an f64.
4674 DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo());
4675 // Round the value down to an f32.
4676 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
4677 DAG.getIntPtrConstant(1, DL));
4678 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
4679 // Merge the rounded value with the chain output of the load.
4680 return DAG.getMergeValues(Ops, DL);
4683 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo());
4686 SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
4687 SelectionDAG &DAG) const {
4688 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
4689 MFI.setFrameAddressIsTaken(true);
4691 EVT VT = Op.getValueType();
4693 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4695 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
4697 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
4698 MachinePointerInfo());
4702 // FIXME? Maybe this could be a TableGen attribute on some registers and
4703 // this table could be generated automatically from RegInfo.
4704 unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT,
4705 SelectionDAG &DAG) const {
4706 unsigned Reg = StringSwitch<unsigned>(RegName)
4707 .Case("sp", AArch64::SP)
4708 .Case("x18", AArch64::X18)
4709 .Case("w18", AArch64::W18)
4711 if ((Reg == AArch64::X18 || Reg == AArch64::W18) &&
4712 !Subtarget->isX18Reserved())
4716 report_fatal_error(Twine("Invalid register name \""
4717 + StringRef(RegName) + "\"."));
4720 SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
4721 SelectionDAG &DAG) const {
4722 MachineFunction &MF = DAG.getMachineFunction();
4723 MachineFrameInfo &MFI = MF.getFrameInfo();
4724 MFI.setReturnAddressIsTaken(true);
4726 EVT VT = Op.getValueType();
4728 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4730 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4731 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
4732 return DAG.getLoad(VT, DL, DAG.getEntryNode(),
4733 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
4734 MachinePointerInfo());
4737 // Return LR, which contains the return address. Mark it an implicit live-in.
4738 unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
4739 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4742 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4743 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
4744 SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
4745 SelectionDAG &DAG) const {
4746 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4747 EVT VT = Op.getValueType();
4748 unsigned VTBits = VT.getSizeInBits();
4750 SDValue ShOpLo = Op.getOperand(0);
4751 SDValue ShOpHi = Op.getOperand(1);
4752 SDValue ShAmt = Op.getOperand(2);
4753 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4755 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4757 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
4758 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
4759 SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4761 // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
4762 // is "undef". We wanted 0, so CSEL it directly.
4763 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
4764 ISD::SETEQ, dl, DAG);
4765 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
4767 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
4768 HiBitsForLo, CCVal, Cmp);
4770 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
4771 DAG.getConstant(VTBits, dl, MVT::i64));
4773 SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4774 SDValue LoForNormalShift =
4775 DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
4777 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
4779 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4780 SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4781 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
4782 LoForNormalShift, CCVal, Cmp);
4784 // AArch64 shifts larger than the register width are wrapped rather than
4785 // clamped, so we can't just emit "hi >> x".
4786 SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4787 SDValue HiForBigShift =
4789 ? DAG.getNode(Opc, dl, VT, ShOpHi,
4790 DAG.getConstant(VTBits - 1, dl, MVT::i64))
4791 : DAG.getConstant(0, dl, VT);
4792 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
4793 HiForNormalShift, CCVal, Cmp);
4795 SDValue Ops[2] = { Lo, Hi };
4796 return DAG.getMergeValues(Ops, dl);
4799 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4800 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
4801 SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
4802 SelectionDAG &DAG) const {
4803 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4804 EVT VT = Op.getValueType();
4805 unsigned VTBits = VT.getSizeInBits();
4807 SDValue ShOpLo = Op.getOperand(0);
4808 SDValue ShOpHi = Op.getOperand(1);
4809 SDValue ShAmt = Op.getOperand(2);
4811 assert(Op.getOpcode() == ISD::SHL_PARTS);
4812 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
4813 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
4814 SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4816 // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
4817 // is "undef". We wanted 0, so CSEL it directly.
4818 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
4819 ISD::SETEQ, dl, DAG);
4820 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
4822 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
4823 LoBitsForHi, CCVal, Cmp);
4825 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
4826 DAG.getConstant(VTBits, dl, MVT::i64));
4827 SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4828 SDValue HiForNormalShift =
4829 DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
4831 SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4833 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
4835 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4836 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
4837 HiForNormalShift, CCVal, Cmp);
4839 // AArch64 shifts of larger than register sizes are wrapped rather than
4840 // clamped, so we can't just emit "lo << a" if a is too big.
4841 SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
4842 SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4843 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
4844 LoForNormalShift, CCVal, Cmp);
4846 SDValue Ops[2] = { Lo, Hi };
4847 return DAG.getMergeValues(Ops, dl);
4850 bool AArch64TargetLowering::isOffsetFoldingLegal(
4851 const GlobalAddressSDNode *GA) const {
4852 // The AArch64 target doesn't support folding offsets into global addresses.
4856 bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4857 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
4858 // FIXME: We should be able to handle f128 as well with a clever lowering.
4859 if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32))
4863 return AArch64_AM::getFP64Imm(Imm) != -1;
4864 else if (VT == MVT::f32)
4865 return AArch64_AM::getFP32Imm(Imm) != -1;
4869 //===----------------------------------------------------------------------===//
4870 // AArch64 Optimization Hooks
4871 //===----------------------------------------------------------------------===//
4873 static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode,
4874 SDValue Operand, SelectionDAG &DAG,
4876 EVT VT = Operand.getValueType();
4877 if (ST->hasNEON() &&
4878 (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 ||
4879 VT == MVT::f32 || VT == MVT::v1f32 ||
4880 VT == MVT::v2f32 || VT == MVT::v4f32)) {
4881 if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified)
4882 // For the reciprocal estimates, convergence is quadratic, so the number
4883 // of digits is doubled after each iteration. In ARMv8, the accuracy of
4884 // the initial estimate is 2^-8. Thus the number of extra steps to refine
4885 // the result for float (23 mantissa bits) is 2 and for double (52
4886 // mantissa bits) is 3.
4887 ExtraSteps = VT == MVT::f64 ? 3 : 2;
4889 return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand);
4895 SDValue AArch64TargetLowering::getSqrtEstimate(SDValue Operand,
4896 SelectionDAG &DAG, int Enabled,
4899 bool Reciprocal) const {
4900 if (Enabled == ReciprocalEstimate::Enabled ||
4901 (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt()))
4902 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, Operand,
4905 EVT VT = Operand.getValueType();
4908 Flags.setUnsafeAlgebra(true);
4910 // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2)
4911 // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N)
4912 for (int i = ExtraSteps; i > 0; --i) {
4913 SDValue Step = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Estimate,
4915 Step = DAG.getNode(AArch64ISD::FRSQRTS, DL, VT, Operand, Step, Flags);
4916 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
4920 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
4922 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
4923 SDValue Eq = DAG.getSetCC(DL, CCVT, Operand, FPZero, ISD::SETEQ);
4925 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Operand, Estimate, Flags);
4926 // Correct the result if the operand is 0.0.
4927 Estimate = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL,
4928 VT, Eq, Operand, Estimate);
4938 SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand,
4939 SelectionDAG &DAG, int Enabled,
4940 int &ExtraSteps) const {
4941 if (Enabled == ReciprocalEstimate::Enabled)
4942 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand,
4945 EVT VT = Operand.getValueType();
4948 Flags.setUnsafeAlgebra(true);
4950 // Newton reciprocal iteration: E * (2 - X * E)
4951 // AArch64 reciprocal iteration instruction: (2 - M * N)
4952 for (int i = ExtraSteps; i > 0; --i) {
4953 SDValue Step = DAG.getNode(AArch64ISD::FRECPS, DL, VT, Operand,
4955 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
4965 //===----------------------------------------------------------------------===//
4966 // AArch64 Inline Assembly Support
4967 //===----------------------------------------------------------------------===//
4969 // Table of Constraints
4970 // TODO: This is the current set of constraints supported by ARM for the
4971 // compiler, not all of them may make sense, e.g. S may be difficult to support.
4973 // r - A general register
4974 // w - An FP/SIMD register of some size in the range v0-v31
4975 // x - An FP/SIMD register of some size in the range v0-v15
4976 // I - Constant that can be used with an ADD instruction
4977 // J - Constant that can be used with a SUB instruction
4978 // K - Constant that can be used with a 32-bit logical instruction
4979 // L - Constant that can be used with a 64-bit logical instruction
4980 // M - Constant that can be used as a 32-bit MOV immediate
4981 // N - Constant that can be used as a 64-bit MOV immediate
4982 // Q - A memory reference with base register and no offset
4983 // S - A symbolic address
4984 // Y - Floating point constant zero
4985 // Z - Integer constant zero
4987 // Note that general register operands will be output using their 64-bit x
4988 // register name, whatever the size of the variable, unless the asm operand
4989 // is prefixed by the %w modifier. Floating-point and SIMD register operands
4990 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
4992 const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
4993 // At this point, we have to lower this constraint to something else, so we
4994 // lower it to an "r" or "w". However, by doing this we will force the result
4995 // to be in register, while the X constraint is much more permissive.
4997 // Although we are correct (we are free to emit anything, without
4998 // constraints), we might break use cases that would expect us to be more
4999 // efficient and emit something else.
5000 if (!Subtarget->hasFPARMv8())
5003 if (ConstraintVT.isFloatingPoint())
5006 if (ConstraintVT.isVector() &&
5007 (ConstraintVT.getSizeInBits() == 64 ||
5008 ConstraintVT.getSizeInBits() == 128))
5014 /// getConstraintType - Given a constraint letter, return the type of
5015 /// constraint it is for this target.
5016 AArch64TargetLowering::ConstraintType
5017 AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
5018 if (Constraint.size() == 1) {
5019 switch (Constraint[0]) {
5026 return C_RegisterClass;
5027 // An address with a single base register. Due to the way we
5028 // currently handle addresses it is the same as 'r'.
5033 return TargetLowering::getConstraintType(Constraint);
5036 /// Examine constraint type and operand type and determine a weight value.
5037 /// This object must already have been set up with the operand type
5038 /// and the current alternative constraint selected.
5039 TargetLowering::ConstraintWeight
5040 AArch64TargetLowering::getSingleConstraintMatchWeight(
5041 AsmOperandInfo &info, const char *constraint) const {
5042 ConstraintWeight weight = CW_Invalid;
5043 Value *CallOperandVal = info.CallOperandVal;
5044 // If we don't have a value, we can't do a match,
5045 // but allow it at the lowest weight.
5046 if (!CallOperandVal)
5048 Type *type = CallOperandVal->getType();
5049 // Look at the constraint type.
5050 switch (*constraint) {
5052 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
5056 if (type->isFloatingPointTy() || type->isVectorTy())
5057 weight = CW_Register;
5060 weight = CW_Constant;
5066 std::pair<unsigned, const TargetRegisterClass *>
5067 AArch64TargetLowering::getRegForInlineAsmConstraint(
5068 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
5069 if (Constraint.size() == 1) {
5070 switch (Constraint[0]) {
5072 if (VT.getSizeInBits() == 64)
5073 return std::make_pair(0U, &AArch64::GPR64commonRegClass);
5074 return std::make_pair(0U, &AArch64::GPR32commonRegClass);
5076 if (VT.getSizeInBits() == 16)
5077 return std::make_pair(0U, &AArch64::FPR16RegClass);
5078 if (VT.getSizeInBits() == 32)
5079 return std::make_pair(0U, &AArch64::FPR32RegClass);
5080 if (VT.getSizeInBits() == 64)
5081 return std::make_pair(0U, &AArch64::FPR64RegClass);
5082 if (VT.getSizeInBits() == 128)
5083 return std::make_pair(0U, &AArch64::FPR128RegClass);
5085 // The instructions that this constraint is designed for can
5086 // only take 128-bit registers so just use that regclass.
5088 if (VT.getSizeInBits() == 128)
5089 return std::make_pair(0U, &AArch64::FPR128_loRegClass);
5093 if (StringRef("{cc}").equals_lower(Constraint))
5094 return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
5096 // Use the default implementation in TargetLowering to convert the register
5097 // constraint into a member of a register class.
5098 std::pair<unsigned, const TargetRegisterClass *> Res;
5099 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
5101 // Not found as a standard register?
5103 unsigned Size = Constraint.size();
5104 if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
5105 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
5107 bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
5108 if (!Failed && RegNo >= 0 && RegNo <= 31) {
5109 // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size.
5110 // By default we'll emit v0-v31 for this unless there's a modifier where
5111 // we'll emit the correct register as well.
5112 if (VT != MVT::Other && VT.getSizeInBits() == 64) {
5113 Res.first = AArch64::FPR64RegClass.getRegister(RegNo);
5114 Res.second = &AArch64::FPR64RegClass;
5116 Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
5117 Res.second = &AArch64::FPR128RegClass;
5126 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
5127 /// vector. If it is invalid, don't add anything to Ops.
5128 void AArch64TargetLowering::LowerAsmOperandForConstraint(
5129 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
5130 SelectionDAG &DAG) const {
5133 // Currently only support length 1 constraints.
5134 if (Constraint.length() != 1)
5137 char ConstraintLetter = Constraint[0];
5138 switch (ConstraintLetter) {
5142 // This set of constraints deal with valid constants for various instructions.
5143 // Validate and return a target constant for them if we can.
5145 // 'z' maps to xzr or wzr so it needs an input of 0.
5146 if (!isNullConstant(Op))
5149 if (Op.getValueType() == MVT::i64)
5150 Result = DAG.getRegister(AArch64::XZR, MVT::i64);
5152 Result = DAG.getRegister(AArch64::WZR, MVT::i32);
5162 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
5166 // Grab the value and do some validation.
5167 uint64_t CVal = C->getZExtValue();
5168 switch (ConstraintLetter) {
5169 // The I constraint applies only to simple ADD or SUB immediate operands:
5170 // i.e. 0 to 4095 with optional shift by 12
5171 // The J constraint applies only to ADD or SUB immediates that would be
5172 // valid when negated, i.e. if [an add pattern] were to be output as a SUB
5173 // instruction [or vice versa], in other words -1 to -4095 with optional
5174 // left shift by 12.
5176 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
5180 uint64_t NVal = -C->getSExtValue();
5181 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
5182 CVal = C->getSExtValue();
5187 // The K and L constraints apply *only* to logical immediates, including
5188 // what used to be the MOVI alias for ORR (though the MOVI alias has now
5189 // been removed and MOV should be used). So these constraints have to
5190 // distinguish between bit patterns that are valid 32-bit or 64-bit
5191 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
5192 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
5195 if (AArch64_AM::isLogicalImmediate(CVal, 32))
5199 if (AArch64_AM::isLogicalImmediate(CVal, 64))
5202 // The M and N constraints are a superset of K and L respectively, for use
5203 // with the MOV (immediate) alias. As well as the logical immediates they
5204 // also match 32 or 64-bit immediates that can be loaded either using a
5205 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
5206 // (M) or 64-bit 0x1234000000000000 (N) etc.
5207 // As a note some of this code is liberally stolen from the asm parser.
5209 if (!isUInt<32>(CVal))
5211 if (AArch64_AM::isLogicalImmediate(CVal, 32))
5213 if ((CVal & 0xFFFF) == CVal)
5215 if ((CVal & 0xFFFF0000ULL) == CVal)
5217 uint64_t NCVal = ~(uint32_t)CVal;
5218 if ((NCVal & 0xFFFFULL) == NCVal)
5220 if ((NCVal & 0xFFFF0000ULL) == NCVal)
5225 if (AArch64_AM::isLogicalImmediate(CVal, 64))
5227 if ((CVal & 0xFFFFULL) == CVal)
5229 if ((CVal & 0xFFFF0000ULL) == CVal)
5231 if ((CVal & 0xFFFF00000000ULL) == CVal)
5233 if ((CVal & 0xFFFF000000000000ULL) == CVal)
5235 uint64_t NCVal = ~CVal;
5236 if ((NCVal & 0xFFFFULL) == NCVal)
5238 if ((NCVal & 0xFFFF0000ULL) == NCVal)
5240 if ((NCVal & 0xFFFF00000000ULL) == NCVal)
5242 if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
5250 // All assembler immediates are 64-bit integers.
5251 Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
5255 if (Result.getNode()) {
5256 Ops.push_back(Result);
5260 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
5263 //===----------------------------------------------------------------------===//
5264 // AArch64 Advanced SIMD Support
5265 //===----------------------------------------------------------------------===//
5267 /// WidenVector - Given a value in the V64 register class, produce the
5268 /// equivalent value in the V128 register class.
5269 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
5270 EVT VT = V64Reg.getValueType();
5271 unsigned NarrowSize = VT.getVectorNumElements();
5272 MVT EltTy = VT.getVectorElementType().getSimpleVT();
5273 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
5276 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
5277 V64Reg, DAG.getConstant(0, DL, MVT::i32));
5280 /// getExtFactor - Determine the adjustment factor for the position when
5281 /// generating an "extract from vector registers" instruction.
5282 static unsigned getExtFactor(SDValue &V) {
5283 EVT EltType = V.getValueType().getVectorElementType();
5284 return EltType.getSizeInBits() / 8;
5287 /// NarrowVector - Given a value in the V128 register class, produce the
5288 /// equivalent value in the V64 register class.
5289 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
5290 EVT VT = V128Reg.getValueType();
5291 unsigned WideSize = VT.getVectorNumElements();
5292 MVT EltTy = VT.getVectorElementType().getSimpleVT();
5293 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
5296 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
5299 // Gather data to see if the operation can be modelled as a
5300 // shuffle in combination with VEXTs.
5301 SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
5302 SelectionDAG &DAG) const {
5303 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
5305 EVT VT = Op.getValueType();
5306 unsigned NumElts = VT.getVectorNumElements();
5308 struct ShuffleSourceInfo {
5313 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
5314 // be compatible with the shuffle we intend to construct. As a result
5315 // ShuffleVec will be some sliding window into the original Vec.
5318 // Code should guarantee that element i in Vec starts at element "WindowBase
5319 // + i * WindowScale in ShuffleVec".
5323 ShuffleSourceInfo(SDValue Vec)
5324 : Vec(Vec), MinElt(std::numeric_limits<unsigned>::max()), MaxElt(0),
5325 ShuffleVec(Vec), WindowBase(0), WindowScale(1) {}
5327 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
5330 // First gather all vectors used as an immediate source for this BUILD_VECTOR
5332 SmallVector<ShuffleSourceInfo, 2> Sources;
5333 for (unsigned i = 0; i < NumElts; ++i) {
5334 SDValue V = Op.getOperand(i);
5337 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5338 !isa<ConstantSDNode>(V.getOperand(1))) {
5339 // A shuffle can only come from building a vector from various
5340 // elements of other vectors, provided their indices are constant.
5344 // Add this element source to the list if it's not already there.
5345 SDValue SourceVec = V.getOperand(0);
5346 auto Source = find(Sources, SourceVec);
5347 if (Source == Sources.end())
5348 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
5350 // Update the minimum and maximum lane number seen.
5351 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5352 Source->MinElt = std::min(Source->MinElt, EltNo);
5353 Source->MaxElt = std::max(Source->MaxElt, EltNo);
5356 // Currently only do something sane when at most two source vectors
5358 if (Sources.size() > 2)
5361 // Find out the smallest element size among result and two sources, and use
5362 // it as element size to build the shuffle_vector.
5363 EVT SmallestEltTy = VT.getVectorElementType();
5364 for (auto &Source : Sources) {
5365 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
5366 if (SrcEltTy.bitsLT(SmallestEltTy)) {
5367 SmallestEltTy = SrcEltTy;
5370 unsigned ResMultiplier =
5371 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
5372 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
5373 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
5375 // If the source vector is too wide or too narrow, we may nevertheless be able
5376 // to construct a compatible shuffle either by concatenating it with UNDEF or
5377 // extracting a suitable range of elements.
5378 for (auto &Src : Sources) {
5379 EVT SrcVT = Src.ShuffleVec.getValueType();
5381 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
5384 // This stage of the search produces a source with the same element type as
5385 // the original, but with a total width matching the BUILD_VECTOR output.
5386 EVT EltVT = SrcVT.getVectorElementType();
5387 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
5388 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
5390 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
5391 assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
5392 // We can pad out the smaller vector for free, so if it's part of a
5395 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
5396 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
5400 assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
5402 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
5403 // Span too large for a VEXT to cope
5407 if (Src.MinElt >= NumSrcElts) {
5408 // The extraction can just take the second half
5410 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5411 DAG.getConstant(NumSrcElts, dl, MVT::i64));
5412 Src.WindowBase = -NumSrcElts;
5413 } else if (Src.MaxElt < NumSrcElts) {
5414 // The extraction can just take the first half
5416 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5417 DAG.getConstant(0, dl, MVT::i64));
5419 // An actual VEXT is needed
5421 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5422 DAG.getConstant(0, dl, MVT::i64));
5424 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
5425 DAG.getConstant(NumSrcElts, dl, MVT::i64));
5426 unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
5428 Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
5430 DAG.getConstant(Imm, dl, MVT::i32));
5431 Src.WindowBase = -Src.MinElt;
5435 // Another possible incompatibility occurs from the vector element types. We
5436 // can fix this by bitcasting the source vectors to the same type we intend
5438 for (auto &Src : Sources) {
5439 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
5440 if (SrcEltTy == SmallestEltTy)
5442 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
5443 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
5444 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
5445 Src.WindowBase *= Src.WindowScale;
5448 // Final sanity check before we try to actually produce a shuffle.
5450 for (auto Src : Sources)
5451 assert(Src.ShuffleVec.getValueType() == ShuffleVT);
5454 // The stars all align, our next step is to produce the mask for the shuffle.
5455 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
5456 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
5457 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
5458 SDValue Entry = Op.getOperand(i);
5459 if (Entry.isUndef())
5462 auto Src = find(Sources, Entry.getOperand(0));
5463 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
5465 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
5466 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
5468 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
5470 std::min(OrigEltTy.getSizeInBits(), VT.getScalarSizeInBits());
5471 int LanesDefined = BitsDefined / BitsPerShuffleLane;
5473 // This source is expected to fill ResMultiplier lanes of the final shuffle,
5474 // starting at the appropriate offset.
5475 int *LaneMask = &Mask[i * ResMultiplier];
5477 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
5478 ExtractBase += NumElts * (Src - Sources.begin());
5479 for (int j = 0; j < LanesDefined; ++j)
5480 LaneMask[j] = ExtractBase + j;
5483 // Final check before we try to produce nonsense...
5484 if (!isShuffleMaskLegal(Mask, ShuffleVT))
5487 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
5488 for (unsigned i = 0; i < Sources.size(); ++i)
5489 ShuffleOps[i] = Sources[i].ShuffleVec;
5491 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
5492 ShuffleOps[1], Mask);
5493 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
5496 // check if an EXT instruction can handle the shuffle mask when the
5497 // vector sources of the shuffle are the same.
5498 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
5499 unsigned NumElts = VT.getVectorNumElements();
5501 // Assume that the first shuffle index is not UNDEF. Fail if it is.
5507 // If this is a VEXT shuffle, the immediate value is the index of the first
5508 // element. The other shuffle indices must be the successive elements after
5510 unsigned ExpectedElt = Imm;
5511 for (unsigned i = 1; i < NumElts; ++i) {
5512 // Increment the expected index. If it wraps around, just follow it
5513 // back to index zero and keep going.
5515 if (ExpectedElt == NumElts)
5519 continue; // ignore UNDEF indices
5520 if (ExpectedElt != static_cast<unsigned>(M[i]))
5527 // check if an EXT instruction can handle the shuffle mask when the
5528 // vector sources of the shuffle are different.
5529 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
5531 // Look for the first non-undef element.
5532 const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; });
5534 // Benefit form APInt to handle overflow when calculating expected element.
5535 unsigned NumElts = VT.getVectorNumElements();
5536 unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
5537 APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
5538 // The following shuffle indices must be the successive elements after the
5539 // first real element.
5540 const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
5541 [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
5542 if (FirstWrongElt != M.end())
5545 // The index of an EXT is the first element if it is not UNDEF.
5546 // Watch out for the beginning UNDEFs. The EXT index should be the expected
5547 // value of the first element. E.g.
5548 // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
5549 // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
5550 // ExpectedElt is the last mask index plus 1.
5551 Imm = ExpectedElt.getZExtValue();
5553 // There are two difference cases requiring to reverse input vectors.
5554 // For example, for vector <4 x i32> we have the following cases,
5555 // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
5556 // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
5557 // For both cases, we finally use mask <5, 6, 7, 0>, which requires
5558 // to reverse two input vectors.
5567 /// isREVMask - Check if a vector shuffle corresponds to a REV
5568 /// instruction with the specified blocksize. (The order of the elements
5569 /// within each block of the vector is reversed.)
5570 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5571 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
5572 "Only possible block sizes for REV are: 16, 32, 64");
5574 unsigned EltSz = VT.getScalarSizeInBits();
5578 unsigned NumElts = VT.getVectorNumElements();
5579 unsigned BlockElts = M[0] + 1;
5580 // If the first shuffle index is UNDEF, be optimistic.
5582 BlockElts = BlockSize / EltSz;
5584 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5587 for (unsigned i = 0; i < NumElts; ++i) {
5589 continue; // ignore UNDEF indices
5590 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
5597 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5598 unsigned NumElts = VT.getVectorNumElements();
5599 WhichResult = (M[0] == 0 ? 0 : 1);
5600 unsigned Idx = WhichResult * NumElts / 2;
5601 for (unsigned i = 0; i != NumElts; i += 2) {
5602 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5603 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
5611 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5612 unsigned NumElts = VT.getVectorNumElements();
5613 WhichResult = (M[0] == 0 ? 0 : 1);
5614 for (unsigned i = 0; i != NumElts; ++i) {
5616 continue; // ignore UNDEF indices
5617 if ((unsigned)M[i] != 2 * i + WhichResult)
5624 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5625 unsigned NumElts = VT.getVectorNumElements();
5626 WhichResult = (M[0] == 0 ? 0 : 1);
5627 for (unsigned i = 0; i < NumElts; i += 2) {
5628 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5629 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
5635 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
5636 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5637 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5638 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5639 unsigned NumElts = VT.getVectorNumElements();
5640 WhichResult = (M[0] == 0 ? 0 : 1);
5641 unsigned Idx = WhichResult * NumElts / 2;
5642 for (unsigned i = 0; i != NumElts; i += 2) {
5643 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5644 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
5652 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
5653 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5654 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5655 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5656 unsigned Half = VT.getVectorNumElements() / 2;
5657 WhichResult = (M[0] == 0 ? 0 : 1);
5658 for (unsigned j = 0; j != 2; ++j) {
5659 unsigned Idx = WhichResult;
5660 for (unsigned i = 0; i != Half; ++i) {
5661 int MIdx = M[i + j * Half];
5662 if (MIdx >= 0 && (unsigned)MIdx != Idx)
5671 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
5672 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5673 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5674 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5675 unsigned NumElts = VT.getVectorNumElements();
5676 WhichResult = (M[0] == 0 ? 0 : 1);
5677 for (unsigned i = 0; i < NumElts; i += 2) {
5678 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5679 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
5685 static bool isINSMask(ArrayRef<int> M, int NumInputElements,
5686 bool &DstIsLeft, int &Anomaly) {
5687 if (M.size() != static_cast<size_t>(NumInputElements))
5690 int NumLHSMatch = 0, NumRHSMatch = 0;
5691 int LastLHSMismatch = -1, LastRHSMismatch = -1;
5693 for (int i = 0; i < NumInputElements; ++i) {
5703 LastLHSMismatch = i;
5705 if (M[i] == i + NumInputElements)
5708 LastRHSMismatch = i;
5711 if (NumLHSMatch == NumInputElements - 1) {
5713 Anomaly = LastLHSMismatch;
5715 } else if (NumRHSMatch == NumInputElements - 1) {
5717 Anomaly = LastRHSMismatch;
5724 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
5725 if (VT.getSizeInBits() != 128)
5728 unsigned NumElts = VT.getVectorNumElements();
5730 for (int I = 0, E = NumElts / 2; I != E; I++) {
5735 int Offset = NumElts / 2;
5736 for (int I = NumElts / 2, E = NumElts; I != E; I++) {
5737 if (Mask[I] != I + SplitLHS * Offset)
5744 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
5746 EVT VT = Op.getValueType();
5747 SDValue V0 = Op.getOperand(0);
5748 SDValue V1 = Op.getOperand(1);
5749 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
5751 if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
5752 VT.getVectorElementType() != V1.getValueType().getVectorElementType())
5755 bool SplitV0 = V0.getValueSizeInBits() == 128;
5757 if (!isConcatMask(Mask, VT, SplitV0))
5760 EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
5761 VT.getVectorNumElements() / 2);
5763 V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
5764 DAG.getConstant(0, DL, MVT::i64));
5766 if (V1.getValueSizeInBits() == 128) {
5767 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
5768 DAG.getConstant(0, DL, MVT::i64));
5770 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
5773 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5774 /// the specified operations to build the shuffle.
5775 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5776 SDValue RHS, SelectionDAG &DAG,
5778 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5779 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
5780 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
5783 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5792 OP_VUZPL, // VUZP, left result
5793 OP_VUZPR, // VUZP, right result
5794 OP_VZIPL, // VZIP, left result
5795 OP_VZIPR, // VZIP, right result
5796 OP_VTRNL, // VTRN, left result
5797 OP_VTRNR // VTRN, right result
5800 if (OpNum == OP_COPY) {
5801 if (LHSID == (1 * 9 + 2) * 9 + 3)
5803 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
5807 SDValue OpLHS, OpRHS;
5808 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5809 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5810 EVT VT = OpLHS.getValueType();
5814 llvm_unreachable("Unknown shuffle opcode!");
5816 // VREV divides the vector in half and swaps within the half.
5817 if (VT.getVectorElementType() == MVT::i32 ||
5818 VT.getVectorElementType() == MVT::f32)
5819 return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
5820 // vrev <4 x i16> -> REV32
5821 if (VT.getVectorElementType() == MVT::i16 ||
5822 VT.getVectorElementType() == MVT::f16)
5823 return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
5824 // vrev <4 x i8> -> REV16
5825 assert(VT.getVectorElementType() == MVT::i8);
5826 return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
5831 EVT EltTy = VT.getVectorElementType();
5833 if (EltTy == MVT::i8)
5834 Opcode = AArch64ISD::DUPLANE8;
5835 else if (EltTy == MVT::i16 || EltTy == MVT::f16)
5836 Opcode = AArch64ISD::DUPLANE16;
5837 else if (EltTy == MVT::i32 || EltTy == MVT::f32)
5838 Opcode = AArch64ISD::DUPLANE32;
5839 else if (EltTy == MVT::i64 || EltTy == MVT::f64)
5840 Opcode = AArch64ISD::DUPLANE64;
5842 llvm_unreachable("Invalid vector element type?");
5844 if (VT.getSizeInBits() == 64)
5845 OpLHS = WidenVector(OpLHS, DAG);
5846 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
5847 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
5852 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
5853 return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
5854 DAG.getConstant(Imm, dl, MVT::i32));
5857 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
5860 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
5863 return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
5866 return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
5869 return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
5872 return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
5877 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
5878 SelectionDAG &DAG) {
5879 // Check to see if we can use the TBL instruction.
5880 SDValue V1 = Op.getOperand(0);
5881 SDValue V2 = Op.getOperand(1);
5884 EVT EltVT = Op.getValueType().getVectorElementType();
5885 unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
5887 SmallVector<SDValue, 8> TBLMask;
5888 for (int Val : ShuffleMask) {
5889 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
5890 unsigned Offset = Byte + Val * BytesPerElt;
5891 TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
5895 MVT IndexVT = MVT::v8i8;
5896 unsigned IndexLen = 8;
5897 if (Op.getValueSizeInBits() == 128) {
5898 IndexVT = MVT::v16i8;
5902 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
5903 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
5906 if (V2.getNode()->isUndef()) {
5908 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
5909 Shuffle = DAG.getNode(
5910 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5911 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
5912 DAG.getBuildVector(IndexVT, DL,
5913 makeArrayRef(TBLMask.data(), IndexLen)));
5915 if (IndexLen == 8) {
5916 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
5917 Shuffle = DAG.getNode(
5918 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5919 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
5920 DAG.getBuildVector(IndexVT, DL,
5921 makeArrayRef(TBLMask.data(), IndexLen)));
5923 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
5924 // cannot currently represent the register constraints on the input
5926 // Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
5927 // DAG.getBuildVector(IndexVT, DL, &TBLMask[0],
5929 Shuffle = DAG.getNode(
5930 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
5931 DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst,
5932 V2Cst, DAG.getBuildVector(IndexVT, DL,
5933 makeArrayRef(TBLMask.data(), IndexLen)));
5936 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
5939 static unsigned getDUPLANEOp(EVT EltType) {
5940 if (EltType == MVT::i8)
5941 return AArch64ISD::DUPLANE8;
5942 if (EltType == MVT::i16 || EltType == MVT::f16)
5943 return AArch64ISD::DUPLANE16;
5944 if (EltType == MVT::i32 || EltType == MVT::f32)
5945 return AArch64ISD::DUPLANE32;
5946 if (EltType == MVT::i64 || EltType == MVT::f64)
5947 return AArch64ISD::DUPLANE64;
5949 llvm_unreachable("Invalid vector element type?");
5952 SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5953 SelectionDAG &DAG) const {
5955 EVT VT = Op.getValueType();
5957 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5959 // Convert shuffles that are directly supported on NEON to target-specific
5960 // DAG nodes, instead of keeping them as shuffles and matching them again
5961 // during code selection. This is more efficient and avoids the possibility
5962 // of inconsistencies between legalization and selection.
5963 ArrayRef<int> ShuffleMask = SVN->getMask();
5965 SDValue V1 = Op.getOperand(0);
5966 SDValue V2 = Op.getOperand(1);
5968 if (SVN->isSplat()) {
5969 int Lane = SVN->getSplatIndex();
5970 // If this is undef splat, generate it via "just" vdup, if possible.
5974 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
5975 return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
5977 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
5978 // constant. If so, we can just reference the lane's definition directly.
5979 if (V1.getOpcode() == ISD::BUILD_VECTOR &&
5980 !isa<ConstantSDNode>(V1.getOperand(Lane)))
5981 return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
5983 // Otherwise, duplicate from the lane of the input vector.
5984 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
5986 // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
5987 // to make a vector of the same size as this SHUFFLE. We can ignore the
5988 // extract entirely, and canonicalise the concat using WidenVector.
5989 if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
5990 Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
5991 V1 = V1.getOperand(0);
5992 } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
5993 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
5994 Lane -= Idx * VT.getVectorNumElements() / 2;
5995 V1 = WidenVector(V1.getOperand(Idx), DAG);
5996 } else if (VT.getSizeInBits() == 64)
5997 V1 = WidenVector(V1, DAG);
5999 return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
6002 if (isREVMask(ShuffleMask, VT, 64))
6003 return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
6004 if (isREVMask(ShuffleMask, VT, 32))
6005 return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
6006 if (isREVMask(ShuffleMask, VT, 16))
6007 return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
6009 bool ReverseEXT = false;
6011 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
6014 Imm *= getExtFactor(V1);
6015 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
6016 DAG.getConstant(Imm, dl, MVT::i32));
6017 } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) {
6018 Imm *= getExtFactor(V1);
6019 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
6020 DAG.getConstant(Imm, dl, MVT::i32));
6023 unsigned WhichResult;
6024 if (isZIPMask(ShuffleMask, VT, WhichResult)) {
6025 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
6026 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6028 if (isUZPMask(ShuffleMask, VT, WhichResult)) {
6029 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
6030 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6032 if (isTRNMask(ShuffleMask, VT, WhichResult)) {
6033 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
6034 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
6037 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6038 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
6039 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6041 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6042 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
6043 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6045 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
6046 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
6047 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
6050 if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG))
6055 int NumInputElements = V1.getValueType().getVectorNumElements();
6056 if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
6057 SDValue DstVec = DstIsLeft ? V1 : V2;
6058 SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
6060 SDValue SrcVec = V1;
6061 int SrcLane = ShuffleMask[Anomaly];
6062 if (SrcLane >= NumInputElements) {
6064 SrcLane -= VT.getVectorNumElements();
6066 SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
6068 EVT ScalarVT = VT.getVectorElementType();
6070 if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
6071 ScalarVT = MVT::i32;
6074 ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6075 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
6079 // If the shuffle is not directly supported and it has 4 elements, use
6080 // the PerfectShuffle-generated table to synthesize it from other shuffles.
6081 unsigned NumElts = VT.getVectorNumElements();
6083 unsigned PFIndexes[4];
6084 for (unsigned i = 0; i != 4; ++i) {
6085 if (ShuffleMask[i] < 0)
6088 PFIndexes[i] = ShuffleMask[i];
6091 // Compute the index in the perfect shuffle table.
6092 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6093 PFIndexes[2] * 9 + PFIndexes[3];
6094 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6095 unsigned Cost = (PFEntry >> 30);
6098 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6101 return GenerateTBL(Op, ShuffleMask, DAG);
6104 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
6106 EVT VT = BVN->getValueType(0);
6107 APInt SplatBits, SplatUndef;
6108 unsigned SplatBitSize;
6110 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
6111 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
6113 for (unsigned i = 0; i < NumSplats; ++i) {
6114 CnstBits <<= SplatBitSize;
6115 UndefBits <<= SplatBitSize;
6116 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
6117 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
6126 SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op,
6127 SelectionDAG &DAG) const {
6128 BuildVectorSDNode *BVN =
6129 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
6130 SDValue LHS = Op.getOperand(0);
6132 EVT VT = Op.getValueType();
6137 APInt CnstBits(VT.getSizeInBits(), 0);
6138 APInt UndefBits(VT.getSizeInBits(), 0);
6139 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
6140 // We only have BIC vector immediate instruction, which is and-not.
6141 CnstBits = ~CnstBits;
6143 // We make use of a little bit of goto ickiness in order to avoid having to
6144 // duplicate the immediate matching logic for the undef toggled case.
6145 bool SecondTry = false;
6148 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
6149 CnstBits = CnstBits.zextOrTrunc(64);
6150 uint64_t CnstVal = CnstBits.getZExtValue();
6152 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6153 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6154 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6155 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
6156 DAG.getConstant(CnstVal, dl, MVT::i32),
6157 DAG.getConstant(0, dl, MVT::i32));
6158 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6161 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6162 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6163 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6164 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
6165 DAG.getConstant(CnstVal, dl, MVT::i32),
6166 DAG.getConstant(8, dl, MVT::i32));
6167 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6170 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6171 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6172 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6173 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
6174 DAG.getConstant(CnstVal, dl, MVT::i32),
6175 DAG.getConstant(16, dl, MVT::i32));
6176 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6179 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6180 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6181 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6182 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
6183 DAG.getConstant(CnstVal, dl, MVT::i32),
6184 DAG.getConstant(24, dl, MVT::i32));
6185 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6188 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6189 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6190 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6191 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
6192 DAG.getConstant(CnstVal, dl, MVT::i32),
6193 DAG.getConstant(0, dl, MVT::i32));
6194 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6197 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6198 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6199 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6200 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
6201 DAG.getConstant(CnstVal, dl, MVT::i32),
6202 DAG.getConstant(8, dl, MVT::i32));
6203 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6210 CnstBits = ~UndefBits;
6214 // We can always fall back to a non-immediate AND.
6219 // Specialized code to quickly find if PotentialBVec is a BuildVector that
6220 // consists of only the same constant int value, returned in reference arg
6222 static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
6223 uint64_t &ConstVal) {
6224 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
6227 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
6230 EVT VT = Bvec->getValueType(0);
6231 unsigned NumElts = VT.getVectorNumElements();
6232 for (unsigned i = 1; i < NumElts; ++i)
6233 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
6235 ConstVal = FirstElt->getZExtValue();
6239 static unsigned getIntrinsicID(const SDNode *N) {
6240 unsigned Opcode = N->getOpcode();
6243 return Intrinsic::not_intrinsic;
6244 case ISD::INTRINSIC_WO_CHAIN: {
6245 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
6246 if (IID < Intrinsic::num_intrinsics)
6248 return Intrinsic::not_intrinsic;
6253 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
6254 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
6255 // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
6256 // Also, logical shift right -> sri, with the same structure.
6257 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
6258 EVT VT = N->getValueType(0);
6265 // Is the first op an AND?
6266 const SDValue And = N->getOperand(0);
6267 if (And.getOpcode() != ISD::AND)
6270 // Is the second op an shl or lshr?
6271 SDValue Shift = N->getOperand(1);
6272 // This will have been turned into: AArch64ISD::VSHL vector, #shift
6273 // or AArch64ISD::VLSHR vector, #shift
6274 unsigned ShiftOpc = Shift.getOpcode();
6275 if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
6277 bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
6279 // Is the shift amount constant?
6280 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
6284 // Is the and mask vector all constant?
6286 if (!isAllConstantBuildVector(And.getOperand(1), C1))
6289 // Is C1 == ~C2, taking into account how much one can shift elements of a
6291 uint64_t C2 = C2node->getZExtValue();
6292 unsigned ElemSizeInBits = VT.getScalarSizeInBits();
6293 if (C2 > ElemSizeInBits)
6295 unsigned ElemMask = (1 << ElemSizeInBits) - 1;
6296 if ((C1 & ElemMask) != (~C2 & ElemMask))
6299 SDValue X = And.getOperand(0);
6300 SDValue Y = Shift.getOperand(0);
6303 IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
6305 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
6306 DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
6307 Shift.getOperand(1));
6309 DEBUG(dbgs() << "aarch64-lower: transformed: \n");
6310 DEBUG(N->dump(&DAG));
6311 DEBUG(dbgs() << "into: \n");
6312 DEBUG(ResultSLI->dump(&DAG));
6318 SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
6319 SelectionDAG &DAG) const {
6320 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
6321 if (EnableAArch64SlrGeneration) {
6322 if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG))
6326 BuildVectorSDNode *BVN =
6327 dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
6328 SDValue LHS = Op.getOperand(1);
6330 EVT VT = Op.getValueType();
6332 // OR commutes, so try swapping the operands.
6334 LHS = Op.getOperand(0);
6335 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
6340 APInt CnstBits(VT.getSizeInBits(), 0);
6341 APInt UndefBits(VT.getSizeInBits(), 0);
6342 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
6343 // We make use of a little bit of goto ickiness in order to avoid having to
6344 // duplicate the immediate matching logic for the undef toggled case.
6345 bool SecondTry = false;
6348 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
6349 CnstBits = CnstBits.zextOrTrunc(64);
6350 uint64_t CnstVal = CnstBits.getZExtValue();
6352 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6353 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6354 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6355 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6356 DAG.getConstant(CnstVal, dl, MVT::i32),
6357 DAG.getConstant(0, dl, MVT::i32));
6358 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6361 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6362 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6363 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6364 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6365 DAG.getConstant(CnstVal, dl, MVT::i32),
6366 DAG.getConstant(8, dl, MVT::i32));
6367 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6370 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6371 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6372 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6373 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6374 DAG.getConstant(CnstVal, dl, MVT::i32),
6375 DAG.getConstant(16, dl, MVT::i32));
6376 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6379 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6380 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6381 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6382 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6383 DAG.getConstant(CnstVal, dl, MVT::i32),
6384 DAG.getConstant(24, dl, MVT::i32));
6385 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6388 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6389 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6390 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6391 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6392 DAG.getConstant(CnstVal, dl, MVT::i32),
6393 DAG.getConstant(0, dl, MVT::i32));
6394 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6397 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6398 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6399 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6400 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
6401 DAG.getConstant(CnstVal, dl, MVT::i32),
6402 DAG.getConstant(8, dl, MVT::i32));
6403 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6410 CnstBits = UndefBits;
6414 // We can always fall back to a non-immediate OR.
6419 // Normalize the operands of BUILD_VECTOR. The value of constant operands will
6420 // be truncated to fit element width.
6421 static SDValue NormalizeBuildVector(SDValue Op,
6422 SelectionDAG &DAG) {
6423 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
6425 EVT VT = Op.getValueType();
6426 EVT EltTy= VT.getVectorElementType();
6428 if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
6431 SmallVector<SDValue, 16> Ops;
6432 for (SDValue Lane : Op->ops()) {
6433 if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
6434 APInt LowBits(EltTy.getSizeInBits(),
6435 CstLane->getZExtValue());
6436 Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
6438 Ops.push_back(Lane);
6440 return DAG.getBuildVector(VT, dl, Ops);
6443 SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
6444 SelectionDAG &DAG) const {
6446 EVT VT = Op.getValueType();
6447 Op = NormalizeBuildVector(Op, DAG);
6448 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
6450 APInt CnstBits(VT.getSizeInBits(), 0);
6451 APInt UndefBits(VT.getSizeInBits(), 0);
6452 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
6453 // We make use of a little bit of goto ickiness in order to avoid having to
6454 // duplicate the immediate matching logic for the undef toggled case.
6455 bool SecondTry = false;
6458 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
6459 CnstBits = CnstBits.zextOrTrunc(64);
6460 uint64_t CnstVal = CnstBits.getZExtValue();
6462 // Certain magic vector constants (used to express things like NOT
6463 // and NEG) are passed through unmodified. This allows codegen patterns
6464 // for these operations to match. Special-purpose patterns will lower
6465 // these immediates to MOVIs if it proves necessary.
6466 if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL))
6469 // The many faces of MOVI...
6470 if (AArch64_AM::isAdvSIMDModImmType10(CnstVal)) {
6471 CnstVal = AArch64_AM::encodeAdvSIMDModImmType10(CnstVal);
6472 if (VT.getSizeInBits() == 128) {
6473 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::v2i64,
6474 DAG.getConstant(CnstVal, dl, MVT::i32));
6475 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6478 // Support the V64 version via subregister insertion.
6479 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::f64,
6480 DAG.getConstant(CnstVal, dl, MVT::i32));
6481 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6484 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6485 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6486 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6487 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6488 DAG.getConstant(CnstVal, dl, MVT::i32),
6489 DAG.getConstant(0, dl, MVT::i32));
6490 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6493 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6494 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6495 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6496 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6497 DAG.getConstant(CnstVal, dl, MVT::i32),
6498 DAG.getConstant(8, dl, MVT::i32));
6499 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6502 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6503 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6504 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6505 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6506 DAG.getConstant(CnstVal, dl, MVT::i32),
6507 DAG.getConstant(16, dl, MVT::i32));
6508 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6511 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6512 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6513 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6514 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6515 DAG.getConstant(CnstVal, dl, MVT::i32),
6516 DAG.getConstant(24, dl, MVT::i32));
6517 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6520 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6521 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6522 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6523 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6524 DAG.getConstant(CnstVal, dl, MVT::i32),
6525 DAG.getConstant(0, dl, MVT::i32));
6526 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6529 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6530 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6531 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6532 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
6533 DAG.getConstant(CnstVal, dl, MVT::i32),
6534 DAG.getConstant(8, dl, MVT::i32));
6535 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6538 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6539 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6540 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6541 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
6542 DAG.getConstant(CnstVal, dl, MVT::i32),
6543 DAG.getConstant(264, dl, MVT::i32));
6544 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6547 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6548 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6549 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6550 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
6551 DAG.getConstant(CnstVal, dl, MVT::i32),
6552 DAG.getConstant(272, dl, MVT::i32));
6553 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6556 if (AArch64_AM::isAdvSIMDModImmType9(CnstVal)) {
6557 CnstVal = AArch64_AM::encodeAdvSIMDModImmType9(CnstVal);
6558 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
6559 SDValue Mov = DAG.getNode(AArch64ISD::MOVI, dl, MovTy,
6560 DAG.getConstant(CnstVal, dl, MVT::i32));
6561 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6564 // The few faces of FMOV...
6565 if (AArch64_AM::isAdvSIMDModImmType11(CnstVal)) {
6566 CnstVal = AArch64_AM::encodeAdvSIMDModImmType11(CnstVal);
6567 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32;
6568 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MovTy,
6569 DAG.getConstant(CnstVal, dl, MVT::i32));
6570 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6573 if (AArch64_AM::isAdvSIMDModImmType12(CnstVal) &&
6574 VT.getSizeInBits() == 128) {
6575 CnstVal = AArch64_AM::encodeAdvSIMDModImmType12(CnstVal);
6576 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MVT::v2f64,
6577 DAG.getConstant(CnstVal, dl, MVT::i32));
6578 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6581 // The many faces of MVNI...
6583 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6584 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6585 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6586 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6587 DAG.getConstant(CnstVal, dl, MVT::i32),
6588 DAG.getConstant(0, dl, MVT::i32));
6589 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6592 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6593 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6594 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6595 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6596 DAG.getConstant(CnstVal, dl, MVT::i32),
6597 DAG.getConstant(8, dl, MVT::i32));
6598 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6601 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6602 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6603 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6604 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6605 DAG.getConstant(CnstVal, dl, MVT::i32),
6606 DAG.getConstant(16, dl, MVT::i32));
6607 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6610 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6611 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6612 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6613 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6614 DAG.getConstant(CnstVal, dl, MVT::i32),
6615 DAG.getConstant(24, dl, MVT::i32));
6616 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6619 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6620 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6621 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6622 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6623 DAG.getConstant(CnstVal, dl, MVT::i32),
6624 DAG.getConstant(0, dl, MVT::i32));
6625 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6628 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6629 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6630 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6631 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
6632 DAG.getConstant(CnstVal, dl, MVT::i32),
6633 DAG.getConstant(8, dl, MVT::i32));
6634 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6637 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6638 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6639 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6640 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
6641 DAG.getConstant(CnstVal, dl, MVT::i32),
6642 DAG.getConstant(264, dl, MVT::i32));
6643 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6646 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6647 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6648 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6649 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
6650 DAG.getConstant(CnstVal, dl, MVT::i32),
6651 DAG.getConstant(272, dl, MVT::i32));
6652 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
6659 CnstBits = UndefBits;
6664 // Scan through the operands to find some interesting properties we can
6666 // 1) If only one value is used, we can use a DUP, or
6667 // 2) if only the low element is not undef, we can just insert that, or
6668 // 3) if only one constant value is used (w/ some non-constant lanes),
6669 // we can splat the constant value into the whole vector then fill
6670 // in the non-constant lanes.
6671 // 4) FIXME: If different constant values are used, but we can intelligently
6672 // select the values we'll be overwriting for the non-constant
6673 // lanes such that we can directly materialize the vector
6674 // some other way (MOVI, e.g.), we can be sneaky.
6675 unsigned NumElts = VT.getVectorNumElements();
6676 bool isOnlyLowElement = true;
6677 bool usesOnlyOneValue = true;
6678 bool usesOnlyOneConstantValue = true;
6679 bool isConstant = true;
6680 unsigned NumConstantLanes = 0;
6682 SDValue ConstantValue;
6683 for (unsigned i = 0; i < NumElts; ++i) {
6684 SDValue V = Op.getOperand(i);
6688 isOnlyLowElement = false;
6689 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6692 if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
6694 if (!ConstantValue.getNode())
6696 else if (ConstantValue != V)
6697 usesOnlyOneConstantValue = false;
6700 if (!Value.getNode())
6702 else if (V != Value)
6703 usesOnlyOneValue = false;
6706 if (!Value.getNode())
6707 return DAG.getUNDEF(VT);
6709 if (isOnlyLowElement)
6710 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
6712 // Use DUP for non-constant splats. For f32 constant splats, reduce to
6713 // i32 and try again.
6714 if (usesOnlyOneValue) {
6716 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6717 Value.getValueType() != VT)
6718 return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
6720 // This is actually a DUPLANExx operation, which keeps everything vectory.
6722 // DUPLANE works on 128-bit vectors, widen it if necessary.
6723 SDValue Lane = Value.getOperand(1);
6724 Value = Value.getOperand(0);
6725 if (Value.getValueSizeInBits() == 64)
6726 Value = WidenVector(Value, DAG);
6728 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
6729 return DAG.getNode(Opcode, dl, VT, Value, Lane);
6732 if (VT.getVectorElementType().isFloatingPoint()) {
6733 SmallVector<SDValue, 8> Ops;
6734 EVT EltTy = VT.getVectorElementType();
6735 assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
6736 "Unsupported floating-point vector type");
6737 MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
6738 for (unsigned i = 0; i < NumElts; ++i)
6739 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
6740 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
6741 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
6742 Val = LowerBUILD_VECTOR(Val, DAG);
6744 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6748 // If there was only one constant value used and for more than one lane,
6749 // start by splatting that value, then replace the non-constant lanes. This
6750 // is better than the default, which will perform a separate initialization
6752 if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
6753 SDValue Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
6754 // Now insert the non-constant lanes.
6755 for (unsigned i = 0; i < NumElts; ++i) {
6756 SDValue V = Op.getOperand(i);
6757 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
6758 if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) {
6759 // Note that type legalization likely mucked about with the VT of the
6760 // source operand, so we may have to convert it here before inserting.
6761 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
6767 // If all elements are constants and the case above didn't get hit, fall back
6768 // to the default expansion, which will generate a load from the constant
6773 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6775 if (SDValue shuffle = ReconstructShuffle(Op, DAG))
6779 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6780 // know the default expansion would otherwise fall back on something even
6781 // worse. For a vector with one or two non-undef values, that's
6782 // scalar_to_vector for the elements followed by a shuffle (provided the
6783 // shuffle is valid for the target) and materialization element by element
6784 // on the stack followed by a load for everything else.
6785 if (!isConstant && !usesOnlyOneValue) {
6786 SDValue Vec = DAG.getUNDEF(VT);
6787 SDValue Op0 = Op.getOperand(0);
6790 // Use SCALAR_TO_VECTOR for lane zero to
6791 // a) Avoid a RMW dependency on the full vector register, and
6792 // b) Allow the register coalescer to fold away the copy if the
6793 // value is already in an S or D register, and we're forced to emit an
6794 // INSERT_SUBREG that we can't fold anywhere.
6796 // We also allow types like i8 and i16 which are illegal scalar but legal
6797 // vector element types. After type-legalization the inserted value is
6798 // extended (i32) and it is safe to cast them to the vector type by ignoring
6799 // the upper bits of the lowest lane (e.g. v8i8, v4i16).
6800 if (!Op0.isUndef()) {
6801 Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op0);
6804 for (; i < NumElts; ++i) {
6805 SDValue V = Op.getOperand(i);
6808 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
6809 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6814 // Just use the default expansion. We failed to find a better alternative.
6818 SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
6819 SelectionDAG &DAG) const {
6820 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
6822 // Check for non-constant or out of range lane.
6823 EVT VT = Op.getOperand(0).getValueType();
6824 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
6825 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
6829 // Insertion/extraction are legal for V128 types.
6830 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
6831 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6835 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
6836 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
6839 // For V64 types, we perform insertion by expanding the value
6840 // to a V128 type and perform the insertion on that.
6842 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6843 EVT WideTy = WideVec.getValueType();
6845 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
6846 Op.getOperand(1), Op.getOperand(2));
6847 // Re-narrow the resultant vector.
6848 return NarrowVector(Node, DAG);
6852 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6853 SelectionDAG &DAG) const {
6854 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
6856 // Check for non-constant or out of range lane.
6857 EVT VT = Op.getOperand(0).getValueType();
6858 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6859 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
6863 // Insertion/extraction are legal for V128 types.
6864 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
6865 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6869 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
6870 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
6873 // For V64 types, we perform extraction by expanding the value
6874 // to a V128 type and perform the extraction on that.
6876 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6877 EVT WideTy = WideVec.getValueType();
6879 EVT ExtrTy = WideTy.getVectorElementType();
6880 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
6883 // For extractions, we just return the result directly.
6884 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
6888 SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
6889 SelectionDAG &DAG) const {
6890 EVT VT = Op.getOperand(0).getValueType();
6896 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6899 unsigned Val = Cst->getZExtValue();
6901 unsigned Size = Op.getValueSizeInBits();
6903 // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
6907 // If this is extracting the upper 64-bits of a 128-bit vector, we match
6909 if (Size == 64 && Val * VT.getScalarSizeInBits() == 64)
6915 bool AArch64TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
6917 if (VT.getVectorNumElements() == 4 &&
6918 (VT.is128BitVector() || VT.is64BitVector())) {
6919 unsigned PFIndexes[4];
6920 for (unsigned i = 0; i != 4; ++i) {
6924 PFIndexes[i] = M[i];
6927 // Compute the index in the perfect shuffle table.
6928 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6929 PFIndexes[2] * 9 + PFIndexes[3];
6930 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6931 unsigned Cost = (PFEntry >> 30);
6939 unsigned DummyUnsigned;
6941 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
6942 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
6943 isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
6944 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
6945 isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
6946 isZIPMask(M, VT, DummyUnsigned) ||
6947 isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
6948 isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
6949 isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
6950 isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
6951 isConcatMask(M, VT, VT.getSizeInBits() == 128));
6954 /// getVShiftImm - Check if this is a valid build_vector for the immediate
6955 /// operand of a vector shift operation, where all the elements of the
6956 /// build_vector must have the same constant integer value.
6957 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
6958 // Ignore bit_converts.
6959 while (Op.getOpcode() == ISD::BITCAST)
6960 Op = Op.getOperand(0);
6961 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6962 APInt SplatBits, SplatUndef;
6963 unsigned SplatBitSize;
6965 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
6966 HasAnyUndefs, ElementBits) ||
6967 SplatBitSize > ElementBits)
6969 Cnt = SplatBits.getSExtValue();
6973 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
6974 /// operand of a vector shift left operation. That value must be in the range:
6975 /// 0 <= Value < ElementBits for a left shift; or
6976 /// 0 <= Value <= ElementBits for a long left shift.
6977 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
6978 assert(VT.isVector() && "vector shift count is not a vector type");
6979 int64_t ElementBits = VT.getScalarSizeInBits();
6980 if (!getVShiftImm(Op, ElementBits, Cnt))
6982 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
6985 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
6986 /// operand of a vector shift right operation. The value must be in the range:
6987 /// 1 <= Value <= ElementBits for a right shift; or
6988 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
6989 assert(VT.isVector() && "vector shift count is not a vector type");
6990 int64_t ElementBits = VT.getScalarSizeInBits();
6991 if (!getVShiftImm(Op, ElementBits, Cnt))
6993 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
6996 SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
6997 SelectionDAG &DAG) const {
6998 EVT VT = Op.getValueType();
7002 if (!Op.getOperand(1).getValueType().isVector())
7004 unsigned EltSize = VT.getScalarSizeInBits();
7006 switch (Op.getOpcode()) {
7008 llvm_unreachable("unexpected shift opcode");
7011 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
7012 return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
7013 DAG.getConstant(Cnt, DL, MVT::i32));
7014 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
7015 DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
7017 Op.getOperand(0), Op.getOperand(1));
7020 // Right shift immediate
7021 if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
7023 (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
7024 return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
7025 DAG.getConstant(Cnt, DL, MVT::i32));
7028 // Right shift register. Note, there is not a shift right register
7029 // instruction, but the shift left register instruction takes a signed
7030 // value, where negative numbers specify a right shift.
7031 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
7032 : Intrinsic::aarch64_neon_ushl;
7033 // negate the shift amount
7034 SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
7035 SDValue NegShiftLeft =
7036 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
7037 DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
7039 return NegShiftLeft;
7045 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
7046 AArch64CC::CondCode CC, bool NoNans, EVT VT,
7047 const SDLoc &dl, SelectionDAG &DAG) {
7048 EVT SrcVT = LHS.getValueType();
7049 assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
7050 "function only supposed to emit natural comparisons");
7052 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
7053 APInt CnstBits(VT.getSizeInBits(), 0);
7054 APInt UndefBits(VT.getSizeInBits(), 0);
7055 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
7056 bool IsZero = IsCnst && (CnstBits == 0);
7058 if (SrcVT.getVectorElementType().isFloatingPoint()) {
7062 case AArch64CC::NE: {
7065 Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
7067 Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
7068 return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
7072 return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
7073 return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
7076 return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
7077 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
7080 return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
7081 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
7084 return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
7085 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
7089 // If we ignore NaNs then we can use to the MI implementation.
7093 return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
7094 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
7101 case AArch64CC::NE: {
7104 Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
7106 Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
7107 return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
7111 return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
7112 return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
7115 return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
7116 return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
7119 return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
7120 return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
7123 return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
7124 return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
7126 return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
7128 return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
7131 return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
7132 return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
7134 return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
7136 return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
7140 SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
7141 SelectionDAG &DAG) const {
7142 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7143 SDValue LHS = Op.getOperand(0);
7144 SDValue RHS = Op.getOperand(1);
7145 EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
7148 if (LHS.getValueType().getVectorElementType().isInteger()) {
7149 assert(LHS.getValueType() == RHS.getValueType());
7150 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
7152 EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
7153 return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
7156 if (LHS.getValueType().getVectorElementType() == MVT::f16)
7159 assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
7160 LHS.getValueType().getVectorElementType() == MVT::f64);
7162 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
7163 // clean. Some of them require two branches to implement.
7164 AArch64CC::CondCode CC1, CC2;
7166 changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
7168 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
7170 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
7174 if (CC2 != AArch64CC::AL) {
7176 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
7177 if (!Cmp2.getNode())
7180 Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
7183 Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
7186 return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
7191 static SDValue getReductionSDNode(unsigned Op, SDLoc DL, SDValue ScalarOp,
7192 SelectionDAG &DAG) {
7193 SDValue VecOp = ScalarOp.getOperand(0);
7194 auto Rdx = DAG.getNode(Op, DL, VecOp.getSimpleValueType(), VecOp);
7195 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarOp.getValueType(), Rdx,
7196 DAG.getConstant(0, DL, MVT::i64));
7199 SDValue AArch64TargetLowering::LowerVECREDUCE(SDValue Op,
7200 SelectionDAG &DAG) const {
7202 switch (Op.getOpcode()) {
7203 case ISD::VECREDUCE_ADD:
7204 return getReductionSDNode(AArch64ISD::UADDV, dl, Op, DAG);
7205 case ISD::VECREDUCE_SMAX:
7206 return getReductionSDNode(AArch64ISD::SMAXV, dl, Op, DAG);
7207 case ISD::VECREDUCE_SMIN:
7208 return getReductionSDNode(AArch64ISD::SMINV, dl, Op, DAG);
7209 case ISD::VECREDUCE_UMAX:
7210 return getReductionSDNode(AArch64ISD::UMAXV, dl, Op, DAG);
7211 case ISD::VECREDUCE_UMIN:
7212 return getReductionSDNode(AArch64ISD::UMINV, dl, Op, DAG);
7213 case ISD::VECREDUCE_FMAX: {
7214 assert(Op->getFlags().hasNoNaNs() && "fmax vector reduction needs NoNaN flag");
7216 ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
7217 DAG.getConstant(Intrinsic::aarch64_neon_fmaxnmv, dl, MVT::i32),
7220 case ISD::VECREDUCE_FMIN: {
7221 assert(Op->getFlags().hasNoNaNs() && "fmin vector reduction needs NoNaN flag");
7223 ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
7224 DAG.getConstant(Intrinsic::aarch64_neon_fminnmv, dl, MVT::i32),
7228 llvm_unreachable("Unhandled reduction");
7232 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
7233 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
7234 /// specified in the intrinsic calls.
7235 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
7237 unsigned Intrinsic) const {
7238 auto &DL = I.getModule()->getDataLayout();
7239 switch (Intrinsic) {
7240 case Intrinsic::aarch64_neon_ld2:
7241 case Intrinsic::aarch64_neon_ld3:
7242 case Intrinsic::aarch64_neon_ld4:
7243 case Intrinsic::aarch64_neon_ld1x2:
7244 case Intrinsic::aarch64_neon_ld1x3:
7245 case Intrinsic::aarch64_neon_ld1x4:
7246 case Intrinsic::aarch64_neon_ld2lane:
7247 case Intrinsic::aarch64_neon_ld3lane:
7248 case Intrinsic::aarch64_neon_ld4lane:
7249 case Intrinsic::aarch64_neon_ld2r:
7250 case Intrinsic::aarch64_neon_ld3r:
7251 case Intrinsic::aarch64_neon_ld4r: {
7252 Info.opc = ISD::INTRINSIC_W_CHAIN;
7253 // Conservatively set memVT to the entire set of vectors loaded.
7254 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
7255 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
7256 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
7259 Info.vol = false; // volatile loads with NEON intrinsics not supported
7260 Info.readMem = true;
7261 Info.writeMem = false;
7264 case Intrinsic::aarch64_neon_st2:
7265 case Intrinsic::aarch64_neon_st3:
7266 case Intrinsic::aarch64_neon_st4:
7267 case Intrinsic::aarch64_neon_st1x2:
7268 case Intrinsic::aarch64_neon_st1x3:
7269 case Intrinsic::aarch64_neon_st1x4:
7270 case Intrinsic::aarch64_neon_st2lane:
7271 case Intrinsic::aarch64_neon_st3lane:
7272 case Intrinsic::aarch64_neon_st4lane: {
7273 Info.opc = ISD::INTRINSIC_VOID;
7274 // Conservatively set memVT to the entire set of vectors stored.
7275 unsigned NumElts = 0;
7276 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
7277 Type *ArgTy = I.getArgOperand(ArgI)->getType();
7278 if (!ArgTy->isVectorTy())
7280 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
7282 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
7283 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
7286 Info.vol = false; // volatile stores with NEON intrinsics not supported
7287 Info.readMem = false;
7288 Info.writeMem = true;
7291 case Intrinsic::aarch64_ldaxr:
7292 case Intrinsic::aarch64_ldxr: {
7293 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
7294 Info.opc = ISD::INTRINSIC_W_CHAIN;
7295 Info.memVT = MVT::getVT(PtrTy->getElementType());
7296 Info.ptrVal = I.getArgOperand(0);
7298 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
7300 Info.readMem = true;
7301 Info.writeMem = false;
7304 case Intrinsic::aarch64_stlxr:
7305 case Intrinsic::aarch64_stxr: {
7306 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
7307 Info.opc = ISD::INTRINSIC_W_CHAIN;
7308 Info.memVT = MVT::getVT(PtrTy->getElementType());
7309 Info.ptrVal = I.getArgOperand(1);
7311 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
7313 Info.readMem = false;
7314 Info.writeMem = true;
7317 case Intrinsic::aarch64_ldaxp:
7318 case Intrinsic::aarch64_ldxp:
7319 Info.opc = ISD::INTRINSIC_W_CHAIN;
7320 Info.memVT = MVT::i128;
7321 Info.ptrVal = I.getArgOperand(0);
7325 Info.readMem = true;
7326 Info.writeMem = false;
7328 case Intrinsic::aarch64_stlxp:
7329 case Intrinsic::aarch64_stxp:
7330 Info.opc = ISD::INTRINSIC_W_CHAIN;
7331 Info.memVT = MVT::i128;
7332 Info.ptrVal = I.getArgOperand(2);
7336 Info.readMem = false;
7337 Info.writeMem = true;
7346 // Truncations from 64-bit GPR to 32-bit GPR is free.
7347 bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
7348 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
7350 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7351 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
7352 return NumBits1 > NumBits2;
7354 bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
7355 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
7357 unsigned NumBits1 = VT1.getSizeInBits();
7358 unsigned NumBits2 = VT2.getSizeInBits();
7359 return NumBits1 > NumBits2;
7362 /// Check if it is profitable to hoist instruction in then/else to if.
7363 /// Not profitable if I and it's user can form a FMA instruction
7364 /// because we prefer FMSUB/FMADD.
7365 bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
7366 if (I->getOpcode() != Instruction::FMul)
7369 if (!I->hasOneUse())
7372 Instruction *User = I->user_back();
7375 !(User->getOpcode() == Instruction::FSub ||
7376 User->getOpcode() == Instruction::FAdd))
7379 const TargetOptions &Options = getTargetMachine().Options;
7380 const DataLayout &DL = I->getModule()->getDataLayout();
7381 EVT VT = getValueType(DL, User->getOperand(0)->getType());
7383 return !(isFMAFasterThanFMulAndFAdd(VT) &&
7384 isOperationLegalOrCustom(ISD::FMA, VT) &&
7385 (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7386 Options.UnsafeFPMath));
7389 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
7391 bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
7392 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
7394 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7395 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
7396 return NumBits1 == 32 && NumBits2 == 64;
7398 bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
7399 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
7401 unsigned NumBits1 = VT1.getSizeInBits();
7402 unsigned NumBits2 = VT2.getSizeInBits();
7403 return NumBits1 == 32 && NumBits2 == 64;
7406 bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
7407 EVT VT1 = Val.getValueType();
7408 if (isZExtFree(VT1, VT2)) {
7412 if (Val.getOpcode() != ISD::LOAD)
7415 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
7416 return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
7417 VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
7418 VT1.getSizeInBits() <= 32);
7421 bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
7422 if (isa<FPExtInst>(Ext))
7425 // Vector types are next free.
7426 if (Ext->getType()->isVectorTy())
7429 for (const Use &U : Ext->uses()) {
7430 // The extension is free if we can fold it with a left shift in an
7431 // addressing mode or an arithmetic operation: add, sub, and cmp.
7433 // Is there a shift?
7434 const Instruction *Instr = cast<Instruction>(U.getUser());
7436 // Is this a constant shift?
7437 switch (Instr->getOpcode()) {
7438 case Instruction::Shl:
7439 if (!isa<ConstantInt>(Instr->getOperand(1)))
7442 case Instruction::GetElementPtr: {
7443 gep_type_iterator GTI = gep_type_begin(Instr);
7444 auto &DL = Ext->getModule()->getDataLayout();
7445 std::advance(GTI, U.getOperandNo()-1);
7446 Type *IdxTy = GTI.getIndexedType();
7447 // This extension will end up with a shift because of the scaling factor.
7448 // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
7449 // Get the shift amount based on the scaling factor:
7450 // log2(sizeof(IdxTy)) - log2(8).
7452 countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3;
7453 // Is the constant foldable in the shift of the addressing mode?
7454 // I.e., shift amount is between 1 and 4 inclusive.
7455 if (ShiftAmt == 0 || ShiftAmt > 4)
7459 case Instruction::Trunc:
7460 // Check if this is a noop.
7461 // trunc(sext ty1 to ty2) to ty1.
7462 if (Instr->getType() == Ext->getOperand(0)->getType())
7469 // At this point we can use the bfm family, so this extension is free
7475 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
7476 unsigned &RequiredAligment) const {
7477 if (!LoadedType.isSimple() ||
7478 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
7480 // Cyclone supports unaligned accesses.
7481 RequiredAligment = 0;
7482 unsigned NumBits = LoadedType.getSizeInBits();
7483 return NumBits == 32 || NumBits == 64;
7486 /// A helper function for determining the number of interleaved accesses we
7487 /// will generate when lowering accesses of the given type.
7489 AArch64TargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
7490 const DataLayout &DL) const {
7491 return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
7494 MachineMemOperand::Flags
7495 AArch64TargetLowering::getMMOFlags(const Instruction &I) const {
7496 if (Subtarget->getProcFamily() == AArch64Subtarget::Falkor &&
7497 I.getMetadata(FALKOR_STRIDED_ACCESS_MD) != nullptr)
7498 return MOStridedAccess;
7499 return MachineMemOperand::MONone;
7502 bool AArch64TargetLowering::isLegalInterleavedAccessType(
7503 VectorType *VecTy, const DataLayout &DL) const {
7505 unsigned VecSize = DL.getTypeSizeInBits(VecTy);
7506 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
7508 // Ensure the number of vector elements is greater than 1.
7509 if (VecTy->getNumElements() < 2)
7512 // Ensure the element type is legal.
7513 if (ElSize != 8 && ElSize != 16 && ElSize != 32 && ElSize != 64)
7516 // Ensure the total vector size is 64 or a multiple of 128. Types larger than
7517 // 128 will be split into multiple interleaved accesses.
7518 return VecSize == 64 || VecSize % 128 == 0;
7521 /// \brief Lower an interleaved load into a ldN intrinsic.
7523 /// E.g. Lower an interleaved load (Factor = 2):
7524 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr
7525 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
7526 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
7529 /// %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
7530 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
7531 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
7532 bool AArch64TargetLowering::lowerInterleavedLoad(
7533 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
7534 ArrayRef<unsigned> Indices, unsigned Factor) const {
7535 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7536 "Invalid interleave factor");
7537 assert(!Shuffles.empty() && "Empty shufflevector input");
7538 assert(Shuffles.size() == Indices.size() &&
7539 "Unmatched number of shufflevectors and indices");
7541 const DataLayout &DL = LI->getModule()->getDataLayout();
7543 VectorType *VecTy = Shuffles[0]->getType();
7545 // Skip if we do not have NEON and skip illegal vector types. We can
7546 // "legalize" wide vector types into multiple interleaved accesses as long as
7547 // the vector types are divisible by 128.
7548 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL))
7551 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
7553 // A pointer vector can not be the return type of the ldN intrinsics. Need to
7554 // load integer vectors first and then convert to pointer vectors.
7555 Type *EltTy = VecTy->getVectorElementType();
7556 if (EltTy->isPointerTy())
7558 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
7560 IRBuilder<> Builder(LI);
7562 // The base address of the load.
7563 Value *BaseAddr = LI->getPointerOperand();
7566 // If we're going to generate more than one load, reset the sub-vector type
7567 // to something legal.
7568 VecTy = VectorType::get(VecTy->getVectorElementType(),
7569 VecTy->getVectorNumElements() / NumLoads);
7571 // We will compute the pointer operand of each load from the original base
7572 // address using GEPs. Cast the base address to a pointer to the scalar
7574 BaseAddr = Builder.CreateBitCast(
7575 BaseAddr, VecTy->getVectorElementType()->getPointerTo(
7576 LI->getPointerAddressSpace()));
7579 Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
7580 Type *Tys[2] = {VecTy, PtrTy};
7581 static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
7582 Intrinsic::aarch64_neon_ld3,
7583 Intrinsic::aarch64_neon_ld4};
7585 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
7587 // Holds sub-vectors extracted from the load intrinsic return values. The
7588 // sub-vectors are associated with the shufflevector instructions they will
7590 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
7592 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
7594 // If we're generating more than one load, compute the base address of
7595 // subsequent loads as an offset from the previous.
7597 BaseAddr = Builder.CreateConstGEP1_32(
7598 BaseAddr, VecTy->getVectorNumElements() * Factor);
7600 CallInst *LdN = Builder.CreateCall(
7601 LdNFunc, Builder.CreateBitCast(BaseAddr, PtrTy), "ldN");
7603 // Extract and store the sub-vectors returned by the load intrinsic.
7604 for (unsigned i = 0; i < Shuffles.size(); i++) {
7605 ShuffleVectorInst *SVI = Shuffles[i];
7606 unsigned Index = Indices[i];
7608 Value *SubVec = Builder.CreateExtractValue(LdN, Index);
7610 // Convert the integer vector to pointer vector if the element is pointer.
7611 if (EltTy->isPointerTy())
7612 SubVec = Builder.CreateIntToPtr(
7613 SubVec, VectorType::get(SVI->getType()->getVectorElementType(),
7614 VecTy->getVectorNumElements()));
7615 SubVecs[SVI].push_back(SubVec);
7619 // Replace uses of the shufflevector instructions with the sub-vectors
7620 // returned by the load intrinsic. If a shufflevector instruction is
7621 // associated with more than one sub-vector, those sub-vectors will be
7622 // concatenated into a single wide vector.
7623 for (ShuffleVectorInst *SVI : Shuffles) {
7624 auto &SubVec = SubVecs[SVI];
7626 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
7627 SVI->replaceAllUsesWith(WideVec);
7633 /// \brief Lower an interleaved store into a stN intrinsic.
7635 /// E.g. Lower an interleaved store (Factor = 3):
7636 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
7637 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
7638 /// store <12 x i32> %i.vec, <12 x i32>* %ptr
7641 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
7642 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
7643 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
7644 /// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
7646 /// Note that the new shufflevectors will be removed and we'll only generate one
7647 /// st3 instruction in CodeGen.
7649 /// Example for a more general valid mask (Factor 3). Lower:
7650 /// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
7651 /// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
7652 /// store <12 x i32> %i.vec, <12 x i32>* %ptr
7655 /// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
7656 /// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
7657 /// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
7658 /// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
7659 bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
7660 ShuffleVectorInst *SVI,
7661 unsigned Factor) const {
7662 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7663 "Invalid interleave factor");
7665 VectorType *VecTy = SVI->getType();
7666 assert(VecTy->getVectorNumElements() % Factor == 0 &&
7667 "Invalid interleaved store");
7669 unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
7670 Type *EltTy = VecTy->getVectorElementType();
7671 VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
7673 const DataLayout &DL = SI->getModule()->getDataLayout();
7675 // Skip if we do not have NEON and skip illegal vector types. We can
7676 // "legalize" wide vector types into multiple interleaved accesses as long as
7677 // the vector types are divisible by 128.
7678 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
7681 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
7683 Value *Op0 = SVI->getOperand(0);
7684 Value *Op1 = SVI->getOperand(1);
7685 IRBuilder<> Builder(SI);
7687 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
7688 // vectors to integer vectors.
7689 if (EltTy->isPointerTy()) {
7690 Type *IntTy = DL.getIntPtrType(EltTy);
7691 unsigned NumOpElts =
7692 dyn_cast<VectorType>(Op0->getType())->getVectorNumElements();
7694 // Convert to the corresponding integer vector.
7695 Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
7696 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
7697 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
7699 SubVecTy = VectorType::get(IntTy, LaneLen);
7702 // The base address of the store.
7703 Value *BaseAddr = SI->getPointerOperand();
7705 if (NumStores > 1) {
7706 // If we're going to generate more than one store, reset the lane length
7707 // and sub-vector type to something legal.
7708 LaneLen /= NumStores;
7709 SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen);
7711 // We will compute the pointer operand of each store from the original base
7712 // address using GEPs. Cast the base address to a pointer to the scalar
7714 BaseAddr = Builder.CreateBitCast(
7715 BaseAddr, SubVecTy->getVectorElementType()->getPointerTo(
7716 SI->getPointerAddressSpace()));
7719 auto Mask = SVI->getShuffleMask();
7721 Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
7722 Type *Tys[2] = {SubVecTy, PtrTy};
7723 static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
7724 Intrinsic::aarch64_neon_st3,
7725 Intrinsic::aarch64_neon_st4};
7727 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
7729 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
7731 SmallVector<Value *, 5> Ops;
7733 // Split the shufflevector operands into sub vectors for the new stN call.
7734 for (unsigned i = 0; i < Factor; i++) {
7735 unsigned IdxI = StoreCount * LaneLen * Factor + i;
7736 if (Mask[IdxI] >= 0) {
7737 Ops.push_back(Builder.CreateShuffleVector(
7738 Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0)));
7740 unsigned StartMask = 0;
7741 for (unsigned j = 1; j < LaneLen; j++) {
7742 unsigned IdxJ = StoreCount * LaneLen * Factor + j;
7743 if (Mask[IdxJ * Factor + IdxI] >= 0) {
7744 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
7748 // Note: Filling undef gaps with random elements is ok, since
7749 // those elements were being written anyway (with undefs).
7750 // In the case of all undefs we're defaulting to using elems from 0
7751 // Note: StartMask cannot be negative, it's checked in
7752 // isReInterleaveMask
7753 Ops.push_back(Builder.CreateShuffleVector(
7754 Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0)));
7758 // If we generating more than one store, we compute the base address of
7759 // subsequent stores as an offset from the previous.
7761 BaseAddr = Builder.CreateConstGEP1_32(BaseAddr, LaneLen * Factor);
7763 Ops.push_back(Builder.CreateBitCast(BaseAddr, PtrTy));
7764 Builder.CreateCall(StNFunc, Ops);
7769 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
7770 unsigned AlignCheck) {
7771 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
7772 (DstAlign == 0 || DstAlign % AlignCheck == 0));
7775 EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
7776 unsigned SrcAlign, bool IsMemset,
7779 MachineFunction &MF) const {
7780 // Don't use AdvSIMD to implement 16-byte memset. It would have taken one
7781 // instruction to materialize the v2i64 zero and one store (with restrictive
7782 // addressing mode). Just do two i64 store of zero-registers.
7784 const Function *F = MF.getFunction();
7785 if (Subtarget->hasFPARMv8() && !IsMemset && Size >= 16 &&
7786 !F->hasFnAttribute(Attribute::NoImplicitFloat) &&
7787 (memOpAlign(SrcAlign, DstAlign, 16) ||
7788 (allowsMisalignedMemoryAccesses(MVT::f128, 0, 1, &Fast) && Fast)))
7792 (memOpAlign(SrcAlign, DstAlign, 8) ||
7793 (allowsMisalignedMemoryAccesses(MVT::i64, 0, 1, &Fast) && Fast)))
7797 (memOpAlign(SrcAlign, DstAlign, 4) ||
7798 (allowsMisalignedMemoryAccesses(MVT::i32, 0, 1, &Fast) && Fast)))
7804 // 12-bit optionally shifted immediates are legal for adds.
7805 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
7806 // Avoid UB for INT64_MIN.
7807 if (Immed == std::numeric_limits<int64_t>::min())
7809 // Same encoding for add/sub, just flip the sign.
7810 Immed = std::abs(Immed);
7811 return ((Immed >> 12) == 0 || ((Immed & 0xfff) == 0 && Immed >> 24 == 0));
7814 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
7815 // immediates is the same as for an add or a sub.
7816 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
7817 return isLegalAddImmediate(Immed);
7820 /// isLegalAddressingMode - Return true if the addressing mode represented
7821 /// by AM is legal for this target, for a load/store of the specified type.
7822 bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
7823 const AddrMode &AM, Type *Ty,
7824 unsigned AS) const {
7825 // AArch64 has five basic addressing modes:
7827 // reg + 9-bit signed offset
7828 // reg + SIZE_IN_BYTES * 12-bit unsigned offset
7830 // reg + SIZE_IN_BYTES * reg
7832 // No global is ever allowed as a base.
7836 // No reg+reg+imm addressing.
7837 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
7840 // check reg + imm case:
7841 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
7842 uint64_t NumBytes = 0;
7843 if (Ty->isSized()) {
7844 uint64_t NumBits = DL.getTypeSizeInBits(Ty);
7845 NumBytes = NumBits / 8;
7846 if (!isPowerOf2_64(NumBits))
7851 int64_t Offset = AM.BaseOffs;
7853 // 9-bit signed offset
7854 if (isInt<9>(Offset))
7857 // 12-bit unsigned offset
7858 unsigned shift = Log2_64(NumBytes);
7859 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
7860 // Must be a multiple of NumBytes (NumBytes is a power of 2)
7861 (Offset >> shift) << shift == Offset)
7866 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
7868 return AM.Scale == 1 || (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes);
7871 int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
7872 const AddrMode &AM, Type *Ty,
7873 unsigned AS) const {
7874 // Scaling factors are not free at all.
7875 // Operands | Rt Latency
7876 // -------------------------------------------
7878 // -------------------------------------------
7879 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5
7880 // Rt, [Xn, Wm, <extend> #imm] |
7881 if (isLegalAddressingMode(DL, AM, Ty, AS))
7882 // Scale represents reg2 * scale, thus account for 1 if
7883 // it is not equal to 0 or 1.
7884 return AM.Scale != 0 && AM.Scale != 1;
7888 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
7889 VT = VT.getScalarType();
7894 switch (VT.getSimpleVT().SimpleTy) {
7906 AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
7907 // LR is a callee-save register, but we must treat it as clobbered by any call
7908 // site. Hence we include LR in the scratch registers, which are in turn added
7909 // as implicit-defs for stackmaps and patchpoints.
7910 static const MCPhysReg ScratchRegs[] = {
7911 AArch64::X16, AArch64::X17, AArch64::LR, 0
7917 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N) const {
7918 EVT VT = N->getValueType(0);
7919 // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
7920 // it with shift to let it be lowered to UBFX.
7921 if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
7922 isa<ConstantSDNode>(N->getOperand(1))) {
7923 uint64_t TruncMask = N->getConstantOperandVal(1);
7924 if (isMask_64(TruncMask) &&
7925 N->getOperand(0).getOpcode() == ISD::SRL &&
7926 isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
7932 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
7934 assert(Ty->isIntegerTy());
7936 unsigned BitSize = Ty->getPrimitiveSizeInBits();
7940 int64_t Val = Imm.getSExtValue();
7941 if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
7944 if ((int64_t)Val < 0)
7947 Val &= (1LL << 32) - 1;
7949 unsigned LZ = countLeadingZeros((uint64_t)Val);
7950 unsigned Shift = (63 - LZ) / 16;
7951 // MOVZ is free so return true for one or fewer MOVK.
7955 /// Turn vector tests of the signbit in the form of:
7956 /// xor (sra X, elt_size(X)-1), -1
7959 static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
7960 const AArch64Subtarget *Subtarget) {
7961 EVT VT = N->getValueType(0);
7962 if (!Subtarget->hasNEON() || !VT.isVector())
7965 // There must be a shift right algebraic before the xor, and the xor must be a
7967 SDValue Shift = N->getOperand(0);
7968 SDValue Ones = N->getOperand(1);
7969 if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() ||
7970 !ISD::isBuildVectorAllOnes(Ones.getNode()))
7973 // The shift should be smearing the sign bit across each vector element.
7974 auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
7975 EVT ShiftEltTy = Shift.getValueType().getVectorElementType();
7976 if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1)
7979 return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0));
7982 // Generate SUBS and CSEL for integer abs.
7983 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
7984 EVT VT = N->getValueType(0);
7986 SDValue N0 = N->getOperand(0);
7987 SDValue N1 = N->getOperand(1);
7990 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
7991 // and change it to SUB and CSEL.
7992 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
7993 N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
7994 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
7995 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
7996 if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
7997 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
7999 // Generate SUBS & CSEL.
8001 DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
8002 N0.getOperand(0), DAG.getConstant(0, DL, VT));
8003 return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
8004 DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
8005 SDValue(Cmp.getNode(), 1));
8010 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
8011 TargetLowering::DAGCombinerInfo &DCI,
8012 const AArch64Subtarget *Subtarget) {
8013 if (DCI.isBeforeLegalizeOps())
8016 if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget))
8019 return performIntegerAbsCombine(N, DAG);
8023 AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
8025 std::vector<SDNode *> *Created) const {
8026 AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes();
8027 if (isIntDivCheap(N->getValueType(0), Attr))
8028 return SDValue(N,0); // Lower SDIV as SDIV
8030 // fold (sdiv X, pow2)
8031 EVT VT = N->getValueType(0);
8032 if ((VT != MVT::i32 && VT != MVT::i64) ||
8033 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
8037 SDValue N0 = N->getOperand(0);
8038 unsigned Lg2 = Divisor.countTrailingZeros();
8039 SDValue Zero = DAG.getConstant(0, DL, VT);
8040 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
8042 // Add (N0 < 0) ? Pow2 - 1 : 0;
8044 SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
8045 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
8046 SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
8049 Created->push_back(Cmp.getNode());
8050 Created->push_back(Add.getNode());
8051 Created->push_back(CSel.getNode());
8056 DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
8058 // If we're dividing by a positive value, we're done. Otherwise, we must
8059 // negate the result.
8060 if (Divisor.isNonNegative())
8064 Created->push_back(SRA.getNode());
8065 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
8068 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
8069 TargetLowering::DAGCombinerInfo &DCI,
8070 const AArch64Subtarget *Subtarget) {
8071 if (DCI.isBeforeLegalizeOps())
8074 // The below optimizations require a constant RHS.
8075 if (!isa<ConstantSDNode>(N->getOperand(1)))
8078 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1));
8079 const APInt &ConstValue = C->getAPIntValue();
8081 // Multiplication of a power of two plus/minus one can be done more
8082 // cheaply as as shift+add/sub. For now, this is true unilaterally. If
8083 // future CPUs have a cheaper MADD instruction, this may need to be
8084 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
8085 // 64-bit is 5 cycles, so this is always a win.
8086 // More aggressively, some multiplications N0 * C can be lowered to
8087 // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M,
8088 // e.g. 6=3*2=(2+1)*2.
8089 // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45
8090 // which equals to (1+2)*16-(1+2).
8091 SDValue N0 = N->getOperand(0);
8092 // TrailingZeroes is used to test if the mul can be lowered to
8094 unsigned TrailingZeroes = ConstValue.countTrailingZeros();
8095 if (TrailingZeroes) {
8096 // Conservatively do not lower to shift+add+shift if the mul might be
8097 // folded into smul or umul.
8098 if (N0->hasOneUse() && (isSignExtended(N0.getNode(), DAG) ||
8099 isZeroExtended(N0.getNode(), DAG)))
8101 // Conservatively do not lower to shift+add+shift if the mul might be
8102 // folded into madd or msub.
8103 if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ADD ||
8104 N->use_begin()->getOpcode() == ISD::SUB))
8107 // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub
8108 // and shift+add+shift.
8109 APInt ShiftedConstValue = ConstValue.ashr(TrailingZeroes);
8111 unsigned ShiftAmt, AddSubOpc;
8112 // Is the shifted value the LHS operand of the add/sub?
8113 bool ShiftValUseIsN0 = true;
8114 // Do we need to negate the result?
8115 bool NegateResult = false;
8117 if (ConstValue.isNonNegative()) {
8118 // (mul x, 2^N + 1) => (add (shl x, N), x)
8119 // (mul x, 2^N - 1) => (sub (shl x, N), x)
8120 // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M)
8121 APInt SCVMinus1 = ShiftedConstValue - 1;
8122 APInt CVPlus1 = ConstValue + 1;
8123 if (SCVMinus1.isPowerOf2()) {
8124 ShiftAmt = SCVMinus1.logBase2();
8125 AddSubOpc = ISD::ADD;
8126 } else if (CVPlus1.isPowerOf2()) {
8127 ShiftAmt = CVPlus1.logBase2();
8128 AddSubOpc = ISD::SUB;
8132 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
8133 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
8134 APInt CVNegPlus1 = -ConstValue + 1;
8135 APInt CVNegMinus1 = -ConstValue - 1;
8136 if (CVNegPlus1.isPowerOf2()) {
8137 ShiftAmt = CVNegPlus1.logBase2();
8138 AddSubOpc = ISD::SUB;
8139 ShiftValUseIsN0 = false;
8140 } else if (CVNegMinus1.isPowerOf2()) {
8141 ShiftAmt = CVNegMinus1.logBase2();
8142 AddSubOpc = ISD::ADD;
8143 NegateResult = true;
8149 EVT VT = N->getValueType(0);
8150 SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, VT, N0,
8151 DAG.getConstant(ShiftAmt, DL, MVT::i64));
8153 SDValue AddSubN0 = ShiftValUseIsN0 ? ShiftedVal : N0;
8154 SDValue AddSubN1 = ShiftValUseIsN0 ? N0 : ShiftedVal;
8155 SDValue Res = DAG.getNode(AddSubOpc, DL, VT, AddSubN0, AddSubN1);
8156 assert(!(NegateResult && TrailingZeroes) &&
8157 "NegateResult and TrailingZeroes cannot both be true for now.");
8158 // Negate the result.
8160 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
8161 // Shift the result.
8163 return DAG.getNode(ISD::SHL, DL, VT, Res,
8164 DAG.getConstant(TrailingZeroes, DL, MVT::i64));
8168 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
8169 SelectionDAG &DAG) {
8170 // Take advantage of vector comparisons producing 0 or -1 in each lane to
8171 // optimize away operation when it's from a constant.
8173 // The general transformation is:
8174 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
8175 // AND(VECTOR_CMP(x,y), constant2)
8176 // constant2 = UNARYOP(constant)
8178 // Early exit if this isn't a vector operation, the operand of the
8179 // unary operation isn't a bitwise AND, or if the sizes of the operations
8181 EVT VT = N->getValueType(0);
8182 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
8183 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
8184 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
8187 // Now check that the other operand of the AND is a constant. We could
8188 // make the transformation for non-constant splats as well, but it's unclear
8189 // that would be a benefit as it would not eliminate any operations, just
8190 // perform one more step in scalar code before moving to the vector unit.
8191 if (BuildVectorSDNode *BV =
8192 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
8193 // Bail out if the vector isn't a constant.
8194 if (!BV->isConstant())
8197 // Everything checks out. Build up the new and improved node.
8199 EVT IntVT = BV->getValueType(0);
8200 // Create a new constant of the appropriate type for the transformed
8202 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
8203 // The AND node needs bitcasts to/from an integer vector type around it.
8204 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
8205 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
8206 N->getOperand(0)->getOperand(0), MaskConst);
8207 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
8214 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
8215 const AArch64Subtarget *Subtarget) {
8216 // First try to optimize away the conversion when it's conditionally from
8217 // a constant. Vectors only.
8218 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
8221 EVT VT = N->getValueType(0);
8222 if (VT != MVT::f32 && VT != MVT::f64)
8225 // Only optimize when the source and destination types have the same width.
8226 if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits())
8229 // If the result of an integer load is only used by an integer-to-float
8230 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
8231 // This eliminates an "integer-to-vector-move" UOP and improves throughput.
8232 SDValue N0 = N->getOperand(0);
8233 if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8234 // Do not change the width of a volatile load.
8235 !cast<LoadSDNode>(N0)->isVolatile()) {
8236 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8237 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
8238 LN0->getPointerInfo(), LN0->getAlignment(),
8239 LN0->getMemOperand()->getFlags());
8241 // Make sure successors of the original load stay after it by updating them
8242 // to use the new Chain.
8243 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
8246 (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
8247 return DAG.getNode(Opcode, SDLoc(N), VT, Load);
8253 /// Fold a floating-point multiply by power of two into floating-point to
8254 /// fixed-point conversion.
8255 static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
8256 TargetLowering::DAGCombinerInfo &DCI,
8257 const AArch64Subtarget *Subtarget) {
8258 if (!Subtarget->hasNEON())
8261 SDValue Op = N->getOperand(0);
8262 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
8263 Op.getOpcode() != ISD::FMUL)
8266 SDValue ConstVec = Op->getOperand(1);
8267 if (!isa<BuildVectorSDNode>(ConstVec))
8270 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
8271 uint32_t FloatBits = FloatTy.getSizeInBits();
8272 if (FloatBits != 32 && FloatBits != 64)
8275 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
8276 uint32_t IntBits = IntTy.getSizeInBits();
8277 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
8280 // Avoid conversions where iN is larger than the float (e.g., float -> i64).
8281 if (IntBits > FloatBits)
8284 BitVector UndefElements;
8285 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
8286 int32_t Bits = IntBits == 64 ? 64 : 32;
8287 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
8288 if (C == -1 || C == 0 || C > Bits)
8292 unsigned NumLanes = Op.getValueType().getVectorNumElements();
8297 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
8300 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
8304 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
8307 assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) &&
8308 "Illegal vector type after legalization");
8311 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
8312 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
8313 : Intrinsic::aarch64_neon_vcvtfp2fxu;
8315 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
8316 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
8317 Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
8318 // We can handle smaller integers by generating an extra trunc.
8319 if (IntBits < FloatBits)
8320 FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
8325 /// Fold a floating-point divide by power of two into fixed-point to
8326 /// floating-point conversion.
8327 static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
8328 TargetLowering::DAGCombinerInfo &DCI,
8329 const AArch64Subtarget *Subtarget) {
8330 if (!Subtarget->hasNEON())
8333 SDValue Op = N->getOperand(0);
8334 unsigned Opc = Op->getOpcode();
8335 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
8336 !Op.getOperand(0).getValueType().isSimple() ||
8337 (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
8340 SDValue ConstVec = N->getOperand(1);
8341 if (!isa<BuildVectorSDNode>(ConstVec))
8344 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
8345 int32_t IntBits = IntTy.getSizeInBits();
8346 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
8349 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
8350 int32_t FloatBits = FloatTy.getSizeInBits();
8351 if (FloatBits != 32 && FloatBits != 64)
8354 // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
8355 if (IntBits > FloatBits)
8358 BitVector UndefElements;
8359 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
8360 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
8361 if (C == -1 || C == 0 || C > FloatBits)
8365 unsigned NumLanes = Op.getValueType().getVectorNumElements();
8370 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
8373 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
8377 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
8381 SDValue ConvInput = Op.getOperand(0);
8382 bool IsSigned = Opc == ISD::SINT_TO_FP;
8383 if (IntBits < FloatBits)
8384 ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
8387 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
8388 : Intrinsic::aarch64_neon_vcvtfxu2fp;
8389 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
8390 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
8391 DAG.getConstant(C, DL, MVT::i32));
8394 /// An EXTR instruction is made up of two shifts, ORed together. This helper
8395 /// searches for and classifies those shifts.
8396 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
8398 if (N.getOpcode() == ISD::SHL)
8400 else if (N.getOpcode() == ISD::SRL)
8405 if (!isa<ConstantSDNode>(N.getOperand(1)))
8408 ShiftAmount = N->getConstantOperandVal(1);
8409 Src = N->getOperand(0);
8413 /// EXTR instruction extracts a contiguous chunk of bits from two existing
8414 /// registers viewed as a high/low pair. This function looks for the pattern:
8415 /// <tt>(or (shl VAL1, \#N), (srl VAL2, \#RegWidth-N))</tt> and replaces it
8416 /// with an EXTR. Can't quite be done in TableGen because the two immediates
8417 /// aren't independent.
8418 static SDValue tryCombineToEXTR(SDNode *N,
8419 TargetLowering::DAGCombinerInfo &DCI) {
8420 SelectionDAG &DAG = DCI.DAG;
8422 EVT VT = N->getValueType(0);
8424 assert(N->getOpcode() == ISD::OR && "Unexpected root");
8426 if (VT != MVT::i32 && VT != MVT::i64)
8430 uint32_t ShiftLHS = 0;
8431 bool LHSFromHi = false;
8432 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
8436 uint32_t ShiftRHS = 0;
8437 bool RHSFromHi = false;
8438 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
8441 // If they're both trying to come from the high part of the register, they're
8442 // not really an EXTR.
8443 if (LHSFromHi == RHSFromHi)
8446 if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
8450 std::swap(LHS, RHS);
8451 std::swap(ShiftLHS, ShiftRHS);
8454 return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
8455 DAG.getConstant(ShiftRHS, DL, MVT::i64));
8458 static SDValue tryCombineToBSL(SDNode *N,
8459 TargetLowering::DAGCombinerInfo &DCI) {
8460 EVT VT = N->getValueType(0);
8461 SelectionDAG &DAG = DCI.DAG;
8467 SDValue N0 = N->getOperand(0);
8468 if (N0.getOpcode() != ISD::AND)
8471 SDValue N1 = N->getOperand(1);
8472 if (N1.getOpcode() != ISD::AND)
8475 // We only have to look for constant vectors here since the general, variable
8476 // case can be handled in TableGen.
8477 unsigned Bits = VT.getScalarSizeInBits();
8478 uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
8479 for (int i = 1; i >= 0; --i)
8480 for (int j = 1; j >= 0; --j) {
8481 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
8482 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
8486 bool FoundMatch = true;
8487 for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
8488 ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
8489 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
8491 CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
8498 return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
8499 N0->getOperand(1 - i), N1->getOperand(1 - j));
8505 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
8506 const AArch64Subtarget *Subtarget) {
8507 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
8508 SelectionDAG &DAG = DCI.DAG;
8509 EVT VT = N->getValueType(0);
8511 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8514 if (SDValue Res = tryCombineToEXTR(N, DCI))
8517 if (SDValue Res = tryCombineToBSL(N, DCI))
8523 static SDValue performSRLCombine(SDNode *N,
8524 TargetLowering::DAGCombinerInfo &DCI) {
8525 SelectionDAG &DAG = DCI.DAG;
8526 EVT VT = N->getValueType(0);
8527 if (VT != MVT::i32 && VT != MVT::i64)
8530 // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the
8531 // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32)
8532 // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero.
8533 SDValue N0 = N->getOperand(0);
8534 if (N0.getOpcode() == ISD::BSWAP) {
8536 SDValue N1 = N->getOperand(1);
8537 SDValue N00 = N0.getOperand(0);
8538 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
8539 uint64_t ShiftAmt = C->getZExtValue();
8540 if (VT == MVT::i32 && ShiftAmt == 16 &&
8541 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16)))
8542 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
8543 if (VT == MVT::i64 && ShiftAmt == 32 &&
8544 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32)))
8545 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
8551 static SDValue performBitcastCombine(SDNode *N,
8552 TargetLowering::DAGCombinerInfo &DCI,
8553 SelectionDAG &DAG) {
8554 // Wait 'til after everything is legalized to try this. That way we have
8555 // legal vector types and such.
8556 if (DCI.isBeforeLegalizeOps())
8559 // Remove extraneous bitcasts around an extract_subvector.
8561 // (v4i16 (bitconvert
8562 // (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
8564 // (extract_subvector ((v8i16 ...), (i64 4)))
8566 // Only interested in 64-bit vectors as the ultimate result.
8567 EVT VT = N->getValueType(0);
8570 if (VT.getSimpleVT().getSizeInBits() != 64)
8572 // Is the operand an extract_subvector starting at the beginning or halfway
8573 // point of the vector? A low half may also come through as an
8574 // EXTRACT_SUBREG, so look for that, too.
8575 SDValue Op0 = N->getOperand(0);
8576 if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
8577 !(Op0->isMachineOpcode() &&
8578 Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
8580 uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
8581 if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
8582 if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
8584 } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
8585 if (idx != AArch64::dsub)
8587 // The dsub reference is equivalent to a lane zero subvector reference.
8590 // Look through the bitcast of the input to the extract.
8591 if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
8593 SDValue Source = Op0->getOperand(0)->getOperand(0);
8594 // If the source type has twice the number of elements as our destination
8595 // type, we know this is an extract of the high or low half of the vector.
8596 EVT SVT = Source->getValueType(0);
8597 if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
8600 DEBUG(dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
8602 // Create the simplified form to just extract the low or high half of the
8603 // vector directly rather than bothering with the bitcasts.
8605 unsigned NumElements = VT.getVectorNumElements();
8607 SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
8608 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
8610 SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
8611 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
8617 static SDValue performConcatVectorsCombine(SDNode *N,
8618 TargetLowering::DAGCombinerInfo &DCI,
8619 SelectionDAG &DAG) {
8621 EVT VT = N->getValueType(0);
8622 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
8624 // Optimize concat_vectors of truncated vectors, where the intermediate
8625 // type is illegal, to avoid said illegality, e.g.,
8626 // (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
8627 // (v2i16 (truncate (v2i64)))))
8629 // (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
8630 // (v4i32 (bitcast (v2i64))),
8632 // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
8633 // on both input and result type, so we might generate worse code.
8634 // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
8635 if (N->getNumOperands() == 2 &&
8636 N0->getOpcode() == ISD::TRUNCATE &&
8637 N1->getOpcode() == ISD::TRUNCATE) {
8638 SDValue N00 = N0->getOperand(0);
8639 SDValue N10 = N1->getOperand(0);
8640 EVT N00VT = N00.getValueType();
8642 if (N00VT == N10.getValueType() &&
8643 (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
8644 N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
8645 MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
8646 SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
8647 for (size_t i = 0; i < Mask.size(); ++i)
8649 return DAG.getNode(ISD::TRUNCATE, dl, VT,
8650 DAG.getVectorShuffle(
8652 DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
8653 DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
8657 // Wait 'til after everything is legalized to try this. That way we have
8658 // legal vector types and such.
8659 if (DCI.isBeforeLegalizeOps())
8662 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
8663 // splat. The indexed instructions are going to be expecting a DUPLANE64, so
8664 // canonicalise to that.
8665 if (N0 == N1 && VT.getVectorNumElements() == 2) {
8666 assert(VT.getScalarSizeInBits() == 64);
8667 return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
8668 DAG.getConstant(0, dl, MVT::i64));
8671 // Canonicalise concat_vectors so that the right-hand vector has as few
8672 // bit-casts as possible before its real operation. The primary matching
8673 // destination for these operations will be the narrowing "2" instructions,
8674 // which depend on the operation being performed on this right-hand vector.
8676 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS))))
8678 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
8680 if (N1->getOpcode() != ISD::BITCAST)
8682 SDValue RHS = N1->getOperand(0);
8683 MVT RHSTy = RHS.getValueType().getSimpleVT();
8684 // If the RHS is not a vector, this is not the pattern we're looking for.
8685 if (!RHSTy.isVector())
8688 DEBUG(dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
8690 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
8691 RHSTy.getVectorNumElements() * 2);
8692 return DAG.getNode(ISD::BITCAST, dl, VT,
8693 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
8694 DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
8698 static SDValue tryCombineFixedPointConvert(SDNode *N,
8699 TargetLowering::DAGCombinerInfo &DCI,
8700 SelectionDAG &DAG) {
8701 // Wait 'til after everything is legalized to try this. That way we have
8702 // legal vector types and such.
8703 if (DCI.isBeforeLegalizeOps())
8705 // Transform a scalar conversion of a value from a lane extract into a
8706 // lane extract of a vector conversion. E.g., from foo1 to foo2:
8707 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
8708 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
8710 // The second form interacts better with instruction selection and the
8711 // register allocator to avoid cross-class register copies that aren't
8712 // coalescable due to a lane reference.
8714 // Check the operand and see if it originates from a lane extract.
8715 SDValue Op1 = N->getOperand(1);
8716 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8717 // Yep, no additional predication needed. Perform the transform.
8718 SDValue IID = N->getOperand(0);
8719 SDValue Shift = N->getOperand(2);
8720 SDValue Vec = Op1.getOperand(0);
8721 SDValue Lane = Op1.getOperand(1);
8722 EVT ResTy = N->getValueType(0);
8726 // The vector width should be 128 bits by the time we get here, even
8727 // if it started as 64 bits (the extract_vector handling will have
8729 assert(Vec.getValueSizeInBits() == 128 &&
8730 "unexpected vector size on extract_vector_elt!");
8731 if (Vec.getValueType() == MVT::v4i32)
8732 VecResTy = MVT::v4f32;
8733 else if (Vec.getValueType() == MVT::v2i64)
8734 VecResTy = MVT::v2f64;
8736 llvm_unreachable("unexpected vector type!");
8739 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
8740 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
8745 // AArch64 high-vector "long" operations are formed by performing the non-high
8746 // version on an extract_subvector of each operand which gets the high half:
8748 // (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
8750 // However, there are cases which don't have an extract_high explicitly, but
8751 // have another operation that can be made compatible with one for free. For
8754 // (dupv64 scalar) --> (extract_high (dup128 scalar))
8756 // This routine does the actual conversion of such DUPs, once outer routines
8757 // have determined that everything else is in order.
8758 // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
8760 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
8761 switch (N.getOpcode()) {
8762 case AArch64ISD::DUP:
8763 case AArch64ISD::DUPLANE8:
8764 case AArch64ISD::DUPLANE16:
8765 case AArch64ISD::DUPLANE32:
8766 case AArch64ISD::DUPLANE64:
8767 case AArch64ISD::MOVI:
8768 case AArch64ISD::MOVIshift:
8769 case AArch64ISD::MOVIedit:
8770 case AArch64ISD::MOVImsl:
8771 case AArch64ISD::MVNIshift:
8772 case AArch64ISD::MVNImsl:
8775 // FMOV could be supported, but isn't very useful, as it would only occur
8776 // if you passed a bitcast' floating point immediate to an eligible long
8777 // integer op (addl, smull, ...).
8781 MVT NarrowTy = N.getSimpleValueType();
8782 if (!NarrowTy.is64BitVector())
8785 MVT ElementTy = NarrowTy.getVectorElementType();
8786 unsigned NumElems = NarrowTy.getVectorNumElements();
8787 MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
8790 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
8791 DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
8792 DAG.getConstant(NumElems, dl, MVT::i64));
8795 static bool isEssentiallyExtractSubvector(SDValue N) {
8796 if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
8799 return N.getOpcode() == ISD::BITCAST &&
8800 N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
8803 /// \brief Helper structure to keep track of ISD::SET_CC operands.
8804 struct GenericSetCCInfo {
8805 const SDValue *Opnd0;
8806 const SDValue *Opnd1;
8810 /// \brief Helper structure to keep track of a SET_CC lowered into AArch64 code.
8811 struct AArch64SetCCInfo {
8813 AArch64CC::CondCode CC;
8816 /// \brief Helper structure to keep track of SetCC information.
8818 GenericSetCCInfo Generic;
8819 AArch64SetCCInfo AArch64;
8822 /// \brief Helper structure to be able to read SetCC information. If set to
8823 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
8824 /// GenericSetCCInfo.
8825 struct SetCCInfoAndKind {
8830 /// \brief Check whether or not \p Op is a SET_CC operation, either a generic or
8832 /// AArch64 lowered one.
8833 /// \p SetCCInfo is filled accordingly.
8834 /// \post SetCCInfo is meanginfull only when this function returns true.
8835 /// \return True when Op is a kind of SET_CC operation.
8836 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
8837 // If this is a setcc, this is straight forward.
8838 if (Op.getOpcode() == ISD::SETCC) {
8839 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
8840 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
8841 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8842 SetCCInfo.IsAArch64 = false;
8845 // Otherwise, check if this is a matching csel instruction.
8849 if (Op.getOpcode() != AArch64ISD::CSEL)
8851 // Set the information about the operands.
8852 // TODO: we want the operands of the Cmp not the csel
8853 SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
8854 SetCCInfo.IsAArch64 = true;
8855 SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
8856 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
8858 // Check that the operands matches the constraints:
8859 // (1) Both operands must be constants.
8860 // (2) One must be 1 and the other must be 0.
8861 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
8862 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8865 if (!TValue || !FValue)
8869 if (!TValue->isOne()) {
8870 // Update the comparison when we are interested in !cc.
8871 std::swap(TValue, FValue);
8872 SetCCInfo.Info.AArch64.CC =
8873 AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
8875 return TValue->isOne() && FValue->isNullValue();
8878 // Returns true if Op is setcc or zext of setcc.
8879 static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
8880 if (isSetCC(Op, Info))
8882 return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
8883 isSetCC(Op->getOperand(0), Info));
8886 // The folding we want to perform is:
8887 // (add x, [zext] (setcc cc ...) )
8889 // (csel x, (add x, 1), !cc ...)
8891 // The latter will get matched to a CSINC instruction.
8892 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
8893 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
8894 SDValue LHS = Op->getOperand(0);
8895 SDValue RHS = Op->getOperand(1);
8896 SetCCInfoAndKind InfoAndKind;
8898 // If neither operand is a SET_CC, give up.
8899 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
8900 std::swap(LHS, RHS);
8901 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
8905 // FIXME: This could be generatized to work for FP comparisons.
8906 EVT CmpVT = InfoAndKind.IsAArch64
8907 ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
8908 : InfoAndKind.Info.Generic.Opnd0->getValueType();
8909 if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
8915 if (InfoAndKind.IsAArch64) {
8916 CCVal = DAG.getConstant(
8917 AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
8919 Cmp = *InfoAndKind.Info.AArch64.Cmp;
8921 Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
8922 *InfoAndKind.Info.Generic.Opnd1,
8923 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
8926 EVT VT = Op->getValueType(0);
8927 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
8928 return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
8931 // The basic add/sub long vector instructions have variants with "2" on the end
8932 // which act on the high-half of their inputs. They are normally matched by
8935 // (add (zeroext (extract_high LHS)),
8936 // (zeroext (extract_high RHS)))
8937 // -> uaddl2 vD, vN, vM
8939 // However, if one of the extracts is something like a duplicate, this
8940 // instruction can still be used profitably. This function puts the DAG into a
8941 // more appropriate form for those patterns to trigger.
8942 static SDValue performAddSubLongCombine(SDNode *N,
8943 TargetLowering::DAGCombinerInfo &DCI,
8944 SelectionDAG &DAG) {
8945 if (DCI.isBeforeLegalizeOps())
8948 MVT VT = N->getSimpleValueType(0);
8949 if (!VT.is128BitVector()) {
8950 if (N->getOpcode() == ISD::ADD)
8951 return performSetccAddFolding(N, DAG);
8955 // Make sure both branches are extended in the same way.
8956 SDValue LHS = N->getOperand(0);
8957 SDValue RHS = N->getOperand(1);
8958 if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
8959 LHS.getOpcode() != ISD::SIGN_EXTEND) ||
8960 LHS.getOpcode() != RHS.getOpcode())
8963 unsigned ExtType = LHS.getOpcode();
8965 // It's not worth doing if at least one of the inputs isn't already an
8966 // extract, but we don't know which it'll be so we have to try both.
8967 if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
8968 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
8972 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
8973 } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
8974 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
8978 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
8981 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
8984 // Massage DAGs which we can use the high-half "long" operations on into
8985 // something isel will recognize better. E.g.
8987 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
8988 // (aarch64_neon_umull (extract_high (v2i64 vec)))
8989 // (extract_high (v2i64 (dup128 scalar)))))
8991 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
8992 TargetLowering::DAGCombinerInfo &DCI,
8993 SelectionDAG &DAG) {
8994 if (DCI.isBeforeLegalizeOps())
8997 SDValue LHS = N->getOperand(1);
8998 SDValue RHS = N->getOperand(2);
8999 assert(LHS.getValueType().is64BitVector() &&
9000 RHS.getValueType().is64BitVector() &&
9001 "unexpected shape for long operation");
9003 // Either node could be a DUP, but it's not worth doing both of them (you'd
9004 // just as well use the non-high version) so look for a corresponding extract
9005 // operation on the other "wing".
9006 if (isEssentiallyExtractSubvector(LHS)) {
9007 RHS = tryExtendDUPToExtractHigh(RHS, DAG);
9010 } else if (isEssentiallyExtractSubvector(RHS)) {
9011 LHS = tryExtendDUPToExtractHigh(LHS, DAG);
9016 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
9017 N->getOperand(0), LHS, RHS);
9020 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
9021 MVT ElemTy = N->getSimpleValueType(0).getScalarType();
9022 unsigned ElemBits = ElemTy.getSizeInBits();
9024 int64_t ShiftAmount;
9025 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
9026 APInt SplatValue, SplatUndef;
9027 unsigned SplatBitSize;
9029 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
9030 HasAnyUndefs, ElemBits) ||
9031 SplatBitSize != ElemBits)
9034 ShiftAmount = SplatValue.getSExtValue();
9035 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
9036 ShiftAmount = CVN->getSExtValue();
9044 llvm_unreachable("Unknown shift intrinsic");
9045 case Intrinsic::aarch64_neon_sqshl:
9046 Opcode = AArch64ISD::SQSHL_I;
9047 IsRightShift = false;
9049 case Intrinsic::aarch64_neon_uqshl:
9050 Opcode = AArch64ISD::UQSHL_I;
9051 IsRightShift = false;
9053 case Intrinsic::aarch64_neon_srshl:
9054 Opcode = AArch64ISD::SRSHR_I;
9055 IsRightShift = true;
9057 case Intrinsic::aarch64_neon_urshl:
9058 Opcode = AArch64ISD::URSHR_I;
9059 IsRightShift = true;
9061 case Intrinsic::aarch64_neon_sqshlu:
9062 Opcode = AArch64ISD::SQSHLU_I;
9063 IsRightShift = false;
9067 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
9069 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
9070 DAG.getConstant(-ShiftAmount, dl, MVT::i32));
9071 } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
9073 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
9074 DAG.getConstant(ShiftAmount, dl, MVT::i32));
9080 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
9081 // the intrinsics must be legal and take an i32, this means there's almost
9082 // certainly going to be a zext in the DAG which we can eliminate.
9083 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
9084 SDValue AndN = N->getOperand(2);
9085 if (AndN.getOpcode() != ISD::AND)
9088 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
9089 if (!CMask || CMask->getZExtValue() != Mask)
9092 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
9093 N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
9096 static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
9097 SelectionDAG &DAG) {
9099 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
9100 DAG.getNode(Opc, dl,
9101 N->getOperand(1).getSimpleValueType(),
9103 DAG.getConstant(0, dl, MVT::i64));
9106 static SDValue performIntrinsicCombine(SDNode *N,
9107 TargetLowering::DAGCombinerInfo &DCI,
9108 const AArch64Subtarget *Subtarget) {
9109 SelectionDAG &DAG = DCI.DAG;
9110 unsigned IID = getIntrinsicID(N);
9114 case Intrinsic::aarch64_neon_vcvtfxs2fp:
9115 case Intrinsic::aarch64_neon_vcvtfxu2fp:
9116 return tryCombineFixedPointConvert(N, DCI, DAG);
9117 case Intrinsic::aarch64_neon_saddv:
9118 return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
9119 case Intrinsic::aarch64_neon_uaddv:
9120 return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
9121 case Intrinsic::aarch64_neon_sminv:
9122 return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
9123 case Intrinsic::aarch64_neon_uminv:
9124 return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
9125 case Intrinsic::aarch64_neon_smaxv:
9126 return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
9127 case Intrinsic::aarch64_neon_umaxv:
9128 return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
9129 case Intrinsic::aarch64_neon_fmax:
9130 return DAG.getNode(ISD::FMAXNAN, SDLoc(N), N->getValueType(0),
9131 N->getOperand(1), N->getOperand(2));
9132 case Intrinsic::aarch64_neon_fmin:
9133 return DAG.getNode(ISD::FMINNAN, SDLoc(N), N->getValueType(0),
9134 N->getOperand(1), N->getOperand(2));
9135 case Intrinsic::aarch64_neon_fmaxnm:
9136 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
9137 N->getOperand(1), N->getOperand(2));
9138 case Intrinsic::aarch64_neon_fminnm:
9139 return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
9140 N->getOperand(1), N->getOperand(2));
9141 case Intrinsic::aarch64_neon_smull:
9142 case Intrinsic::aarch64_neon_umull:
9143 case Intrinsic::aarch64_neon_pmull:
9144 case Intrinsic::aarch64_neon_sqdmull:
9145 return tryCombineLongOpWithDup(IID, N, DCI, DAG);
9146 case Intrinsic::aarch64_neon_sqshl:
9147 case Intrinsic::aarch64_neon_uqshl:
9148 case Intrinsic::aarch64_neon_sqshlu:
9149 case Intrinsic::aarch64_neon_srshl:
9150 case Intrinsic::aarch64_neon_urshl:
9151 return tryCombineShiftImm(IID, N, DAG);
9152 case Intrinsic::aarch64_crc32b:
9153 case Intrinsic::aarch64_crc32cb:
9154 return tryCombineCRC32(0xff, N, DAG);
9155 case Intrinsic::aarch64_crc32h:
9156 case Intrinsic::aarch64_crc32ch:
9157 return tryCombineCRC32(0xffff, N, DAG);
9162 static SDValue performExtendCombine(SDNode *N,
9163 TargetLowering::DAGCombinerInfo &DCI,
9164 SelectionDAG &DAG) {
9165 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
9166 // we can convert that DUP into another extract_high (of a bigger DUP), which
9167 // helps the backend to decide that an sabdl2 would be useful, saving a real
9168 // extract_high operation.
9169 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
9170 N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
9171 SDNode *ABDNode = N->getOperand(0).getNode();
9172 unsigned IID = getIntrinsicID(ABDNode);
9173 if (IID == Intrinsic::aarch64_neon_sabd ||
9174 IID == Intrinsic::aarch64_neon_uabd) {
9175 SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
9176 if (!NewABD.getNode())
9179 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
9184 // This is effectively a custom type legalization for AArch64.
9186 // Type legalization will split an extend of a small, legal, type to a larger
9187 // illegal type by first splitting the destination type, often creating
9188 // illegal source types, which then get legalized in isel-confusing ways,
9189 // leading to really terrible codegen. E.g.,
9190 // %result = v8i32 sext v8i8 %value
9192 // %losrc = extract_subreg %value, ...
9193 // %hisrc = extract_subreg %value, ...
9194 // %lo = v4i32 sext v4i8 %losrc
9195 // %hi = v4i32 sext v4i8 %hisrc
9196 // Things go rapidly downhill from there.
9198 // For AArch64, the [sz]ext vector instructions can only go up one element
9199 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
9200 // take two instructions.
9202 // This implies that the most efficient way to do the extend from v8i8
9203 // to two v4i32 values is to first extend the v8i8 to v8i16, then do
9204 // the normal splitting to happen for the v8i16->v8i32.
9206 // This is pre-legalization to catch some cases where the default
9207 // type legalization will create ill-tempered code.
9208 if (!DCI.isBeforeLegalizeOps())
9211 // We're only interested in cleaning things up for non-legal vector types
9212 // here. If both the source and destination are legal, things will just
9213 // work naturally without any fiddling.
9214 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9215 EVT ResVT = N->getValueType(0);
9216 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
9218 // If the vector type isn't a simple VT, it's beyond the scope of what
9219 // we're worried about here. Let legalization do its thing and hope for
9221 SDValue Src = N->getOperand(0);
9222 EVT SrcVT = Src->getValueType(0);
9223 if (!ResVT.isSimple() || !SrcVT.isSimple())
9226 // If the source VT is a 64-bit vector, we can play games and get the
9227 // better results we want.
9228 if (SrcVT.getSizeInBits() != 64)
9231 unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
9232 unsigned ElementCount = SrcVT.getVectorNumElements();
9233 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
9235 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
9237 // Now split the rest of the operation into two halves, each with a 64
9241 unsigned NumElements = ResVT.getVectorNumElements();
9242 assert(!(NumElements & 1) && "Splitting vector, but not in half!");
9243 LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
9244 ResVT.getVectorElementType(), NumElements / 2);
9246 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
9247 LoVT.getVectorNumElements());
9248 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
9249 DAG.getConstant(0, DL, MVT::i64));
9250 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
9251 DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
9252 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
9253 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
9255 // Now combine the parts back together so we still have a single result
9256 // like the combiner expects.
9257 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
9260 static SDValue splitStoreSplat(SelectionDAG &DAG, StoreSDNode &St,
9261 SDValue SplatVal, unsigned NumVecElts) {
9262 unsigned OrigAlignment = St.getAlignment();
9263 unsigned EltOffset = SplatVal.getValueType().getSizeInBits() / 8;
9265 // Create scalar stores. This is at least as good as the code sequence for a
9266 // split unaligned store which is a dup.s, ext.b, and two stores.
9267 // Most of the time the three stores should be replaced by store pair
9268 // instructions (stp).
9270 SDValue BasePtr = St.getBasePtr();
9271 uint64_t BaseOffset = 0;
9273 const MachinePointerInfo &PtrInfo = St.getPointerInfo();
9275 DAG.getStore(St.getChain(), DL, SplatVal, BasePtr, PtrInfo,
9276 OrigAlignment, St.getMemOperand()->getFlags());
9278 // As this in ISel, we will not merge this add which may degrade results.
9279 if (BasePtr->getOpcode() == ISD::ADD &&
9280 isa<ConstantSDNode>(BasePtr->getOperand(1))) {
9281 BaseOffset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue();
9282 BasePtr = BasePtr->getOperand(0);
9285 unsigned Offset = EltOffset;
9286 while (--NumVecElts) {
9287 unsigned Alignment = MinAlign(OrigAlignment, Offset);
9289 DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
9290 DAG.getConstant(BaseOffset + Offset, DL, MVT::i64));
9291 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
9292 PtrInfo.getWithOffset(Offset), Alignment,
9293 St.getMemOperand()->getFlags());
9294 Offset += EltOffset;
9299 /// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR. The
9300 /// load store optimizer pass will merge them to store pair stores. This should
9301 /// be better than a movi to create the vector zero followed by a vector store
9302 /// if the zero constant is not re-used, since one instructions and one register
9303 /// live range will be removed.
9305 /// For example, the final generated code should be:
9307 /// stp xzr, xzr, [x0]
9314 static SDValue replaceZeroVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
9315 SDValue StVal = St.getValue();
9316 EVT VT = StVal.getValueType();
9318 // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or
9319 // 2, 3 or 4 i32 elements.
9320 int NumVecElts = VT.getVectorNumElements();
9321 if (!(((NumVecElts == 2 || NumVecElts == 3) &&
9322 VT.getVectorElementType().getSizeInBits() == 64) ||
9323 ((NumVecElts == 2 || NumVecElts == 3 || NumVecElts == 4) &&
9324 VT.getVectorElementType().getSizeInBits() == 32)))
9327 if (StVal.getOpcode() != ISD::BUILD_VECTOR)
9330 // If the zero constant has more than one use then the vector store could be
9331 // better since the constant mov will be amortized and stp q instructions
9332 // should be able to be formed.
9333 if (!StVal.hasOneUse())
9336 // If the immediate offset of the address operand is too large for the stp
9337 // instruction, then bail out.
9338 if (DAG.isBaseWithConstantOffset(St.getBasePtr())) {
9339 int64_t Offset = St.getBasePtr()->getConstantOperandVal(1);
9340 if (Offset < -512 || Offset > 504)
9344 for (int I = 0; I < NumVecElts; ++I) {
9345 SDValue EltVal = StVal.getOperand(I);
9346 if (!isNullConstant(EltVal) && !isNullFPConstant(EltVal))
9350 // Use WZR/XZR here to prevent DAGCombiner::MergeConsecutiveStores from
9351 // undoing this transformation.
9352 SDValue SplatVal = VT.getVectorElementType().getSizeInBits() == 32
9353 ? DAG.getRegister(AArch64::WZR, MVT::i32)
9354 : DAG.getRegister(AArch64::XZR, MVT::i64);
9355 return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
9358 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
9359 /// value. The load store optimizer pass will merge them to store pair stores.
9360 /// This has better performance than a splat of the scalar followed by a split
9361 /// vector store. Even if the stores are not merged it is four stores vs a dup,
9362 /// followed by an ext.b and two stores.
9363 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
9364 SDValue StVal = St.getValue();
9365 EVT VT = StVal.getValueType();
9367 // Don't replace floating point stores, they possibly won't be transformed to
9368 // stp because of the store pair suppress pass.
9369 if (VT.isFloatingPoint())
9372 // We can express a splat as store pair(s) for 2 or 4 elements.
9373 unsigned NumVecElts = VT.getVectorNumElements();
9374 if (NumVecElts != 4 && NumVecElts != 2)
9377 // Check that this is a splat.
9378 // Make sure that each of the relevant vector element locations are inserted
9379 // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32.
9380 std::bitset<4> IndexNotInserted((1 << NumVecElts) - 1);
9382 for (unsigned I = 0; I < NumVecElts; ++I) {
9383 // Check for insert vector elements.
9384 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
9387 // Check that same value is inserted at each vector element.
9389 SplatVal = StVal.getOperand(1);
9390 else if (StVal.getOperand(1) != SplatVal)
9393 // Check insert element index.
9394 ConstantSDNode *CIndex = dyn_cast<ConstantSDNode>(StVal.getOperand(2));
9397 uint64_t IndexVal = CIndex->getZExtValue();
9398 if (IndexVal >= NumVecElts)
9400 IndexNotInserted.reset(IndexVal);
9402 StVal = StVal.getOperand(0);
9404 // Check that all vector element locations were inserted to.
9405 if (IndexNotInserted.any())
9408 return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
9411 static SDValue splitStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
9413 const AArch64Subtarget *Subtarget) {
9414 if (!DCI.isBeforeLegalize())
9417 StoreSDNode *S = cast<StoreSDNode>(N);
9418 if (S->isVolatile() || S->isIndexed())
9421 SDValue StVal = S->getValue();
9422 EVT VT = StVal.getValueType();
9426 // If we get a splat of zeros, convert this vector store to a store of
9427 // scalars. They will be merged into store pairs of xzr thereby removing one
9428 // instruction and one register.
9429 if (SDValue ReplacedZeroSplat = replaceZeroVectorStore(DAG, *S))
9430 return ReplacedZeroSplat;
9432 // FIXME: The logic for deciding if an unaligned store should be split should
9433 // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
9434 // a call to that function here.
9436 if (!Subtarget->isMisaligned128StoreSlow())
9439 // Don't split at -Oz.
9440 if (DAG.getMachineFunction().getFunction()->optForMinSize())
9443 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
9444 // those up regresses performance on micro-benchmarks and olden/bh.
9445 if (VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
9448 // Split unaligned 16B stores. They are terrible for performance.
9449 // Don't split stores with alignment of 1 or 2. Code that uses clang vector
9450 // extensions can use this to mark that it does not want splitting to happen
9451 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
9452 // eliminating alignment hazards is only 1 in 8 for alignment of 2.
9453 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
9454 S->getAlignment() <= 2)
9457 // If we get a splat of a scalar convert this vector store to a store of
9458 // scalars. They will be merged into store pairs thereby removing two
9460 if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, *S))
9461 return ReplacedSplat;
9464 unsigned NumElts = VT.getVectorNumElements() / 2;
9465 // Split VT into two.
9467 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
9468 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
9469 DAG.getConstant(0, DL, MVT::i64));
9470 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
9471 DAG.getConstant(NumElts, DL, MVT::i64));
9472 SDValue BasePtr = S->getBasePtr();
9474 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
9475 S->getAlignment(), S->getMemOperand()->getFlags());
9476 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
9477 DAG.getConstant(8, DL, MVT::i64));
9478 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
9479 S->getPointerInfo(), S->getAlignment(),
9480 S->getMemOperand()->getFlags());
9483 /// Target-specific DAG combine function for post-increment LD1 (lane) and
9484 /// post-increment LD1R.
9485 static SDValue performPostLD1Combine(SDNode *N,
9486 TargetLowering::DAGCombinerInfo &DCI,
9488 if (DCI.isBeforeLegalizeOps())
9491 SelectionDAG &DAG = DCI.DAG;
9492 EVT VT = N->getValueType(0);
9494 unsigned LoadIdx = IsLaneOp ? 1 : 0;
9495 SDNode *LD = N->getOperand(LoadIdx).getNode();
9496 // If it is not LOAD, can not do such combine.
9497 if (LD->getOpcode() != ISD::LOAD)
9500 LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
9501 EVT MemVT = LoadSDN->getMemoryVT();
9502 // Check if memory operand is the same type as the vector element.
9503 if (MemVT != VT.getVectorElementType())
9506 // Check if there are other uses. If so, do not combine as it will introduce
9508 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
9510 if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
9516 SDValue Addr = LD->getOperand(1);
9517 SDValue Vector = N->getOperand(0);
9518 // Search for a use of the address operand that is an increment.
9519 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
9520 Addr.getNode()->use_end(); UI != UE; ++UI) {
9522 if (User->getOpcode() != ISD::ADD
9523 || UI.getUse().getResNo() != Addr.getResNo())
9526 // Check that the add is independent of the load. Otherwise, folding it
9527 // would create a cycle.
9528 if (User->isPredecessorOf(LD) || LD->isPredecessorOf(User))
9530 // Also check that add is not used in the vector operand. This would also
9532 if (User->isPredecessorOf(Vector.getNode()))
9535 // If the increment is a constant, it must match the memory ref size.
9536 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9537 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9538 uint32_t IncVal = CInc->getZExtValue();
9539 unsigned NumBytes = VT.getScalarSizeInBits() / 8;
9540 if (IncVal != NumBytes)
9542 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
9545 // Finally, check that the vector doesn't depend on the load.
9546 // Again, this would create a cycle.
9547 // The load depending on the vector is fine, as that's the case for the
9548 // LD1*post we'll eventually generate anyway.
9549 if (LoadSDN->isPredecessorOf(Vector.getNode()))
9552 SmallVector<SDValue, 8> Ops;
9553 Ops.push_back(LD->getOperand(0)); // Chain
9555 Ops.push_back(Vector); // The vector to be inserted
9556 Ops.push_back(N->getOperand(2)); // The lane to be inserted in the vector
9558 Ops.push_back(Addr);
9561 EVT Tys[3] = { VT, MVT::i64, MVT::Other };
9562 SDVTList SDTys = DAG.getVTList(Tys);
9563 unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
9564 SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
9566 LoadSDN->getMemOperand());
9569 SDValue NewResults[] = {
9570 SDValue(LD, 0), // The result of load
9571 SDValue(UpdN.getNode(), 2) // Chain
9573 DCI.CombineTo(LD, NewResults);
9574 DCI.CombineTo(N, SDValue(UpdN.getNode(), 0)); // Dup/Inserted Result
9575 DCI.CombineTo(User, SDValue(UpdN.getNode(), 1)); // Write back register
9582 /// Simplify ``Addr`` given that the top byte of it is ignored by HW during
9583 /// address translation.
9584 static bool performTBISimplification(SDValue Addr,
9585 TargetLowering::DAGCombinerInfo &DCI,
9586 SelectionDAG &DAG) {
9587 APInt DemandedMask = APInt::getLowBitsSet(64, 56);
9589 TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
9590 !DCI.isBeforeLegalizeOps());
9591 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9592 if (TLI.SimplifyDemandedBits(Addr, DemandedMask, Known, TLO)) {
9593 DCI.CommitTargetLoweringOpt(TLO);
9599 static SDValue performSTORECombine(SDNode *N,
9600 TargetLowering::DAGCombinerInfo &DCI,
9602 const AArch64Subtarget *Subtarget) {
9603 if (SDValue Split = splitStores(N, DCI, DAG, Subtarget))
9606 if (Subtarget->supportsAddressTopByteIgnored() &&
9607 performTBISimplification(N->getOperand(2), DCI, DAG))
9608 return SDValue(N, 0);
9614 /// Target-specific DAG combine function for NEON load/store intrinsics
9615 /// to merge base address updates.
9616 static SDValue performNEONPostLDSTCombine(SDNode *N,
9617 TargetLowering::DAGCombinerInfo &DCI,
9618 SelectionDAG &DAG) {
9619 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9622 unsigned AddrOpIdx = N->getNumOperands() - 1;
9623 SDValue Addr = N->getOperand(AddrOpIdx);
9625 // Search for a use of the address operand that is an increment.
9626 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9627 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9629 if (User->getOpcode() != ISD::ADD ||
9630 UI.getUse().getResNo() != Addr.getResNo())
9633 // Check that the add is independent of the load/store. Otherwise, folding
9634 // it would create a cycle.
9635 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9638 // Find the new opcode for the updating load/store.
9639 bool IsStore = false;
9640 bool IsLaneOp = false;
9641 bool IsDupOp = false;
9642 unsigned NewOpc = 0;
9643 unsigned NumVecs = 0;
9644 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9646 default: llvm_unreachable("unexpected intrinsic for Neon base update");
9647 case Intrinsic::aarch64_neon_ld2: NewOpc = AArch64ISD::LD2post;
9649 case Intrinsic::aarch64_neon_ld3: NewOpc = AArch64ISD::LD3post;
9651 case Intrinsic::aarch64_neon_ld4: NewOpc = AArch64ISD::LD4post;
9653 case Intrinsic::aarch64_neon_st2: NewOpc = AArch64ISD::ST2post;
9654 NumVecs = 2; IsStore = true; break;
9655 case Intrinsic::aarch64_neon_st3: NewOpc = AArch64ISD::ST3post;
9656 NumVecs = 3; IsStore = true; break;
9657 case Intrinsic::aarch64_neon_st4: NewOpc = AArch64ISD::ST4post;
9658 NumVecs = 4; IsStore = true; break;
9659 case Intrinsic::aarch64_neon_ld1x2: NewOpc = AArch64ISD::LD1x2post;
9661 case Intrinsic::aarch64_neon_ld1x3: NewOpc = AArch64ISD::LD1x3post;
9663 case Intrinsic::aarch64_neon_ld1x4: NewOpc = AArch64ISD::LD1x4post;
9665 case Intrinsic::aarch64_neon_st1x2: NewOpc = AArch64ISD::ST1x2post;
9666 NumVecs = 2; IsStore = true; break;
9667 case Intrinsic::aarch64_neon_st1x3: NewOpc = AArch64ISD::ST1x3post;
9668 NumVecs = 3; IsStore = true; break;
9669 case Intrinsic::aarch64_neon_st1x4: NewOpc = AArch64ISD::ST1x4post;
9670 NumVecs = 4; IsStore = true; break;
9671 case Intrinsic::aarch64_neon_ld2r: NewOpc = AArch64ISD::LD2DUPpost;
9672 NumVecs = 2; IsDupOp = true; break;
9673 case Intrinsic::aarch64_neon_ld3r: NewOpc = AArch64ISD::LD3DUPpost;
9674 NumVecs = 3; IsDupOp = true; break;
9675 case Intrinsic::aarch64_neon_ld4r: NewOpc = AArch64ISD::LD4DUPpost;
9676 NumVecs = 4; IsDupOp = true; break;
9677 case Intrinsic::aarch64_neon_ld2lane: NewOpc = AArch64ISD::LD2LANEpost;
9678 NumVecs = 2; IsLaneOp = true; break;
9679 case Intrinsic::aarch64_neon_ld3lane: NewOpc = AArch64ISD::LD3LANEpost;
9680 NumVecs = 3; IsLaneOp = true; break;
9681 case Intrinsic::aarch64_neon_ld4lane: NewOpc = AArch64ISD::LD4LANEpost;
9682 NumVecs = 4; IsLaneOp = true; break;
9683 case Intrinsic::aarch64_neon_st2lane: NewOpc = AArch64ISD::ST2LANEpost;
9684 NumVecs = 2; IsStore = true; IsLaneOp = true; break;
9685 case Intrinsic::aarch64_neon_st3lane: NewOpc = AArch64ISD::ST3LANEpost;
9686 NumVecs = 3; IsStore = true; IsLaneOp = true; break;
9687 case Intrinsic::aarch64_neon_st4lane: NewOpc = AArch64ISD::ST4LANEpost;
9688 NumVecs = 4; IsStore = true; IsLaneOp = true; break;
9693 VecTy = N->getOperand(2).getValueType();
9695 VecTy = N->getValueType(0);
9697 // If the increment is a constant, it must match the memory ref size.
9698 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9699 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9700 uint32_t IncVal = CInc->getZExtValue();
9701 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9702 if (IsLaneOp || IsDupOp)
9703 NumBytes /= VecTy.getVectorNumElements();
9704 if (IncVal != NumBytes)
9706 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
9708 SmallVector<SDValue, 8> Ops;
9709 Ops.push_back(N->getOperand(0)); // Incoming chain
9710 // Load lane and store have vector list as input.
9711 if (IsLaneOp || IsStore)
9712 for (unsigned i = 2; i < AddrOpIdx; ++i)
9713 Ops.push_back(N->getOperand(i));
9714 Ops.push_back(Addr); // Base register
9719 unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
9721 for (n = 0; n < NumResultVecs; ++n)
9723 Tys[n++] = MVT::i64; // Type of write back register
9724 Tys[n] = MVT::Other; // Type of the chain
9725 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
9727 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9728 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
9729 MemInt->getMemoryVT(),
9730 MemInt->getMemOperand());
9733 std::vector<SDValue> NewResults;
9734 for (unsigned i = 0; i < NumResultVecs; ++i) {
9735 NewResults.push_back(SDValue(UpdN.getNode(), i));
9737 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
9738 DCI.CombineTo(N, NewResults);
9739 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9746 // Checks to see if the value is the prescribed width and returns information
9747 // about its extension mode.
9749 bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
9750 ExtType = ISD::NON_EXTLOAD;
9751 switch(V.getNode()->getOpcode()) {
9755 LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
9756 if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
9757 || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
9758 ExtType = LoadNode->getExtensionType();
9763 case ISD::AssertSext: {
9764 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9765 if ((TypeNode->getVT() == MVT::i8 && width == 8)
9766 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9767 ExtType = ISD::SEXTLOAD;
9772 case ISD::AssertZext: {
9773 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9774 if ((TypeNode->getVT() == MVT::i8 && width == 8)
9775 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9776 ExtType = ISD::ZEXTLOAD;
9782 case ISD::TargetConstant: {
9783 return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
9791 // This function does a whole lot of voodoo to determine if the tests are
9792 // equivalent without and with a mask. Essentially what happens is that given a
9795 // +-------------+ +-------------+ +-------------+ +-------------+
9796 // | Input | | AddConstant | | CompConstant| | CC |
9797 // +-------------+ +-------------+ +-------------+ +-------------+
9799 // V V | +----------+
9800 // +-------------+ +----+ | |
9801 // | ADD | |0xff| | |
9802 // +-------------+ +----+ | |
9805 // +-------------+ | |
9807 // +-------------+ | |
9816 // The AND node may be safely removed for some combinations of inputs. In
9817 // particular we need to take into account the extension type of the Input,
9818 // the exact values of AddConstant, CompConstant, and CC, along with the nominal
9819 // width of the input (this can work for any width inputs, the above graph is
9820 // specific to 8 bits.
9822 // The specific equations were worked out by generating output tables for each
9823 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
9824 // problem was simplified by working with 4 bit inputs, which means we only
9825 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
9826 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
9827 // patterns present in both extensions (0,7). For every distinct set of
9828 // AddConstant and CompConstants bit patterns we can consider the masked and
9829 // unmasked versions to be equivalent if the result of this function is true for
9830 // all 16 distinct bit patterns of for the current extension type of Input (w0).
9833 // and w10, w8, #0x0f
9835 // cset w9, AArch64CC
9837 // cset w11, AArch64CC
9842 // Since the above function shows when the outputs are equivalent it defines
9843 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
9844 // would be expensive to run during compiles. The equations below were written
9845 // in a test harness that confirmed they gave equivalent outputs to the above
9846 // for all inputs function, so they can be used determine if the removal is
9849 // isEquivalentMaskless() is the code for testing if the AND can be removed
9850 // factored out of the DAG recognition as the DAG can take several forms.
9852 static bool isEquivalentMaskless(unsigned CC, unsigned width,
9853 ISD::LoadExtType ExtType, int AddConstant,
9855 // By being careful about our equations and only writing the in term
9856 // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
9857 // make them generally applicable to all bit widths.
9858 int MaxUInt = (1 << width);
9860 // For the purposes of these comparisons sign extending the type is
9861 // equivalent to zero extending the add and displacing it by half the integer
9862 // width. Provided we are careful and make sure our equations are valid over
9863 // the whole range we can just adjust the input and avoid writing equations
9864 // for sign extended inputs.
9865 if (ExtType == ISD::SEXTLOAD)
9866 AddConstant -= (1 << (width-1));
9871 if ((AddConstant == 0) ||
9872 (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
9873 (AddConstant >= 0 && CompConstant < 0) ||
9874 (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
9879 if ((AddConstant == 0) ||
9880 (AddConstant >= 0 && CompConstant <= 0) ||
9881 (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
9886 if ((AddConstant >= 0 && CompConstant < 0) ||
9887 (AddConstant <= 0 && CompConstant >= -1 &&
9888 CompConstant < AddConstant + MaxUInt))
9893 if ((AddConstant == 0) ||
9894 (AddConstant > 0 && CompConstant <= 0) ||
9895 (AddConstant < 0 && CompConstant <= AddConstant))
9900 if ((AddConstant >= 0 && CompConstant <= 0) ||
9901 (AddConstant <= 0 && CompConstant >= 0 &&
9902 CompConstant <= AddConstant + MaxUInt))
9907 if ((AddConstant > 0 && CompConstant < 0) ||
9908 (AddConstant < 0 && CompConstant >= 0 &&
9909 CompConstant < AddConstant + MaxUInt) ||
9910 (AddConstant >= 0 && CompConstant >= 0 &&
9911 CompConstant >= AddConstant) ||
9912 (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
9920 case AArch64CC::Invalid:
9928 SDValue performCONDCombine(SDNode *N,
9929 TargetLowering::DAGCombinerInfo &DCI,
9930 SelectionDAG &DAG, unsigned CCIndex,
9931 unsigned CmpIndex) {
9932 unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
9933 SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
9934 unsigned CondOpcode = SubsNode->getOpcode();
9936 if (CondOpcode != AArch64ISD::SUBS)
9939 // There is a SUBS feeding this condition. Is it fed by a mask we can
9942 SDNode *AndNode = SubsNode->getOperand(0).getNode();
9943 unsigned MaskBits = 0;
9945 if (AndNode->getOpcode() != ISD::AND)
9948 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
9949 uint32_t CNV = CN->getZExtValue();
9952 else if (CNV == 65535)
9959 SDValue AddValue = AndNode->getOperand(0);
9961 if (AddValue.getOpcode() != ISD::ADD)
9964 // The basic dag structure is correct, grab the inputs and validate them.
9966 SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
9967 SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
9968 SDValue SubsInputValue = SubsNode->getOperand(1);
9970 // The mask is present and the provenance of all the values is a smaller type,
9971 // lets see if the mask is superfluous.
9973 if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
9974 !isa<ConstantSDNode>(SubsInputValue.getNode()))
9977 ISD::LoadExtType ExtType;
9979 if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
9980 !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
9981 !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
9984 if(!isEquivalentMaskless(CC, MaskBits, ExtType,
9985 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
9986 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
9989 // The AND is not necessary, remove it.
9991 SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
9992 SubsNode->getValueType(1));
9993 SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
9995 SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
9996 DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
9998 return SDValue(N, 0);
10001 // Optimize compare with zero and branch.
10002 static SDValue performBRCONDCombine(SDNode *N,
10003 TargetLowering::DAGCombinerInfo &DCI,
10004 SelectionDAG &DAG) {
10005 if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3))
10007 SDValue Chain = N->getOperand(0);
10008 SDValue Dest = N->getOperand(1);
10009 SDValue CCVal = N->getOperand(2);
10010 SDValue Cmp = N->getOperand(3);
10012 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
10013 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
10014 if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
10017 unsigned CmpOpc = Cmp.getOpcode();
10018 if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
10021 // Only attempt folding if there is only one use of the flag and no use of the
10023 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
10026 SDValue LHS = Cmp.getOperand(0);
10027 SDValue RHS = Cmp.getOperand(1);
10029 assert(LHS.getValueType() == RHS.getValueType() &&
10030 "Expected the value type to be the same for both operands!");
10031 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
10034 if (isNullConstant(LHS))
10035 std::swap(LHS, RHS);
10037 if (!isNullConstant(RHS))
10040 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
10041 LHS.getOpcode() == ISD::SRL)
10044 // Fold the compare into the branch instruction.
10046 if (CC == AArch64CC::EQ)
10047 BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
10049 BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
10051 // Do not add new nodes to DAG combiner worklist.
10052 DCI.CombineTo(N, BR, false);
10057 // Optimize some simple tbz/tbnz cases. Returns the new operand and bit to test
10058 // as well as whether the test should be inverted. This code is required to
10059 // catch these cases (as opposed to standard dag combines) because
10060 // AArch64ISD::TBZ is matched during legalization.
10061 static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert,
10062 SelectionDAG &DAG) {
10064 if (!Op->hasOneUse())
10067 // We don't handle undef/constant-fold cases below, as they should have
10068 // already been taken care of (e.g. and of 0, test of undefined shifted bits,
10071 // (tbz (trunc x), b) -> (tbz x, b)
10072 // This case is just here to enable more of the below cases to be caught.
10073 if (Op->getOpcode() == ISD::TRUNCATE &&
10074 Bit < Op->getValueType(0).getSizeInBits()) {
10075 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10078 if (Op->getNumOperands() != 2)
10081 auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
10085 switch (Op->getOpcode()) {
10089 // (tbz (and x, m), b) -> (tbz x, b)
10091 if ((C->getZExtValue() >> Bit) & 1)
10092 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10095 // (tbz (shl x, c), b) -> (tbz x, b-c)
10097 if (C->getZExtValue() <= Bit &&
10098 (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
10099 Bit = Bit - C->getZExtValue();
10100 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10104 // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
10106 Bit = Bit + C->getZExtValue();
10107 if (Bit >= Op->getValueType(0).getSizeInBits())
10108 Bit = Op->getValueType(0).getSizeInBits() - 1;
10109 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10111 // (tbz (srl x, c), b) -> (tbz x, b+c)
10113 if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
10114 Bit = Bit + C->getZExtValue();
10115 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10119 // (tbz (xor x, -1), b) -> (tbnz x, b)
10121 if ((C->getZExtValue() >> Bit) & 1)
10123 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10127 // Optimize test single bit zero/non-zero and branch.
10128 static SDValue performTBZCombine(SDNode *N,
10129 TargetLowering::DAGCombinerInfo &DCI,
10130 SelectionDAG &DAG) {
10131 unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
10132 bool Invert = false;
10133 SDValue TestSrc = N->getOperand(1);
10134 SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG);
10136 if (TestSrc == NewTestSrc)
10139 unsigned NewOpc = N->getOpcode();
10141 if (NewOpc == AArch64ISD::TBZ)
10142 NewOpc = AArch64ISD::TBNZ;
10144 assert(NewOpc == AArch64ISD::TBNZ);
10145 NewOpc = AArch64ISD::TBZ;
10150 return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc,
10151 DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3));
10154 // vselect (v1i1 setcc) ->
10155 // vselect (v1iXX setcc) (XX is the size of the compared operand type)
10156 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
10157 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
10159 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
10160 SDValue N0 = N->getOperand(0);
10161 EVT CCVT = N0.getValueType();
10163 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
10164 CCVT.getVectorElementType() != MVT::i1)
10167 EVT ResVT = N->getValueType(0);
10168 EVT CmpVT = N0.getOperand(0).getValueType();
10169 // Only combine when the result type is of the same size as the compared
10171 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
10174 SDValue IfTrue = N->getOperand(1);
10175 SDValue IfFalse = N->getOperand(2);
10177 DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
10178 N0.getOperand(0), N0.getOperand(1),
10179 cast<CondCodeSDNode>(N0.getOperand(2))->get());
10180 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
10184 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
10185 /// the compare-mask instructions rather than going via NZCV, even if LHS and
10186 /// RHS are really scalar. This replaces any scalar setcc in the above pattern
10187 /// with a vector one followed by a DUP shuffle on the result.
10188 static SDValue performSelectCombine(SDNode *N,
10189 TargetLowering::DAGCombinerInfo &DCI) {
10190 SelectionDAG &DAG = DCI.DAG;
10191 SDValue N0 = N->getOperand(0);
10192 EVT ResVT = N->getValueType(0);
10194 if (N0.getOpcode() != ISD::SETCC)
10197 // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
10198 // scalar SetCCResultType. We also don't expect vectors, because we assume
10199 // that selects fed by vector SETCCs are canonicalized to VSELECT.
10200 assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
10201 "Scalar-SETCC feeding SELECT has unexpected result type!");
10203 // If NumMaskElts == 0, the comparison is larger than select result. The
10204 // largest real NEON comparison is 64-bits per lane, which means the result is
10205 // at most 32-bits and an illegal vector. Just bail out for now.
10206 EVT SrcVT = N0.getOperand(0).getValueType();
10208 // Don't try to do this optimization when the setcc itself has i1 operands.
10209 // There are no legal vectors of i1, so this would be pointless.
10210 if (SrcVT == MVT::i1)
10213 int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
10214 if (!ResVT.isVector() || NumMaskElts == 0)
10217 SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
10218 EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
10220 // Also bail out if the vector CCVT isn't the same size as ResVT.
10221 // This can happen if the SETCC operand size doesn't divide the ResVT size
10222 // (e.g., f64 vs v3f32).
10223 if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
10226 // Make sure we didn't create illegal types, if we're not supposed to.
10227 assert(DCI.isBeforeLegalize() ||
10228 DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
10230 // First perform a vector comparison, where lane 0 is the one we're interested
10234 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
10236 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
10237 SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
10239 // Now duplicate the comparison mask we want across all other lanes.
10240 SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
10241 SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask);
10242 Mask = DAG.getNode(ISD::BITCAST, DL,
10243 ResVT.changeVectorElementTypeToInteger(), Mask);
10245 return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
10248 /// Get rid of unnecessary NVCASTs (that don't change the type).
10249 static SDValue performNVCASTCombine(SDNode *N) {
10250 if (N->getValueType(0) == N->getOperand(0).getValueType())
10251 return N->getOperand(0);
10256 SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
10257 DAGCombinerInfo &DCI) const {
10258 SelectionDAG &DAG = DCI.DAG;
10259 switch (N->getOpcode()) {
10264 return performAddSubLongCombine(N, DCI, DAG);
10266 return performXorCombine(N, DAG, DCI, Subtarget);
10268 return performMulCombine(N, DAG, DCI, Subtarget);
10269 case ISD::SINT_TO_FP:
10270 case ISD::UINT_TO_FP:
10271 return performIntToFpCombine(N, DAG, Subtarget);
10272 case ISD::FP_TO_SINT:
10273 case ISD::FP_TO_UINT:
10274 return performFpToIntCombine(N, DAG, DCI, Subtarget);
10276 return performFDivCombine(N, DAG, DCI, Subtarget);
10278 return performORCombine(N, DCI, Subtarget);
10280 return performSRLCombine(N, DCI);
10281 case ISD::INTRINSIC_WO_CHAIN:
10282 return performIntrinsicCombine(N, DCI, Subtarget);
10283 case ISD::ANY_EXTEND:
10284 case ISD::ZERO_EXTEND:
10285 case ISD::SIGN_EXTEND:
10286 return performExtendCombine(N, DCI, DAG);
10288 return performBitcastCombine(N, DCI, DAG);
10289 case ISD::CONCAT_VECTORS:
10290 return performConcatVectorsCombine(N, DCI, DAG);
10292 return performSelectCombine(N, DCI);
10294 return performVSelectCombine(N, DCI.DAG);
10296 if (performTBISimplification(N->getOperand(1), DCI, DAG))
10297 return SDValue(N, 0);
10300 return performSTORECombine(N, DCI, DAG, Subtarget);
10301 case AArch64ISD::BRCOND:
10302 return performBRCONDCombine(N, DCI, DAG);
10303 case AArch64ISD::TBNZ:
10304 case AArch64ISD::TBZ:
10305 return performTBZCombine(N, DCI, DAG);
10306 case AArch64ISD::CSEL:
10307 return performCONDCombine(N, DCI, DAG, 2, 3);
10308 case AArch64ISD::DUP:
10309 return performPostLD1Combine(N, DCI, false);
10310 case AArch64ISD::NVCAST:
10311 return performNVCASTCombine(N);
10312 case ISD::INSERT_VECTOR_ELT:
10313 return performPostLD1Combine(N, DCI, true);
10314 case ISD::INTRINSIC_VOID:
10315 case ISD::INTRINSIC_W_CHAIN:
10316 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10317 case Intrinsic::aarch64_neon_ld2:
10318 case Intrinsic::aarch64_neon_ld3:
10319 case Intrinsic::aarch64_neon_ld4:
10320 case Intrinsic::aarch64_neon_ld1x2:
10321 case Intrinsic::aarch64_neon_ld1x3:
10322 case Intrinsic::aarch64_neon_ld1x4:
10323 case Intrinsic::aarch64_neon_ld2lane:
10324 case Intrinsic::aarch64_neon_ld3lane:
10325 case Intrinsic::aarch64_neon_ld4lane:
10326 case Intrinsic::aarch64_neon_ld2r:
10327 case Intrinsic::aarch64_neon_ld3r:
10328 case Intrinsic::aarch64_neon_ld4r:
10329 case Intrinsic::aarch64_neon_st2:
10330 case Intrinsic::aarch64_neon_st3:
10331 case Intrinsic::aarch64_neon_st4:
10332 case Intrinsic::aarch64_neon_st1x2:
10333 case Intrinsic::aarch64_neon_st1x3:
10334 case Intrinsic::aarch64_neon_st1x4:
10335 case Intrinsic::aarch64_neon_st2lane:
10336 case Intrinsic::aarch64_neon_st3lane:
10337 case Intrinsic::aarch64_neon_st4lane:
10338 return performNEONPostLDSTCombine(N, DCI, DAG);
10346 // Check if the return value is used as only a return value, as otherwise
10347 // we can't perform a tail-call. In particular, we need to check for
10348 // target ISD nodes that are returns and any other "odd" constructs
10349 // that the generic analysis code won't necessarily catch.
10350 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
10351 SDValue &Chain) const {
10352 if (N->getNumValues() != 1)
10354 if (!N->hasNUsesOfValue(1, 0))
10357 SDValue TCChain = Chain;
10358 SDNode *Copy = *N->use_begin();
10359 if (Copy->getOpcode() == ISD::CopyToReg) {
10360 // If the copy has a glue operand, we conservatively assume it isn't safe to
10361 // perform a tail call.
10362 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
10365 TCChain = Copy->getOperand(0);
10366 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
10369 bool HasRet = false;
10370 for (SDNode *Node : Copy->uses()) {
10371 if (Node->getOpcode() != AArch64ISD::RET_FLAG)
10383 // Return whether the an instruction can potentially be optimized to a tail
10384 // call. This will cause the optimizers to attempt to move, or duplicate,
10385 // return instructions to help enable tail call optimizations for this
10387 bool AArch64TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
10388 return CI->isTailCall();
10391 bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
10393 ISD::MemIndexedMode &AM,
10395 SelectionDAG &DAG) const {
10396 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
10399 Base = Op->getOperand(0);
10400 // All of the indexed addressing mode instructions take a signed
10401 // 9 bit immediate offset.
10402 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
10403 int64_t RHSC = RHS->getSExtValue();
10404 if (Op->getOpcode() == ISD::SUB)
10405 RHSC = -(uint64_t)RHSC;
10406 if (!isInt<9>(RHSC))
10408 IsInc = (Op->getOpcode() == ISD::ADD);
10409 Offset = Op->getOperand(1);
10415 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10417 ISD::MemIndexedMode &AM,
10418 SelectionDAG &DAG) const {
10421 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10422 VT = LD->getMemoryVT();
10423 Ptr = LD->getBasePtr();
10424 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10425 VT = ST->getMemoryVT();
10426 Ptr = ST->getBasePtr();
10431 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
10433 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
10437 bool AArch64TargetLowering::getPostIndexedAddressParts(
10438 SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
10439 ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
10442 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10443 VT = LD->getMemoryVT();
10444 Ptr = LD->getBasePtr();
10445 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10446 VT = ST->getMemoryVT();
10447 Ptr = ST->getBasePtr();
10452 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
10454 // Post-indexing updates the base, so it's not a valid transform
10455 // if that's not the same as the load's pointer.
10458 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
10462 static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
10463 SelectionDAG &DAG) {
10465 SDValue Op = N->getOperand(0);
10467 if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
10471 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
10472 DAG.getUNDEF(MVT::i32), Op,
10473 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
10475 Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
10476 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
10479 static void ReplaceReductionResults(SDNode *N,
10480 SmallVectorImpl<SDValue> &Results,
10481 SelectionDAG &DAG, unsigned InterOp,
10482 unsigned AcrossOp) {
10486 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
10487 std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
10488 SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
10489 SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
10490 Results.push_back(SplitVal);
10493 static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) {
10495 SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N);
10496 SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64,
10497 DAG.getNode(ISD::SRL, DL, MVT::i128, N,
10498 DAG.getConstant(64, DL, MVT::i64)));
10499 return std::make_pair(Lo, Hi);
10502 static void ReplaceCMP_SWAP_128Results(SDNode *N,
10503 SmallVectorImpl<SDValue> & Results,
10504 SelectionDAG &DAG) {
10505 assert(N->getValueType(0) == MVT::i128 &&
10506 "AtomicCmpSwap on types less than 128 should be legal");
10507 auto Desired = splitInt128(N->getOperand(2), DAG);
10508 auto New = splitInt128(N->getOperand(3), DAG);
10509 SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second,
10510 New.first, New.second, N->getOperand(0)};
10511 SDNode *CmpSwap = DAG.getMachineNode(
10512 AArch64::CMP_SWAP_128, SDLoc(N),
10513 DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops);
10515 MachineFunction &MF = DAG.getMachineFunction();
10516 MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1);
10517 MemOp[0] = cast<MemSDNode>(N)->getMemOperand();
10518 cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1);
10520 Results.push_back(SDValue(CmpSwap, 0));
10521 Results.push_back(SDValue(CmpSwap, 1));
10522 Results.push_back(SDValue(CmpSwap, 3));
10525 void AArch64TargetLowering::ReplaceNodeResults(
10526 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
10527 switch (N->getOpcode()) {
10529 llvm_unreachable("Don't know how to custom expand this");
10531 ReplaceBITCASTResults(N, Results, DAG);
10533 case ISD::VECREDUCE_ADD:
10534 case ISD::VECREDUCE_SMAX:
10535 case ISD::VECREDUCE_SMIN:
10536 case ISD::VECREDUCE_UMAX:
10537 case ISD::VECREDUCE_UMIN:
10538 Results.push_back(LowerVECREDUCE(SDValue(N, 0), DAG));
10541 case AArch64ISD::SADDV:
10542 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
10544 case AArch64ISD::UADDV:
10545 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
10547 case AArch64ISD::SMINV:
10548 ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
10550 case AArch64ISD::UMINV:
10551 ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
10553 case AArch64ISD::SMAXV:
10554 ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
10556 case AArch64ISD::UMAXV:
10557 ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
10559 case ISD::FP_TO_UINT:
10560 case ISD::FP_TO_SINT:
10561 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
10562 // Let normal code take care of it by not adding anything to Results.
10564 case ISD::ATOMIC_CMP_SWAP:
10565 ReplaceCMP_SWAP_128Results(N, Results, DAG);
10570 bool AArch64TargetLowering::useLoadStackGuardNode() const {
10571 if (Subtarget->isTargetAndroid() || Subtarget->isTargetFuchsia())
10572 return TargetLowering::useLoadStackGuardNode();
10576 unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
10577 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
10578 // reciprocal if there are three or more FDIVs.
10582 TargetLoweringBase::LegalizeTypeAction
10583 AArch64TargetLowering::getPreferredVectorAction(EVT VT) const {
10584 MVT SVT = VT.getSimpleVT();
10585 // During type legalization, we prefer to widen v1i8, v1i16, v1i32 to v8i8,
10586 // v4i16, v2i32 instead of to promote.
10587 if (SVT == MVT::v1i8 || SVT == MVT::v1i16 || SVT == MVT::v1i32
10588 || SVT == MVT::v1f32)
10589 return TypeWidenVector;
10591 return TargetLoweringBase::getPreferredVectorAction(VT);
10594 // Loads and stores less than 128-bits are already atomic; ones above that
10595 // are doomed anyway, so defer to the default libcall and blame the OS when
10596 // things go wrong.
10597 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
10598 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
10599 return Size == 128;
10602 // Loads and stores less than 128-bits are already atomic; ones above that
10603 // are doomed anyway, so defer to the default libcall and blame the OS when
10604 // things go wrong.
10605 TargetLowering::AtomicExpansionKind
10606 AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
10607 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
10608 return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
10611 // For the real atomic operations, we have ldxr/stxr up to 128 bits,
10612 TargetLowering::AtomicExpansionKind
10613 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
10614 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
10615 if (Size > 128) return AtomicExpansionKind::None;
10616 // Nand not supported in LSE.
10617 if (AI->getOperation() == AtomicRMWInst::Nand) return AtomicExpansionKind::LLSC;
10618 // Leave 128 bits to LLSC.
10619 return (Subtarget->hasLSE() && Size < 128) ? AtomicExpansionKind::None : AtomicExpansionKind::LLSC;
10622 bool AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
10623 AtomicCmpXchgInst *AI) const {
10624 // If subtarget has LSE, leave cmpxchg intact for codegen.
10625 if (Subtarget->hasLSE()) return false;
10626 // At -O0, fast-regalloc cannot cope with the live vregs necessary to
10627 // implement cmpxchg without spilling. If the address being exchanged is also
10628 // on the stack and close enough to the spill slot, this can lead to a
10629 // situation where the monitor always gets cleared and the atomic operation
10630 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
10631 return getTargetMachine().getOptLevel() != 0;
10634 Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
10635 AtomicOrdering Ord) const {
10636 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10637 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
10638 bool IsAcquire = isAcquireOrStronger(Ord);
10640 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
10641 // intrinsic must return {i64, i64} and we have to recombine them into a
10642 // single i128 here.
10643 if (ValTy->getPrimitiveSizeInBits() == 128) {
10644 Intrinsic::ID Int =
10645 IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
10646 Function *Ldxr = Intrinsic::getDeclaration(M, Int);
10648 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10649 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
10651 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
10652 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
10653 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
10654 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
10655 return Builder.CreateOr(
10656 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
10659 Type *Tys[] = { Addr->getType() };
10660 Intrinsic::ID Int =
10661 IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
10662 Function *Ldxr = Intrinsic::getDeclaration(M, Int, Tys);
10664 return Builder.CreateTruncOrBitCast(
10665 Builder.CreateCall(Ldxr, Addr),
10666 cast<PointerType>(Addr->getType())->getElementType());
10669 void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
10670 IRBuilder<> &Builder) const {
10671 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10672 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
10675 Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
10676 Value *Val, Value *Addr,
10677 AtomicOrdering Ord) const {
10678 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10679 bool IsRelease = isReleaseOrStronger(Ord);
10681 // Since the intrinsics must have legal type, the i128 intrinsics take two
10682 // parameters: "i64, i64". We must marshal Val into the appropriate form
10683 // before the call.
10684 if (Val->getType()->getPrimitiveSizeInBits() == 128) {
10685 Intrinsic::ID Int =
10686 IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
10687 Function *Stxr = Intrinsic::getDeclaration(M, Int);
10688 Type *Int64Ty = Type::getInt64Ty(M->getContext());
10690 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
10691 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
10692 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10693 return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
10696 Intrinsic::ID Int =
10697 IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
10698 Type *Tys[] = { Addr->getType() };
10699 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
10701 return Builder.CreateCall(Stxr,
10702 {Builder.CreateZExtOrBitCast(
10703 Val, Stxr->getFunctionType()->getParamType(0)),
10707 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
10708 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
10709 return Ty->isArrayTy();
10712 bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
10717 static Value *UseTlsOffset(IRBuilder<> &IRB, unsigned Offset) {
10718 Module *M = IRB.GetInsertBlock()->getParent()->getParent();
10719 Function *ThreadPointerFunc =
10720 Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
10721 return IRB.CreatePointerCast(
10722 IRB.CreateConstGEP1_32(IRB.CreateCall(ThreadPointerFunc), Offset),
10723 Type::getInt8PtrTy(IRB.getContext())->getPointerTo(0));
10726 Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const {
10727 // Android provides a fixed TLS slot for the stack cookie. See the definition
10728 // of TLS_SLOT_STACK_GUARD in
10729 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
10730 if (Subtarget->isTargetAndroid())
10731 return UseTlsOffset(IRB, 0x28);
10733 // Fuchsia is similar.
10734 // <magenta/tls.h> defines MX_TLS_STACK_GUARD_OFFSET with this value.
10735 if (Subtarget->isTargetFuchsia())
10736 return UseTlsOffset(IRB, -0x10);
10738 return TargetLowering::getIRStackGuard(IRB);
10741 Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
10742 // Android provides a fixed TLS slot for the SafeStack pointer. See the
10743 // definition of TLS_SLOT_SAFESTACK in
10744 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
10745 if (Subtarget->isTargetAndroid())
10746 return UseTlsOffset(IRB, 0x48);
10748 // Fuchsia is similar.
10749 // <magenta/tls.h> defines MX_TLS_UNSAFE_SP_OFFSET with this value.
10750 if (Subtarget->isTargetFuchsia())
10751 return UseTlsOffset(IRB, -0x8);
10753 return TargetLowering::getSafeStackPointerLocation(IRB);
10756 bool AArch64TargetLowering::isMaskAndCmp0FoldingBeneficial(
10757 const Instruction &AndI) const {
10758 // Only sink 'and' mask to cmp use block if it is masking a single bit, since
10759 // this is likely to be fold the and/cmp/br into a single tbz instruction. It
10760 // may be beneficial to sink in other cases, but we would have to check that
10761 // the cmp would not get folded into the br to form a cbz for these to be
10763 ConstantInt* Mask = dyn_cast<ConstantInt>(AndI.getOperand(1));
10766 return Mask->getUniqueInteger().isPowerOf2();
10769 void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
10770 // Update IsSplitCSR in AArch64unctionInfo.
10771 AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>();
10772 AFI->setIsSplitCSR(true);
10775 void AArch64TargetLowering::insertCopiesSplitCSR(
10776 MachineBasicBlock *Entry,
10777 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
10778 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
10779 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
10783 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10784 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
10785 MachineBasicBlock::iterator MBBI = Entry->begin();
10786 for (const MCPhysReg *I = IStart; *I; ++I) {
10787 const TargetRegisterClass *RC = nullptr;
10788 if (AArch64::GPR64RegClass.contains(*I))
10789 RC = &AArch64::GPR64RegClass;
10790 else if (AArch64::FPR64RegClass.contains(*I))
10791 RC = &AArch64::FPR64RegClass;
10793 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
10795 unsigned NewVR = MRI->createVirtualRegister(RC);
10796 // Create copy from CSR to a virtual register.
10797 // FIXME: this currently does not emit CFI pseudo-instructions, it works
10798 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
10799 // nounwind. If we want to generalize this later, we may need to emit
10800 // CFI pseudo-instructions.
10801 assert(Entry->getParent()->getFunction()->hasFnAttribute(
10802 Attribute::NoUnwind) &&
10803 "Function should be nounwind in insertCopiesSplitCSR!");
10804 Entry->addLiveIn(*I);
10805 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
10808 // Insert the copy-back instructions right before the terminator.
10809 for (auto *Exit : Exits)
10810 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
10811 TII->get(TargetOpcode::COPY), *I)
10816 bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const {
10817 // Integer division on AArch64 is expensive. However, when aggressively
10818 // optimizing for code size, we prefer to use a div instruction, as it is
10819 // usually smaller than the alternative sequence.
10820 // The exception to this is vector division. Since AArch64 doesn't have vector
10821 // integer division, leaving the division as-is is a loss even in terms of
10822 // size, because it will have to be scalarized, while the alternative code
10823 // sequence can be performed in vector form.
10825 Attr.hasAttribute(AttributeList::FunctionIndex, Attribute::MinSize);
10826 return OptSize && !VT.isVector();
10830 AArch64TargetLowering::getVaListSizeInBits(const DataLayout &DL) const {
10831 if (Subtarget->isTargetDarwin() || Subtarget->isTargetWindows())
10832 return getPointerTy(DL).getSizeInBits();
10834 return 3 * getPointerTy(DL).getSizeInBits() + 2 * 32;