1 //===-- AArch64ISelLowering.cpp - AArch64 DAG Lowering Implementation ----===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file implements the AArch64TargetLowering class.
11 //===----------------------------------------------------------------------===//
13 #include "AArch64ExpandImm.h"
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/RuntimeLibcalls.h"
42 #include "llvm/CodeGen/SelectionDAG.h"
43 #include "llvm/CodeGen/SelectionDAGNodes.h"
44 #include "llvm/CodeGen/TargetCallingConv.h"
45 #include "llvm/CodeGen/TargetInstrInfo.h"
46 #include "llvm/CodeGen/ValueTypes.h"
47 #include "llvm/IR/Attributes.h"
48 #include "llvm/IR/Constants.h"
49 #include "llvm/IR/DataLayout.h"
50 #include "llvm/IR/DebugLoc.h"
51 #include "llvm/IR/DerivedTypes.h"
52 #include "llvm/IR/Function.h"
53 #include "llvm/IR/GetElementPtrTypeIterator.h"
54 #include "llvm/IR/GlobalValue.h"
55 #include "llvm/IR/IRBuilder.h"
56 #include "llvm/IR/Instruction.h"
57 #include "llvm/IR/Instructions.h"
58 #include "llvm/IR/IntrinsicInst.h"
59 #include "llvm/IR/Intrinsics.h"
60 #include "llvm/IR/Module.h"
61 #include "llvm/IR/OperandTraits.h"
62 #include "llvm/IR/PatternMatch.h"
63 #include "llvm/IR/Type.h"
64 #include "llvm/IR/Use.h"
65 #include "llvm/IR/Value.h"
66 #include "llvm/MC/MCRegisterInfo.h"
67 #include "llvm/Support/Casting.h"
68 #include "llvm/Support/CodeGen.h"
69 #include "llvm/Support/CommandLine.h"
70 #include "llvm/Support/Compiler.h"
71 #include "llvm/Support/Debug.h"
72 #include "llvm/Support/ErrorHandling.h"
73 #include "llvm/Support/KnownBits.h"
74 #include "llvm/Support/MachineValueType.h"
75 #include "llvm/Support/MathExtras.h"
76 #include "llvm/Support/raw_ostream.h"
77 #include "llvm/Target/TargetMachine.h"
78 #include "llvm/Target/TargetOptions.h"
92 using namespace llvm::PatternMatch
;
94 #define DEBUG_TYPE "aarch64-lower"
96 STATISTIC(NumTailCalls
, "Number of tail calls");
97 STATISTIC(NumShiftInserts
, "Number of vector shift inserts");
98 STATISTIC(NumOptimizedImms
, "Number of times immediates were optimized");
101 EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden
,
102 cl::desc("Allow AArch64 SLI/SRI formation"),
105 // FIXME: The necessary dtprel relocations don't seem to be supported
106 // well in the GNU bfd and gold linkers at the moment. Therefore, by
107 // default, for now, fall back to GeneralDynamic code generation.
108 cl::opt
<bool> EnableAArch64ELFLocalDynamicTLSGeneration(
109 "aarch64-elf-ldtls-generation", cl::Hidden
,
110 cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
114 EnableOptimizeLogicalImm("aarch64-enable-logical-imm", cl::Hidden
,
115 cl::desc("Enable AArch64 logical imm instruction "
119 /// Value type used for condition codes.
120 static const MVT MVT_CC
= MVT::i32
;
122 AArch64TargetLowering::AArch64TargetLowering(const TargetMachine
&TM
,
123 const AArch64Subtarget
&STI
)
124 : TargetLowering(TM
), Subtarget(&STI
) {
125 // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
126 // we have to make something up. Arbitrarily, choose ZeroOrOne.
127 setBooleanContents(ZeroOrOneBooleanContent
);
128 // When comparing vectors the result sets the different elements in the
129 // vector to all-one or all-zero.
130 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent
);
132 // Set up the register classes.
133 addRegisterClass(MVT::i32
, &AArch64::GPR32allRegClass
);
134 addRegisterClass(MVT::i64
, &AArch64::GPR64allRegClass
);
136 if (Subtarget
->hasFPARMv8()) {
137 addRegisterClass(MVT::f16
, &AArch64::FPR16RegClass
);
138 addRegisterClass(MVT::f32
, &AArch64::FPR32RegClass
);
139 addRegisterClass(MVT::f64
, &AArch64::FPR64RegClass
);
140 addRegisterClass(MVT::f128
, &AArch64::FPR128RegClass
);
143 if (Subtarget
->hasNEON()) {
144 addRegisterClass(MVT::v16i8
, &AArch64::FPR8RegClass
);
145 addRegisterClass(MVT::v8i16
, &AArch64::FPR16RegClass
);
146 // Someone set us up the NEON.
147 addDRTypeForNEON(MVT::v2f32
);
148 addDRTypeForNEON(MVT::v8i8
);
149 addDRTypeForNEON(MVT::v4i16
);
150 addDRTypeForNEON(MVT::v2i32
);
151 addDRTypeForNEON(MVT::v1i64
);
152 addDRTypeForNEON(MVT::v1f64
);
153 addDRTypeForNEON(MVT::v4f16
);
155 addQRTypeForNEON(MVT::v4f32
);
156 addQRTypeForNEON(MVT::v2f64
);
157 addQRTypeForNEON(MVT::v16i8
);
158 addQRTypeForNEON(MVT::v8i16
);
159 addQRTypeForNEON(MVT::v4i32
);
160 addQRTypeForNEON(MVT::v2i64
);
161 addQRTypeForNEON(MVT::v8f16
);
164 if (Subtarget
->hasSVE()) {
165 // Add legal sve predicate types
166 addRegisterClass(MVT::nxv2i1
, &AArch64::PPRRegClass
);
167 addRegisterClass(MVT::nxv4i1
, &AArch64::PPRRegClass
);
168 addRegisterClass(MVT::nxv8i1
, &AArch64::PPRRegClass
);
169 addRegisterClass(MVT::nxv16i1
, &AArch64::PPRRegClass
);
171 // Add legal sve data types
172 addRegisterClass(MVT::nxv16i8
, &AArch64::ZPRRegClass
);
173 addRegisterClass(MVT::nxv8i16
, &AArch64::ZPRRegClass
);
174 addRegisterClass(MVT::nxv4i32
, &AArch64::ZPRRegClass
);
175 addRegisterClass(MVT::nxv2i64
, &AArch64::ZPRRegClass
);
177 addRegisterClass(MVT::nxv2f16
, &AArch64::ZPRRegClass
);
178 addRegisterClass(MVT::nxv4f16
, &AArch64::ZPRRegClass
);
179 addRegisterClass(MVT::nxv8f16
, &AArch64::ZPRRegClass
);
180 addRegisterClass(MVT::nxv1f32
, &AArch64::ZPRRegClass
);
181 addRegisterClass(MVT::nxv2f32
, &AArch64::ZPRRegClass
);
182 addRegisterClass(MVT::nxv4f32
, &AArch64::ZPRRegClass
);
183 addRegisterClass(MVT::nxv1f64
, &AArch64::ZPRRegClass
);
184 addRegisterClass(MVT::nxv2f64
, &AArch64::ZPRRegClass
);
187 // Compute derived properties from the register classes
188 computeRegisterProperties(Subtarget
->getRegisterInfo());
190 // Provide all sorts of operation actions
191 setOperationAction(ISD::GlobalAddress
, MVT::i64
, Custom
);
192 setOperationAction(ISD::GlobalTLSAddress
, MVT::i64
, Custom
);
193 setOperationAction(ISD::SETCC
, MVT::i32
, Custom
);
194 setOperationAction(ISD::SETCC
, MVT::i64
, Custom
);
195 setOperationAction(ISD::SETCC
, MVT::f16
, Custom
);
196 setOperationAction(ISD::SETCC
, MVT::f32
, Custom
);
197 setOperationAction(ISD::SETCC
, MVT::f64
, Custom
);
198 setOperationAction(ISD::BITREVERSE
, MVT::i32
, Legal
);
199 setOperationAction(ISD::BITREVERSE
, MVT::i64
, Legal
);
200 setOperationAction(ISD::BRCOND
, MVT::Other
, Expand
);
201 setOperationAction(ISD::BR_CC
, MVT::i32
, Custom
);
202 setOperationAction(ISD::BR_CC
, MVT::i64
, Custom
);
203 setOperationAction(ISD::BR_CC
, MVT::f16
, Custom
);
204 setOperationAction(ISD::BR_CC
, MVT::f32
, Custom
);
205 setOperationAction(ISD::BR_CC
, MVT::f64
, Custom
);
206 setOperationAction(ISD::SELECT
, MVT::i32
, Custom
);
207 setOperationAction(ISD::SELECT
, MVT::i64
, Custom
);
208 setOperationAction(ISD::SELECT
, MVT::f16
, Custom
);
209 setOperationAction(ISD::SELECT
, MVT::f32
, Custom
);
210 setOperationAction(ISD::SELECT
, MVT::f64
, Custom
);
211 setOperationAction(ISD::SELECT_CC
, MVT::i32
, Custom
);
212 setOperationAction(ISD::SELECT_CC
, MVT::i64
, Custom
);
213 setOperationAction(ISD::SELECT_CC
, MVT::f16
, Custom
);
214 setOperationAction(ISD::SELECT_CC
, MVT::f32
, Custom
);
215 setOperationAction(ISD::SELECT_CC
, MVT::f64
, Custom
);
216 setOperationAction(ISD::BR_JT
, MVT::Other
, Custom
);
217 setOperationAction(ISD::JumpTable
, MVT::i64
, Custom
);
219 setOperationAction(ISD::SHL_PARTS
, MVT::i64
, Custom
);
220 setOperationAction(ISD::SRA_PARTS
, MVT::i64
, Custom
);
221 setOperationAction(ISD::SRL_PARTS
, MVT::i64
, Custom
);
223 setOperationAction(ISD::FREM
, MVT::f32
, Expand
);
224 setOperationAction(ISD::FREM
, MVT::f64
, Expand
);
225 setOperationAction(ISD::FREM
, MVT::f80
, Expand
);
227 setOperationAction(ISD::BUILD_PAIR
, MVT::i64
, Expand
);
229 // Custom lowering hooks are needed for XOR
230 // to fold it into CSINC/CSINV.
231 setOperationAction(ISD::XOR
, MVT::i32
, Custom
);
232 setOperationAction(ISD::XOR
, MVT::i64
, Custom
);
234 // Virtually no operation on f128 is legal, but LLVM can't expand them when
235 // there's a valid register class, so we need custom operations in most cases.
236 setOperationAction(ISD::FABS
, MVT::f128
, Expand
);
237 setOperationAction(ISD::FADD
, MVT::f128
, Custom
);
238 setOperationAction(ISD::FCOPYSIGN
, MVT::f128
, Expand
);
239 setOperationAction(ISD::FCOS
, MVT::f128
, Expand
);
240 setOperationAction(ISD::FDIV
, MVT::f128
, Custom
);
241 setOperationAction(ISD::FMA
, MVT::f128
, Expand
);
242 setOperationAction(ISD::FMUL
, MVT::f128
, Custom
);
243 setOperationAction(ISD::FNEG
, MVT::f128
, Expand
);
244 setOperationAction(ISD::FPOW
, MVT::f128
, Expand
);
245 setOperationAction(ISD::FREM
, MVT::f128
, Expand
);
246 setOperationAction(ISD::FRINT
, MVT::f128
, Expand
);
247 setOperationAction(ISD::FSIN
, MVT::f128
, Expand
);
248 setOperationAction(ISD::FSINCOS
, MVT::f128
, Expand
);
249 setOperationAction(ISD::FSQRT
, MVT::f128
, Expand
);
250 setOperationAction(ISD::FSUB
, MVT::f128
, Custom
);
251 setOperationAction(ISD::FTRUNC
, MVT::f128
, Expand
);
252 setOperationAction(ISD::SETCC
, MVT::f128
, Custom
);
253 setOperationAction(ISD::BR_CC
, MVT::f128
, Custom
);
254 setOperationAction(ISD::SELECT
, MVT::f128
, Custom
);
255 setOperationAction(ISD::SELECT_CC
, MVT::f128
, Custom
);
256 setOperationAction(ISD::FP_EXTEND
, MVT::f128
, Custom
);
258 // Lowering for many of the conversions is actually specified by the non-f128
259 // type. The LowerXXX function will be trivial when f128 isn't involved.
260 setOperationAction(ISD::FP_TO_SINT
, MVT::i32
, Custom
);
261 setOperationAction(ISD::FP_TO_SINT
, MVT::i64
, Custom
);
262 setOperationAction(ISD::FP_TO_SINT
, MVT::i128
, Custom
);
263 setOperationAction(ISD::FP_TO_UINT
, MVT::i32
, Custom
);
264 setOperationAction(ISD::FP_TO_UINT
, MVT::i64
, Custom
);
265 setOperationAction(ISD::FP_TO_UINT
, MVT::i128
, Custom
);
266 setOperationAction(ISD::SINT_TO_FP
, MVT::i32
, Custom
);
267 setOperationAction(ISD::SINT_TO_FP
, MVT::i64
, Custom
);
268 setOperationAction(ISD::SINT_TO_FP
, MVT::i128
, Custom
);
269 setOperationAction(ISD::UINT_TO_FP
, MVT::i32
, Custom
);
270 setOperationAction(ISD::UINT_TO_FP
, MVT::i64
, Custom
);
271 setOperationAction(ISD::UINT_TO_FP
, MVT::i128
, Custom
);
272 setOperationAction(ISD::FP_ROUND
, MVT::f32
, Custom
);
273 setOperationAction(ISD::FP_ROUND
, MVT::f64
, Custom
);
275 // Variable arguments.
276 setOperationAction(ISD::VASTART
, MVT::Other
, Custom
);
277 setOperationAction(ISD::VAARG
, MVT::Other
, Custom
);
278 setOperationAction(ISD::VACOPY
, MVT::Other
, Custom
);
279 setOperationAction(ISD::VAEND
, MVT::Other
, Expand
);
281 // Variable-sized objects.
282 setOperationAction(ISD::STACKSAVE
, MVT::Other
, Expand
);
283 setOperationAction(ISD::STACKRESTORE
, MVT::Other
, Expand
);
285 if (Subtarget
->isTargetWindows())
286 setOperationAction(ISD::DYNAMIC_STACKALLOC
, MVT::i64
, Custom
);
288 setOperationAction(ISD::DYNAMIC_STACKALLOC
, MVT::i64
, Expand
);
290 // Constant pool entries
291 setOperationAction(ISD::ConstantPool
, MVT::i64
, Custom
);
294 setOperationAction(ISD::BlockAddress
, MVT::i64
, Custom
);
296 // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
297 setOperationAction(ISD::ADDC
, MVT::i32
, Custom
);
298 setOperationAction(ISD::ADDE
, MVT::i32
, Custom
);
299 setOperationAction(ISD::SUBC
, MVT::i32
, Custom
);
300 setOperationAction(ISD::SUBE
, MVT::i32
, Custom
);
301 setOperationAction(ISD::ADDC
, MVT::i64
, Custom
);
302 setOperationAction(ISD::ADDE
, MVT::i64
, Custom
);
303 setOperationAction(ISD::SUBC
, MVT::i64
, Custom
);
304 setOperationAction(ISD::SUBE
, MVT::i64
, Custom
);
306 // AArch64 lacks both left-rotate and popcount instructions.
307 setOperationAction(ISD::ROTL
, MVT::i32
, Expand
);
308 setOperationAction(ISD::ROTL
, MVT::i64
, Expand
);
309 for (MVT VT
: MVT::vector_valuetypes()) {
310 setOperationAction(ISD::ROTL
, VT
, Expand
);
311 setOperationAction(ISD::ROTR
, VT
, Expand
);
314 // AArch64 doesn't have {U|S}MUL_LOHI.
315 setOperationAction(ISD::UMUL_LOHI
, MVT::i64
, Expand
);
316 setOperationAction(ISD::SMUL_LOHI
, MVT::i64
, Expand
);
318 setOperationAction(ISD::CTPOP
, MVT::i32
, Custom
);
319 setOperationAction(ISD::CTPOP
, MVT::i64
, Custom
);
321 setOperationAction(ISD::SDIVREM
, MVT::i32
, Expand
);
322 setOperationAction(ISD::SDIVREM
, MVT::i64
, Expand
);
323 for (MVT VT
: MVT::vector_valuetypes()) {
324 setOperationAction(ISD::SDIVREM
, VT
, Expand
);
325 setOperationAction(ISD::UDIVREM
, VT
, Expand
);
327 setOperationAction(ISD::SREM
, MVT::i32
, Expand
);
328 setOperationAction(ISD::SREM
, MVT::i64
, Expand
);
329 setOperationAction(ISD::UDIVREM
, MVT::i32
, Expand
);
330 setOperationAction(ISD::UDIVREM
, MVT::i64
, Expand
);
331 setOperationAction(ISD::UREM
, MVT::i32
, Expand
);
332 setOperationAction(ISD::UREM
, MVT::i64
, Expand
);
334 // Custom lower Add/Sub/Mul with overflow.
335 setOperationAction(ISD::SADDO
, MVT::i32
, Custom
);
336 setOperationAction(ISD::SADDO
, MVT::i64
, Custom
);
337 setOperationAction(ISD::UADDO
, MVT::i32
, Custom
);
338 setOperationAction(ISD::UADDO
, MVT::i64
, Custom
);
339 setOperationAction(ISD::SSUBO
, MVT::i32
, Custom
);
340 setOperationAction(ISD::SSUBO
, MVT::i64
, Custom
);
341 setOperationAction(ISD::USUBO
, MVT::i32
, Custom
);
342 setOperationAction(ISD::USUBO
, MVT::i64
, Custom
);
343 setOperationAction(ISD::SMULO
, MVT::i32
, Custom
);
344 setOperationAction(ISD::SMULO
, MVT::i64
, Custom
);
345 setOperationAction(ISD::UMULO
, MVT::i32
, Custom
);
346 setOperationAction(ISD::UMULO
, MVT::i64
, Custom
);
348 setOperationAction(ISD::FSIN
, MVT::f32
, Expand
);
349 setOperationAction(ISD::FSIN
, MVT::f64
, Expand
);
350 setOperationAction(ISD::FCOS
, MVT::f32
, Expand
);
351 setOperationAction(ISD::FCOS
, MVT::f64
, Expand
);
352 setOperationAction(ISD::FPOW
, MVT::f32
, Expand
);
353 setOperationAction(ISD::FPOW
, MVT::f64
, Expand
);
354 setOperationAction(ISD::FCOPYSIGN
, MVT::f64
, Custom
);
355 setOperationAction(ISD::FCOPYSIGN
, MVT::f32
, Custom
);
356 if (Subtarget
->hasFullFP16())
357 setOperationAction(ISD::FCOPYSIGN
, MVT::f16
, Custom
);
359 setOperationAction(ISD::FCOPYSIGN
, MVT::f16
, Promote
);
361 setOperationAction(ISD::FREM
, MVT::f16
, Promote
);
362 setOperationAction(ISD::FREM
, MVT::v4f16
, Expand
);
363 setOperationAction(ISD::FREM
, MVT::v8f16
, Expand
);
364 setOperationAction(ISD::FPOW
, MVT::f16
, Promote
);
365 setOperationAction(ISD::FPOW
, MVT::v4f16
, Expand
);
366 setOperationAction(ISD::FPOW
, MVT::v8f16
, Expand
);
367 setOperationAction(ISD::FPOWI
, MVT::f16
, Promote
);
368 setOperationAction(ISD::FPOWI
, MVT::v4f16
, Expand
);
369 setOperationAction(ISD::FPOWI
, MVT::v8f16
, Expand
);
370 setOperationAction(ISD::FCOS
, MVT::f16
, Promote
);
371 setOperationAction(ISD::FCOS
, MVT::v4f16
, Expand
);
372 setOperationAction(ISD::FCOS
, MVT::v8f16
, Expand
);
373 setOperationAction(ISD::FSIN
, MVT::f16
, Promote
);
374 setOperationAction(ISD::FSIN
, MVT::v4f16
, Expand
);
375 setOperationAction(ISD::FSIN
, MVT::v8f16
, Expand
);
376 setOperationAction(ISD::FSINCOS
, MVT::f16
, Promote
);
377 setOperationAction(ISD::FSINCOS
, MVT::v4f16
, Expand
);
378 setOperationAction(ISD::FSINCOS
, MVT::v8f16
, Expand
);
379 setOperationAction(ISD::FEXP
, MVT::f16
, Promote
);
380 setOperationAction(ISD::FEXP
, MVT::v4f16
, Expand
);
381 setOperationAction(ISD::FEXP
, MVT::v8f16
, Expand
);
382 setOperationAction(ISD::FEXP2
, MVT::f16
, Promote
);
383 setOperationAction(ISD::FEXP2
, MVT::v4f16
, Expand
);
384 setOperationAction(ISD::FEXP2
, MVT::v8f16
, Expand
);
385 setOperationAction(ISD::FLOG
, MVT::f16
, Promote
);
386 setOperationAction(ISD::FLOG
, MVT::v4f16
, Expand
);
387 setOperationAction(ISD::FLOG
, MVT::v8f16
, Expand
);
388 setOperationAction(ISD::FLOG2
, MVT::f16
, Promote
);
389 setOperationAction(ISD::FLOG2
, MVT::v4f16
, Expand
);
390 setOperationAction(ISD::FLOG2
, MVT::v8f16
, Expand
);
391 setOperationAction(ISD::FLOG10
, MVT::f16
, Promote
);
392 setOperationAction(ISD::FLOG10
, MVT::v4f16
, Expand
);
393 setOperationAction(ISD::FLOG10
, MVT::v8f16
, Expand
);
395 if (!Subtarget
->hasFullFP16()) {
396 setOperationAction(ISD::SELECT
, MVT::f16
, Promote
);
397 setOperationAction(ISD::SELECT_CC
, MVT::f16
, Promote
);
398 setOperationAction(ISD::SETCC
, MVT::f16
, Promote
);
399 setOperationAction(ISD::BR_CC
, MVT::f16
, Promote
);
400 setOperationAction(ISD::FADD
, MVT::f16
, Promote
);
401 setOperationAction(ISD::FSUB
, MVT::f16
, Promote
);
402 setOperationAction(ISD::FMUL
, MVT::f16
, Promote
);
403 setOperationAction(ISD::FDIV
, MVT::f16
, Promote
);
404 setOperationAction(ISD::FMA
, MVT::f16
, Promote
);
405 setOperationAction(ISD::FNEG
, MVT::f16
, Promote
);
406 setOperationAction(ISD::FABS
, MVT::f16
, Promote
);
407 setOperationAction(ISD::FCEIL
, MVT::f16
, Promote
);
408 setOperationAction(ISD::FSQRT
, MVT::f16
, Promote
);
409 setOperationAction(ISD::FFLOOR
, MVT::f16
, Promote
);
410 setOperationAction(ISD::FNEARBYINT
, MVT::f16
, Promote
);
411 setOperationAction(ISD::FRINT
, MVT::f16
, Promote
);
412 setOperationAction(ISD::FROUND
, MVT::f16
, Promote
);
413 setOperationAction(ISD::FTRUNC
, MVT::f16
, Promote
);
414 setOperationAction(ISD::FMINNUM
, MVT::f16
, Promote
);
415 setOperationAction(ISD::FMAXNUM
, MVT::f16
, Promote
);
416 setOperationAction(ISD::FMINIMUM
, MVT::f16
, Promote
);
417 setOperationAction(ISD::FMAXIMUM
, MVT::f16
, Promote
);
419 // promote v4f16 to v4f32 when that is known to be safe.
420 setOperationAction(ISD::FADD
, MVT::v4f16
, Promote
);
421 setOperationAction(ISD::FSUB
, MVT::v4f16
, Promote
);
422 setOperationAction(ISD::FMUL
, MVT::v4f16
, Promote
);
423 setOperationAction(ISD::FDIV
, MVT::v4f16
, Promote
);
424 setOperationAction(ISD::FP_EXTEND
, MVT::v4f16
, Promote
);
425 setOperationAction(ISD::FP_ROUND
, MVT::v4f16
, Promote
);
426 AddPromotedToType(ISD::FADD
, MVT::v4f16
, MVT::v4f32
);
427 AddPromotedToType(ISD::FSUB
, MVT::v4f16
, MVT::v4f32
);
428 AddPromotedToType(ISD::FMUL
, MVT::v4f16
, MVT::v4f32
);
429 AddPromotedToType(ISD::FDIV
, MVT::v4f16
, MVT::v4f32
);
430 AddPromotedToType(ISD::FP_EXTEND
, MVT::v4f16
, MVT::v4f32
);
431 AddPromotedToType(ISD::FP_ROUND
, MVT::v4f16
, MVT::v4f32
);
433 setOperationAction(ISD::FABS
, MVT::v4f16
, Expand
);
434 setOperationAction(ISD::FNEG
, MVT::v4f16
, Expand
);
435 setOperationAction(ISD::FROUND
, MVT::v4f16
, Expand
);
436 setOperationAction(ISD::FMA
, MVT::v4f16
, Expand
);
437 setOperationAction(ISD::SETCC
, MVT::v4f16
, Expand
);
438 setOperationAction(ISD::BR_CC
, MVT::v4f16
, Expand
);
439 setOperationAction(ISD::SELECT
, MVT::v4f16
, Expand
);
440 setOperationAction(ISD::SELECT_CC
, MVT::v4f16
, Expand
);
441 setOperationAction(ISD::FTRUNC
, MVT::v4f16
, Expand
);
442 setOperationAction(ISD::FCOPYSIGN
, MVT::v4f16
, Expand
);
443 setOperationAction(ISD::FFLOOR
, MVT::v4f16
, Expand
);
444 setOperationAction(ISD::FCEIL
, MVT::v4f16
, Expand
);
445 setOperationAction(ISD::FRINT
, MVT::v4f16
, Expand
);
446 setOperationAction(ISD::FNEARBYINT
, MVT::v4f16
, Expand
);
447 setOperationAction(ISD::FSQRT
, MVT::v4f16
, Expand
);
449 setOperationAction(ISD::FABS
, MVT::v8f16
, Expand
);
450 setOperationAction(ISD::FADD
, MVT::v8f16
, Expand
);
451 setOperationAction(ISD::FCEIL
, MVT::v8f16
, Expand
);
452 setOperationAction(ISD::FCOPYSIGN
, MVT::v8f16
, Expand
);
453 setOperationAction(ISD::FDIV
, MVT::v8f16
, Expand
);
454 setOperationAction(ISD::FFLOOR
, MVT::v8f16
, Expand
);
455 setOperationAction(ISD::FMA
, MVT::v8f16
, Expand
);
456 setOperationAction(ISD::FMUL
, MVT::v8f16
, Expand
);
457 setOperationAction(ISD::FNEARBYINT
, MVT::v8f16
, Expand
);
458 setOperationAction(ISD::FNEG
, MVT::v8f16
, Expand
);
459 setOperationAction(ISD::FROUND
, MVT::v8f16
, Expand
);
460 setOperationAction(ISD::FRINT
, MVT::v8f16
, Expand
);
461 setOperationAction(ISD::FSQRT
, MVT::v8f16
, Expand
);
462 setOperationAction(ISD::FSUB
, MVT::v8f16
, Expand
);
463 setOperationAction(ISD::FTRUNC
, MVT::v8f16
, Expand
);
464 setOperationAction(ISD::SETCC
, MVT::v8f16
, Expand
);
465 setOperationAction(ISD::BR_CC
, MVT::v8f16
, Expand
);
466 setOperationAction(ISD::SELECT
, MVT::v8f16
, Expand
);
467 setOperationAction(ISD::SELECT_CC
, MVT::v8f16
, Expand
);
468 setOperationAction(ISD::FP_EXTEND
, MVT::v8f16
, Expand
);
471 // AArch64 has implementations of a lot of rounding-like FP operations.
472 for (MVT Ty
: {MVT::f32
, MVT::f64
}) {
473 setOperationAction(ISD::FFLOOR
, Ty
, Legal
);
474 setOperationAction(ISD::FNEARBYINT
, Ty
, Legal
);
475 setOperationAction(ISD::FCEIL
, Ty
, Legal
);
476 setOperationAction(ISD::FRINT
, Ty
, Legal
);
477 setOperationAction(ISD::FTRUNC
, Ty
, Legal
);
478 setOperationAction(ISD::FROUND
, Ty
, Legal
);
479 setOperationAction(ISD::FMINNUM
, Ty
, Legal
);
480 setOperationAction(ISD::FMAXNUM
, Ty
, Legal
);
481 setOperationAction(ISD::FMINIMUM
, Ty
, Legal
);
482 setOperationAction(ISD::FMAXIMUM
, Ty
, Legal
);
483 setOperationAction(ISD::LROUND
, Ty
, Legal
);
484 setOperationAction(ISD::LLROUND
, Ty
, Legal
);
485 setOperationAction(ISD::LRINT
, Ty
, Legal
);
486 setOperationAction(ISD::LLRINT
, Ty
, Legal
);
489 if (Subtarget
->hasFullFP16()) {
490 setOperationAction(ISD::FNEARBYINT
, MVT::f16
, Legal
);
491 setOperationAction(ISD::FFLOOR
, MVT::f16
, Legal
);
492 setOperationAction(ISD::FCEIL
, MVT::f16
, Legal
);
493 setOperationAction(ISD::FRINT
, MVT::f16
, Legal
);
494 setOperationAction(ISD::FTRUNC
, MVT::f16
, Legal
);
495 setOperationAction(ISD::FROUND
, MVT::f16
, Legal
);
496 setOperationAction(ISD::FMINNUM
, MVT::f16
, Legal
);
497 setOperationAction(ISD::FMAXNUM
, MVT::f16
, Legal
);
498 setOperationAction(ISD::FMINIMUM
, MVT::f16
, Legal
);
499 setOperationAction(ISD::FMAXIMUM
, MVT::f16
, Legal
);
502 setOperationAction(ISD::PREFETCH
, MVT::Other
, Custom
);
504 setOperationAction(ISD::FLT_ROUNDS_
, MVT::i32
, Custom
);
506 setOperationAction(ISD::ATOMIC_CMP_SWAP
, MVT::i128
, Custom
);
507 setOperationAction(ISD::ATOMIC_LOAD_SUB
, MVT::i32
, Custom
);
508 setOperationAction(ISD::ATOMIC_LOAD_SUB
, MVT::i64
, Custom
);
509 setOperationAction(ISD::ATOMIC_LOAD_AND
, MVT::i32
, Custom
);
510 setOperationAction(ISD::ATOMIC_LOAD_AND
, MVT::i64
, Custom
);
512 // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
513 // This requires the Performance Monitors extension.
514 if (Subtarget
->hasPerfMon())
515 setOperationAction(ISD::READCYCLECOUNTER
, MVT::i64
, Legal
);
517 if (getLibcallName(RTLIB::SINCOS_STRET_F32
) != nullptr &&
518 getLibcallName(RTLIB::SINCOS_STRET_F64
) != nullptr) {
519 // Issue __sincos_stret if available.
520 setOperationAction(ISD::FSINCOS
, MVT::f64
, Custom
);
521 setOperationAction(ISD::FSINCOS
, MVT::f32
, Custom
);
523 setOperationAction(ISD::FSINCOS
, MVT::f64
, Expand
);
524 setOperationAction(ISD::FSINCOS
, MVT::f32
, Expand
);
527 // Make floating-point constants legal for the large code model, so they don't
528 // become loads from the constant pool.
529 if (Subtarget
->isTargetMachO() && TM
.getCodeModel() == CodeModel::Large
) {
530 setOperationAction(ISD::ConstantFP
, MVT::f32
, Legal
);
531 setOperationAction(ISD::ConstantFP
, MVT::f64
, Legal
);
534 // AArch64 does not have floating-point extending loads, i1 sign-extending
535 // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
536 for (MVT VT
: MVT::fp_valuetypes()) {
537 setLoadExtAction(ISD::EXTLOAD
, VT
, MVT::f16
, Expand
);
538 setLoadExtAction(ISD::EXTLOAD
, VT
, MVT::f32
, Expand
);
539 setLoadExtAction(ISD::EXTLOAD
, VT
, MVT::f64
, Expand
);
540 setLoadExtAction(ISD::EXTLOAD
, VT
, MVT::f80
, Expand
);
542 for (MVT VT
: MVT::integer_valuetypes())
543 setLoadExtAction(ISD::SEXTLOAD
, VT
, MVT::i1
, Expand
);
545 setTruncStoreAction(MVT::f32
, MVT::f16
, Expand
);
546 setTruncStoreAction(MVT::f64
, MVT::f32
, Expand
);
547 setTruncStoreAction(MVT::f64
, MVT::f16
, Expand
);
548 setTruncStoreAction(MVT::f128
, MVT::f80
, Expand
);
549 setTruncStoreAction(MVT::f128
, MVT::f64
, Expand
);
550 setTruncStoreAction(MVT::f128
, MVT::f32
, Expand
);
551 setTruncStoreAction(MVT::f128
, MVT::f16
, Expand
);
553 setOperationAction(ISD::BITCAST
, MVT::i16
, Custom
);
554 setOperationAction(ISD::BITCAST
, MVT::f16
, Custom
);
556 // Indexed loads and stores are supported.
557 for (unsigned im
= (unsigned)ISD::PRE_INC
;
558 im
!= (unsigned)ISD::LAST_INDEXED_MODE
; ++im
) {
559 setIndexedLoadAction(im
, MVT::i8
, Legal
);
560 setIndexedLoadAction(im
, MVT::i16
, Legal
);
561 setIndexedLoadAction(im
, MVT::i32
, Legal
);
562 setIndexedLoadAction(im
, MVT::i64
, Legal
);
563 setIndexedLoadAction(im
, MVT::f64
, Legal
);
564 setIndexedLoadAction(im
, MVT::f32
, Legal
);
565 setIndexedLoadAction(im
, MVT::f16
, Legal
);
566 setIndexedStoreAction(im
, MVT::i8
, Legal
);
567 setIndexedStoreAction(im
, MVT::i16
, Legal
);
568 setIndexedStoreAction(im
, MVT::i32
, Legal
);
569 setIndexedStoreAction(im
, MVT::i64
, Legal
);
570 setIndexedStoreAction(im
, MVT::f64
, Legal
);
571 setIndexedStoreAction(im
, MVT::f32
, Legal
);
572 setIndexedStoreAction(im
, MVT::f16
, Legal
);
576 setOperationAction(ISD::TRAP
, MVT::Other
, Legal
);
577 if (Subtarget
->isTargetWindows())
578 setOperationAction(ISD::DEBUGTRAP
, MVT::Other
, Legal
);
580 // We combine OR nodes for bitfield operations.
581 setTargetDAGCombine(ISD::OR
);
582 // Try to create BICs for vector ANDs.
583 setTargetDAGCombine(ISD::AND
);
585 // Vector add and sub nodes may conceal a high-half opportunity.
586 // Also, try to fold ADD into CSINC/CSINV..
587 setTargetDAGCombine(ISD::ADD
);
588 setTargetDAGCombine(ISD::SUB
);
589 setTargetDAGCombine(ISD::SRL
);
590 setTargetDAGCombine(ISD::XOR
);
591 setTargetDAGCombine(ISD::SINT_TO_FP
);
592 setTargetDAGCombine(ISD::UINT_TO_FP
);
594 setTargetDAGCombine(ISD::FP_TO_SINT
);
595 setTargetDAGCombine(ISD::FP_TO_UINT
);
596 setTargetDAGCombine(ISD::FDIV
);
598 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN
);
600 setTargetDAGCombine(ISD::ANY_EXTEND
);
601 setTargetDAGCombine(ISD::ZERO_EXTEND
);
602 setTargetDAGCombine(ISD::SIGN_EXTEND
);
603 setTargetDAGCombine(ISD::BITCAST
);
604 setTargetDAGCombine(ISD::CONCAT_VECTORS
);
605 setTargetDAGCombine(ISD::STORE
);
606 if (Subtarget
->supportsAddressTopByteIgnored())
607 setTargetDAGCombine(ISD::LOAD
);
609 setTargetDAGCombine(ISD::MUL
);
611 setTargetDAGCombine(ISD::SELECT
);
612 setTargetDAGCombine(ISD::VSELECT
);
614 setTargetDAGCombine(ISD::INTRINSIC_VOID
);
615 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN
);
616 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT
);
618 setTargetDAGCombine(ISD::GlobalAddress
);
620 // In case of strict alignment, avoid an excessive number of byte wide stores.
621 MaxStoresPerMemsetOptSize
= 8;
622 MaxStoresPerMemset
= Subtarget
->requiresStrictAlign()
623 ? MaxStoresPerMemsetOptSize
: 32;
625 MaxGluedStoresPerMemcpy
= 4;
626 MaxStoresPerMemcpyOptSize
= 4;
627 MaxStoresPerMemcpy
= Subtarget
->requiresStrictAlign()
628 ? MaxStoresPerMemcpyOptSize
: 16;
630 MaxStoresPerMemmoveOptSize
= MaxStoresPerMemmove
= 4;
632 MaxLoadsPerMemcmpOptSize
= 4;
633 MaxLoadsPerMemcmp
= Subtarget
->requiresStrictAlign()
634 ? MaxLoadsPerMemcmpOptSize
: 8;
636 setStackPointerRegisterToSaveRestore(AArch64::SP
);
638 setSchedulingPreference(Sched::Hybrid
);
640 EnableExtLdPromotion
= true;
642 // Set required alignment.
643 setMinFunctionAlignment(llvm::Align(4));
644 // Set preferred alignments.
645 setPrefFunctionLogAlignment(STI
.getPrefFunctionLogAlignment());
646 setPrefLoopLogAlignment(STI
.getPrefLoopLogAlignment());
648 // Only change the limit for entries in a jump table if specified by
649 // the sub target, but not at the command line.
650 unsigned MaxJT
= STI
.getMaximumJumpTableSize();
651 if (MaxJT
&& getMaximumJumpTableSize() == UINT_MAX
)
652 setMaximumJumpTableSize(MaxJT
);
654 setHasExtractBitsInsn(true);
656 setOperationAction(ISD::INTRINSIC_WO_CHAIN
, MVT::Other
, Custom
);
658 if (Subtarget
->hasNEON()) {
659 // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
660 // silliness like this:
661 setOperationAction(ISD::FABS
, MVT::v1f64
, Expand
);
662 setOperationAction(ISD::FADD
, MVT::v1f64
, Expand
);
663 setOperationAction(ISD::FCEIL
, MVT::v1f64
, Expand
);
664 setOperationAction(ISD::FCOPYSIGN
, MVT::v1f64
, Expand
);
665 setOperationAction(ISD::FCOS
, MVT::v1f64
, Expand
);
666 setOperationAction(ISD::FDIV
, MVT::v1f64
, Expand
);
667 setOperationAction(ISD::FFLOOR
, MVT::v1f64
, Expand
);
668 setOperationAction(ISD::FMA
, MVT::v1f64
, Expand
);
669 setOperationAction(ISD::FMUL
, MVT::v1f64
, Expand
);
670 setOperationAction(ISD::FNEARBYINT
, MVT::v1f64
, Expand
);
671 setOperationAction(ISD::FNEG
, MVT::v1f64
, Expand
);
672 setOperationAction(ISD::FPOW
, MVT::v1f64
, Expand
);
673 setOperationAction(ISD::FREM
, MVT::v1f64
, Expand
);
674 setOperationAction(ISD::FROUND
, MVT::v1f64
, Expand
);
675 setOperationAction(ISD::FRINT
, MVT::v1f64
, Expand
);
676 setOperationAction(ISD::FSIN
, MVT::v1f64
, Expand
);
677 setOperationAction(ISD::FSINCOS
, MVT::v1f64
, Expand
);
678 setOperationAction(ISD::FSQRT
, MVT::v1f64
, Expand
);
679 setOperationAction(ISD::FSUB
, MVT::v1f64
, Expand
);
680 setOperationAction(ISD::FTRUNC
, MVT::v1f64
, Expand
);
681 setOperationAction(ISD::SETCC
, MVT::v1f64
, Expand
);
682 setOperationAction(ISD::BR_CC
, MVT::v1f64
, Expand
);
683 setOperationAction(ISD::SELECT
, MVT::v1f64
, Expand
);
684 setOperationAction(ISD::SELECT_CC
, MVT::v1f64
, Expand
);
685 setOperationAction(ISD::FP_EXTEND
, MVT::v1f64
, Expand
);
687 setOperationAction(ISD::FP_TO_SINT
, MVT::v1i64
, Expand
);
688 setOperationAction(ISD::FP_TO_UINT
, MVT::v1i64
, Expand
);
689 setOperationAction(ISD::SINT_TO_FP
, MVT::v1i64
, Expand
);
690 setOperationAction(ISD::UINT_TO_FP
, MVT::v1i64
, Expand
);
691 setOperationAction(ISD::FP_ROUND
, MVT::v1f64
, Expand
);
693 setOperationAction(ISD::MUL
, MVT::v1i64
, Expand
);
695 // AArch64 doesn't have a direct vector ->f32 conversion instructions for
696 // elements smaller than i32, so promote the input to i32 first.
697 setOperationPromotedToType(ISD::UINT_TO_FP
, MVT::v4i8
, MVT::v4i32
);
698 setOperationPromotedToType(ISD::SINT_TO_FP
, MVT::v4i8
, MVT::v4i32
);
699 // i8 vector elements also need promotion to i32 for v8i8
700 setOperationPromotedToType(ISD::SINT_TO_FP
, MVT::v8i8
, MVT::v8i32
);
701 setOperationPromotedToType(ISD::UINT_TO_FP
, MVT::v8i8
, MVT::v8i32
);
702 // Similarly, there is no direct i32 -> f64 vector conversion instruction.
703 setOperationAction(ISD::SINT_TO_FP
, MVT::v2i32
, Custom
);
704 setOperationAction(ISD::UINT_TO_FP
, MVT::v2i32
, Custom
);
705 setOperationAction(ISD::SINT_TO_FP
, MVT::v2i64
, Custom
);
706 setOperationAction(ISD::UINT_TO_FP
, MVT::v2i64
, Custom
);
707 // Or, direct i32 -> f16 vector conversion. Set it so custom, so the
708 // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
709 setOperationAction(ISD::SINT_TO_FP
, MVT::v4i32
, Custom
);
710 setOperationAction(ISD::UINT_TO_FP
, MVT::v4i32
, Custom
);
712 if (Subtarget
->hasFullFP16()) {
713 setOperationAction(ISD::SINT_TO_FP
, MVT::v4i16
, Custom
);
714 setOperationAction(ISD::UINT_TO_FP
, MVT::v4i16
, Custom
);
715 setOperationAction(ISD::SINT_TO_FP
, MVT::v8i16
, Custom
);
716 setOperationAction(ISD::UINT_TO_FP
, MVT::v8i16
, Custom
);
718 // when AArch64 doesn't have fullfp16 support, promote the input
720 setOperationPromotedToType(ISD::UINT_TO_FP
, MVT::v4i16
, MVT::v4i32
);
721 setOperationPromotedToType(ISD::SINT_TO_FP
, MVT::v4i16
, MVT::v4i32
);
722 setOperationPromotedToType(ISD::SINT_TO_FP
, MVT::v8i16
, MVT::v8i32
);
723 setOperationPromotedToType(ISD::UINT_TO_FP
, MVT::v8i16
, MVT::v8i32
);
726 setOperationAction(ISD::CTLZ
, MVT::v1i64
, Expand
);
727 setOperationAction(ISD::CTLZ
, MVT::v2i64
, Expand
);
729 // AArch64 doesn't have MUL.2d:
730 setOperationAction(ISD::MUL
, MVT::v2i64
, Expand
);
731 // Custom handling for some quad-vector types to detect MULL.
732 setOperationAction(ISD::MUL
, MVT::v8i16
, Custom
);
733 setOperationAction(ISD::MUL
, MVT::v4i32
, Custom
);
734 setOperationAction(ISD::MUL
, MVT::v2i64
, Custom
);
737 for (MVT VT
: { MVT::v8i8
, MVT::v4i16
, MVT::v2i32
,
738 MVT::v16i8
, MVT::v8i16
, MVT::v4i32
, MVT::v2i64
}) {
739 setOperationAction(ISD::VECREDUCE_ADD
, VT
, Custom
);
740 setOperationAction(ISD::VECREDUCE_SMAX
, VT
, Custom
);
741 setOperationAction(ISD::VECREDUCE_SMIN
, VT
, Custom
);
742 setOperationAction(ISD::VECREDUCE_UMAX
, VT
, Custom
);
743 setOperationAction(ISD::VECREDUCE_UMIN
, VT
, Custom
);
745 for (MVT VT
: { MVT::v4f16
, MVT::v2f32
,
746 MVT::v8f16
, MVT::v4f32
, MVT::v2f64
}) {
747 setOperationAction(ISD::VECREDUCE_FMAX
, VT
, Custom
);
748 setOperationAction(ISD::VECREDUCE_FMIN
, VT
, Custom
);
751 setOperationAction(ISD::ANY_EXTEND
, MVT::v4i32
, Legal
);
752 setTruncStoreAction(MVT::v2i32
, MVT::v2i16
, Expand
);
753 // Likewise, narrowing and extending vector loads/stores aren't handled
755 for (MVT VT
: MVT::vector_valuetypes()) {
756 setOperationAction(ISD::SIGN_EXTEND_INREG
, VT
, Expand
);
758 if (VT
== MVT::v16i8
|| VT
== MVT::v8i16
|| VT
== MVT::v4i32
) {
759 setOperationAction(ISD::MULHS
, VT
, Legal
);
760 setOperationAction(ISD::MULHU
, VT
, Legal
);
762 setOperationAction(ISD::MULHS
, VT
, Expand
);
763 setOperationAction(ISD::MULHU
, VT
, Expand
);
765 setOperationAction(ISD::SMUL_LOHI
, VT
, Expand
);
766 setOperationAction(ISD::UMUL_LOHI
, VT
, Expand
);
768 setOperationAction(ISD::BSWAP
, VT
, Expand
);
769 setOperationAction(ISD::CTTZ
, VT
, Expand
);
771 for (MVT InnerVT
: MVT::vector_valuetypes()) {
772 setTruncStoreAction(VT
, InnerVT
, Expand
);
773 setLoadExtAction(ISD::SEXTLOAD
, VT
, InnerVT
, Expand
);
774 setLoadExtAction(ISD::ZEXTLOAD
, VT
, InnerVT
, Expand
);
775 setLoadExtAction(ISD::EXTLOAD
, VT
, InnerVT
, Expand
);
779 // AArch64 has implementations of a lot of rounding-like FP operations.
780 for (MVT Ty
: {MVT::v2f32
, MVT::v4f32
, MVT::v2f64
}) {
781 setOperationAction(ISD::FFLOOR
, Ty
, Legal
);
782 setOperationAction(ISD::FNEARBYINT
, Ty
, Legal
);
783 setOperationAction(ISD::FCEIL
, Ty
, Legal
);
784 setOperationAction(ISD::FRINT
, Ty
, Legal
);
785 setOperationAction(ISD::FTRUNC
, Ty
, Legal
);
786 setOperationAction(ISD::FROUND
, Ty
, Legal
);
789 if (Subtarget
->hasFullFP16()) {
790 for (MVT Ty
: {MVT::v4f16
, MVT::v8f16
}) {
791 setOperationAction(ISD::FFLOOR
, Ty
, Legal
);
792 setOperationAction(ISD::FNEARBYINT
, Ty
, Legal
);
793 setOperationAction(ISD::FCEIL
, Ty
, Legal
);
794 setOperationAction(ISD::FRINT
, Ty
, Legal
);
795 setOperationAction(ISD::FTRUNC
, Ty
, Legal
);
796 setOperationAction(ISD::FROUND
, Ty
, Legal
);
800 setTruncStoreAction(MVT::v4i16
, MVT::v4i8
, Custom
);
803 PredictableSelectIsExpensive
= Subtarget
->predictableSelectIsExpensive();
806 void AArch64TargetLowering::addTypeForNEON(MVT VT
, MVT PromotedBitwiseVT
) {
807 assert(VT
.isVector() && "VT should be a vector type");
809 if (VT
.isFloatingPoint()) {
810 MVT PromoteTo
= EVT(VT
).changeVectorElementTypeToInteger().getSimpleVT();
811 setOperationPromotedToType(ISD::LOAD
, VT
, PromoteTo
);
812 setOperationPromotedToType(ISD::STORE
, VT
, PromoteTo
);
815 // Mark vector float intrinsics as expand.
816 if (VT
== MVT::v2f32
|| VT
== MVT::v4f32
|| VT
== MVT::v2f64
) {
817 setOperationAction(ISD::FSIN
, VT
, Expand
);
818 setOperationAction(ISD::FCOS
, VT
, Expand
);
819 setOperationAction(ISD::FPOW
, VT
, Expand
);
820 setOperationAction(ISD::FLOG
, VT
, Expand
);
821 setOperationAction(ISD::FLOG2
, VT
, Expand
);
822 setOperationAction(ISD::FLOG10
, VT
, Expand
);
823 setOperationAction(ISD::FEXP
, VT
, Expand
);
824 setOperationAction(ISD::FEXP2
, VT
, Expand
);
826 // But we do support custom-lowering for FCOPYSIGN.
827 setOperationAction(ISD::FCOPYSIGN
, VT
, Custom
);
830 setOperationAction(ISD::EXTRACT_VECTOR_ELT
, VT
, Custom
);
831 setOperationAction(ISD::INSERT_VECTOR_ELT
, VT
, Custom
);
832 setOperationAction(ISD::BUILD_VECTOR
, VT
, Custom
);
833 setOperationAction(ISD::VECTOR_SHUFFLE
, VT
, Custom
);
834 setOperationAction(ISD::EXTRACT_SUBVECTOR
, VT
, Custom
);
835 setOperationAction(ISD::SRA
, VT
, Custom
);
836 setOperationAction(ISD::SRL
, VT
, Custom
);
837 setOperationAction(ISD::SHL
, VT
, Custom
);
838 setOperationAction(ISD::OR
, VT
, Custom
);
839 setOperationAction(ISD::SETCC
, VT
, Custom
);
840 setOperationAction(ISD::CONCAT_VECTORS
, VT
, Legal
);
842 setOperationAction(ISD::SELECT
, VT
, Expand
);
843 setOperationAction(ISD::SELECT_CC
, VT
, Expand
);
844 setOperationAction(ISD::VSELECT
, VT
, Expand
);
845 for (MVT InnerVT
: MVT::all_valuetypes())
846 setLoadExtAction(ISD::EXTLOAD
, InnerVT
, VT
, Expand
);
848 // CNT supports only B element sizes, then use UADDLP to widen.
849 if (VT
!= MVT::v8i8
&& VT
!= MVT::v16i8
)
850 setOperationAction(ISD::CTPOP
, VT
, Custom
);
852 setOperationAction(ISD::UDIV
, VT
, Expand
);
853 setOperationAction(ISD::SDIV
, VT
, Expand
);
854 setOperationAction(ISD::UREM
, VT
, Expand
);
855 setOperationAction(ISD::SREM
, VT
, Expand
);
856 setOperationAction(ISD::FREM
, VT
, Expand
);
858 setOperationAction(ISD::FP_TO_SINT
, VT
, Custom
);
859 setOperationAction(ISD::FP_TO_UINT
, VT
, Custom
);
861 if (!VT
.isFloatingPoint())
862 setOperationAction(ISD::ABS
, VT
, Legal
);
864 // [SU][MIN|MAX] are available for all NEON types apart from i64.
865 if (!VT
.isFloatingPoint() && VT
!= MVT::v2i64
&& VT
!= MVT::v1i64
)
866 for (unsigned Opcode
: {ISD::SMIN
, ISD::SMAX
, ISD::UMIN
, ISD::UMAX
})
867 setOperationAction(Opcode
, VT
, Legal
);
869 // F[MIN|MAX][NUM|NAN] are available for all FP NEON types.
870 if (VT
.isFloatingPoint() &&
871 (VT
.getVectorElementType() != MVT::f16
|| Subtarget
->hasFullFP16()))
872 for (unsigned Opcode
:
873 {ISD::FMINIMUM
, ISD::FMAXIMUM
, ISD::FMINNUM
, ISD::FMAXNUM
})
874 setOperationAction(Opcode
, VT
, Legal
);
876 if (Subtarget
->isLittleEndian()) {
877 for (unsigned im
= (unsigned)ISD::PRE_INC
;
878 im
!= (unsigned)ISD::LAST_INDEXED_MODE
; ++im
) {
879 setIndexedLoadAction(im
, VT
, Legal
);
880 setIndexedStoreAction(im
, VT
, Legal
);
885 void AArch64TargetLowering::addDRTypeForNEON(MVT VT
) {
886 addRegisterClass(VT
, &AArch64::FPR64RegClass
);
887 addTypeForNEON(VT
, MVT::v2i32
);
890 void AArch64TargetLowering::addQRTypeForNEON(MVT VT
) {
891 addRegisterClass(VT
, &AArch64::FPR128RegClass
);
892 addTypeForNEON(VT
, MVT::v4i32
);
895 EVT
AArch64TargetLowering::getSetCCResultType(const DataLayout
&, LLVMContext
&,
899 return VT
.changeVectorElementTypeToInteger();
902 static bool optimizeLogicalImm(SDValue Op
, unsigned Size
, uint64_t Imm
,
903 const APInt
&Demanded
,
904 TargetLowering::TargetLoweringOpt
&TLO
,
906 uint64_t OldImm
= Imm
, NewImm
, Enc
;
907 uint64_t Mask
= ((uint64_t)(-1LL) >> (64 - Size
)), OrigMask
= Mask
;
909 // Return if the immediate is already all zeros, all ones, a bimm32 or a
911 if (Imm
== 0 || Imm
== Mask
||
912 AArch64_AM::isLogicalImmediate(Imm
& Mask
, Size
))
915 unsigned EltSize
= Size
;
916 uint64_t DemandedBits
= Demanded
.getZExtValue();
918 // Clear bits that are not demanded.
922 // The goal here is to set the non-demanded bits in a way that minimizes
923 // the number of switching between 0 and 1. In order to achieve this goal,
924 // we set the non-demanded bits to the value of the preceding demanded bits.
925 // For example, if we have an immediate 0bx10xx0x1 ('x' indicates a
926 // non-demanded bit), we copy bit0 (1) to the least significant 'x',
927 // bit2 (0) to 'xx', and bit6 (1) to the most significant 'x'.
928 // The final result is 0b11000011.
929 uint64_t NonDemandedBits
= ~DemandedBits
;
930 uint64_t InvertedImm
= ~Imm
& DemandedBits
;
931 uint64_t RotatedImm
=
932 ((InvertedImm
<< 1) | (InvertedImm
>> (EltSize
- 1) & 1)) &
934 uint64_t Sum
= RotatedImm
+ NonDemandedBits
;
935 bool Carry
= NonDemandedBits
& ~Sum
& (1ULL << (EltSize
- 1));
936 uint64_t Ones
= (Sum
+ Carry
) & NonDemandedBits
;
937 NewImm
= (Imm
| Ones
) & Mask
;
939 // If NewImm or its bitwise NOT is a shifted mask, it is a bitmask immediate
940 // or all-ones or all-zeros, in which case we can stop searching. Otherwise,
941 // we halve the element size and continue the search.
942 if (isShiftedMask_64(NewImm
) || isShiftedMask_64(~(NewImm
| ~Mask
)))
945 // We cannot shrink the element size any further if it is 2-bits.
951 uint64_t Hi
= Imm
>> EltSize
, DemandedBitsHi
= DemandedBits
>> EltSize
;
953 // Return if there is mismatch in any of the demanded bits of Imm and Hi.
954 if (((Imm
^ Hi
) & (DemandedBits
& DemandedBitsHi
) & Mask
) != 0)
957 // Merge the upper and lower halves of Imm and DemandedBits.
959 DemandedBits
|= DemandedBitsHi
;
964 // Replicate the element across the register width.
965 while (EltSize
< Size
) {
966 NewImm
|= NewImm
<< EltSize
;
971 assert(((OldImm
^ NewImm
) & Demanded
.getZExtValue()) == 0 &&
972 "demanded bits should never be altered");
973 assert(OldImm
!= NewImm
&& "the new imm shouldn't be equal to the old imm");
975 // Create the new constant immediate node.
976 EVT VT
= Op
.getValueType();
980 // If the new constant immediate is all-zeros or all-ones, let the target
981 // independent DAG combine optimize this node.
982 if (NewImm
== 0 || NewImm
== OrigMask
) {
983 New
= TLO
.DAG
.getNode(Op
.getOpcode(), DL
, VT
, Op
.getOperand(0),
984 TLO
.DAG
.getConstant(NewImm
, DL
, VT
));
985 // Otherwise, create a machine node so that target independent DAG combine
986 // doesn't undo this optimization.
988 Enc
= AArch64_AM::encodeLogicalImmediate(NewImm
, Size
);
989 SDValue EncConst
= TLO
.DAG
.getTargetConstant(Enc
, DL
, VT
);
991 TLO
.DAG
.getMachineNode(NewOpc
, DL
, VT
, Op
.getOperand(0), EncConst
), 0);
994 return TLO
.CombineTo(Op
, New
);
997 bool AArch64TargetLowering::targetShrinkDemandedConstant(
998 SDValue Op
, const APInt
&Demanded
, TargetLoweringOpt
&TLO
) const {
999 // Delay this optimization to as late as possible.
1003 if (!EnableOptimizeLogicalImm
)
1006 EVT VT
= Op
.getValueType();
1010 unsigned Size
= VT
.getSizeInBits();
1011 assert((Size
== 32 || Size
== 64) &&
1012 "i32 or i64 is expected after legalization.");
1014 // Exit early if we demand all bits.
1015 if (Demanded
.countPopulation() == Size
)
1019 switch (Op
.getOpcode()) {
1023 NewOpc
= Size
== 32 ? AArch64::ANDWri
: AArch64::ANDXri
;
1026 NewOpc
= Size
== 32 ? AArch64::ORRWri
: AArch64::ORRXri
;
1029 NewOpc
= Size
== 32 ? AArch64::EORWri
: AArch64::EORXri
;
1032 ConstantSDNode
*C
= dyn_cast
<ConstantSDNode
>(Op
.getOperand(1));
1035 uint64_t Imm
= C
->getZExtValue();
1036 return optimizeLogicalImm(Op
, Size
, Imm
, Demanded
, TLO
, NewOpc
);
1039 /// computeKnownBitsForTargetNode - Determine which of the bits specified in
1040 /// Mask are known to be either zero or one and return them Known.
1041 void AArch64TargetLowering::computeKnownBitsForTargetNode(
1042 const SDValue Op
, KnownBits
&Known
,
1043 const APInt
&DemandedElts
, const SelectionDAG
&DAG
, unsigned Depth
) const {
1044 switch (Op
.getOpcode()) {
1047 case AArch64ISD::CSEL
: {
1049 Known
= DAG
.computeKnownBits(Op
->getOperand(0), Depth
+ 1);
1050 Known2
= DAG
.computeKnownBits(Op
->getOperand(1), Depth
+ 1);
1051 Known
.Zero
&= Known2
.Zero
;
1052 Known
.One
&= Known2
.One
;
1055 case ISD::INTRINSIC_W_CHAIN
: {
1056 ConstantSDNode
*CN
= cast
<ConstantSDNode
>(Op
->getOperand(1));
1057 Intrinsic::ID IntID
= static_cast<Intrinsic::ID
>(CN
->getZExtValue());
1060 case Intrinsic::aarch64_ldaxr
:
1061 case Intrinsic::aarch64_ldxr
: {
1062 unsigned BitWidth
= Known
.getBitWidth();
1063 EVT VT
= cast
<MemIntrinsicSDNode
>(Op
)->getMemoryVT();
1064 unsigned MemBits
= VT
.getScalarSizeInBits();
1065 Known
.Zero
|= APInt::getHighBitsSet(BitWidth
, BitWidth
- MemBits
);
1071 case ISD::INTRINSIC_WO_CHAIN
:
1072 case ISD::INTRINSIC_VOID
: {
1073 unsigned IntNo
= cast
<ConstantSDNode
>(Op
.getOperand(0))->getZExtValue();
1077 case Intrinsic::aarch64_neon_umaxv
:
1078 case Intrinsic::aarch64_neon_uminv
: {
1079 // Figure out the datatype of the vector operand. The UMINV instruction
1080 // will zero extend the result, so we can mark as known zero all the
1081 // bits larger than the element datatype. 32-bit or larget doesn't need
1082 // this as those are legal types and will be handled by isel directly.
1083 MVT VT
= Op
.getOperand(1).getValueType().getSimpleVT();
1084 unsigned BitWidth
= Known
.getBitWidth();
1085 if (VT
== MVT::v8i8
|| VT
== MVT::v16i8
) {
1086 assert(BitWidth
>= 8 && "Unexpected width!");
1087 APInt Mask
= APInt::getHighBitsSet(BitWidth
, BitWidth
- 8);
1089 } else if (VT
== MVT::v4i16
|| VT
== MVT::v8i16
) {
1090 assert(BitWidth
>= 16 && "Unexpected width!");
1091 APInt Mask
= APInt::getHighBitsSet(BitWidth
, BitWidth
- 16);
1101 MVT
AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout
&DL
,
1106 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(
1107 EVT VT
, unsigned AddrSpace
, unsigned Align
, MachineMemOperand::Flags Flags
,
1109 if (Subtarget
->requiresStrictAlign())
1113 // Some CPUs are fine with unaligned stores except for 128-bit ones.
1114 *Fast
= !Subtarget
->isMisaligned128StoreSlow() || VT
.getStoreSize() != 16 ||
1115 // See comments in performSTORECombine() for more details about
1116 // these conditions.
1118 // Code that uses clang vector extensions can mark that it
1119 // wants unaligned accesses to be treated as fast by
1120 // underspecifying alignment to be 1 or 2.
1123 // Disregard v2i64. Memcpy lowering produces those and splitting
1124 // them regresses performance on micro-benchmarks and olden/bh.
1130 // Same as above but handling LLTs instead.
1131 bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(
1132 LLT Ty
, unsigned AddrSpace
, unsigned Align
, MachineMemOperand::Flags Flags
,
1134 if (Subtarget
->requiresStrictAlign())
1138 // Some CPUs are fine with unaligned stores except for 128-bit ones.
1139 *Fast
= !Subtarget
->isMisaligned128StoreSlow() ||
1140 Ty
.getSizeInBytes() != 16 ||
1141 // See comments in performSTORECombine() for more details about
1142 // these conditions.
1144 // Code that uses clang vector extensions can mark that it
1145 // wants unaligned accesses to be treated as fast by
1146 // underspecifying alignment to be 1 or 2.
1149 // Disregard v2i64. Memcpy lowering produces those and splitting
1150 // them regresses performance on micro-benchmarks and olden/bh.
1151 Ty
== LLT::vector(2, 64);
1157 AArch64TargetLowering::createFastISel(FunctionLoweringInfo
&funcInfo
,
1158 const TargetLibraryInfo
*libInfo
) const {
1159 return AArch64::createFastISel(funcInfo
, libInfo
);
1162 const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode
) const {
1163 switch ((AArch64ISD::NodeType
)Opcode
) {
1164 case AArch64ISD::FIRST_NUMBER
: break;
1165 case AArch64ISD::CALL
: return "AArch64ISD::CALL";
1166 case AArch64ISD::ADRP
: return "AArch64ISD::ADRP";
1167 case AArch64ISD::ADR
: return "AArch64ISD::ADR";
1168 case AArch64ISD::ADDlow
: return "AArch64ISD::ADDlow";
1169 case AArch64ISD::LOADgot
: return "AArch64ISD::LOADgot";
1170 case AArch64ISD::RET_FLAG
: return "AArch64ISD::RET_FLAG";
1171 case AArch64ISD::BRCOND
: return "AArch64ISD::BRCOND";
1172 case AArch64ISD::CSEL
: return "AArch64ISD::CSEL";
1173 case AArch64ISD::FCSEL
: return "AArch64ISD::FCSEL";
1174 case AArch64ISD::CSINV
: return "AArch64ISD::CSINV";
1175 case AArch64ISD::CSNEG
: return "AArch64ISD::CSNEG";
1176 case AArch64ISD::CSINC
: return "AArch64ISD::CSINC";
1177 case AArch64ISD::THREAD_POINTER
: return "AArch64ISD::THREAD_POINTER";
1178 case AArch64ISD::TLSDESC_CALLSEQ
: return "AArch64ISD::TLSDESC_CALLSEQ";
1179 case AArch64ISD::ADC
: return "AArch64ISD::ADC";
1180 case AArch64ISD::SBC
: return "AArch64ISD::SBC";
1181 case AArch64ISD::ADDS
: return "AArch64ISD::ADDS";
1182 case AArch64ISD::SUBS
: return "AArch64ISD::SUBS";
1183 case AArch64ISD::ADCS
: return "AArch64ISD::ADCS";
1184 case AArch64ISD::SBCS
: return "AArch64ISD::SBCS";
1185 case AArch64ISD::ANDS
: return "AArch64ISD::ANDS";
1186 case AArch64ISD::CCMP
: return "AArch64ISD::CCMP";
1187 case AArch64ISD::CCMN
: return "AArch64ISD::CCMN";
1188 case AArch64ISD::FCCMP
: return "AArch64ISD::FCCMP";
1189 case AArch64ISD::FCMP
: return "AArch64ISD::FCMP";
1190 case AArch64ISD::DUP
: return "AArch64ISD::DUP";
1191 case AArch64ISD::DUPLANE8
: return "AArch64ISD::DUPLANE8";
1192 case AArch64ISD::DUPLANE16
: return "AArch64ISD::DUPLANE16";
1193 case AArch64ISD::DUPLANE32
: return "AArch64ISD::DUPLANE32";
1194 case AArch64ISD::DUPLANE64
: return "AArch64ISD::DUPLANE64";
1195 case AArch64ISD::MOVI
: return "AArch64ISD::MOVI";
1196 case AArch64ISD::MOVIshift
: return "AArch64ISD::MOVIshift";
1197 case AArch64ISD::MOVIedit
: return "AArch64ISD::MOVIedit";
1198 case AArch64ISD::MOVImsl
: return "AArch64ISD::MOVImsl";
1199 case AArch64ISD::FMOV
: return "AArch64ISD::FMOV";
1200 case AArch64ISD::MVNIshift
: return "AArch64ISD::MVNIshift";
1201 case AArch64ISD::MVNImsl
: return "AArch64ISD::MVNImsl";
1202 case AArch64ISD::BICi
: return "AArch64ISD::BICi";
1203 case AArch64ISD::ORRi
: return "AArch64ISD::ORRi";
1204 case AArch64ISD::BSL
: return "AArch64ISD::BSL";
1205 case AArch64ISD::NEG
: return "AArch64ISD::NEG";
1206 case AArch64ISD::EXTR
: return "AArch64ISD::EXTR";
1207 case AArch64ISD::ZIP1
: return "AArch64ISD::ZIP1";
1208 case AArch64ISD::ZIP2
: return "AArch64ISD::ZIP2";
1209 case AArch64ISD::UZP1
: return "AArch64ISD::UZP1";
1210 case AArch64ISD::UZP2
: return "AArch64ISD::UZP2";
1211 case AArch64ISD::TRN1
: return "AArch64ISD::TRN1";
1212 case AArch64ISD::TRN2
: return "AArch64ISD::TRN2";
1213 case AArch64ISD::REV16
: return "AArch64ISD::REV16";
1214 case AArch64ISD::REV32
: return "AArch64ISD::REV32";
1215 case AArch64ISD::REV64
: return "AArch64ISD::REV64";
1216 case AArch64ISD::EXT
: return "AArch64ISD::EXT";
1217 case AArch64ISD::VSHL
: return "AArch64ISD::VSHL";
1218 case AArch64ISD::VLSHR
: return "AArch64ISD::VLSHR";
1219 case AArch64ISD::VASHR
: return "AArch64ISD::VASHR";
1220 case AArch64ISD::CMEQ
: return "AArch64ISD::CMEQ";
1221 case AArch64ISD::CMGE
: return "AArch64ISD::CMGE";
1222 case AArch64ISD::CMGT
: return "AArch64ISD::CMGT";
1223 case AArch64ISD::CMHI
: return "AArch64ISD::CMHI";
1224 case AArch64ISD::CMHS
: return "AArch64ISD::CMHS";
1225 case AArch64ISD::FCMEQ
: return "AArch64ISD::FCMEQ";
1226 case AArch64ISD::FCMGE
: return "AArch64ISD::FCMGE";
1227 case AArch64ISD::FCMGT
: return "AArch64ISD::FCMGT";
1228 case AArch64ISD::CMEQz
: return "AArch64ISD::CMEQz";
1229 case AArch64ISD::CMGEz
: return "AArch64ISD::CMGEz";
1230 case AArch64ISD::CMGTz
: return "AArch64ISD::CMGTz";
1231 case AArch64ISD::CMLEz
: return "AArch64ISD::CMLEz";
1232 case AArch64ISD::CMLTz
: return "AArch64ISD::CMLTz";
1233 case AArch64ISD::FCMEQz
: return "AArch64ISD::FCMEQz";
1234 case AArch64ISD::FCMGEz
: return "AArch64ISD::FCMGEz";
1235 case AArch64ISD::FCMGTz
: return "AArch64ISD::FCMGTz";
1236 case AArch64ISD::FCMLEz
: return "AArch64ISD::FCMLEz";
1237 case AArch64ISD::FCMLTz
: return "AArch64ISD::FCMLTz";
1238 case AArch64ISD::SADDV
: return "AArch64ISD::SADDV";
1239 case AArch64ISD::UADDV
: return "AArch64ISD::UADDV";
1240 case AArch64ISD::SMINV
: return "AArch64ISD::SMINV";
1241 case AArch64ISD::UMINV
: return "AArch64ISD::UMINV";
1242 case AArch64ISD::SMAXV
: return "AArch64ISD::SMAXV";
1243 case AArch64ISD::UMAXV
: return "AArch64ISD::UMAXV";
1244 case AArch64ISD::NOT
: return "AArch64ISD::NOT";
1245 case AArch64ISD::BIT
: return "AArch64ISD::BIT";
1246 case AArch64ISD::CBZ
: return "AArch64ISD::CBZ";
1247 case AArch64ISD::CBNZ
: return "AArch64ISD::CBNZ";
1248 case AArch64ISD::TBZ
: return "AArch64ISD::TBZ";
1249 case AArch64ISD::TBNZ
: return "AArch64ISD::TBNZ";
1250 case AArch64ISD::TC_RETURN
: return "AArch64ISD::TC_RETURN";
1251 case AArch64ISD::PREFETCH
: return "AArch64ISD::PREFETCH";
1252 case AArch64ISD::SITOF
: return "AArch64ISD::SITOF";
1253 case AArch64ISD::UITOF
: return "AArch64ISD::UITOF";
1254 case AArch64ISD::NVCAST
: return "AArch64ISD::NVCAST";
1255 case AArch64ISD::SQSHL_I
: return "AArch64ISD::SQSHL_I";
1256 case AArch64ISD::UQSHL_I
: return "AArch64ISD::UQSHL_I";
1257 case AArch64ISD::SRSHR_I
: return "AArch64ISD::SRSHR_I";
1258 case AArch64ISD::URSHR_I
: return "AArch64ISD::URSHR_I";
1259 case AArch64ISD::SQSHLU_I
: return "AArch64ISD::SQSHLU_I";
1260 case AArch64ISD::WrapperLarge
: return "AArch64ISD::WrapperLarge";
1261 case AArch64ISD::LD2post
: return "AArch64ISD::LD2post";
1262 case AArch64ISD::LD3post
: return "AArch64ISD::LD3post";
1263 case AArch64ISD::LD4post
: return "AArch64ISD::LD4post";
1264 case AArch64ISD::ST2post
: return "AArch64ISD::ST2post";
1265 case AArch64ISD::ST3post
: return "AArch64ISD::ST3post";
1266 case AArch64ISD::ST4post
: return "AArch64ISD::ST4post";
1267 case AArch64ISD::LD1x2post
: return "AArch64ISD::LD1x2post";
1268 case AArch64ISD::LD1x3post
: return "AArch64ISD::LD1x3post";
1269 case AArch64ISD::LD1x4post
: return "AArch64ISD::LD1x4post";
1270 case AArch64ISD::ST1x2post
: return "AArch64ISD::ST1x2post";
1271 case AArch64ISD::ST1x3post
: return "AArch64ISD::ST1x3post";
1272 case AArch64ISD::ST1x4post
: return "AArch64ISD::ST1x4post";
1273 case AArch64ISD::LD1DUPpost
: return "AArch64ISD::LD1DUPpost";
1274 case AArch64ISD::LD2DUPpost
: return "AArch64ISD::LD2DUPpost";
1275 case AArch64ISD::LD3DUPpost
: return "AArch64ISD::LD3DUPpost";
1276 case AArch64ISD::LD4DUPpost
: return "AArch64ISD::LD4DUPpost";
1277 case AArch64ISD::LD1LANEpost
: return "AArch64ISD::LD1LANEpost";
1278 case AArch64ISD::LD2LANEpost
: return "AArch64ISD::LD2LANEpost";
1279 case AArch64ISD::LD3LANEpost
: return "AArch64ISD::LD3LANEpost";
1280 case AArch64ISD::LD4LANEpost
: return "AArch64ISD::LD4LANEpost";
1281 case AArch64ISD::ST2LANEpost
: return "AArch64ISD::ST2LANEpost";
1282 case AArch64ISD::ST3LANEpost
: return "AArch64ISD::ST3LANEpost";
1283 case AArch64ISD::ST4LANEpost
: return "AArch64ISD::ST4LANEpost";
1284 case AArch64ISD::SMULL
: return "AArch64ISD::SMULL";
1285 case AArch64ISD::UMULL
: return "AArch64ISD::UMULL";
1286 case AArch64ISD::FRECPE
: return "AArch64ISD::FRECPE";
1287 case AArch64ISD::FRECPS
: return "AArch64ISD::FRECPS";
1288 case AArch64ISD::FRSQRTE
: return "AArch64ISD::FRSQRTE";
1289 case AArch64ISD::FRSQRTS
: return "AArch64ISD::FRSQRTS";
1290 case AArch64ISD::STG
: return "AArch64ISD::STG";
1291 case AArch64ISD::STZG
: return "AArch64ISD::STZG";
1292 case AArch64ISD::ST2G
: return "AArch64ISD::ST2G";
1293 case AArch64ISD::STZ2G
: return "AArch64ISD::STZ2G";
1299 AArch64TargetLowering::EmitF128CSEL(MachineInstr
&MI
,
1300 MachineBasicBlock
*MBB
) const {
1301 // We materialise the F128CSEL pseudo-instruction as some control flow and a
1305 // [... previous instrs leading to comparison ...]
1311 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
1313 MachineFunction
*MF
= MBB
->getParent();
1314 const TargetInstrInfo
*TII
= Subtarget
->getInstrInfo();
1315 const BasicBlock
*LLVM_BB
= MBB
->getBasicBlock();
1316 DebugLoc DL
= MI
.getDebugLoc();
1317 MachineFunction::iterator It
= ++MBB
->getIterator();
1319 Register DestReg
= MI
.getOperand(0).getReg();
1320 Register IfTrueReg
= MI
.getOperand(1).getReg();
1321 Register IfFalseReg
= MI
.getOperand(2).getReg();
1322 unsigned CondCode
= MI
.getOperand(3).getImm();
1323 bool NZCVKilled
= MI
.getOperand(4).isKill();
1325 MachineBasicBlock
*TrueBB
= MF
->CreateMachineBasicBlock(LLVM_BB
);
1326 MachineBasicBlock
*EndBB
= MF
->CreateMachineBasicBlock(LLVM_BB
);
1327 MF
->insert(It
, TrueBB
);
1328 MF
->insert(It
, EndBB
);
1330 // Transfer rest of current basic-block to EndBB
1331 EndBB
->splice(EndBB
->begin(), MBB
, std::next(MachineBasicBlock::iterator(MI
)),
1333 EndBB
->transferSuccessorsAndUpdatePHIs(MBB
);
1335 BuildMI(MBB
, DL
, TII
->get(AArch64::Bcc
)).addImm(CondCode
).addMBB(TrueBB
);
1336 BuildMI(MBB
, DL
, TII
->get(AArch64::B
)).addMBB(EndBB
);
1337 MBB
->addSuccessor(TrueBB
);
1338 MBB
->addSuccessor(EndBB
);
1340 // TrueBB falls through to the end.
1341 TrueBB
->addSuccessor(EndBB
);
1344 TrueBB
->addLiveIn(AArch64::NZCV
);
1345 EndBB
->addLiveIn(AArch64::NZCV
);
1348 BuildMI(*EndBB
, EndBB
->begin(), DL
, TII
->get(AArch64::PHI
), DestReg
)
1354 MI
.eraseFromParent();
1358 MachineBasicBlock
*AArch64TargetLowering::EmitLoweredCatchRet(
1359 MachineInstr
&MI
, MachineBasicBlock
*BB
) const {
1360 assert(!isAsynchronousEHPersonality(classifyEHPersonality(
1361 BB
->getParent()->getFunction().getPersonalityFn())) &&
1362 "SEH does not use catchret!");
1366 MachineBasicBlock
*AArch64TargetLowering::EmitLoweredCatchPad(
1367 MachineInstr
&MI
, MachineBasicBlock
*BB
) const {
1368 MI
.eraseFromParent();
1372 MachineBasicBlock
*AArch64TargetLowering::EmitInstrWithCustomInserter(
1373 MachineInstr
&MI
, MachineBasicBlock
*BB
) const {
1374 switch (MI
.getOpcode()) {
1379 llvm_unreachable("Unexpected instruction for custom inserter!");
1381 case AArch64::F128CSEL
:
1382 return EmitF128CSEL(MI
, BB
);
1384 case TargetOpcode::STACKMAP
:
1385 case TargetOpcode::PATCHPOINT
:
1386 return emitPatchPoint(MI
, BB
);
1388 case AArch64::CATCHRET
:
1389 return EmitLoweredCatchRet(MI
, BB
);
1390 case AArch64::CATCHPAD
:
1391 return EmitLoweredCatchPad(MI
, BB
);
1395 //===----------------------------------------------------------------------===//
1396 // AArch64 Lowering private implementation.
1397 //===----------------------------------------------------------------------===//
1399 //===----------------------------------------------------------------------===//
1401 //===----------------------------------------------------------------------===//
1403 /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1405 static AArch64CC::CondCode
changeIntCCToAArch64CC(ISD::CondCode CC
) {
1408 llvm_unreachable("Unknown condition code!");
1410 return AArch64CC::NE
;
1412 return AArch64CC::EQ
;
1414 return AArch64CC::GT
;
1416 return AArch64CC::GE
;
1418 return AArch64CC::LT
;
1420 return AArch64CC::LE
;
1422 return AArch64CC::HI
;
1424 return AArch64CC::HS
;
1426 return AArch64CC::LO
;
1428 return AArch64CC::LS
;
1432 /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1433 static void changeFPCCToAArch64CC(ISD::CondCode CC
,
1434 AArch64CC::CondCode
&CondCode
,
1435 AArch64CC::CondCode
&CondCode2
) {
1436 CondCode2
= AArch64CC::AL
;
1439 llvm_unreachable("Unknown FP condition!");
1442 CondCode
= AArch64CC::EQ
;
1446 CondCode
= AArch64CC::GT
;
1450 CondCode
= AArch64CC::GE
;
1453 CondCode
= AArch64CC::MI
;
1456 CondCode
= AArch64CC::LS
;
1459 CondCode
= AArch64CC::MI
;
1460 CondCode2
= AArch64CC::GT
;
1463 CondCode
= AArch64CC::VC
;
1466 CondCode
= AArch64CC::VS
;
1469 CondCode
= AArch64CC::EQ
;
1470 CondCode2
= AArch64CC::VS
;
1473 CondCode
= AArch64CC::HI
;
1476 CondCode
= AArch64CC::PL
;
1480 CondCode
= AArch64CC::LT
;
1484 CondCode
= AArch64CC::LE
;
1488 CondCode
= AArch64CC::NE
;
1493 /// Convert a DAG fp condition code to an AArch64 CC.
1494 /// This differs from changeFPCCToAArch64CC in that it returns cond codes that
1495 /// should be AND'ed instead of OR'ed.
1496 static void changeFPCCToANDAArch64CC(ISD::CondCode CC
,
1497 AArch64CC::CondCode
&CondCode
,
1498 AArch64CC::CondCode
&CondCode2
) {
1499 CondCode2
= AArch64CC::AL
;
1502 changeFPCCToAArch64CC(CC
, CondCode
, CondCode2
);
1503 assert(CondCode2
== AArch64CC::AL
);
1507 // == ((a olt b) || (a ogt b))
1508 // == ((a ord b) && (a une b))
1509 CondCode
= AArch64CC::VC
;
1510 CondCode2
= AArch64CC::NE
;
1514 // == ((a uno b) || (a oeq b))
1515 // == ((a ule b) && (a uge b))
1516 CondCode
= AArch64CC::PL
;
1517 CondCode2
= AArch64CC::LE
;
1522 /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1523 /// CC usable with the vector instructions. Fewer operations are available
1524 /// without a real NZCV register, so we have to use less efficient combinations
1525 /// to get the same effect.
1526 static void changeVectorFPCCToAArch64CC(ISD::CondCode CC
,
1527 AArch64CC::CondCode
&CondCode
,
1528 AArch64CC::CondCode
&CondCode2
,
1533 // Mostly the scalar mappings work fine.
1534 changeFPCCToAArch64CC(CC
, CondCode
, CondCode2
);
1540 CondCode
= AArch64CC::MI
;
1541 CondCode2
= AArch64CC::GE
;
1548 // All of the compare-mask comparisons are ordered, but we can switch
1549 // between the two by a double inversion. E.g. ULE == !OGT.
1551 changeFPCCToAArch64CC(getSetCCInverse(CC
, false), CondCode
, CondCode2
);
1556 static bool isLegalArithImmed(uint64_t C
) {
1557 // Matches AArch64DAGToDAGISel::SelectArithImmed().
1558 bool IsLegal
= (C
>> 12 == 0) || ((C
& 0xFFFULL
) == 0 && C
>> 24 == 0);
1559 LLVM_DEBUG(dbgs() << "Is imm " << C
1560 << " legal: " << (IsLegal
? "yes\n" : "no\n"));
1564 // Can a (CMP op1, (sub 0, op2) be turned into a CMN instruction on
1565 // the grounds that "op1 - (-op2) == op1 + op2" ? Not always, the C and V flags
1566 // can be set differently by this operation. It comes down to whether
1567 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1568 // everything is fine. If not then the optimization is wrong. Thus general
1569 // comparisons are only valid if op2 != 0.
1571 // So, finally, the only LLVM-native comparisons that don't mention C and V
1572 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1573 // the absence of information about op2.
1574 static bool isCMN(SDValue Op
, ISD::CondCode CC
) {
1575 return Op
.getOpcode() == ISD::SUB
&& isNullConstant(Op
.getOperand(0)) &&
1576 (CC
== ISD::SETEQ
|| CC
== ISD::SETNE
);
1579 static SDValue
emitComparison(SDValue LHS
, SDValue RHS
, ISD::CondCode CC
,
1580 const SDLoc
&dl
, SelectionDAG
&DAG
) {
1581 EVT VT
= LHS
.getValueType();
1582 const bool FullFP16
=
1583 static_cast<const AArch64Subtarget
&>(DAG
.getSubtarget()).hasFullFP16();
1585 if (VT
.isFloatingPoint()) {
1586 assert(VT
!= MVT::f128
);
1587 if (VT
== MVT::f16
&& !FullFP16
) {
1588 LHS
= DAG
.getNode(ISD::FP_EXTEND
, dl
, MVT::f32
, LHS
);
1589 RHS
= DAG
.getNode(ISD::FP_EXTEND
, dl
, MVT::f32
, RHS
);
1592 return DAG
.getNode(AArch64ISD::FCMP
, dl
, VT
, LHS
, RHS
);
1595 // The CMP instruction is just an alias for SUBS, and representing it as
1596 // SUBS means that it's possible to get CSE with subtract operations.
1597 // A later phase can perform the optimization of setting the destination
1598 // register to WZR/XZR if it ends up being unused.
1599 unsigned Opcode
= AArch64ISD::SUBS
;
1601 if (isCMN(RHS
, CC
)) {
1602 // Can we combine a (CMP op1, (sub 0, op2) into a CMN instruction ?
1603 Opcode
= AArch64ISD::ADDS
;
1604 RHS
= RHS
.getOperand(1);
1605 } else if (isCMN(LHS
, CC
)) {
1606 // As we are looking for EQ/NE compares, the operands can be commuted ; can
1607 // we combine a (CMP (sub 0, op1), op2) into a CMN instruction ?
1608 Opcode
= AArch64ISD::ADDS
;
1609 LHS
= LHS
.getOperand(1);
1610 } else if (LHS
.getOpcode() == ISD::AND
&& isNullConstant(RHS
) &&
1611 !isUnsignedIntSetCC(CC
)) {
1612 // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1613 // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1614 // of the signed comparisons.
1615 Opcode
= AArch64ISD::ANDS
;
1616 RHS
= LHS
.getOperand(1);
1617 LHS
= LHS
.getOperand(0);
1620 return DAG
.getNode(Opcode
, dl
, DAG
.getVTList(VT
, MVT_CC
), LHS
, RHS
)
1624 /// \defgroup AArch64CCMP CMP;CCMP matching
1626 /// These functions deal with the formation of CMP;CCMP;... sequences.
1627 /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1628 /// a comparison. They set the NZCV flags to a predefined value if their
1629 /// predicate is false. This allows to express arbitrary conjunctions, for
1630 /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B)))"
1633 /// ccmp B, inv(CB), CA
1634 /// check for CB flags
1636 /// This naturally lets us implement chains of AND operations with SETCC
1637 /// operands. And we can even implement some other situations by transforming
1639 /// - We can implement (NEG SETCC) i.e. negating a single comparison by
1640 /// negating the flags used in a CCMP/FCCMP operations.
1641 /// - We can negate the result of a whole chain of CMP/CCMP/FCCMP operations
1642 /// by negating the flags we test for afterwards. i.e.
1643 /// NEG (CMP CCMP CCCMP ...) can be implemented.
1644 /// - Note that we can only ever negate all previously processed results.
1645 /// What we can not implement by flipping the flags to test is a negation
1646 /// of two sub-trees (because the negation affects all sub-trees emitted so
1647 /// far, so the 2nd sub-tree we emit would also affect the first).
1648 /// With those tools we can implement some OR operations:
1649 /// - (OR (SETCC A) (SETCC B)) can be implemented via:
1650 /// NEG (AND (NEG (SETCC A)) (NEG (SETCC B)))
1651 /// - After transforming OR to NEG/AND combinations we may be able to use NEG
1652 /// elimination rules from earlier to implement the whole thing as a
1653 /// CCMP/FCCMP chain.
1655 /// As complete example:
1656 /// or (or (setCA (cmp A)) (setCB (cmp B)))
1657 /// (and (setCC (cmp C)) (setCD (cmp D)))"
1658 /// can be reassociated to:
1659 /// or (and (setCC (cmp C)) setCD (cmp D))
1660 // (or (setCA (cmp A)) (setCB (cmp B)))
1661 /// can be transformed to:
1662 /// not (and (not (and (setCC (cmp C)) (setCD (cmp D))))
1663 /// (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1664 /// which can be implemented as:
1666 /// ccmp D, inv(CD), CC
1667 /// ccmp A, CA, inv(CD)
1668 /// ccmp B, CB, inv(CA)
1669 /// check for CB flags
1671 /// A counterexample is "or (and A B) (and C D)" which translates to
1672 /// not (and (not (and (not A) (not B))) (not (and (not C) (not D)))), we
1673 /// can only implement 1 of the inner (not) operations, but not both!
1676 /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
1677 static SDValue
emitConditionalComparison(SDValue LHS
, SDValue RHS
,
1678 ISD::CondCode CC
, SDValue CCOp
,
1679 AArch64CC::CondCode Predicate
,
1680 AArch64CC::CondCode OutCC
,
1681 const SDLoc
&DL
, SelectionDAG
&DAG
) {
1682 unsigned Opcode
= 0;
1683 const bool FullFP16
=
1684 static_cast<const AArch64Subtarget
&>(DAG
.getSubtarget()).hasFullFP16();
1686 if (LHS
.getValueType().isFloatingPoint()) {
1687 assert(LHS
.getValueType() != MVT::f128
);
1688 if (LHS
.getValueType() == MVT::f16
&& !FullFP16
) {
1689 LHS
= DAG
.getNode(ISD::FP_EXTEND
, DL
, MVT::f32
, LHS
);
1690 RHS
= DAG
.getNode(ISD::FP_EXTEND
, DL
, MVT::f32
, RHS
);
1692 Opcode
= AArch64ISD::FCCMP
;
1693 } else if (RHS
.getOpcode() == ISD::SUB
) {
1694 SDValue SubOp0
= RHS
.getOperand(0);
1695 if (isNullConstant(SubOp0
) && (CC
== ISD::SETEQ
|| CC
== ISD::SETNE
)) {
1696 // See emitComparison() on why we can only do this for SETEQ and SETNE.
1697 Opcode
= AArch64ISD::CCMN
;
1698 RHS
= RHS
.getOperand(1);
1702 Opcode
= AArch64ISD::CCMP
;
1704 SDValue Condition
= DAG
.getConstant(Predicate
, DL
, MVT_CC
);
1705 AArch64CC::CondCode InvOutCC
= AArch64CC::getInvertedCondCode(OutCC
);
1706 unsigned NZCV
= AArch64CC::getNZCVToSatisfyCondCode(InvOutCC
);
1707 SDValue NZCVOp
= DAG
.getConstant(NZCV
, DL
, MVT::i32
);
1708 return DAG
.getNode(Opcode
, DL
, MVT_CC
, LHS
, RHS
, NZCVOp
, Condition
, CCOp
);
1711 /// Returns true if @p Val is a tree of AND/OR/SETCC operations that can be
1712 /// expressed as a conjunction. See \ref AArch64CCMP.
1713 /// \param CanNegate Set to true if we can negate the whole sub-tree just by
1714 /// changing the conditions on the SETCC tests.
1715 /// (this means we can call emitConjunctionRec() with
1716 /// Negate==true on this sub-tree)
1717 /// \param MustBeFirst Set to true if this subtree needs to be negated and we
1718 /// cannot do the negation naturally. We are required to
1719 /// emit the subtree first in this case.
1720 /// \param WillNegate Is true if are called when the result of this
1721 /// subexpression must be negated. This happens when the
1722 /// outer expression is an OR. We can use this fact to know
1723 /// that we have a double negation (or (or ...) ...) that
1724 /// can be implemented for free.
1725 static bool canEmitConjunction(const SDValue Val
, bool &CanNegate
,
1726 bool &MustBeFirst
, bool WillNegate
,
1727 unsigned Depth
= 0) {
1728 if (!Val
.hasOneUse())
1730 unsigned Opcode
= Val
->getOpcode();
1731 if (Opcode
== ISD::SETCC
) {
1732 if (Val
->getOperand(0).getValueType() == MVT::f128
)
1735 MustBeFirst
= false;
1738 // Protect against exponential runtime and stack overflow.
1741 if (Opcode
== ISD::AND
|| Opcode
== ISD::OR
) {
1742 bool IsOR
= Opcode
== ISD::OR
;
1743 SDValue O0
= Val
->getOperand(0);
1744 SDValue O1
= Val
->getOperand(1);
1747 if (!canEmitConjunction(O0
, CanNegateL
, MustBeFirstL
, IsOR
, Depth
+1))
1751 if (!canEmitConjunction(O1
, CanNegateR
, MustBeFirstR
, IsOR
, Depth
+1))
1754 if (MustBeFirstL
&& MustBeFirstR
)
1758 // For an OR expression we need to be able to naturally negate at least
1759 // one side or we cannot do the transformation at all.
1760 if (!CanNegateL
&& !CanNegateR
)
1762 // If we the result of the OR will be negated and we can naturally negate
1763 // the leafs, then this sub-tree as a whole negates naturally.
1764 CanNegate
= WillNegate
&& CanNegateL
&& CanNegateR
;
1765 // If we cannot naturally negate the whole sub-tree, then this must be
1767 MustBeFirst
= !CanNegate
;
1769 assert(Opcode
== ISD::AND
&& "Must be OR or AND");
1770 // We cannot naturally negate an AND operation.
1772 MustBeFirst
= MustBeFirstL
|| MustBeFirstR
;
1779 /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1780 /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1781 /// Tries to transform the given i1 producing node @p Val to a series compare
1782 /// and conditional compare operations. @returns an NZCV flags producing node
1783 /// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1784 /// transformation was not possible.
1785 /// \p Negate is true if we want this sub-tree being negated just by changing
1786 /// SETCC conditions.
1787 static SDValue
emitConjunctionRec(SelectionDAG
&DAG
, SDValue Val
,
1788 AArch64CC::CondCode
&OutCC
, bool Negate
, SDValue CCOp
,
1789 AArch64CC::CondCode Predicate
) {
1790 // We're at a tree leaf, produce a conditional comparison operation.
1791 unsigned Opcode
= Val
->getOpcode();
1792 if (Opcode
== ISD::SETCC
) {
1793 SDValue LHS
= Val
->getOperand(0);
1794 SDValue RHS
= Val
->getOperand(1);
1795 ISD::CondCode CC
= cast
<CondCodeSDNode
>(Val
->getOperand(2))->get();
1796 bool isInteger
= LHS
.getValueType().isInteger();
1798 CC
= getSetCCInverse(CC
, isInteger
);
1800 // Determine OutCC and handle FP special case.
1802 OutCC
= changeIntCCToAArch64CC(CC
);
1804 assert(LHS
.getValueType().isFloatingPoint());
1805 AArch64CC::CondCode ExtraCC
;
1806 changeFPCCToANDAArch64CC(CC
, OutCC
, ExtraCC
);
1807 // Some floating point conditions can't be tested with a single condition
1808 // code. Construct an additional comparison in this case.
1809 if (ExtraCC
!= AArch64CC::AL
) {
1811 if (!CCOp
.getNode())
1812 ExtraCmp
= emitComparison(LHS
, RHS
, CC
, DL
, DAG
);
1814 ExtraCmp
= emitConditionalComparison(LHS
, RHS
, CC
, CCOp
, Predicate
,
1817 Predicate
= ExtraCC
;
1821 // Produce a normal comparison if we are first in the chain
1823 return emitComparison(LHS
, RHS
, CC
, DL
, DAG
);
1824 // Otherwise produce a ccmp.
1825 return emitConditionalComparison(LHS
, RHS
, CC
, CCOp
, Predicate
, OutCC
, DL
,
1828 assert(Val
->hasOneUse() && "Valid conjunction/disjunction tree");
1830 bool IsOR
= Opcode
== ISD::OR
;
1832 SDValue LHS
= Val
->getOperand(0);
1835 bool ValidL
= canEmitConjunction(LHS
, CanNegateL
, MustBeFirstL
, IsOR
);
1836 assert(ValidL
&& "Valid conjunction/disjunction tree");
1839 SDValue RHS
= Val
->getOperand(1);
1842 bool ValidR
= canEmitConjunction(RHS
, CanNegateR
, MustBeFirstR
, IsOR
);
1843 assert(ValidR
&& "Valid conjunction/disjunction tree");
1846 // Swap sub-tree that must come first to the right side.
1848 assert(!MustBeFirstR
&& "Valid conjunction/disjunction tree");
1849 std::swap(LHS
, RHS
);
1850 std::swap(CanNegateL
, CanNegateR
);
1851 std::swap(MustBeFirstL
, MustBeFirstR
);
1857 bool NegateAfterAll
;
1858 if (Opcode
== ISD::OR
) {
1859 // Swap the sub-tree that we can negate naturally to the left.
1861 assert(CanNegateR
&& "at least one side must be negatable");
1862 assert(!MustBeFirstR
&& "invalid conjunction/disjunction tree");
1864 std::swap(LHS
, RHS
);
1866 NegateAfterR
= true;
1868 // Negate the left sub-tree if possible, otherwise negate the result.
1869 NegateR
= CanNegateR
;
1870 NegateAfterR
= !CanNegateR
;
1873 NegateAfterAll
= !Negate
;
1875 assert(Opcode
== ISD::AND
&& "Valid conjunction/disjunction tree");
1876 assert(!Negate
&& "Valid conjunction/disjunction tree");
1880 NegateAfterR
= false;
1881 NegateAfterAll
= false;
1885 AArch64CC::CondCode RHSCC
;
1886 SDValue CmpR
= emitConjunctionRec(DAG
, RHS
, RHSCC
, NegateR
, CCOp
, Predicate
);
1888 RHSCC
= AArch64CC::getInvertedCondCode(RHSCC
);
1889 SDValue CmpL
= emitConjunctionRec(DAG
, LHS
, OutCC
, NegateL
, CmpR
, RHSCC
);
1891 OutCC
= AArch64CC::getInvertedCondCode(OutCC
);
1895 /// Emit expression as a conjunction (a series of CCMP/CFCMP ops).
1896 /// In some cases this is even possible with OR operations in the expression.
1897 /// See \ref AArch64CCMP.
1898 /// \see emitConjunctionRec().
1899 static SDValue
emitConjunction(SelectionDAG
&DAG
, SDValue Val
,
1900 AArch64CC::CondCode
&OutCC
) {
1901 bool DummyCanNegate
;
1902 bool DummyMustBeFirst
;
1903 if (!canEmitConjunction(Val
, DummyCanNegate
, DummyMustBeFirst
, false))
1906 return emitConjunctionRec(DAG
, Val
, OutCC
, false, SDValue(), AArch64CC::AL
);
1911 /// Returns how profitable it is to fold a comparison's operand's shift and/or
1912 /// extension operations.
1913 static unsigned getCmpOperandFoldingProfit(SDValue Op
) {
1914 auto isSupportedExtend
= [&](SDValue V
) {
1915 if (V
.getOpcode() == ISD::SIGN_EXTEND_INREG
)
1918 if (V
.getOpcode() == ISD::AND
)
1919 if (ConstantSDNode
*MaskCst
= dyn_cast
<ConstantSDNode
>(V
.getOperand(1))) {
1920 uint64_t Mask
= MaskCst
->getZExtValue();
1921 return (Mask
== 0xFF || Mask
== 0xFFFF || Mask
== 0xFFFFFFFF);
1927 if (!Op
.hasOneUse())
1930 if (isSupportedExtend(Op
))
1933 unsigned Opc
= Op
.getOpcode();
1934 if (Opc
== ISD::SHL
|| Opc
== ISD::SRL
|| Opc
== ISD::SRA
)
1935 if (ConstantSDNode
*ShiftCst
= dyn_cast
<ConstantSDNode
>(Op
.getOperand(1))) {
1936 uint64_t Shift
= ShiftCst
->getZExtValue();
1937 if (isSupportedExtend(Op
.getOperand(0)))
1938 return (Shift
<= 4) ? 2 : 1;
1939 EVT VT
= Op
.getValueType();
1940 if ((VT
== MVT::i32
&& Shift
<= 31) || (VT
== MVT::i64
&& Shift
<= 63))
1947 static SDValue
getAArch64Cmp(SDValue LHS
, SDValue RHS
, ISD::CondCode CC
,
1948 SDValue
&AArch64cc
, SelectionDAG
&DAG
,
1950 if (ConstantSDNode
*RHSC
= dyn_cast
<ConstantSDNode
>(RHS
.getNode())) {
1951 EVT VT
= RHS
.getValueType();
1952 uint64_t C
= RHSC
->getZExtValue();
1953 if (!isLegalArithImmed(C
)) {
1954 // Constant does not fit, try adjusting it by one?
1960 if ((VT
== MVT::i32
&& C
!= 0x80000000 &&
1961 isLegalArithImmed((uint32_t)(C
- 1))) ||
1962 (VT
== MVT::i64
&& C
!= 0x80000000ULL
&&
1963 isLegalArithImmed(C
- 1ULL))) {
1964 CC
= (CC
== ISD::SETLT
) ? ISD::SETLE
: ISD::SETGT
;
1965 C
= (VT
== MVT::i32
) ? (uint32_t)(C
- 1) : C
- 1;
1966 RHS
= DAG
.getConstant(C
, dl
, VT
);
1971 if ((VT
== MVT::i32
&& C
!= 0 &&
1972 isLegalArithImmed((uint32_t)(C
- 1))) ||
1973 (VT
== MVT::i64
&& C
!= 0ULL && isLegalArithImmed(C
- 1ULL))) {
1974 CC
= (CC
== ISD::SETULT
) ? ISD::SETULE
: ISD::SETUGT
;
1975 C
= (VT
== MVT::i32
) ? (uint32_t)(C
- 1) : C
- 1;
1976 RHS
= DAG
.getConstant(C
, dl
, VT
);
1981 if ((VT
== MVT::i32
&& C
!= INT32_MAX
&&
1982 isLegalArithImmed((uint32_t)(C
+ 1))) ||
1983 (VT
== MVT::i64
&& C
!= INT64_MAX
&&
1984 isLegalArithImmed(C
+ 1ULL))) {
1985 CC
= (CC
== ISD::SETLE
) ? ISD::SETLT
: ISD::SETGE
;
1986 C
= (VT
== MVT::i32
) ? (uint32_t)(C
+ 1) : C
+ 1;
1987 RHS
= DAG
.getConstant(C
, dl
, VT
);
1992 if ((VT
== MVT::i32
&& C
!= UINT32_MAX
&&
1993 isLegalArithImmed((uint32_t)(C
+ 1))) ||
1994 (VT
== MVT::i64
&& C
!= UINT64_MAX
&&
1995 isLegalArithImmed(C
+ 1ULL))) {
1996 CC
= (CC
== ISD::SETULE
) ? ISD::SETULT
: ISD::SETUGE
;
1997 C
= (VT
== MVT::i32
) ? (uint32_t)(C
+ 1) : C
+ 1;
1998 RHS
= DAG
.getConstant(C
, dl
, VT
);
2005 // Comparisons are canonicalized so that the RHS operand is simpler than the
2006 // LHS one, the extreme case being when RHS is an immediate. However, AArch64
2007 // can fold some shift+extend operations on the RHS operand, so swap the
2008 // operands if that can be done.
2013 // can be turned into:
2014 // cmp w12, w11, lsl #1
2015 if (!isa
<ConstantSDNode
>(RHS
) ||
2016 !isLegalArithImmed(cast
<ConstantSDNode
>(RHS
)->getZExtValue())) {
2017 SDValue TheLHS
= isCMN(LHS
, CC
) ? LHS
.getOperand(1) : LHS
;
2019 if (getCmpOperandFoldingProfit(TheLHS
) > getCmpOperandFoldingProfit(RHS
)) {
2020 std::swap(LHS
, RHS
);
2021 CC
= ISD::getSetCCSwappedOperands(CC
);
2026 AArch64CC::CondCode AArch64CC
;
2027 if ((CC
== ISD::SETEQ
|| CC
== ISD::SETNE
) && isa
<ConstantSDNode
>(RHS
)) {
2028 const ConstantSDNode
*RHSC
= cast
<ConstantSDNode
>(RHS
);
2030 // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
2031 // For the i8 operand, the largest immediate is 255, so this can be easily
2032 // encoded in the compare instruction. For the i16 operand, however, the
2033 // largest immediate cannot be encoded in the compare.
2034 // Therefore, use a sign extending load and cmn to avoid materializing the
2035 // -1 constant. For example,
2037 // ldrh w0, [x0, #0]
2040 // ldrsh w0, [x0, #0]
2042 // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
2043 // if and only if (sext LHS) == (sext RHS). The checks are in place to
2044 // ensure both the LHS and RHS are truly zero extended and to make sure the
2045 // transformation is profitable.
2046 if ((RHSC
->getZExtValue() >> 16 == 0) && isa
<LoadSDNode
>(LHS
) &&
2047 cast
<LoadSDNode
>(LHS
)->getExtensionType() == ISD::ZEXTLOAD
&&
2048 cast
<LoadSDNode
>(LHS
)->getMemoryVT() == MVT::i16
&&
2049 LHS
.getNode()->hasNUsesOfValue(1, 0)) {
2050 int16_t ValueofRHS
= cast
<ConstantSDNode
>(RHS
)->getZExtValue();
2051 if (ValueofRHS
< 0 && isLegalArithImmed(-ValueofRHS
)) {
2053 DAG
.getNode(ISD::SIGN_EXTEND_INREG
, dl
, LHS
.getValueType(), LHS
,
2054 DAG
.getValueType(MVT::i16
));
2055 Cmp
= emitComparison(SExt
, DAG
.getConstant(ValueofRHS
, dl
,
2056 RHS
.getValueType()),
2058 AArch64CC
= changeIntCCToAArch64CC(CC
);
2062 if (!Cmp
&& (RHSC
->isNullValue() || RHSC
->isOne())) {
2063 if ((Cmp
= emitConjunction(DAG
, LHS
, AArch64CC
))) {
2064 if ((CC
== ISD::SETNE
) ^ RHSC
->isNullValue())
2065 AArch64CC
= AArch64CC::getInvertedCondCode(AArch64CC
);
2071 Cmp
= emitComparison(LHS
, RHS
, CC
, dl
, DAG
);
2072 AArch64CC
= changeIntCCToAArch64CC(CC
);
2074 AArch64cc
= DAG
.getConstant(AArch64CC
, dl
, MVT_CC
);
2078 static std::pair
<SDValue
, SDValue
>
2079 getAArch64XALUOOp(AArch64CC::CondCode
&CC
, SDValue Op
, SelectionDAG
&DAG
) {
2080 assert((Op
.getValueType() == MVT::i32
|| Op
.getValueType() == MVT::i64
) &&
2081 "Unsupported value type");
2082 SDValue Value
, Overflow
;
2084 SDValue LHS
= Op
.getOperand(0);
2085 SDValue RHS
= Op
.getOperand(1);
2087 switch (Op
.getOpcode()) {
2089 llvm_unreachable("Unknown overflow instruction!");
2091 Opc
= AArch64ISD::ADDS
;
2095 Opc
= AArch64ISD::ADDS
;
2099 Opc
= AArch64ISD::SUBS
;
2103 Opc
= AArch64ISD::SUBS
;
2106 // Multiply needs a little bit extra work.
2110 bool IsSigned
= Op
.getOpcode() == ISD::SMULO
;
2111 if (Op
.getValueType() == MVT::i32
) {
2112 unsigned ExtendOpc
= IsSigned
? ISD::SIGN_EXTEND
: ISD::ZERO_EXTEND
;
2113 // For a 32 bit multiply with overflow check we want the instruction
2114 // selector to generate a widening multiply (SMADDL/UMADDL). For that we
2115 // need to generate the following pattern:
2116 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
2117 LHS
= DAG
.getNode(ExtendOpc
, DL
, MVT::i64
, LHS
);
2118 RHS
= DAG
.getNode(ExtendOpc
, DL
, MVT::i64
, RHS
);
2119 SDValue Mul
= DAG
.getNode(ISD::MUL
, DL
, MVT::i64
, LHS
, RHS
);
2120 SDValue Add
= DAG
.getNode(ISD::ADD
, DL
, MVT::i64
, Mul
,
2121 DAG
.getConstant(0, DL
, MVT::i64
));
2122 // On AArch64 the upper 32 bits are always zero extended for a 32 bit
2123 // operation. We need to clear out the upper 32 bits, because we used a
2124 // widening multiply that wrote all 64 bits. In the end this should be a
2126 Value
= DAG
.getNode(ISD::TRUNCATE
, DL
, MVT::i32
, Add
);
2128 // The signed overflow check requires more than just a simple check for
2129 // any bit set in the upper 32 bits of the result. These bits could be
2130 // just the sign bits of a negative number. To perform the overflow
2131 // check we have to arithmetic shift right the 32nd bit of the result by
2132 // 31 bits. Then we compare the result to the upper 32 bits.
2133 SDValue UpperBits
= DAG
.getNode(ISD::SRL
, DL
, MVT::i64
, Add
,
2134 DAG
.getConstant(32, DL
, MVT::i64
));
2135 UpperBits
= DAG
.getNode(ISD::TRUNCATE
, DL
, MVT::i32
, UpperBits
);
2136 SDValue LowerBits
= DAG
.getNode(ISD::SRA
, DL
, MVT::i32
, Value
,
2137 DAG
.getConstant(31, DL
, MVT::i64
));
2138 // It is important that LowerBits is last, otherwise the arithmetic
2139 // shift will not be folded into the compare (SUBS).
2140 SDVTList VTs
= DAG
.getVTList(MVT::i32
, MVT::i32
);
2141 Overflow
= DAG
.getNode(AArch64ISD::SUBS
, DL
, VTs
, UpperBits
, LowerBits
)
2144 // The overflow check for unsigned multiply is easy. We only need to
2145 // check if any of the upper 32 bits are set. This can be done with a
2146 // CMP (shifted register). For that we need to generate the following
2148 // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
2149 SDValue UpperBits
= DAG
.getNode(ISD::SRL
, DL
, MVT::i64
, Mul
,
2150 DAG
.getConstant(32, DL
, MVT::i64
));
2151 SDVTList VTs
= DAG
.getVTList(MVT::i64
, MVT::i32
);
2153 DAG
.getNode(AArch64ISD::SUBS
, DL
, VTs
,
2154 DAG
.getConstant(0, DL
, MVT::i64
),
2155 UpperBits
).getValue(1);
2159 assert(Op
.getValueType() == MVT::i64
&& "Expected an i64 value type");
2160 // For the 64 bit multiply
2161 Value
= DAG
.getNode(ISD::MUL
, DL
, MVT::i64
, LHS
, RHS
);
2163 SDValue UpperBits
= DAG
.getNode(ISD::MULHS
, DL
, MVT::i64
, LHS
, RHS
);
2164 SDValue LowerBits
= DAG
.getNode(ISD::SRA
, DL
, MVT::i64
, Value
,
2165 DAG
.getConstant(63, DL
, MVT::i64
));
2166 // It is important that LowerBits is last, otherwise the arithmetic
2167 // shift will not be folded into the compare (SUBS).
2168 SDVTList VTs
= DAG
.getVTList(MVT::i64
, MVT::i32
);
2169 Overflow
= DAG
.getNode(AArch64ISD::SUBS
, DL
, VTs
, UpperBits
, LowerBits
)
2172 SDValue UpperBits
= DAG
.getNode(ISD::MULHU
, DL
, MVT::i64
, LHS
, RHS
);
2173 SDVTList VTs
= DAG
.getVTList(MVT::i64
, MVT::i32
);
2175 DAG
.getNode(AArch64ISD::SUBS
, DL
, VTs
,
2176 DAG
.getConstant(0, DL
, MVT::i64
),
2177 UpperBits
).getValue(1);
2184 SDVTList VTs
= DAG
.getVTList(Op
->getValueType(0), MVT::i32
);
2186 // Emit the AArch64 operation with overflow check.
2187 Value
= DAG
.getNode(Opc
, DL
, VTs
, LHS
, RHS
);
2188 Overflow
= Value
.getValue(1);
2190 return std::make_pair(Value
, Overflow
);
2193 SDValue
AArch64TargetLowering::LowerF128Call(SDValue Op
, SelectionDAG
&DAG
,
2194 RTLIB::Libcall Call
) const {
2195 SmallVector
<SDValue
, 2> Ops(Op
->op_begin(), Op
->op_end());
2196 MakeLibCallOptions CallOptions
;
2197 return makeLibCall(DAG
, Call
, MVT::f128
, Ops
, CallOptions
, SDLoc(Op
)).first
;
2200 // Returns true if the given Op is the overflow flag result of an overflow
2201 // intrinsic operation.
2202 static bool isOverflowIntrOpRes(SDValue Op
) {
2203 unsigned Opc
= Op
.getOpcode();
2204 return (Op
.getResNo() == 1 &&
2205 (Opc
== ISD::SADDO
|| Opc
== ISD::UADDO
|| Opc
== ISD::SSUBO
||
2206 Opc
== ISD::USUBO
|| Opc
== ISD::SMULO
|| Opc
== ISD::UMULO
));
2209 static SDValue
LowerXOR(SDValue Op
, SelectionDAG
&DAG
) {
2210 SDValue Sel
= Op
.getOperand(0);
2211 SDValue Other
= Op
.getOperand(1);
2214 // If the operand is an overflow checking operation, invert the condition
2215 // code and kill the Not operation. I.e., transform:
2216 // (xor (overflow_op_bool, 1))
2218 // (csel 1, 0, invert(cc), overflow_op_bool)
2219 // ... which later gets transformed to just a cset instruction with an
2220 // inverted condition code, rather than a cset + eor sequence.
2221 if (isOneConstant(Other
) && isOverflowIntrOpRes(Sel
)) {
2222 // Only lower legal XALUO ops.
2223 if (!DAG
.getTargetLoweringInfo().isTypeLegal(Sel
->getValueType(0)))
2226 SDValue TVal
= DAG
.getConstant(1, dl
, MVT::i32
);
2227 SDValue FVal
= DAG
.getConstant(0, dl
, MVT::i32
);
2228 AArch64CC::CondCode CC
;
2229 SDValue Value
, Overflow
;
2230 std::tie(Value
, Overflow
) = getAArch64XALUOOp(CC
, Sel
.getValue(0), DAG
);
2231 SDValue CCVal
= DAG
.getConstant(getInvertedCondCode(CC
), dl
, MVT::i32
);
2232 return DAG
.getNode(AArch64ISD::CSEL
, dl
, Op
.getValueType(), TVal
, FVal
,
2235 // If neither operand is a SELECT_CC, give up.
2236 if (Sel
.getOpcode() != ISD::SELECT_CC
)
2237 std::swap(Sel
, Other
);
2238 if (Sel
.getOpcode() != ISD::SELECT_CC
)
2241 // The folding we want to perform is:
2242 // (xor x, (select_cc a, b, cc, 0, -1) )
2244 // (csel x, (xor x, -1), cc ...)
2246 // The latter will get matched to a CSINV instruction.
2248 ISD::CondCode CC
= cast
<CondCodeSDNode
>(Sel
.getOperand(4))->get();
2249 SDValue LHS
= Sel
.getOperand(0);
2250 SDValue RHS
= Sel
.getOperand(1);
2251 SDValue TVal
= Sel
.getOperand(2);
2252 SDValue FVal
= Sel
.getOperand(3);
2254 // FIXME: This could be generalized to non-integer comparisons.
2255 if (LHS
.getValueType() != MVT::i32
&& LHS
.getValueType() != MVT::i64
)
2258 ConstantSDNode
*CFVal
= dyn_cast
<ConstantSDNode
>(FVal
);
2259 ConstantSDNode
*CTVal
= dyn_cast
<ConstantSDNode
>(TVal
);
2261 // The values aren't constants, this isn't the pattern we're looking for.
2262 if (!CFVal
|| !CTVal
)
2265 // We can commute the SELECT_CC by inverting the condition. This
2266 // might be needed to make this fit into a CSINV pattern.
2267 if (CTVal
->isAllOnesValue() && CFVal
->isNullValue()) {
2268 std::swap(TVal
, FVal
);
2269 std::swap(CTVal
, CFVal
);
2270 CC
= ISD::getSetCCInverse(CC
, true);
2273 // If the constants line up, perform the transform!
2274 if (CTVal
->isNullValue() && CFVal
->isAllOnesValue()) {
2276 SDValue Cmp
= getAArch64Cmp(LHS
, RHS
, CC
, CCVal
, DAG
, dl
);
2279 TVal
= DAG
.getNode(ISD::XOR
, dl
, Other
.getValueType(), Other
,
2280 DAG
.getConstant(-1ULL, dl
, Other
.getValueType()));
2282 return DAG
.getNode(AArch64ISD::CSEL
, dl
, Sel
.getValueType(), FVal
, TVal
,
2289 static SDValue
LowerADDC_ADDE_SUBC_SUBE(SDValue Op
, SelectionDAG
&DAG
) {
2290 EVT VT
= Op
.getValueType();
2292 // Let legalize expand this if it isn't a legal type yet.
2293 if (!DAG
.getTargetLoweringInfo().isTypeLegal(VT
))
2296 SDVTList VTs
= DAG
.getVTList(VT
, MVT::i32
);
2299 bool ExtraOp
= false;
2300 switch (Op
.getOpcode()) {
2302 llvm_unreachable("Invalid code");
2304 Opc
= AArch64ISD::ADDS
;
2307 Opc
= AArch64ISD::SUBS
;
2310 Opc
= AArch64ISD::ADCS
;
2314 Opc
= AArch64ISD::SBCS
;
2320 return DAG
.getNode(Opc
, SDLoc(Op
), VTs
, Op
.getOperand(0), Op
.getOperand(1));
2321 return DAG
.getNode(Opc
, SDLoc(Op
), VTs
, Op
.getOperand(0), Op
.getOperand(1),
2325 static SDValue
LowerXALUO(SDValue Op
, SelectionDAG
&DAG
) {
2326 // Let legalize expand this if it isn't a legal type yet.
2327 if (!DAG
.getTargetLoweringInfo().isTypeLegal(Op
.getValueType()))
2331 AArch64CC::CondCode CC
;
2332 // The actual operation that sets the overflow or carry flag.
2333 SDValue Value
, Overflow
;
2334 std::tie(Value
, Overflow
) = getAArch64XALUOOp(CC
, Op
, DAG
);
2336 // We use 0 and 1 as false and true values.
2337 SDValue TVal
= DAG
.getConstant(1, dl
, MVT::i32
);
2338 SDValue FVal
= DAG
.getConstant(0, dl
, MVT::i32
);
2340 // We use an inverted condition, because the conditional select is inverted
2341 // too. This will allow it to be selected to a single instruction:
2342 // CSINC Wd, WZR, WZR, invert(cond).
2343 SDValue CCVal
= DAG
.getConstant(getInvertedCondCode(CC
), dl
, MVT::i32
);
2344 Overflow
= DAG
.getNode(AArch64ISD::CSEL
, dl
, MVT::i32
, FVal
, TVal
,
2347 SDVTList VTs
= DAG
.getVTList(Op
.getValueType(), MVT::i32
);
2348 return DAG
.getNode(ISD::MERGE_VALUES
, dl
, VTs
, Value
, Overflow
);
2351 // Prefetch operands are:
2352 // 1: Address to prefetch
2354 // 3: int locality (0 = no locality ... 3 = extreme locality)
2355 // 4: bool isDataCache
2356 static SDValue
LowerPREFETCH(SDValue Op
, SelectionDAG
&DAG
) {
2358 unsigned IsWrite
= cast
<ConstantSDNode
>(Op
.getOperand(2))->getZExtValue();
2359 unsigned Locality
= cast
<ConstantSDNode
>(Op
.getOperand(3))->getZExtValue();
2360 unsigned IsData
= cast
<ConstantSDNode
>(Op
.getOperand(4))->getZExtValue();
2362 bool IsStream
= !Locality
;
2363 // When the locality number is set
2365 // The front-end should have filtered out the out-of-range values
2366 assert(Locality
<= 3 && "Prefetch locality out-of-range");
2367 // The locality degree is the opposite of the cache speed.
2368 // Put the number the other way around.
2369 // The encoding starts at 0 for level 1
2370 Locality
= 3 - Locality
;
2373 // built the mask value encoding the expected behavior.
2374 unsigned PrfOp
= (IsWrite
<< 4) | // Load/Store bit
2375 (!IsData
<< 3) | // IsDataCache bit
2376 (Locality
<< 1) | // Cache level bits
2377 (unsigned)IsStream
; // Stream bit
2378 return DAG
.getNode(AArch64ISD::PREFETCH
, DL
, MVT::Other
, Op
.getOperand(0),
2379 DAG
.getConstant(PrfOp
, DL
, MVT::i32
), Op
.getOperand(1));
2382 SDValue
AArch64TargetLowering::LowerFP_EXTEND(SDValue Op
,
2383 SelectionDAG
&DAG
) const {
2384 assert(Op
.getValueType() == MVT::f128
&& "Unexpected lowering");
2387 LC
= RTLIB::getFPEXT(Op
.getOperand(0).getValueType(), Op
.getValueType());
2389 return LowerF128Call(Op
, DAG
, LC
);
2392 SDValue
AArch64TargetLowering::LowerFP_ROUND(SDValue Op
,
2393 SelectionDAG
&DAG
) const {
2394 if (Op
.getOperand(0).getValueType() != MVT::f128
) {
2395 // It's legal except when f128 is involved
2400 LC
= RTLIB::getFPROUND(Op
.getOperand(0).getValueType(), Op
.getValueType());
2402 // FP_ROUND node has a second operand indicating whether it is known to be
2403 // precise. That doesn't take part in the LibCall so we can't directly use
2405 SDValue SrcVal
= Op
.getOperand(0);
2406 MakeLibCallOptions CallOptions
;
2407 return makeLibCall(DAG
, LC
, Op
.getValueType(), SrcVal
, CallOptions
,
2411 SDValue
AArch64TargetLowering::LowerVectorFP_TO_INT(SDValue Op
,
2412 SelectionDAG
&DAG
) const {
2413 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2414 // Any additional optimization in this function should be recorded
2415 // in the cost tables.
2416 EVT InVT
= Op
.getOperand(0).getValueType();
2417 EVT VT
= Op
.getValueType();
2418 unsigned NumElts
= InVT
.getVectorNumElements();
2420 // f16 conversions are promoted to f32 when full fp16 is not supported.
2421 if (InVT
.getVectorElementType() == MVT::f16
&&
2422 !Subtarget
->hasFullFP16()) {
2423 MVT NewVT
= MVT::getVectorVT(MVT::f32
, NumElts
);
2426 Op
.getOpcode(), dl
, Op
.getValueType(),
2427 DAG
.getNode(ISD::FP_EXTEND
, dl
, NewVT
, Op
.getOperand(0)));
2430 if (VT
.getSizeInBits() < InVT
.getSizeInBits()) {
2433 DAG
.getNode(Op
.getOpcode(), dl
, InVT
.changeVectorElementTypeToInteger(),
2435 return DAG
.getNode(ISD::TRUNCATE
, dl
, VT
, Cv
);
2438 if (VT
.getSizeInBits() > InVT
.getSizeInBits()) {
2441 MVT::getVectorVT(MVT::getFloatingPointVT(VT
.getScalarSizeInBits()),
2442 VT
.getVectorNumElements());
2443 SDValue Ext
= DAG
.getNode(ISD::FP_EXTEND
, dl
, ExtVT
, Op
.getOperand(0));
2444 return DAG
.getNode(Op
.getOpcode(), dl
, VT
, Ext
);
2447 // Type changing conversions are illegal.
2451 SDValue
AArch64TargetLowering::LowerFP_TO_INT(SDValue Op
,
2452 SelectionDAG
&DAG
) const {
2453 if (Op
.getOperand(0).getValueType().isVector())
2454 return LowerVectorFP_TO_INT(Op
, DAG
);
2456 // f16 conversions are promoted to f32 when full fp16 is not supported.
2457 if (Op
.getOperand(0).getValueType() == MVT::f16
&&
2458 !Subtarget
->hasFullFP16()) {
2461 Op
.getOpcode(), dl
, Op
.getValueType(),
2462 DAG
.getNode(ISD::FP_EXTEND
, dl
, MVT::f32
, Op
.getOperand(0)));
2465 if (Op
.getOperand(0).getValueType() != MVT::f128
) {
2466 // It's legal except when f128 is involved
2471 if (Op
.getOpcode() == ISD::FP_TO_SINT
)
2472 LC
= RTLIB::getFPTOSINT(Op
.getOperand(0).getValueType(), Op
.getValueType());
2474 LC
= RTLIB::getFPTOUINT(Op
.getOperand(0).getValueType(), Op
.getValueType());
2476 SmallVector
<SDValue
, 2> Ops(Op
->op_begin(), Op
->op_end());
2477 MakeLibCallOptions CallOptions
;
2478 return makeLibCall(DAG
, LC
, Op
.getValueType(), Ops
, CallOptions
, SDLoc(Op
)).first
;
2481 static SDValue
LowerVectorINT_TO_FP(SDValue Op
, SelectionDAG
&DAG
) {
2482 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2483 // Any additional optimization in this function should be recorded
2484 // in the cost tables.
2485 EVT VT
= Op
.getValueType();
2487 SDValue In
= Op
.getOperand(0);
2488 EVT InVT
= In
.getValueType();
2490 if (VT
.getSizeInBits() < InVT
.getSizeInBits()) {
2492 MVT::getVectorVT(MVT::getFloatingPointVT(InVT
.getScalarSizeInBits()),
2493 InVT
.getVectorNumElements());
2494 In
= DAG
.getNode(Op
.getOpcode(), dl
, CastVT
, In
);
2495 return DAG
.getNode(ISD::FP_ROUND
, dl
, VT
, In
, DAG
.getIntPtrConstant(0, dl
));
2498 if (VT
.getSizeInBits() > InVT
.getSizeInBits()) {
2500 Op
.getOpcode() == ISD::SINT_TO_FP
? ISD::SIGN_EXTEND
: ISD::ZERO_EXTEND
;
2501 EVT CastVT
= VT
.changeVectorElementTypeToInteger();
2502 In
= DAG
.getNode(CastOpc
, dl
, CastVT
, In
);
2503 return DAG
.getNode(Op
.getOpcode(), dl
, VT
, In
);
2509 SDValue
AArch64TargetLowering::LowerINT_TO_FP(SDValue Op
,
2510 SelectionDAG
&DAG
) const {
2511 if (Op
.getValueType().isVector())
2512 return LowerVectorINT_TO_FP(Op
, DAG
);
2514 // f16 conversions are promoted to f32 when full fp16 is not supported.
2515 if (Op
.getValueType() == MVT::f16
&&
2516 !Subtarget
->hasFullFP16()) {
2519 ISD::FP_ROUND
, dl
, MVT::f16
,
2520 DAG
.getNode(Op
.getOpcode(), dl
, MVT::f32
, Op
.getOperand(0)),
2521 DAG
.getIntPtrConstant(0, dl
));
2524 // i128 conversions are libcalls.
2525 if (Op
.getOperand(0).getValueType() == MVT::i128
)
2528 // Other conversions are legal, unless it's to the completely software-based
2530 if (Op
.getValueType() != MVT::f128
)
2534 if (Op
.getOpcode() == ISD::SINT_TO_FP
)
2535 LC
= RTLIB::getSINTTOFP(Op
.getOperand(0).getValueType(), Op
.getValueType());
2537 LC
= RTLIB::getUINTTOFP(Op
.getOperand(0).getValueType(), Op
.getValueType());
2539 return LowerF128Call(Op
, DAG
, LC
);
2542 SDValue
AArch64TargetLowering::LowerFSINCOS(SDValue Op
,
2543 SelectionDAG
&DAG
) const {
2544 // For iOS, we want to call an alternative entry point: __sincos_stret,
2545 // which returns the values in two S / D registers.
2547 SDValue Arg
= Op
.getOperand(0);
2548 EVT ArgVT
= Arg
.getValueType();
2549 Type
*ArgTy
= ArgVT
.getTypeForEVT(*DAG
.getContext());
2556 Entry
.IsSExt
= false;
2557 Entry
.IsZExt
= false;
2558 Args
.push_back(Entry
);
2560 RTLIB::Libcall LC
= ArgVT
== MVT::f64
? RTLIB::SINCOS_STRET_F64
2561 : RTLIB::SINCOS_STRET_F32
;
2562 const char *LibcallName
= getLibcallName(LC
);
2564 DAG
.getExternalSymbol(LibcallName
, getPointerTy(DAG
.getDataLayout()));
2566 StructType
*RetTy
= StructType::get(ArgTy
, ArgTy
);
2567 TargetLowering::CallLoweringInfo
CLI(DAG
);
2569 .setChain(DAG
.getEntryNode())
2570 .setLibCallee(CallingConv::Fast
, RetTy
, Callee
, std::move(Args
));
2572 std::pair
<SDValue
, SDValue
> CallResult
= LowerCallTo(CLI
);
2573 return CallResult
.first
;
2576 static SDValue
LowerBITCAST(SDValue Op
, SelectionDAG
&DAG
) {
2577 if (Op
.getValueType() != MVT::f16
)
2580 assert(Op
.getOperand(0).getValueType() == MVT::i16
);
2583 Op
= DAG
.getNode(ISD::ANY_EXTEND
, DL
, MVT::i32
, Op
.getOperand(0));
2584 Op
= DAG
.getNode(ISD::BITCAST
, DL
, MVT::f32
, Op
);
2586 DAG
.getMachineNode(TargetOpcode::EXTRACT_SUBREG
, DL
, MVT::f16
, Op
,
2587 DAG
.getTargetConstant(AArch64::hsub
, DL
, MVT::i32
)),
2591 static EVT
getExtensionTo64Bits(const EVT
&OrigVT
) {
2592 if (OrigVT
.getSizeInBits() >= 64)
2595 assert(OrigVT
.isSimple() && "Expecting a simple value type");
2597 MVT::SimpleValueType OrigSimpleTy
= OrigVT
.getSimpleVT().SimpleTy
;
2598 switch (OrigSimpleTy
) {
2599 default: llvm_unreachable("Unexpected Vector Type");
2608 static SDValue
addRequiredExtensionForVectorMULL(SDValue N
, SelectionDAG
&DAG
,
2611 unsigned ExtOpcode
) {
2612 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2613 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2614 // 64-bits we need to insert a new extension so that it will be 64-bits.
2615 assert(ExtTy
.is128BitVector() && "Unexpected extension size");
2616 if (OrigTy
.getSizeInBits() >= 64)
2619 // Must extend size to at least 64 bits to be used as an operand for VMULL.
2620 EVT NewVT
= getExtensionTo64Bits(OrigTy
);
2622 return DAG
.getNode(ExtOpcode
, SDLoc(N
), NewVT
, N
);
2625 static bool isExtendedBUILD_VECTOR(SDNode
*N
, SelectionDAG
&DAG
,
2627 EVT VT
= N
->getValueType(0);
2629 if (N
->getOpcode() != ISD::BUILD_VECTOR
)
2632 for (const SDValue
&Elt
: N
->op_values()) {
2633 if (ConstantSDNode
*C
= dyn_cast
<ConstantSDNode
>(Elt
)) {
2634 unsigned EltSize
= VT
.getScalarSizeInBits();
2635 unsigned HalfSize
= EltSize
/ 2;
2637 if (!isIntN(HalfSize
, C
->getSExtValue()))
2640 if (!isUIntN(HalfSize
, C
->getZExtValue()))
2651 static SDValue
skipExtensionForVectorMULL(SDNode
*N
, SelectionDAG
&DAG
) {
2652 if (N
->getOpcode() == ISD::SIGN_EXTEND
|| N
->getOpcode() == ISD::ZERO_EXTEND
)
2653 return addRequiredExtensionForVectorMULL(N
->getOperand(0), DAG
,
2654 N
->getOperand(0)->getValueType(0),
2658 assert(N
->getOpcode() == ISD::BUILD_VECTOR
&& "expected BUILD_VECTOR");
2659 EVT VT
= N
->getValueType(0);
2661 unsigned EltSize
= VT
.getScalarSizeInBits() / 2;
2662 unsigned NumElts
= VT
.getVectorNumElements();
2663 MVT TruncVT
= MVT::getIntegerVT(EltSize
);
2664 SmallVector
<SDValue
, 8> Ops
;
2665 for (unsigned i
= 0; i
!= NumElts
; ++i
) {
2666 ConstantSDNode
*C
= cast
<ConstantSDNode
>(N
->getOperand(i
));
2667 const APInt
&CInt
= C
->getAPIntValue();
2668 // Element types smaller than 32 bits are not legal, so use i32 elements.
2669 // The values are implicitly truncated so sext vs. zext doesn't matter.
2670 Ops
.push_back(DAG
.getConstant(CInt
.zextOrTrunc(32), dl
, MVT::i32
));
2672 return DAG
.getBuildVector(MVT::getVectorVT(TruncVT
, NumElts
), dl
, Ops
);
2675 static bool isSignExtended(SDNode
*N
, SelectionDAG
&DAG
) {
2676 return N
->getOpcode() == ISD::SIGN_EXTEND
||
2677 isExtendedBUILD_VECTOR(N
, DAG
, true);
2680 static bool isZeroExtended(SDNode
*N
, SelectionDAG
&DAG
) {
2681 return N
->getOpcode() == ISD::ZERO_EXTEND
||
2682 isExtendedBUILD_VECTOR(N
, DAG
, false);
2685 static bool isAddSubSExt(SDNode
*N
, SelectionDAG
&DAG
) {
2686 unsigned Opcode
= N
->getOpcode();
2687 if (Opcode
== ISD::ADD
|| Opcode
== ISD::SUB
) {
2688 SDNode
*N0
= N
->getOperand(0).getNode();
2689 SDNode
*N1
= N
->getOperand(1).getNode();
2690 return N0
->hasOneUse() && N1
->hasOneUse() &&
2691 isSignExtended(N0
, DAG
) && isSignExtended(N1
, DAG
);
2696 static bool isAddSubZExt(SDNode
*N
, SelectionDAG
&DAG
) {
2697 unsigned Opcode
= N
->getOpcode();
2698 if (Opcode
== ISD::ADD
|| Opcode
== ISD::SUB
) {
2699 SDNode
*N0
= N
->getOperand(0).getNode();
2700 SDNode
*N1
= N
->getOperand(1).getNode();
2701 return N0
->hasOneUse() && N1
->hasOneUse() &&
2702 isZeroExtended(N0
, DAG
) && isZeroExtended(N1
, DAG
);
2707 SDValue
AArch64TargetLowering::LowerFLT_ROUNDS_(SDValue Op
,
2708 SelectionDAG
&DAG
) const {
2709 // The rounding mode is in bits 23:22 of the FPSCR.
2710 // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
2711 // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
2712 // so that the shift + and get folded into a bitfield extract.
2715 SDValue FPCR_64
= DAG
.getNode(ISD::INTRINSIC_WO_CHAIN
, dl
, MVT::i64
,
2716 DAG
.getConstant(Intrinsic::aarch64_get_fpcr
, dl
,
2718 SDValue FPCR_32
= DAG
.getNode(ISD::TRUNCATE
, dl
, MVT::i32
, FPCR_64
);
2719 SDValue FltRounds
= DAG
.getNode(ISD::ADD
, dl
, MVT::i32
, FPCR_32
,
2720 DAG
.getConstant(1U << 22, dl
, MVT::i32
));
2721 SDValue RMODE
= DAG
.getNode(ISD::SRL
, dl
, MVT::i32
, FltRounds
,
2722 DAG
.getConstant(22, dl
, MVT::i32
));
2723 return DAG
.getNode(ISD::AND
, dl
, MVT::i32
, RMODE
,
2724 DAG
.getConstant(3, dl
, MVT::i32
));
2727 static SDValue
LowerMUL(SDValue Op
, SelectionDAG
&DAG
) {
2728 // Multiplications are only custom-lowered for 128-bit vectors so that
2729 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
2730 EVT VT
= Op
.getValueType();
2731 assert(VT
.is128BitVector() && VT
.isInteger() &&
2732 "unexpected type for custom-lowering ISD::MUL");
2733 SDNode
*N0
= Op
.getOperand(0).getNode();
2734 SDNode
*N1
= Op
.getOperand(1).getNode();
2735 unsigned NewOpc
= 0;
2737 bool isN0SExt
= isSignExtended(N0
, DAG
);
2738 bool isN1SExt
= isSignExtended(N1
, DAG
);
2739 if (isN0SExt
&& isN1SExt
)
2740 NewOpc
= AArch64ISD::SMULL
;
2742 bool isN0ZExt
= isZeroExtended(N0
, DAG
);
2743 bool isN1ZExt
= isZeroExtended(N1
, DAG
);
2744 if (isN0ZExt
&& isN1ZExt
)
2745 NewOpc
= AArch64ISD::UMULL
;
2746 else if (isN1SExt
|| isN1ZExt
) {
2747 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2748 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2749 if (isN1SExt
&& isAddSubSExt(N0
, DAG
)) {
2750 NewOpc
= AArch64ISD::SMULL
;
2752 } else if (isN1ZExt
&& isAddSubZExt(N0
, DAG
)) {
2753 NewOpc
= AArch64ISD::UMULL
;
2755 } else if (isN0ZExt
&& isAddSubZExt(N1
, DAG
)) {
2757 NewOpc
= AArch64ISD::UMULL
;
2763 if (VT
== MVT::v2i64
)
2764 // Fall through to expand this. It is not legal.
2767 // Other vector multiplications are legal.
2772 // Legalize to a S/UMULL instruction
2775 SDValue Op1
= skipExtensionForVectorMULL(N1
, DAG
);
2777 Op0
= skipExtensionForVectorMULL(N0
, DAG
);
2778 assert(Op0
.getValueType().is64BitVector() &&
2779 Op1
.getValueType().is64BitVector() &&
2780 "unexpected types for extended operands to VMULL");
2781 return DAG
.getNode(NewOpc
, DL
, VT
, Op0
, Op1
);
2783 // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2784 // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2785 // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2786 SDValue N00
= skipExtensionForVectorMULL(N0
->getOperand(0).getNode(), DAG
);
2787 SDValue N01
= skipExtensionForVectorMULL(N0
->getOperand(1).getNode(), DAG
);
2788 EVT Op1VT
= Op1
.getValueType();
2789 return DAG
.getNode(N0
->getOpcode(), DL
, VT
,
2790 DAG
.getNode(NewOpc
, DL
, VT
,
2791 DAG
.getNode(ISD::BITCAST
, DL
, Op1VT
, N00
), Op1
),
2792 DAG
.getNode(NewOpc
, DL
, VT
,
2793 DAG
.getNode(ISD::BITCAST
, DL
, Op1VT
, N01
), Op1
));
2796 SDValue
AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op
,
2797 SelectionDAG
&DAG
) const {
2798 unsigned IntNo
= cast
<ConstantSDNode
>(Op
.getOperand(0))->getZExtValue();
2801 default: return SDValue(); // Don't custom lower most intrinsics.
2802 case Intrinsic::thread_pointer
: {
2803 EVT PtrVT
= getPointerTy(DAG
.getDataLayout());
2804 return DAG
.getNode(AArch64ISD::THREAD_POINTER
, dl
, PtrVT
);
2806 case Intrinsic::aarch64_neon_abs
: {
2807 EVT Ty
= Op
.getValueType();
2808 if (Ty
== MVT::i64
) {
2809 SDValue Result
= DAG
.getNode(ISD::BITCAST
, dl
, MVT::v1i64
,
2811 Result
= DAG
.getNode(ISD::ABS
, dl
, MVT::v1i64
, Result
);
2812 return DAG
.getNode(ISD::BITCAST
, dl
, MVT::i64
, Result
);
2813 } else if (Ty
.isVector() && Ty
.isInteger() && isTypeLegal(Ty
)) {
2814 return DAG
.getNode(ISD::ABS
, dl
, Ty
, Op
.getOperand(1));
2816 report_fatal_error("Unexpected type for AArch64 NEON intrinic");
2819 case Intrinsic::aarch64_neon_smax
:
2820 return DAG
.getNode(ISD::SMAX
, dl
, Op
.getValueType(),
2821 Op
.getOperand(1), Op
.getOperand(2));
2822 case Intrinsic::aarch64_neon_umax
:
2823 return DAG
.getNode(ISD::UMAX
, dl
, Op
.getValueType(),
2824 Op
.getOperand(1), Op
.getOperand(2));
2825 case Intrinsic::aarch64_neon_smin
:
2826 return DAG
.getNode(ISD::SMIN
, dl
, Op
.getValueType(),
2827 Op
.getOperand(1), Op
.getOperand(2));
2828 case Intrinsic::aarch64_neon_umin
:
2829 return DAG
.getNode(ISD::UMIN
, dl
, Op
.getValueType(),
2830 Op
.getOperand(1), Op
.getOperand(2));
2832 case Intrinsic::localaddress
: {
2833 const auto &MF
= DAG
.getMachineFunction();
2834 const auto *RegInfo
= Subtarget
->getRegisterInfo();
2835 unsigned Reg
= RegInfo
->getLocalAddressRegister(MF
);
2836 return DAG
.getCopyFromReg(DAG
.getEntryNode(), dl
, Reg
,
2837 Op
.getSimpleValueType());
2840 case Intrinsic::eh_recoverfp
: {
2841 // FIXME: This needs to be implemented to correctly handle highly aligned
2842 // stack objects. For now we simply return the incoming FP. Refer D53541
2843 // for more details.
2844 SDValue FnOp
= Op
.getOperand(1);
2845 SDValue IncomingFPOp
= Op
.getOperand(2);
2846 GlobalAddressSDNode
*GSD
= dyn_cast
<GlobalAddressSDNode
>(FnOp
);
2847 auto *Fn
= dyn_cast_or_null
<Function
>(GSD
? GSD
->getGlobal() : nullptr);
2850 "llvm.eh.recoverfp must take a function as the first argument");
2851 return IncomingFPOp
;
2856 // Custom lower trunc store for v4i8 vectors, since it is promoted to v4i16.
2857 static SDValue
LowerTruncateVectorStore(SDLoc DL
, StoreSDNode
*ST
,
2859 SelectionDAG
&DAG
) {
2860 assert(VT
.isVector() && "VT should be a vector type");
2861 assert(MemVT
== MVT::v4i8
&& VT
== MVT::v4i16
);
2863 SDValue Value
= ST
->getValue();
2865 // It first extend the promoted v4i16 to v8i16, truncate to v8i8, and extract
2866 // the word lane which represent the v4i8 subvector. It optimizes the store
2872 SDValue Undef
= DAG
.getUNDEF(MVT::i16
);
2873 SDValue UndefVec
= DAG
.getBuildVector(MVT::v4i16
, DL
,
2874 {Undef
, Undef
, Undef
, Undef
});
2876 SDValue TruncExt
= DAG
.getNode(ISD::CONCAT_VECTORS
, DL
, MVT::v8i16
,
2878 SDValue Trunc
= DAG
.getNode(ISD::TRUNCATE
, DL
, MVT::v8i8
, TruncExt
);
2880 Trunc
= DAG
.getNode(ISD::BITCAST
, DL
, MVT::v2i32
, Trunc
);
2881 SDValue ExtractTrunc
= DAG
.getNode(ISD::EXTRACT_VECTOR_ELT
, DL
, MVT::i32
,
2882 Trunc
, DAG
.getConstant(0, DL
, MVT::i64
));
2884 return DAG
.getStore(ST
->getChain(), DL
, ExtractTrunc
,
2885 ST
->getBasePtr(), ST
->getMemOperand());
2888 // Custom lowering for any store, vector or scalar and/or default or with
2889 // a truncate operations. Currently only custom lower truncate operation
2890 // from vector v4i16 to v4i8.
2891 SDValue
AArch64TargetLowering::LowerSTORE(SDValue Op
,
2892 SelectionDAG
&DAG
) const {
2894 StoreSDNode
*StoreNode
= cast
<StoreSDNode
>(Op
);
2895 assert (StoreNode
&& "Can only custom lower store nodes");
2897 SDValue Value
= StoreNode
->getValue();
2899 EVT VT
= Value
.getValueType();
2900 EVT MemVT
= StoreNode
->getMemoryVT();
2902 assert (VT
.isVector() && "Can only custom lower vector store types");
2904 unsigned AS
= StoreNode
->getAddressSpace();
2905 unsigned Align
= StoreNode
->getAlignment();
2906 if (Align
< MemVT
.getStoreSize() &&
2907 !allowsMisalignedMemoryAccesses(
2908 MemVT
, AS
, Align
, StoreNode
->getMemOperand()->getFlags(), nullptr)) {
2909 return scalarizeVectorStore(StoreNode
, DAG
);
2912 if (StoreNode
->isTruncatingStore()) {
2913 return LowerTruncateVectorStore(Dl
, StoreNode
, VT
, MemVT
, DAG
);
2919 SDValue
AArch64TargetLowering::LowerOperation(SDValue Op
,
2920 SelectionDAG
&DAG
) const {
2921 LLVM_DEBUG(dbgs() << "Custom lowering: ");
2922 LLVM_DEBUG(Op
.dump());
2924 switch (Op
.getOpcode()) {
2926 llvm_unreachable("unimplemented operand");
2929 return LowerBITCAST(Op
, DAG
);
2930 case ISD::GlobalAddress
:
2931 return LowerGlobalAddress(Op
, DAG
);
2932 case ISD::GlobalTLSAddress
:
2933 return LowerGlobalTLSAddress(Op
, DAG
);
2935 return LowerSETCC(Op
, DAG
);
2937 return LowerBR_CC(Op
, DAG
);
2939 return LowerSELECT(Op
, DAG
);
2940 case ISD::SELECT_CC
:
2941 return LowerSELECT_CC(Op
, DAG
);
2942 case ISD::JumpTable
:
2943 return LowerJumpTable(Op
, DAG
);
2945 return LowerBR_JT(Op
, DAG
);
2946 case ISD::ConstantPool
:
2947 return LowerConstantPool(Op
, DAG
);
2948 case ISD::BlockAddress
:
2949 return LowerBlockAddress(Op
, DAG
);
2951 return LowerVASTART(Op
, DAG
);
2953 return LowerVACOPY(Op
, DAG
);
2955 return LowerVAARG(Op
, DAG
);
2960 return LowerADDC_ADDE_SUBC_SUBE(Op
, DAG
);
2967 return LowerXALUO(Op
, DAG
);
2969 return LowerF128Call(Op
, DAG
, RTLIB::ADD_F128
);
2971 return LowerF128Call(Op
, DAG
, RTLIB::SUB_F128
);
2973 return LowerF128Call(Op
, DAG
, RTLIB::MUL_F128
);
2975 return LowerF128Call(Op
, DAG
, RTLIB::DIV_F128
);
2977 return LowerFP_ROUND(Op
, DAG
);
2978 case ISD::FP_EXTEND
:
2979 return LowerFP_EXTEND(Op
, DAG
);
2980 case ISD::FRAMEADDR
:
2981 return LowerFRAMEADDR(Op
, DAG
);
2982 case ISD::SPONENTRY
:
2983 return LowerSPONENTRY(Op
, DAG
);
2984 case ISD::RETURNADDR
:
2985 return LowerRETURNADDR(Op
, DAG
);
2986 case ISD::ADDROFRETURNADDR
:
2987 return LowerADDROFRETURNADDR(Op
, DAG
);
2988 case ISD::INSERT_VECTOR_ELT
:
2989 return LowerINSERT_VECTOR_ELT(Op
, DAG
);
2990 case ISD::EXTRACT_VECTOR_ELT
:
2991 return LowerEXTRACT_VECTOR_ELT(Op
, DAG
);
2992 case ISD::BUILD_VECTOR
:
2993 return LowerBUILD_VECTOR(Op
, DAG
);
2994 case ISD::VECTOR_SHUFFLE
:
2995 return LowerVECTOR_SHUFFLE(Op
, DAG
);
2996 case ISD::EXTRACT_SUBVECTOR
:
2997 return LowerEXTRACT_SUBVECTOR(Op
, DAG
);
3001 return LowerVectorSRA_SRL_SHL(Op
, DAG
);
3002 case ISD::SHL_PARTS
:
3003 return LowerShiftLeftParts(Op
, DAG
);
3004 case ISD::SRL_PARTS
:
3005 case ISD::SRA_PARTS
:
3006 return LowerShiftRightParts(Op
, DAG
);
3008 return LowerCTPOP(Op
, DAG
);
3009 case ISD::FCOPYSIGN
:
3010 return LowerFCOPYSIGN(Op
, DAG
);
3012 return LowerVectorOR(Op
, DAG
);
3014 return LowerXOR(Op
, DAG
);
3016 return LowerPREFETCH(Op
, DAG
);
3017 case ISD::SINT_TO_FP
:
3018 case ISD::UINT_TO_FP
:
3019 return LowerINT_TO_FP(Op
, DAG
);
3020 case ISD::FP_TO_SINT
:
3021 case ISD::FP_TO_UINT
:
3022 return LowerFP_TO_INT(Op
, DAG
);
3024 return LowerFSINCOS(Op
, DAG
);
3025 case ISD::FLT_ROUNDS_
:
3026 return LowerFLT_ROUNDS_(Op
, DAG
);
3028 return LowerMUL(Op
, DAG
);
3029 case ISD::INTRINSIC_WO_CHAIN
:
3030 return LowerINTRINSIC_WO_CHAIN(Op
, DAG
);
3032 return LowerSTORE(Op
, DAG
);
3033 case ISD::VECREDUCE_ADD
:
3034 case ISD::VECREDUCE_SMAX
:
3035 case ISD::VECREDUCE_SMIN
:
3036 case ISD::VECREDUCE_UMAX
:
3037 case ISD::VECREDUCE_UMIN
:
3038 case ISD::VECREDUCE_FMAX
:
3039 case ISD::VECREDUCE_FMIN
:
3040 return LowerVECREDUCE(Op
, DAG
);
3041 case ISD::ATOMIC_LOAD_SUB
:
3042 return LowerATOMIC_LOAD_SUB(Op
, DAG
);
3043 case ISD::ATOMIC_LOAD_AND
:
3044 return LowerATOMIC_LOAD_AND(Op
, DAG
);
3045 case ISD::DYNAMIC_STACKALLOC
:
3046 return LowerDYNAMIC_STACKALLOC(Op
, DAG
);
3050 //===----------------------------------------------------------------------===//
3051 // Calling Convention Implementation
3052 //===----------------------------------------------------------------------===//
3054 /// Selects the correct CCAssignFn for a given CallingConvention value.
3055 CCAssignFn
*AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC
,
3056 bool IsVarArg
) const {
3059 report_fatal_error("Unsupported calling convention.");
3060 case CallingConv::WebKit_JS
:
3061 return CC_AArch64_WebKit_JS
;
3062 case CallingConv::GHC
:
3063 return CC_AArch64_GHC
;
3064 case CallingConv::C
:
3065 case CallingConv::Fast
:
3066 case CallingConv::PreserveMost
:
3067 case CallingConv::CXX_FAST_TLS
:
3068 case CallingConv::Swift
:
3069 if (Subtarget
->isTargetWindows() && IsVarArg
)
3070 return CC_AArch64_Win64_VarArg
;
3071 if (!Subtarget
->isTargetDarwin())
3072 return CC_AArch64_AAPCS
;
3073 return IsVarArg
? CC_AArch64_DarwinPCS_VarArg
: CC_AArch64_DarwinPCS
;
3074 case CallingConv::Win64
:
3075 return IsVarArg
? CC_AArch64_Win64_VarArg
: CC_AArch64_AAPCS
;
3076 case CallingConv::AArch64_VectorCall
:
3077 return CC_AArch64_AAPCS
;
3082 AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC
) const {
3083 return CC
== CallingConv::WebKit_JS
? RetCC_AArch64_WebKit_JS
3084 : RetCC_AArch64_AAPCS
;
3087 SDValue
AArch64TargetLowering::LowerFormalArguments(
3088 SDValue Chain
, CallingConv::ID CallConv
, bool isVarArg
,
3089 const SmallVectorImpl
<ISD::InputArg
> &Ins
, const SDLoc
&DL
,
3090 SelectionDAG
&DAG
, SmallVectorImpl
<SDValue
> &InVals
) const {
3091 MachineFunction
&MF
= DAG
.getMachineFunction();
3092 MachineFrameInfo
&MFI
= MF
.getFrameInfo();
3093 bool IsWin64
= Subtarget
->isCallingConvWin64(MF
.getFunction().getCallingConv());
3095 // Assign locations to all of the incoming arguments.
3096 SmallVector
<CCValAssign
, 16> ArgLocs
;
3097 CCState
CCInfo(CallConv
, isVarArg
, DAG
.getMachineFunction(), ArgLocs
,
3100 // At this point, Ins[].VT may already be promoted to i32. To correctly
3101 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
3102 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
3103 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
3104 // we use a special version of AnalyzeFormalArguments to pass in ValVT and
3106 unsigned NumArgs
= Ins
.size();
3107 Function::const_arg_iterator CurOrigArg
= MF
.getFunction().arg_begin();
3108 unsigned CurArgIdx
= 0;
3109 for (unsigned i
= 0; i
!= NumArgs
; ++i
) {
3110 MVT ValVT
= Ins
[i
].VT
;
3111 if (Ins
[i
].isOrigArg()) {
3112 std::advance(CurOrigArg
, Ins
[i
].getOrigArgIndex() - CurArgIdx
);
3113 CurArgIdx
= Ins
[i
].getOrigArgIndex();
3115 // Get type of the original argument.
3116 EVT ActualVT
= getValueType(DAG
.getDataLayout(), CurOrigArg
->getType(),
3117 /*AllowUnknown*/ true);
3118 MVT ActualMVT
= ActualVT
.isSimple() ? ActualVT
.getSimpleVT() : MVT::Other
;
3119 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
3120 if (ActualMVT
== MVT::i1
|| ActualMVT
== MVT::i8
)
3122 else if (ActualMVT
== MVT::i16
)
3125 CCAssignFn
*AssignFn
= CCAssignFnForCall(CallConv
, /*IsVarArg=*/false);
3127 AssignFn(i
, ValVT
, ValVT
, CCValAssign::Full
, Ins
[i
].Flags
, CCInfo
);
3128 assert(!Res
&& "Call operand has unhandled type");
3131 assert(ArgLocs
.size() == Ins
.size());
3132 SmallVector
<SDValue
, 16> ArgValues
;
3133 for (unsigned i
= 0, e
= ArgLocs
.size(); i
!= e
; ++i
) {
3134 CCValAssign
&VA
= ArgLocs
[i
];
3136 if (Ins
[i
].Flags
.isByVal()) {
3137 // Byval is used for HFAs in the PCS, but the system should work in a
3138 // non-compliant manner for larger structs.
3139 EVT PtrVT
= getPointerTy(DAG
.getDataLayout());
3140 int Size
= Ins
[i
].Flags
.getByValSize();
3141 unsigned NumRegs
= (Size
+ 7) / 8;
3143 // FIXME: This works on big-endian for composite byvals, which are the common
3144 // case. It should also work for fundamental types too.
3146 MFI
.CreateFixedObject(8 * NumRegs
, VA
.getLocMemOffset(), false);
3147 SDValue FrameIdxN
= DAG
.getFrameIndex(FrameIdx
, PtrVT
);
3148 InVals
.push_back(FrameIdxN
);
3153 if (VA
.isRegLoc()) {
3154 // Arguments stored in registers.
3155 EVT RegVT
= VA
.getLocVT();
3158 const TargetRegisterClass
*RC
;
3160 if (RegVT
== MVT::i32
)
3161 RC
= &AArch64::GPR32RegClass
;
3162 else if (RegVT
== MVT::i64
)
3163 RC
= &AArch64::GPR64RegClass
;
3164 else if (RegVT
== MVT::f16
)
3165 RC
= &AArch64::FPR16RegClass
;
3166 else if (RegVT
== MVT::f32
)
3167 RC
= &AArch64::FPR32RegClass
;
3168 else if (RegVT
== MVT::f64
|| RegVT
.is64BitVector())
3169 RC
= &AArch64::FPR64RegClass
;
3170 else if (RegVT
== MVT::f128
|| RegVT
.is128BitVector())
3171 RC
= &AArch64::FPR128RegClass
;
3172 else if (RegVT
.isScalableVector() &&
3173 RegVT
.getVectorElementType() == MVT::i1
)
3174 RC
= &AArch64::PPRRegClass
;
3175 else if (RegVT
.isScalableVector())
3176 RC
= &AArch64::ZPRRegClass
;
3178 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3180 // Transform the arguments in physical registers into virtual ones.
3181 unsigned Reg
= MF
.addLiveIn(VA
.getLocReg(), RC
);
3182 ArgValue
= DAG
.getCopyFromReg(Chain
, DL
, Reg
, RegVT
);
3184 // If this is an 8, 16 or 32-bit value, it is really passed promoted
3185 // to 64 bits. Insert an assert[sz]ext to capture this, then
3186 // truncate to the right size.
3187 switch (VA
.getLocInfo()) {
3189 llvm_unreachable("Unknown loc info!");
3190 case CCValAssign::Full
:
3192 case CCValAssign::Indirect
:
3193 assert(VA
.getValVT().isScalableVector() &&
3194 "Only scalable vectors can be passed indirectly");
3195 llvm_unreachable("Spilling of SVE vectors not yet implemented");
3196 case CCValAssign::BCvt
:
3197 ArgValue
= DAG
.getNode(ISD::BITCAST
, DL
, VA
.getValVT(), ArgValue
);
3199 case CCValAssign::AExt
:
3200 case CCValAssign::SExt
:
3201 case CCValAssign::ZExt
:
3202 // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
3203 // nodes after our lowering.
3204 assert(RegVT
== Ins
[i
].VT
&& "incorrect register location selected");
3208 InVals
.push_back(ArgValue
);
3210 } else { // VA.isRegLoc()
3211 assert(VA
.isMemLoc() && "CCValAssign is neither reg nor mem");
3212 unsigned ArgOffset
= VA
.getLocMemOffset();
3213 unsigned ArgSize
= VA
.getValVT().getSizeInBits() / 8;
3215 uint32_t BEAlign
= 0;
3216 if (!Subtarget
->isLittleEndian() && ArgSize
< 8 &&
3217 !Ins
[i
].Flags
.isInConsecutiveRegs())
3218 BEAlign
= 8 - ArgSize
;
3220 int FI
= MFI
.CreateFixedObject(ArgSize
, ArgOffset
+ BEAlign
, true);
3222 // Create load nodes to retrieve arguments from the stack.
3223 SDValue FIN
= DAG
.getFrameIndex(FI
, getPointerTy(DAG
.getDataLayout()));
3226 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
3227 ISD::LoadExtType ExtType
= ISD::NON_EXTLOAD
;
3228 MVT MemVT
= VA
.getValVT();
3230 switch (VA
.getLocInfo()) {
3233 case CCValAssign::BCvt
:
3234 MemVT
= VA
.getLocVT();
3236 case CCValAssign::Indirect
:
3237 assert(VA
.getValVT().isScalableVector() &&
3238 "Only scalable vectors can be passed indirectly");
3239 llvm_unreachable("Spilling of SVE vectors not yet implemented");
3240 case CCValAssign::SExt
:
3241 ExtType
= ISD::SEXTLOAD
;
3243 case CCValAssign::ZExt
:
3244 ExtType
= ISD::ZEXTLOAD
;
3246 case CCValAssign::AExt
:
3247 ExtType
= ISD::EXTLOAD
;
3251 ArgValue
= DAG
.getExtLoad(
3252 ExtType
, DL
, VA
.getLocVT(), Chain
, FIN
,
3253 MachinePointerInfo::getFixedStack(DAG
.getMachineFunction(), FI
),
3256 InVals
.push_back(ArgValue
);
3261 AArch64FunctionInfo
*FuncInfo
= MF
.getInfo
<AArch64FunctionInfo
>();
3263 if (!Subtarget
->isTargetDarwin() || IsWin64
) {
3264 // The AAPCS variadic function ABI is identical to the non-variadic
3265 // one. As a result there may be more arguments in registers and we should
3266 // save them for future reference.
3267 // Win64 variadic functions also pass arguments in registers, but all float
3268 // arguments are passed in integer registers.
3269 saveVarArgRegisters(CCInfo
, DAG
, DL
, Chain
);
3272 // This will point to the next argument passed via stack.
3273 unsigned StackOffset
= CCInfo
.getNextStackOffset();
3274 // We currently pass all varargs at 8-byte alignment.
3275 StackOffset
= ((StackOffset
+ 7) & ~7);
3276 FuncInfo
->setVarArgsStackIndex(MFI
.CreateFixedObject(4, StackOffset
, true));
3278 if (MFI
.hasMustTailInVarArgFunc()) {
3279 SmallVector
<MVT
, 2> RegParmTypes
;
3280 RegParmTypes
.push_back(MVT::i64
);
3281 RegParmTypes
.push_back(MVT::f128
);
3282 // Compute the set of forwarded registers. The rest are scratch.
3283 SmallVectorImpl
<ForwardedRegister
> &Forwards
=
3284 FuncInfo
->getForwardedMustTailRegParms();
3285 CCInfo
.analyzeMustTailForwardedRegisters(Forwards
, RegParmTypes
,
3288 // Conservatively forward X8, since it might be used for aggregate return.
3289 if (!CCInfo
.isAllocated(AArch64::X8
)) {
3290 unsigned X8VReg
= MF
.addLiveIn(AArch64::X8
, &AArch64::GPR64RegClass
);
3291 Forwards
.push_back(ForwardedRegister(X8VReg
, AArch64::X8
, MVT::i64
));
3296 // On Windows, InReg pointers must be returned, so record the pointer in a
3297 // virtual register at the start of the function so it can be returned in the
3300 for (unsigned I
= 0, E
= Ins
.size(); I
!= E
; ++I
) {
3301 if (Ins
[I
].Flags
.isInReg()) {
3302 assert(!FuncInfo
->getSRetReturnReg());
3304 MVT PtrTy
= getPointerTy(DAG
.getDataLayout());
3306 MF
.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy
));
3307 FuncInfo
->setSRetReturnReg(Reg
);
3309 SDValue Copy
= DAG
.getCopyToReg(DAG
.getEntryNode(), DL
, Reg
, InVals
[I
]);
3310 Chain
= DAG
.getNode(ISD::TokenFactor
, DL
, MVT::Other
, Copy
, Chain
);
3316 unsigned StackArgSize
= CCInfo
.getNextStackOffset();
3317 bool TailCallOpt
= MF
.getTarget().Options
.GuaranteedTailCallOpt
;
3318 if (DoesCalleeRestoreStack(CallConv
, TailCallOpt
)) {
3319 // This is a non-standard ABI so by fiat I say we're allowed to make full
3320 // use of the stack area to be popped, which must be aligned to 16 bytes in
3322 StackArgSize
= alignTo(StackArgSize
, 16);
3324 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
3325 // a multiple of 16.
3326 FuncInfo
->setArgumentStackToRestore(StackArgSize
);
3328 // This realignment carries over to the available bytes below. Our own
3329 // callers will guarantee the space is free by giving an aligned value to
3332 // Even if we're not expected to free up the space, it's useful to know how
3333 // much is there while considering tail calls (because we can reuse it).
3334 FuncInfo
->setBytesInStackArgArea(StackArgSize
);
3336 if (Subtarget
->hasCustomCallingConv())
3337 Subtarget
->getRegisterInfo()->UpdateCustomCalleeSavedRegs(MF
);
3342 void AArch64TargetLowering::saveVarArgRegisters(CCState
&CCInfo
,
3345 SDValue
&Chain
) const {
3346 MachineFunction
&MF
= DAG
.getMachineFunction();
3347 MachineFrameInfo
&MFI
= MF
.getFrameInfo();
3348 AArch64FunctionInfo
*FuncInfo
= MF
.getInfo
<AArch64FunctionInfo
>();
3349 auto PtrVT
= getPointerTy(DAG
.getDataLayout());
3350 bool IsWin64
= Subtarget
->isCallingConvWin64(MF
.getFunction().getCallingConv());
3352 SmallVector
<SDValue
, 8> MemOps
;
3354 static const MCPhysReg GPRArgRegs
[] = { AArch64::X0
, AArch64::X1
, AArch64::X2
,
3355 AArch64::X3
, AArch64::X4
, AArch64::X5
,
3356 AArch64::X6
, AArch64::X7
};
3357 static const unsigned NumGPRArgRegs
= array_lengthof(GPRArgRegs
);
3358 unsigned FirstVariadicGPR
= CCInfo
.getFirstUnallocated(GPRArgRegs
);
3360 unsigned GPRSaveSize
= 8 * (NumGPRArgRegs
- FirstVariadicGPR
);
3362 if (GPRSaveSize
!= 0) {
3364 GPRIdx
= MFI
.CreateFixedObject(GPRSaveSize
, -(int)GPRSaveSize
, false);
3365 if (GPRSaveSize
& 15)
3366 // The extra size here, if triggered, will always be 8.
3367 MFI
.CreateFixedObject(16 - (GPRSaveSize
& 15), -(int)alignTo(GPRSaveSize
, 16), false);
3369 GPRIdx
= MFI
.CreateStackObject(GPRSaveSize
, 8, false);
3371 SDValue FIN
= DAG
.getFrameIndex(GPRIdx
, PtrVT
);
3373 for (unsigned i
= FirstVariadicGPR
; i
< NumGPRArgRegs
; ++i
) {
3374 unsigned VReg
= MF
.addLiveIn(GPRArgRegs
[i
], &AArch64::GPR64RegClass
);
3375 SDValue Val
= DAG
.getCopyFromReg(Chain
, DL
, VReg
, MVT::i64
);
3376 SDValue Store
= DAG
.getStore(
3377 Val
.getValue(1), DL
, Val
, FIN
,
3379 ? MachinePointerInfo::getFixedStack(DAG
.getMachineFunction(),
3381 (i
- FirstVariadicGPR
) * 8)
3382 : MachinePointerInfo::getStack(DAG
.getMachineFunction(), i
* 8));
3383 MemOps
.push_back(Store
);
3385 DAG
.getNode(ISD::ADD
, DL
, PtrVT
, FIN
, DAG
.getConstant(8, DL
, PtrVT
));
3388 FuncInfo
->setVarArgsGPRIndex(GPRIdx
);
3389 FuncInfo
->setVarArgsGPRSize(GPRSaveSize
);
3391 if (Subtarget
->hasFPARMv8() && !IsWin64
) {
3392 static const MCPhysReg FPRArgRegs
[] = {
3393 AArch64::Q0
, AArch64::Q1
, AArch64::Q2
, AArch64::Q3
,
3394 AArch64::Q4
, AArch64::Q5
, AArch64::Q6
, AArch64::Q7
};
3395 static const unsigned NumFPRArgRegs
= array_lengthof(FPRArgRegs
);
3396 unsigned FirstVariadicFPR
= CCInfo
.getFirstUnallocated(FPRArgRegs
);
3398 unsigned FPRSaveSize
= 16 * (NumFPRArgRegs
- FirstVariadicFPR
);
3400 if (FPRSaveSize
!= 0) {
3401 FPRIdx
= MFI
.CreateStackObject(FPRSaveSize
, 16, false);
3403 SDValue FIN
= DAG
.getFrameIndex(FPRIdx
, PtrVT
);
3405 for (unsigned i
= FirstVariadicFPR
; i
< NumFPRArgRegs
; ++i
) {
3406 unsigned VReg
= MF
.addLiveIn(FPRArgRegs
[i
], &AArch64::FPR128RegClass
);
3407 SDValue Val
= DAG
.getCopyFromReg(Chain
, DL
, VReg
, MVT::f128
);
3409 SDValue Store
= DAG
.getStore(
3410 Val
.getValue(1), DL
, Val
, FIN
,
3411 MachinePointerInfo::getStack(DAG
.getMachineFunction(), i
* 16));
3412 MemOps
.push_back(Store
);
3413 FIN
= DAG
.getNode(ISD::ADD
, DL
, PtrVT
, FIN
,
3414 DAG
.getConstant(16, DL
, PtrVT
));
3417 FuncInfo
->setVarArgsFPRIndex(FPRIdx
);
3418 FuncInfo
->setVarArgsFPRSize(FPRSaveSize
);
3421 if (!MemOps
.empty()) {
3422 Chain
= DAG
.getNode(ISD::TokenFactor
, DL
, MVT::Other
, MemOps
);
3426 /// LowerCallResult - Lower the result values of a call into the
3427 /// appropriate copies out of appropriate physical registers.
3428 SDValue
AArch64TargetLowering::LowerCallResult(
3429 SDValue Chain
, SDValue InFlag
, CallingConv::ID CallConv
, bool isVarArg
,
3430 const SmallVectorImpl
<ISD::InputArg
> &Ins
, const SDLoc
&DL
,
3431 SelectionDAG
&DAG
, SmallVectorImpl
<SDValue
> &InVals
, bool isThisReturn
,
3432 SDValue ThisVal
) const {
3433 CCAssignFn
*RetCC
= CallConv
== CallingConv::WebKit_JS
3434 ? RetCC_AArch64_WebKit_JS
3435 : RetCC_AArch64_AAPCS
;
3436 // Assign locations to each value returned by this call.
3437 SmallVector
<CCValAssign
, 16> RVLocs
;
3438 CCState
CCInfo(CallConv
, isVarArg
, DAG
.getMachineFunction(), RVLocs
,
3440 CCInfo
.AnalyzeCallResult(Ins
, RetCC
);
3442 // Copy all of the result registers out of their specified physreg.
3443 for (unsigned i
= 0; i
!= RVLocs
.size(); ++i
) {
3444 CCValAssign VA
= RVLocs
[i
];
3446 // Pass 'this' value directly from the argument to return value, to avoid
3447 // reg unit interference
3448 if (i
== 0 && isThisReturn
) {
3449 assert(!VA
.needsCustom() && VA
.getLocVT() == MVT::i64
&&
3450 "unexpected return calling convention register assignment");
3451 InVals
.push_back(ThisVal
);
3456 DAG
.getCopyFromReg(Chain
, DL
, VA
.getLocReg(), VA
.getLocVT(), InFlag
);
3457 Chain
= Val
.getValue(1);
3458 InFlag
= Val
.getValue(2);
3460 switch (VA
.getLocInfo()) {
3462 llvm_unreachable("Unknown loc info!");
3463 case CCValAssign::Full
:
3465 case CCValAssign::BCvt
:
3466 Val
= DAG
.getNode(ISD::BITCAST
, DL
, VA
.getValVT(), Val
);
3470 InVals
.push_back(Val
);
3476 /// Return true if the calling convention is one that we can guarantee TCO for.
3477 static bool canGuaranteeTCO(CallingConv::ID CC
) {
3478 return CC
== CallingConv::Fast
;
3481 /// Return true if we might ever do TCO for calls with this calling convention.
3482 static bool mayTailCallThisCC(CallingConv::ID CC
) {
3484 case CallingConv::C
:
3485 case CallingConv::PreserveMost
:
3486 case CallingConv::Swift
:
3489 return canGuaranteeTCO(CC
);
3493 bool AArch64TargetLowering::isEligibleForTailCallOptimization(
3494 SDValue Callee
, CallingConv::ID CalleeCC
, bool isVarArg
,
3495 const SmallVectorImpl
<ISD::OutputArg
> &Outs
,
3496 const SmallVectorImpl
<SDValue
> &OutVals
,
3497 const SmallVectorImpl
<ISD::InputArg
> &Ins
, SelectionDAG
&DAG
) const {
3498 if (!mayTailCallThisCC(CalleeCC
))
3501 MachineFunction
&MF
= DAG
.getMachineFunction();
3502 const Function
&CallerF
= MF
.getFunction();
3503 CallingConv::ID CallerCC
= CallerF
.getCallingConv();
3504 bool CCMatch
= CallerCC
== CalleeCC
;
3506 // Byval parameters hand the function a pointer directly into the stack area
3507 // we want to reuse during a tail call. Working around this *is* possible (see
3508 // X86) but less efficient and uglier in LowerCall.
3509 for (Function::const_arg_iterator i
= CallerF
.arg_begin(),
3510 e
= CallerF
.arg_end();
3512 if (i
->hasByValAttr())
3515 // On Windows, "inreg" attributes signify non-aggregate indirect returns.
3516 // In this case, it is necessary to save/restore X0 in the callee. Tail
3517 // call opt interferes with this. So we disable tail call opt when the
3518 // caller has an argument with "inreg" attribute.
3520 // FIXME: Check whether the callee also has an "inreg" argument.
3521 if (i
->hasInRegAttr())
3525 if (getTargetMachine().Options
.GuaranteedTailCallOpt
)
3526 return canGuaranteeTCO(CalleeCC
) && CCMatch
;
3528 // Externally-defined functions with weak linkage should not be
3529 // tail-called on AArch64 when the OS does not support dynamic
3530 // pre-emption of symbols, as the AAELF spec requires normal calls
3531 // to undefined weak functions to be replaced with a NOP or jump to the
3532 // next instruction. The behaviour of branch instructions in this
3533 // situation (as used for tail calls) is implementation-defined, so we
3534 // cannot rely on the linker replacing the tail call with a return.
3535 if (GlobalAddressSDNode
*G
= dyn_cast
<GlobalAddressSDNode
>(Callee
)) {
3536 const GlobalValue
*GV
= G
->getGlobal();
3537 const Triple
&TT
= getTargetMachine().getTargetTriple();
3538 if (GV
->hasExternalWeakLinkage() &&
3539 (!TT
.isOSWindows() || TT
.isOSBinFormatELF() || TT
.isOSBinFormatMachO()))
3543 // Now we search for cases where we can use a tail call without changing the
3544 // ABI. Sibcall is used in some places (particularly gcc) to refer to this
3547 // I want anyone implementing a new calling convention to think long and hard
3548 // about this assert.
3549 assert((!isVarArg
|| CalleeCC
== CallingConv::C
) &&
3550 "Unexpected variadic calling convention");
3552 LLVMContext
&C
= *DAG
.getContext();
3553 if (isVarArg
&& !Outs
.empty()) {
3554 // At least two cases here: if caller is fastcc then we can't have any
3555 // memory arguments (we'd be expected to clean up the stack afterwards). If
3556 // caller is C then we could potentially use its argument area.
3558 // FIXME: for now we take the most conservative of these in both cases:
3559 // disallow all variadic memory operands.
3560 SmallVector
<CCValAssign
, 16> ArgLocs
;
3561 CCState
CCInfo(CalleeCC
, isVarArg
, MF
, ArgLocs
, C
);
3563 CCInfo
.AnalyzeCallOperands(Outs
, CCAssignFnForCall(CalleeCC
, true));
3564 for (const CCValAssign
&ArgLoc
: ArgLocs
)
3565 if (!ArgLoc
.isRegLoc())
3569 // Check that the call results are passed in the same way.
3570 if (!CCState::resultsCompatible(CalleeCC
, CallerCC
, MF
, C
, Ins
,
3571 CCAssignFnForCall(CalleeCC
, isVarArg
),
3572 CCAssignFnForCall(CallerCC
, isVarArg
)))
3574 // The callee has to preserve all registers the caller needs to preserve.
3575 const AArch64RegisterInfo
*TRI
= Subtarget
->getRegisterInfo();
3576 const uint32_t *CallerPreserved
= TRI
->getCallPreservedMask(MF
, CallerCC
);
3578 const uint32_t *CalleePreserved
= TRI
->getCallPreservedMask(MF
, CalleeCC
);
3579 if (Subtarget
->hasCustomCallingConv()) {
3580 TRI
->UpdateCustomCallPreservedMask(MF
, &CallerPreserved
);
3581 TRI
->UpdateCustomCallPreservedMask(MF
, &CalleePreserved
);
3583 if (!TRI
->regmaskSubsetEqual(CallerPreserved
, CalleePreserved
))
3587 // Nothing more to check if the callee is taking no arguments
3591 SmallVector
<CCValAssign
, 16> ArgLocs
;
3592 CCState
CCInfo(CalleeCC
, isVarArg
, MF
, ArgLocs
, C
);
3594 CCInfo
.AnalyzeCallOperands(Outs
, CCAssignFnForCall(CalleeCC
, isVarArg
));
3596 const AArch64FunctionInfo
*FuncInfo
= MF
.getInfo
<AArch64FunctionInfo
>();
3598 // If the stack arguments for this call do not fit into our own save area then
3599 // the call cannot be made tail.
3600 if (CCInfo
.getNextStackOffset() > FuncInfo
->getBytesInStackArgArea())
3603 const MachineRegisterInfo
&MRI
= MF
.getRegInfo();
3604 if (!parametersInCSRMatch(MRI
, CallerPreserved
, ArgLocs
, OutVals
))
3610 SDValue
AArch64TargetLowering::addTokenForArgument(SDValue Chain
,
3612 MachineFrameInfo
&MFI
,
3613 int ClobberedFI
) const {
3614 SmallVector
<SDValue
, 8> ArgChains
;
3615 int64_t FirstByte
= MFI
.getObjectOffset(ClobberedFI
);
3616 int64_t LastByte
= FirstByte
+ MFI
.getObjectSize(ClobberedFI
) - 1;
3618 // Include the original chain at the beginning of the list. When this is
3619 // used by target LowerCall hooks, this helps legalize find the
3620 // CALLSEQ_BEGIN node.
3621 ArgChains
.push_back(Chain
);
3623 // Add a chain value for each stack argument corresponding
3624 for (SDNode::use_iterator U
= DAG
.getEntryNode().getNode()->use_begin(),
3625 UE
= DAG
.getEntryNode().getNode()->use_end();
3627 if (LoadSDNode
*L
= dyn_cast
<LoadSDNode
>(*U
))
3628 if (FrameIndexSDNode
*FI
= dyn_cast
<FrameIndexSDNode
>(L
->getBasePtr()))
3629 if (FI
->getIndex() < 0) {
3630 int64_t InFirstByte
= MFI
.getObjectOffset(FI
->getIndex());
3631 int64_t InLastByte
= InFirstByte
;
3632 InLastByte
+= MFI
.getObjectSize(FI
->getIndex()) - 1;
3634 if ((InFirstByte
<= FirstByte
&& FirstByte
<= InLastByte
) ||
3635 (FirstByte
<= InFirstByte
&& InFirstByte
<= LastByte
))
3636 ArgChains
.push_back(SDValue(L
, 1));
3639 // Build a tokenfactor for all the chains.
3640 return DAG
.getNode(ISD::TokenFactor
, SDLoc(Chain
), MVT::Other
, ArgChains
);
3643 bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC
,
3644 bool TailCallOpt
) const {
3645 return CallCC
== CallingConv::Fast
&& TailCallOpt
;
3648 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
3649 /// and add input and output parameter nodes.
3651 AArch64TargetLowering::LowerCall(CallLoweringInfo
&CLI
,
3652 SmallVectorImpl
<SDValue
> &InVals
) const {
3653 SelectionDAG
&DAG
= CLI
.DAG
;
3655 SmallVector
<ISD::OutputArg
, 32> &Outs
= CLI
.Outs
;
3656 SmallVector
<SDValue
, 32> &OutVals
= CLI
.OutVals
;
3657 SmallVector
<ISD::InputArg
, 32> &Ins
= CLI
.Ins
;
3658 SDValue Chain
= CLI
.Chain
;
3659 SDValue Callee
= CLI
.Callee
;
3660 bool &IsTailCall
= CLI
.IsTailCall
;
3661 CallingConv::ID CallConv
= CLI
.CallConv
;
3662 bool IsVarArg
= CLI
.IsVarArg
;
3664 MachineFunction
&MF
= DAG
.getMachineFunction();
3665 bool IsThisReturn
= false;
3667 AArch64FunctionInfo
*FuncInfo
= MF
.getInfo
<AArch64FunctionInfo
>();
3668 bool TailCallOpt
= MF
.getTarget().Options
.GuaranteedTailCallOpt
;
3669 bool IsSibCall
= false;
3672 // Check if it's really possible to do a tail call.
3673 IsTailCall
= isEligibleForTailCallOptimization(
3674 Callee
, CallConv
, IsVarArg
, Outs
, OutVals
, Ins
, DAG
);
3675 if (!IsTailCall
&& CLI
.CS
&& CLI
.CS
.isMustTailCall())
3676 report_fatal_error("failed to perform tail call elimination on a call "
3677 "site marked musttail");
3679 // A sibling call is one where we're under the usual C ABI and not planning
3680 // to change that but can still do a tail call:
3681 if (!TailCallOpt
&& IsTailCall
)
3688 // Analyze operands of the call, assigning locations to each operand.
3689 SmallVector
<CCValAssign
, 16> ArgLocs
;
3690 CCState
CCInfo(CallConv
, IsVarArg
, DAG
.getMachineFunction(), ArgLocs
,
3694 // Handle fixed and variable vector arguments differently.
3695 // Variable vector arguments always go into memory.
3696 unsigned NumArgs
= Outs
.size();
3698 for (unsigned i
= 0; i
!= NumArgs
; ++i
) {
3699 MVT ArgVT
= Outs
[i
].VT
;
3700 ISD::ArgFlagsTy ArgFlags
= Outs
[i
].Flags
;
3701 CCAssignFn
*AssignFn
= CCAssignFnForCall(CallConv
,
3702 /*IsVarArg=*/ !Outs
[i
].IsFixed
);
3703 bool Res
= AssignFn(i
, ArgVT
, ArgVT
, CCValAssign::Full
, ArgFlags
, CCInfo
);
3704 assert(!Res
&& "Call operand has unhandled type");
3708 // At this point, Outs[].VT may already be promoted to i32. To correctly
3709 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
3710 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
3711 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
3712 // we use a special version of AnalyzeCallOperands to pass in ValVT and
3714 unsigned NumArgs
= Outs
.size();
3715 for (unsigned i
= 0; i
!= NumArgs
; ++i
) {
3716 MVT ValVT
= Outs
[i
].VT
;
3717 // Get type of the original argument.
3718 EVT ActualVT
= getValueType(DAG
.getDataLayout(),
3719 CLI
.getArgs()[Outs
[i
].OrigArgIndex
].Ty
,
3720 /*AllowUnknown*/ true);
3721 MVT ActualMVT
= ActualVT
.isSimple() ? ActualVT
.getSimpleVT() : ValVT
;
3722 ISD::ArgFlagsTy ArgFlags
= Outs
[i
].Flags
;
3723 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
3724 if (ActualMVT
== MVT::i1
|| ActualMVT
== MVT::i8
)
3726 else if (ActualMVT
== MVT::i16
)
3729 CCAssignFn
*AssignFn
= CCAssignFnForCall(CallConv
, /*IsVarArg=*/false);
3730 bool Res
= AssignFn(i
, ValVT
, ValVT
, CCValAssign::Full
, ArgFlags
, CCInfo
);
3731 assert(!Res
&& "Call operand has unhandled type");
3736 // Get a count of how many bytes are to be pushed on the stack.
3737 unsigned NumBytes
= CCInfo
.getNextStackOffset();
3740 // Since we're not changing the ABI to make this a tail call, the memory
3741 // operands are already available in the caller's incoming argument space.
3745 // FPDiff is the byte offset of the call's argument area from the callee's.
3746 // Stores to callee stack arguments will be placed in FixedStackSlots offset
3747 // by this amount for a tail call. In a sibling call it must be 0 because the
3748 // caller will deallocate the entire stack and the callee still expects its
3749 // arguments to begin at SP+0. Completely unused for non-tail calls.
3752 if (IsTailCall
&& !IsSibCall
) {
3753 unsigned NumReusableBytes
= FuncInfo
->getBytesInStackArgArea();
3755 // Since callee will pop argument stack as a tail call, we must keep the
3756 // popped size 16-byte aligned.
3757 NumBytes
= alignTo(NumBytes
, 16);
3759 // FPDiff will be negative if this tail call requires more space than we
3760 // would automatically have in our incoming argument space. Positive if we
3761 // can actually shrink the stack.
3762 FPDiff
= NumReusableBytes
- NumBytes
;
3764 // The stack pointer must be 16-byte aligned at all times it's used for a
3765 // memory operation, which in practice means at *all* times and in
3766 // particular across call boundaries. Therefore our own arguments started at
3767 // a 16-byte aligned SP and the delta applied for the tail call should
3768 // satisfy the same constraint.
3769 assert(FPDiff
% 16 == 0 && "unaligned stack on tail call");
3772 // Adjust the stack pointer for the new arguments...
3773 // These operations are automatically eliminated by the prolog/epilog pass
3775 Chain
= DAG
.getCALLSEQ_START(Chain
, NumBytes
, 0, DL
);
3777 SDValue StackPtr
= DAG
.getCopyFromReg(Chain
, DL
, AArch64::SP
,
3778 getPointerTy(DAG
.getDataLayout()));
3780 SmallVector
<std::pair
<unsigned, SDValue
>, 8> RegsToPass
;
3781 SmallVector
<SDValue
, 8> MemOpChains
;
3782 auto PtrVT
= getPointerTy(DAG
.getDataLayout());
3784 if (IsVarArg
&& CLI
.CS
&& CLI
.CS
.isMustTailCall()) {
3785 const auto &Forwards
= FuncInfo
->getForwardedMustTailRegParms();
3786 for (const auto &F
: Forwards
) {
3787 SDValue Val
= DAG
.getCopyFromReg(Chain
, DL
, F
.VReg
, F
.VT
);
3788 RegsToPass
.push_back(std::make_pair(unsigned(F
.PReg
), Val
));
3792 // Walk the register/memloc assignments, inserting copies/loads.
3793 for (unsigned i
= 0, realArgIdx
= 0, e
= ArgLocs
.size(); i
!= e
;
3794 ++i
, ++realArgIdx
) {
3795 CCValAssign
&VA
= ArgLocs
[i
];
3796 SDValue Arg
= OutVals
[realArgIdx
];
3797 ISD::ArgFlagsTy Flags
= Outs
[realArgIdx
].Flags
;
3799 // Promote the value if needed.
3800 switch (VA
.getLocInfo()) {
3802 llvm_unreachable("Unknown loc info!");
3803 case CCValAssign::Full
:
3805 case CCValAssign::SExt
:
3806 Arg
= DAG
.getNode(ISD::SIGN_EXTEND
, DL
, VA
.getLocVT(), Arg
);
3808 case CCValAssign::ZExt
:
3809 Arg
= DAG
.getNode(ISD::ZERO_EXTEND
, DL
, VA
.getLocVT(), Arg
);
3811 case CCValAssign::AExt
:
3812 if (Outs
[realArgIdx
].ArgVT
== MVT::i1
) {
3813 // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
3814 Arg
= DAG
.getNode(ISD::TRUNCATE
, DL
, MVT::i1
, Arg
);
3815 Arg
= DAG
.getNode(ISD::ZERO_EXTEND
, DL
, MVT::i8
, Arg
);
3817 Arg
= DAG
.getNode(ISD::ANY_EXTEND
, DL
, VA
.getLocVT(), Arg
);
3819 case CCValAssign::BCvt
:
3820 Arg
= DAG
.getNode(ISD::BITCAST
, DL
, VA
.getLocVT(), Arg
);
3822 case CCValAssign::FPExt
:
3823 Arg
= DAG
.getNode(ISD::FP_EXTEND
, DL
, VA
.getLocVT(), Arg
);
3825 case CCValAssign::Indirect
:
3826 assert(VA
.getValVT().isScalableVector() &&
3827 "Only scalable vectors can be passed indirectly");
3828 llvm_unreachable("Spilling of SVE vectors not yet implemented");
3831 if (VA
.isRegLoc()) {
3832 if (realArgIdx
== 0 && Flags
.isReturned() && !Flags
.isSwiftSelf() &&
3833 Outs
[0].VT
== MVT::i64
) {
3834 assert(VA
.getLocVT() == MVT::i64
&&
3835 "unexpected calling convention register assignment");
3836 assert(!Ins
.empty() && Ins
[0].VT
== MVT::i64
&&
3837 "unexpected use of 'returned'");
3838 IsThisReturn
= true;
3840 RegsToPass
.push_back(std::make_pair(VA
.getLocReg(), Arg
));
3842 assert(VA
.isMemLoc());
3845 MachinePointerInfo DstInfo
;
3847 // FIXME: This works on big-endian for composite byvals, which are the
3848 // common case. It should also work for fundamental types too.
3849 uint32_t BEAlign
= 0;
3850 unsigned OpSize
= Flags
.isByVal() ? Flags
.getByValSize() * 8
3851 : VA
.getValVT().getSizeInBits();
3852 OpSize
= (OpSize
+ 7) / 8;
3853 if (!Subtarget
->isLittleEndian() && !Flags
.isByVal() &&
3854 !Flags
.isInConsecutiveRegs()) {
3856 BEAlign
= 8 - OpSize
;
3858 unsigned LocMemOffset
= VA
.getLocMemOffset();
3859 int32_t Offset
= LocMemOffset
+ BEAlign
;
3860 SDValue PtrOff
= DAG
.getIntPtrConstant(Offset
, DL
);
3861 PtrOff
= DAG
.getNode(ISD::ADD
, DL
, PtrVT
, StackPtr
, PtrOff
);
3864 Offset
= Offset
+ FPDiff
;
3865 int FI
= MF
.getFrameInfo().CreateFixedObject(OpSize
, Offset
, true);
3867 DstAddr
= DAG
.getFrameIndex(FI
, PtrVT
);
3869 MachinePointerInfo::getFixedStack(DAG
.getMachineFunction(), FI
);
3871 // Make sure any stack arguments overlapping with where we're storing
3872 // are loaded before this eventual operation. Otherwise they'll be
3874 Chain
= addTokenForArgument(Chain
, DAG
, MF
.getFrameInfo(), FI
);
3876 SDValue PtrOff
= DAG
.getIntPtrConstant(Offset
, DL
);
3878 DstAddr
= DAG
.getNode(ISD::ADD
, DL
, PtrVT
, StackPtr
, PtrOff
);
3879 DstInfo
= MachinePointerInfo::getStack(DAG
.getMachineFunction(),
3883 if (Outs
[i
].Flags
.isByVal()) {
3885 DAG
.getConstant(Outs
[i
].Flags
.getByValSize(), DL
, MVT::i64
);
3886 SDValue Cpy
= DAG
.getMemcpy(
3887 Chain
, DL
, DstAddr
, Arg
, SizeNode
, Outs
[i
].Flags
.getByValAlign(),
3888 /*isVol = */ false, /*AlwaysInline = */ false,
3889 /*isTailCall = */ false,
3890 DstInfo
, MachinePointerInfo());
3892 MemOpChains
.push_back(Cpy
);
3894 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
3895 // promoted to a legal register type i32, we should truncate Arg back to
3897 if (VA
.getValVT() == MVT::i1
|| VA
.getValVT() == MVT::i8
||
3898 VA
.getValVT() == MVT::i16
)
3899 Arg
= DAG
.getNode(ISD::TRUNCATE
, DL
, VA
.getValVT(), Arg
);
3901 SDValue Store
= DAG
.getStore(Chain
, DL
, Arg
, DstAddr
, DstInfo
);
3902 MemOpChains
.push_back(Store
);
3907 if (!MemOpChains
.empty())
3908 Chain
= DAG
.getNode(ISD::TokenFactor
, DL
, MVT::Other
, MemOpChains
);
3910 // Build a sequence of copy-to-reg nodes chained together with token chain
3911 // and flag operands which copy the outgoing args into the appropriate regs.
3913 for (auto &RegToPass
: RegsToPass
) {
3914 Chain
= DAG
.getCopyToReg(Chain
, DL
, RegToPass
.first
,
3915 RegToPass
.second
, InFlag
);
3916 InFlag
= Chain
.getValue(1);
3919 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3920 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3921 // node so that legalize doesn't hack it.
3922 if (auto *G
= dyn_cast
<GlobalAddressSDNode
>(Callee
)) {
3923 auto GV
= G
->getGlobal();
3924 if (Subtarget
->classifyGlobalFunctionReference(GV
, getTargetMachine()) ==
3925 AArch64II::MO_GOT
) {
3926 Callee
= DAG
.getTargetGlobalAddress(GV
, DL
, PtrVT
, 0, AArch64II::MO_GOT
);
3927 Callee
= DAG
.getNode(AArch64ISD::LOADgot
, DL
, PtrVT
, Callee
);
3928 } else if (Subtarget
->isTargetCOFF() && GV
->hasDLLImportStorageClass()) {
3929 assert(Subtarget
->isTargetWindows() &&
3930 "Windows is the only supported COFF target");
3931 Callee
= getGOT(G
, DAG
, AArch64II::MO_DLLIMPORT
);
3933 const GlobalValue
*GV
= G
->getGlobal();
3934 Callee
= DAG
.getTargetGlobalAddress(GV
, DL
, PtrVT
, 0, 0);
3936 } else if (auto *S
= dyn_cast
<ExternalSymbolSDNode
>(Callee
)) {
3937 if (getTargetMachine().getCodeModel() == CodeModel::Large
&&
3938 Subtarget
->isTargetMachO()) {
3939 const char *Sym
= S
->getSymbol();
3940 Callee
= DAG
.getTargetExternalSymbol(Sym
, PtrVT
, AArch64II::MO_GOT
);
3941 Callee
= DAG
.getNode(AArch64ISD::LOADgot
, DL
, PtrVT
, Callee
);
3943 const char *Sym
= S
->getSymbol();
3944 Callee
= DAG
.getTargetExternalSymbol(Sym
, PtrVT
, 0);
3948 // We don't usually want to end the call-sequence here because we would tidy
3949 // the frame up *after* the call, however in the ABI-changing tail-call case
3950 // we've carefully laid out the parameters so that when sp is reset they'll be
3951 // in the correct location.
3952 if (IsTailCall
&& !IsSibCall
) {
3953 Chain
= DAG
.getCALLSEQ_END(Chain
, DAG
.getIntPtrConstant(NumBytes
, DL
, true),
3954 DAG
.getIntPtrConstant(0, DL
, true), InFlag
, DL
);
3955 InFlag
= Chain
.getValue(1);
3958 std::vector
<SDValue
> Ops
;
3959 Ops
.push_back(Chain
);
3960 Ops
.push_back(Callee
);
3963 // Each tail call may have to adjust the stack by a different amount, so
3964 // this information must travel along with the operation for eventual
3965 // consumption by emitEpilogue.
3966 Ops
.push_back(DAG
.getTargetConstant(FPDiff
, DL
, MVT::i32
));
3969 // Add argument registers to the end of the list so that they are known live
3971 for (auto &RegToPass
: RegsToPass
)
3972 Ops
.push_back(DAG
.getRegister(RegToPass
.first
,
3973 RegToPass
.second
.getValueType()));
3975 // Check callee args/returns for SVE registers and set calling convention
3977 if (CallConv
== CallingConv::C
) {
3978 bool CalleeOutSVE
= any_of(Outs
, [](ISD::OutputArg
&Out
){
3979 return Out
.VT
.isScalableVector();
3981 bool CalleeInSVE
= any_of(Ins
, [](ISD::InputArg
&In
){
3982 return In
.VT
.isScalableVector();
3985 if (CalleeInSVE
|| CalleeOutSVE
)
3986 CallConv
= CallingConv::AArch64_SVE_VectorCall
;
3989 // Add a register mask operand representing the call-preserved registers.
3990 const uint32_t *Mask
;
3991 const AArch64RegisterInfo
*TRI
= Subtarget
->getRegisterInfo();
3993 // For 'this' returns, use the X0-preserving mask if applicable
3994 Mask
= TRI
->getThisReturnPreservedMask(MF
, CallConv
);
3996 IsThisReturn
= false;
3997 Mask
= TRI
->getCallPreservedMask(MF
, CallConv
);
4000 Mask
= TRI
->getCallPreservedMask(MF
, CallConv
);
4002 if (Subtarget
->hasCustomCallingConv())
4003 TRI
->UpdateCustomCallPreservedMask(MF
, &Mask
);
4005 if (TRI
->isAnyArgRegReserved(MF
))
4006 TRI
->emitReservedArgRegCallError(MF
);
4008 assert(Mask
&& "Missing call preserved mask for calling convention");
4009 Ops
.push_back(DAG
.getRegisterMask(Mask
));
4011 if (InFlag
.getNode())
4012 Ops
.push_back(InFlag
);
4014 SDVTList NodeTys
= DAG
.getVTList(MVT::Other
, MVT::Glue
);
4016 // If we're doing a tall call, use a TC_RETURN here rather than an
4017 // actual call instruction.
4019 MF
.getFrameInfo().setHasTailCall();
4020 return DAG
.getNode(AArch64ISD::TC_RETURN
, DL
, NodeTys
, Ops
);
4023 // Returns a chain and a flag for retval copy to use.
4024 Chain
= DAG
.getNode(AArch64ISD::CALL
, DL
, NodeTys
, Ops
);
4025 InFlag
= Chain
.getValue(1);
4027 uint64_t CalleePopBytes
=
4028 DoesCalleeRestoreStack(CallConv
, TailCallOpt
) ? alignTo(NumBytes
, 16) : 0;
4030 Chain
= DAG
.getCALLSEQ_END(Chain
, DAG
.getIntPtrConstant(NumBytes
, DL
, true),
4031 DAG
.getIntPtrConstant(CalleePopBytes
, DL
, true),
4034 InFlag
= Chain
.getValue(1);
4036 // Handle result values, copying them out of physregs into vregs that we
4038 return LowerCallResult(Chain
, InFlag
, CallConv
, IsVarArg
, Ins
, DL
, DAG
,
4039 InVals
, IsThisReturn
,
4040 IsThisReturn
? OutVals
[0] : SDValue());
4043 bool AArch64TargetLowering::CanLowerReturn(
4044 CallingConv::ID CallConv
, MachineFunction
&MF
, bool isVarArg
,
4045 const SmallVectorImpl
<ISD::OutputArg
> &Outs
, LLVMContext
&Context
) const {
4046 CCAssignFn
*RetCC
= CallConv
== CallingConv::WebKit_JS
4047 ? RetCC_AArch64_WebKit_JS
4048 : RetCC_AArch64_AAPCS
;
4049 SmallVector
<CCValAssign
, 16> RVLocs
;
4050 CCState
CCInfo(CallConv
, isVarArg
, MF
, RVLocs
, Context
);
4051 return CCInfo
.CheckReturn(Outs
, RetCC
);
4055 AArch64TargetLowering::LowerReturn(SDValue Chain
, CallingConv::ID CallConv
,
4057 const SmallVectorImpl
<ISD::OutputArg
> &Outs
,
4058 const SmallVectorImpl
<SDValue
> &OutVals
,
4059 const SDLoc
&DL
, SelectionDAG
&DAG
) const {
4060 auto &MF
= DAG
.getMachineFunction();
4061 auto *FuncInfo
= MF
.getInfo
<AArch64FunctionInfo
>();
4063 CCAssignFn
*RetCC
= CallConv
== CallingConv::WebKit_JS
4064 ? RetCC_AArch64_WebKit_JS
4065 : RetCC_AArch64_AAPCS
;
4066 SmallVector
<CCValAssign
, 16> RVLocs
;
4067 CCState
CCInfo(CallConv
, isVarArg
, DAG
.getMachineFunction(), RVLocs
,
4069 CCInfo
.AnalyzeReturn(Outs
, RetCC
);
4071 // Copy the result values into the output registers.
4073 SmallVector
<SDValue
, 4> RetOps(1, Chain
);
4074 for (unsigned i
= 0, realRVLocIdx
= 0; i
!= RVLocs
.size();
4075 ++i
, ++realRVLocIdx
) {
4076 CCValAssign
&VA
= RVLocs
[i
];
4077 assert(VA
.isRegLoc() && "Can only return in registers!");
4078 SDValue Arg
= OutVals
[realRVLocIdx
];
4080 switch (VA
.getLocInfo()) {
4082 llvm_unreachable("Unknown loc info!");
4083 case CCValAssign::Full
:
4084 if (Outs
[i
].ArgVT
== MVT::i1
) {
4085 // AAPCS requires i1 to be zero-extended to i8 by the producer of the
4086 // value. This is strictly redundant on Darwin (which uses "zeroext
4087 // i1"), but will be optimised out before ISel.
4088 Arg
= DAG
.getNode(ISD::TRUNCATE
, DL
, MVT::i1
, Arg
);
4089 Arg
= DAG
.getNode(ISD::ZERO_EXTEND
, DL
, VA
.getLocVT(), Arg
);
4092 case CCValAssign::BCvt
:
4093 Arg
= DAG
.getNode(ISD::BITCAST
, DL
, VA
.getLocVT(), Arg
);
4097 Chain
= DAG
.getCopyToReg(Chain
, DL
, VA
.getLocReg(), Arg
, Flag
);
4098 Flag
= Chain
.getValue(1);
4099 RetOps
.push_back(DAG
.getRegister(VA
.getLocReg(), VA
.getLocVT()));
4102 // Windows AArch64 ABIs require that for returning structs by value we copy
4103 // the sret argument into X0 for the return.
4104 // We saved the argument into a virtual register in the entry block,
4105 // so now we copy the value out and into X0.
4106 if (unsigned SRetReg
= FuncInfo
->getSRetReturnReg()) {
4107 SDValue Val
= DAG
.getCopyFromReg(RetOps
[0], DL
, SRetReg
,
4108 getPointerTy(MF
.getDataLayout()));
4110 unsigned RetValReg
= AArch64::X0
;
4111 Chain
= DAG
.getCopyToReg(Chain
, DL
, RetValReg
, Val
, Flag
);
4112 Flag
= Chain
.getValue(1);
4115 DAG
.getRegister(RetValReg
, getPointerTy(DAG
.getDataLayout())));
4118 const AArch64RegisterInfo
*TRI
= Subtarget
->getRegisterInfo();
4119 const MCPhysReg
*I
=
4120 TRI
->getCalleeSavedRegsViaCopy(&DAG
.getMachineFunction());
4123 if (AArch64::GPR64RegClass
.contains(*I
))
4124 RetOps
.push_back(DAG
.getRegister(*I
, MVT::i64
));
4125 else if (AArch64::FPR64RegClass
.contains(*I
))
4126 RetOps
.push_back(DAG
.getRegister(*I
, MVT::getFloatingPointVT(64)));
4128 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
4132 RetOps
[0] = Chain
; // Update chain.
4134 // Add the flag if we have it.
4136 RetOps
.push_back(Flag
);
4138 return DAG
.getNode(AArch64ISD::RET_FLAG
, DL
, MVT::Other
, RetOps
);
4141 //===----------------------------------------------------------------------===//
4142 // Other Lowering Code
4143 //===----------------------------------------------------------------------===//
4145 SDValue
AArch64TargetLowering::getTargetNode(GlobalAddressSDNode
*N
, EVT Ty
,
4147 unsigned Flag
) const {
4148 return DAG
.getTargetGlobalAddress(N
->getGlobal(), SDLoc(N
), Ty
,
4149 N
->getOffset(), Flag
);
4152 SDValue
AArch64TargetLowering::getTargetNode(JumpTableSDNode
*N
, EVT Ty
,
4154 unsigned Flag
) const {
4155 return DAG
.getTargetJumpTable(N
->getIndex(), Ty
, Flag
);
4158 SDValue
AArch64TargetLowering::getTargetNode(ConstantPoolSDNode
*N
, EVT Ty
,
4160 unsigned Flag
) const {
4161 return DAG
.getTargetConstantPool(N
->getConstVal(), Ty
, N
->getAlignment(),
4162 N
->getOffset(), Flag
);
4165 SDValue
AArch64TargetLowering::getTargetNode(BlockAddressSDNode
* N
, EVT Ty
,
4167 unsigned Flag
) const {
4168 return DAG
.getTargetBlockAddress(N
->getBlockAddress(), Ty
, 0, Flag
);
4172 template <class NodeTy
>
4173 SDValue
AArch64TargetLowering::getGOT(NodeTy
*N
, SelectionDAG
&DAG
,
4174 unsigned Flags
) const {
4175 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getGOT\n");
4177 EVT Ty
= getPointerTy(DAG
.getDataLayout());
4178 SDValue GotAddr
= getTargetNode(N
, Ty
, DAG
, AArch64II::MO_GOT
| Flags
);
4179 // FIXME: Once remat is capable of dealing with instructions with register
4180 // operands, expand this into two nodes instead of using a wrapper node.
4181 return DAG
.getNode(AArch64ISD::LOADgot
, DL
, Ty
, GotAddr
);
4184 // (wrapper %highest(sym), %higher(sym), %hi(sym), %lo(sym))
4185 template <class NodeTy
>
4186 SDValue
AArch64TargetLowering::getAddrLarge(NodeTy
*N
, SelectionDAG
&DAG
,
4187 unsigned Flags
) const {
4188 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrLarge\n");
4190 EVT Ty
= getPointerTy(DAG
.getDataLayout());
4191 const unsigned char MO_NC
= AArch64II::MO_NC
;
4193 AArch64ISD::WrapperLarge
, DL
, Ty
,
4194 getTargetNode(N
, Ty
, DAG
, AArch64II::MO_G3
| Flags
),
4195 getTargetNode(N
, Ty
, DAG
, AArch64II::MO_G2
| MO_NC
| Flags
),
4196 getTargetNode(N
, Ty
, DAG
, AArch64II::MO_G1
| MO_NC
| Flags
),
4197 getTargetNode(N
, Ty
, DAG
, AArch64II::MO_G0
| MO_NC
| Flags
));
4200 // (addlow (adrp %hi(sym)) %lo(sym))
4201 template <class NodeTy
>
4202 SDValue
AArch64TargetLowering::getAddr(NodeTy
*N
, SelectionDAG
&DAG
,
4203 unsigned Flags
) const {
4204 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddr\n");
4206 EVT Ty
= getPointerTy(DAG
.getDataLayout());
4207 SDValue Hi
= getTargetNode(N
, Ty
, DAG
, AArch64II::MO_PAGE
| Flags
);
4208 SDValue Lo
= getTargetNode(N
, Ty
, DAG
,
4209 AArch64II::MO_PAGEOFF
| AArch64II::MO_NC
| Flags
);
4210 SDValue ADRP
= DAG
.getNode(AArch64ISD::ADRP
, DL
, Ty
, Hi
);
4211 return DAG
.getNode(AArch64ISD::ADDlow
, DL
, Ty
, ADRP
, Lo
);
4215 template <class NodeTy
>
4216 SDValue
AArch64TargetLowering::getAddrTiny(NodeTy
*N
, SelectionDAG
&DAG
,
4217 unsigned Flags
) const {
4218 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrTiny\n");
4220 EVT Ty
= getPointerTy(DAG
.getDataLayout());
4221 SDValue Sym
= getTargetNode(N
, Ty
, DAG
, Flags
);
4222 return DAG
.getNode(AArch64ISD::ADR
, DL
, Ty
, Sym
);
4225 SDValue
AArch64TargetLowering::LowerGlobalAddress(SDValue Op
,
4226 SelectionDAG
&DAG
) const {
4227 GlobalAddressSDNode
*GN
= cast
<GlobalAddressSDNode
>(Op
);
4228 const GlobalValue
*GV
= GN
->getGlobal();
4229 unsigned OpFlags
= Subtarget
->ClassifyGlobalReference(GV
, getTargetMachine());
4231 if (OpFlags
!= AArch64II::MO_NO_FLAG
)
4232 assert(cast
<GlobalAddressSDNode
>(Op
)->getOffset() == 0 &&
4233 "unexpected offset in global node");
4235 // This also catches the large code model case for Darwin, and tiny code
4236 // model with got relocations.
4237 if ((OpFlags
& AArch64II::MO_GOT
) != 0) {
4238 return getGOT(GN
, DAG
, OpFlags
);
4242 if (getTargetMachine().getCodeModel() == CodeModel::Large
) {
4243 Result
= getAddrLarge(GN
, DAG
, OpFlags
);
4244 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny
) {
4245 Result
= getAddrTiny(GN
, DAG
, OpFlags
);
4247 Result
= getAddr(GN
, DAG
, OpFlags
);
4249 EVT PtrVT
= getPointerTy(DAG
.getDataLayout());
4251 if (OpFlags
& (AArch64II::MO_DLLIMPORT
| AArch64II::MO_COFFSTUB
))
4252 Result
= DAG
.getLoad(PtrVT
, DL
, DAG
.getEntryNode(), Result
,
4253 MachinePointerInfo::getGOT(DAG
.getMachineFunction()));
4257 /// Convert a TLS address reference into the correct sequence of loads
4258 /// and calls to compute the variable's address (for Darwin, currently) and
4259 /// return an SDValue containing the final node.
4261 /// Darwin only has one TLS scheme which must be capable of dealing with the
4262 /// fully general situation, in the worst case. This means:
4263 /// + "extern __thread" declaration.
4264 /// + Defined in a possibly unknown dynamic library.
4266 /// The general system is that each __thread variable has a [3 x i64] descriptor
4267 /// which contains information used by the runtime to calculate the address. The
4268 /// only part of this the compiler needs to know about is the first xword, which
4269 /// contains a function pointer that must be called with the address of the
4270 /// entire descriptor in "x0".
4272 /// Since this descriptor may be in a different unit, in general even the
4273 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
4275 /// adrp x0, _var@TLVPPAGE
4276 /// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor
4277 /// ldr x1, [x0] ; x1 contains 1st entry of descriptor,
4278 /// ; the function pointer
4279 /// blr x1 ; Uses descriptor address in x0
4280 /// ; Address of _var is now in x0.
4282 /// If the address of _var's descriptor *is* known to the linker, then it can
4283 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
4284 /// a slight efficiency gain.
4286 AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op
,
4287 SelectionDAG
&DAG
) const {
4288 assert(Subtarget
->isTargetDarwin() &&
4289 "This function expects a Darwin target");
4292 MVT PtrVT
= getPointerTy(DAG
.getDataLayout());
4293 const GlobalValue
*GV
= cast
<GlobalAddressSDNode
>(Op
)->getGlobal();
4296 DAG
.getTargetGlobalAddress(GV
, DL
, PtrVT
, 0, AArch64II::MO_TLS
);
4297 SDValue DescAddr
= DAG
.getNode(AArch64ISD::LOADgot
, DL
, PtrVT
, TLVPAddr
);
4299 // The first entry in the descriptor is a function pointer that we must call
4300 // to obtain the address of the variable.
4301 SDValue Chain
= DAG
.getEntryNode();
4302 SDValue FuncTLVGet
= DAG
.getLoad(
4303 MVT::i64
, DL
, Chain
, DescAddr
,
4304 MachinePointerInfo::getGOT(DAG
.getMachineFunction()),
4305 /* Alignment = */ 8,
4306 MachineMemOperand::MOInvariant
| MachineMemOperand::MODereferenceable
);
4307 Chain
= FuncTLVGet
.getValue(1);
4309 MachineFrameInfo
&MFI
= DAG
.getMachineFunction().getFrameInfo();
4310 MFI
.setAdjustsStack(true);
4312 // TLS calls preserve all registers except those that absolutely must be
4313 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
4315 const AArch64RegisterInfo
*TRI
= Subtarget
->getRegisterInfo();
4316 const uint32_t *Mask
= TRI
->getTLSCallPreservedMask();
4317 if (Subtarget
->hasCustomCallingConv())
4318 TRI
->UpdateCustomCallPreservedMask(DAG
.getMachineFunction(), &Mask
);
4320 // Finally, we can make the call. This is just a degenerate version of a
4321 // normal AArch64 call node: x0 takes the address of the descriptor, and
4322 // returns the address of the variable in this thread.
4323 Chain
= DAG
.getCopyToReg(Chain
, DL
, AArch64::X0
, DescAddr
, SDValue());
4325 DAG
.getNode(AArch64ISD::CALL
, DL
, DAG
.getVTList(MVT::Other
, MVT::Glue
),
4326 Chain
, FuncTLVGet
, DAG
.getRegister(AArch64::X0
, MVT::i64
),
4327 DAG
.getRegisterMask(Mask
), Chain
.getValue(1));
4328 return DAG
.getCopyFromReg(Chain
, DL
, AArch64::X0
, PtrVT
, Chain
.getValue(1));
4331 /// When accessing thread-local variables under either the general-dynamic or
4332 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
4333 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
4334 /// is a function pointer to carry out the resolution.
4336 /// The sequence is:
4337 /// adrp x0, :tlsdesc:var
4338 /// ldr x1, [x0, #:tlsdesc_lo12:var]
4339 /// add x0, x0, #:tlsdesc_lo12:var
4340 /// .tlsdesccall var
4342 /// (TPIDR_EL0 offset now in x0)
4344 /// The above sequence must be produced unscheduled, to enable the linker to
4345 /// optimize/relax this sequence.
4346 /// Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
4347 /// above sequence, and expanded really late in the compilation flow, to ensure
4348 /// the sequence is produced as per above.
4349 SDValue
AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr
,
4351 SelectionDAG
&DAG
) const {
4352 EVT PtrVT
= getPointerTy(DAG
.getDataLayout());
4354 SDValue Chain
= DAG
.getEntryNode();
4355 SDVTList NodeTys
= DAG
.getVTList(MVT::Other
, MVT::Glue
);
4358 DAG
.getNode(AArch64ISD::TLSDESC_CALLSEQ
, DL
, NodeTys
, {Chain
, SymAddr
});
4359 SDValue Glue
= Chain
.getValue(1);
4361 return DAG
.getCopyFromReg(Chain
, DL
, AArch64::X0
, PtrVT
, Glue
);
4365 AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op
,
4366 SelectionDAG
&DAG
) const {
4367 assert(Subtarget
->isTargetELF() && "This function expects an ELF target");
4368 if (getTargetMachine().getCodeModel() == CodeModel::Large
)
4369 report_fatal_error("ELF TLS only supported in small memory model");
4370 // Different choices can be made for the maximum size of the TLS area for a
4371 // module. For the small address model, the default TLS size is 16MiB and the
4372 // maximum TLS size is 4GiB.
4373 // FIXME: add -mtls-size command line option and make it control the 16MiB
4374 // vs. 4GiB code sequence generation.
4375 // FIXME: add tiny codemodel support. We currently generate the same code as
4376 // small, which may be larger than needed.
4377 const GlobalAddressSDNode
*GA
= cast
<GlobalAddressSDNode
>(Op
);
4379 TLSModel::Model Model
= getTargetMachine().getTLSModel(GA
->getGlobal());
4381 if (!EnableAArch64ELFLocalDynamicTLSGeneration
) {
4382 if (Model
== TLSModel::LocalDynamic
)
4383 Model
= TLSModel::GeneralDynamic
;
4387 EVT PtrVT
= getPointerTy(DAG
.getDataLayout());
4389 const GlobalValue
*GV
= GA
->getGlobal();
4391 SDValue ThreadBase
= DAG
.getNode(AArch64ISD::THREAD_POINTER
, DL
, PtrVT
);
4393 if (Model
== TLSModel::LocalExec
) {
4394 SDValue HiVar
= DAG
.getTargetGlobalAddress(
4395 GV
, DL
, PtrVT
, 0, AArch64II::MO_TLS
| AArch64II::MO_HI12
);
4396 SDValue LoVar
= DAG
.getTargetGlobalAddress(
4398 AArch64II::MO_TLS
| AArch64II::MO_PAGEOFF
| AArch64II::MO_NC
);
4400 SDValue TPWithOff_lo
=
4401 SDValue(DAG
.getMachineNode(AArch64::ADDXri
, DL
, PtrVT
, ThreadBase
,
4403 DAG
.getTargetConstant(0, DL
, MVT::i32
)),
4406 SDValue(DAG
.getMachineNode(AArch64::ADDXri
, DL
, PtrVT
, TPWithOff_lo
,
4408 DAG
.getTargetConstant(0, DL
, MVT::i32
)),
4411 } else if (Model
== TLSModel::InitialExec
) {
4412 TPOff
= DAG
.getTargetGlobalAddress(GV
, DL
, PtrVT
, 0, AArch64II::MO_TLS
);
4413 TPOff
= DAG
.getNode(AArch64ISD::LOADgot
, DL
, PtrVT
, TPOff
);
4414 } else if (Model
== TLSModel::LocalDynamic
) {
4415 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
4416 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
4417 // the beginning of the module's TLS region, followed by a DTPREL offset
4420 // These accesses will need deduplicating if there's more than one.
4421 AArch64FunctionInfo
*MFI
=
4422 DAG
.getMachineFunction().getInfo
<AArch64FunctionInfo
>();
4423 MFI
->incNumLocalDynamicTLSAccesses();
4425 // The call needs a relocation too for linker relaxation. It doesn't make
4426 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
4428 SDValue SymAddr
= DAG
.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT
,
4431 // Now we can calculate the offset from TPIDR_EL0 to this module's
4432 // thread-local area.
4433 TPOff
= LowerELFTLSDescCallSeq(SymAddr
, DL
, DAG
);
4435 // Now use :dtprel_whatever: operations to calculate this variable's offset
4436 // in its thread-storage area.
4437 SDValue HiVar
= DAG
.getTargetGlobalAddress(
4438 GV
, DL
, MVT::i64
, 0, AArch64II::MO_TLS
| AArch64II::MO_HI12
);
4439 SDValue LoVar
= DAG
.getTargetGlobalAddress(
4440 GV
, DL
, MVT::i64
, 0,
4441 AArch64II::MO_TLS
| AArch64II::MO_PAGEOFF
| AArch64II::MO_NC
);
4443 TPOff
= SDValue(DAG
.getMachineNode(AArch64::ADDXri
, DL
, PtrVT
, TPOff
, HiVar
,
4444 DAG
.getTargetConstant(0, DL
, MVT::i32
)),
4446 TPOff
= SDValue(DAG
.getMachineNode(AArch64::ADDXri
, DL
, PtrVT
, TPOff
, LoVar
,
4447 DAG
.getTargetConstant(0, DL
, MVT::i32
)),
4449 } else if (Model
== TLSModel::GeneralDynamic
) {
4450 // The call needs a relocation too for linker relaxation. It doesn't make
4451 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
4454 DAG
.getTargetGlobalAddress(GV
, DL
, PtrVT
, 0, AArch64II::MO_TLS
);
4456 // Finally we can make a call to calculate the offset from tpidr_el0.
4457 TPOff
= LowerELFTLSDescCallSeq(SymAddr
, DL
, DAG
);
4459 llvm_unreachable("Unsupported ELF TLS access model");
4461 return DAG
.getNode(ISD::ADD
, DL
, PtrVT
, ThreadBase
, TPOff
);
4465 AArch64TargetLowering::LowerWindowsGlobalTLSAddress(SDValue Op
,
4466 SelectionDAG
&DAG
) const {
4467 assert(Subtarget
->isTargetWindows() && "Windows specific TLS lowering");
4469 SDValue Chain
= DAG
.getEntryNode();
4470 EVT PtrVT
= getPointerTy(DAG
.getDataLayout());
4473 SDValue TEB
= DAG
.getRegister(AArch64::X18
, MVT::i64
);
4475 // Load the ThreadLocalStoragePointer from the TEB
4476 // A pointer to the TLS array is located at offset 0x58 from the TEB.
4478 DAG
.getNode(ISD::ADD
, DL
, PtrVT
, TEB
, DAG
.getIntPtrConstant(0x58, DL
));
4479 TLSArray
= DAG
.getLoad(PtrVT
, DL
, Chain
, TLSArray
, MachinePointerInfo());
4480 Chain
= TLSArray
.getValue(1);
4482 // Load the TLS index from the C runtime;
4483 // This does the same as getAddr(), but without having a GlobalAddressSDNode.
4484 // This also does the same as LOADgot, but using a generic i32 load,
4485 // while LOADgot only loads i64.
4486 SDValue TLSIndexHi
=
4487 DAG
.getTargetExternalSymbol("_tls_index", PtrVT
, AArch64II::MO_PAGE
);
4488 SDValue TLSIndexLo
= DAG
.getTargetExternalSymbol(
4489 "_tls_index", PtrVT
, AArch64II::MO_PAGEOFF
| AArch64II::MO_NC
);
4490 SDValue ADRP
= DAG
.getNode(AArch64ISD::ADRP
, DL
, PtrVT
, TLSIndexHi
);
4492 DAG
.getNode(AArch64ISD::ADDlow
, DL
, PtrVT
, ADRP
, TLSIndexLo
);
4493 TLSIndex
= DAG
.getLoad(MVT::i32
, DL
, Chain
, TLSIndex
, MachinePointerInfo());
4494 Chain
= TLSIndex
.getValue(1);
4496 // The pointer to the thread's TLS data area is at the TLS Index scaled by 8
4497 // offset into the TLSArray.
4498 TLSIndex
= DAG
.getNode(ISD::ZERO_EXTEND
, DL
, PtrVT
, TLSIndex
);
4499 SDValue Slot
= DAG
.getNode(ISD::SHL
, DL
, PtrVT
, TLSIndex
,
4500 DAG
.getConstant(3, DL
, PtrVT
));
4501 SDValue TLS
= DAG
.getLoad(PtrVT
, DL
, Chain
,
4502 DAG
.getNode(ISD::ADD
, DL
, PtrVT
, TLSArray
, Slot
),
4503 MachinePointerInfo());
4504 Chain
= TLS
.getValue(1);
4506 const GlobalAddressSDNode
*GA
= cast
<GlobalAddressSDNode
>(Op
);
4507 const GlobalValue
*GV
= GA
->getGlobal();
4508 SDValue TGAHi
= DAG
.getTargetGlobalAddress(
4509 GV
, DL
, PtrVT
, 0, AArch64II::MO_TLS
| AArch64II::MO_HI12
);
4510 SDValue TGALo
= DAG
.getTargetGlobalAddress(
4512 AArch64II::MO_TLS
| AArch64II::MO_PAGEOFF
| AArch64II::MO_NC
);
4514 // Add the offset from the start of the .tls section (section base).
4516 SDValue(DAG
.getMachineNode(AArch64::ADDXri
, DL
, PtrVT
, TLS
, TGAHi
,
4517 DAG
.getTargetConstant(0, DL
, MVT::i32
)),
4519 Addr
= DAG
.getNode(AArch64ISD::ADDlow
, DL
, PtrVT
, Addr
, TGALo
);
4523 SDValue
AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op
,
4524 SelectionDAG
&DAG
) const {
4525 const GlobalAddressSDNode
*GA
= cast
<GlobalAddressSDNode
>(Op
);
4526 if (DAG
.getTarget().useEmulatedTLS())
4527 return LowerToTLSEmulatedModel(GA
, DAG
);
4529 if (Subtarget
->isTargetDarwin())
4530 return LowerDarwinGlobalTLSAddress(Op
, DAG
);
4531 if (Subtarget
->isTargetELF())
4532 return LowerELFGlobalTLSAddress(Op
, DAG
);
4533 if (Subtarget
->isTargetWindows())
4534 return LowerWindowsGlobalTLSAddress(Op
, DAG
);
4536 llvm_unreachable("Unexpected platform trying to use TLS");
4539 SDValue
AArch64TargetLowering::LowerBR_CC(SDValue Op
, SelectionDAG
&DAG
) const {
4540 SDValue Chain
= Op
.getOperand(0);
4541 ISD::CondCode CC
= cast
<CondCodeSDNode
>(Op
.getOperand(1))->get();
4542 SDValue LHS
= Op
.getOperand(2);
4543 SDValue RHS
= Op
.getOperand(3);
4544 SDValue Dest
= Op
.getOperand(4);
4547 MachineFunction
&MF
= DAG
.getMachineFunction();
4548 // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
4549 // will not be produced, as they are conditional branch instructions that do
4551 bool ProduceNonFlagSettingCondBr
=
4552 !MF
.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening
);
4554 // Handle f128 first, since lowering it will result in comparing the return
4555 // value of a libcall against zero, which is just what the rest of LowerBR_CC
4556 // is expecting to deal with.
4557 if (LHS
.getValueType() == MVT::f128
) {
4558 softenSetCCOperands(DAG
, MVT::f128
, LHS
, RHS
, CC
, dl
, LHS
, RHS
);
4560 // If softenSetCCOperands returned a scalar, we need to compare the result
4561 // against zero to select between true and false values.
4562 if (!RHS
.getNode()) {
4563 RHS
= DAG
.getConstant(0, dl
, LHS
.getValueType());
4568 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
4570 if (isOverflowIntrOpRes(LHS
) && isOneConstant(RHS
) &&
4571 (CC
== ISD::SETEQ
|| CC
== ISD::SETNE
)) {
4572 // Only lower legal XALUO ops.
4573 if (!DAG
.getTargetLoweringInfo().isTypeLegal(LHS
->getValueType(0)))
4576 // The actual operation with overflow check.
4577 AArch64CC::CondCode OFCC
;
4578 SDValue Value
, Overflow
;
4579 std::tie(Value
, Overflow
) = getAArch64XALUOOp(OFCC
, LHS
.getValue(0), DAG
);
4581 if (CC
== ISD::SETNE
)
4582 OFCC
= getInvertedCondCode(OFCC
);
4583 SDValue CCVal
= DAG
.getConstant(OFCC
, dl
, MVT::i32
);
4585 return DAG
.getNode(AArch64ISD::BRCOND
, dl
, MVT::Other
, Chain
, Dest
, CCVal
,
4589 if (LHS
.getValueType().isInteger()) {
4590 assert((LHS
.getValueType() == RHS
.getValueType()) &&
4591 (LHS
.getValueType() == MVT::i32
|| LHS
.getValueType() == MVT::i64
));
4593 // If the RHS of the comparison is zero, we can potentially fold this
4594 // to a specialized branch.
4595 const ConstantSDNode
*RHSC
= dyn_cast
<ConstantSDNode
>(RHS
);
4596 if (RHSC
&& RHSC
->getZExtValue() == 0 && ProduceNonFlagSettingCondBr
) {
4597 if (CC
== ISD::SETEQ
) {
4598 // See if we can use a TBZ to fold in an AND as well.
4599 // TBZ has a smaller branch displacement than CBZ. If the offset is
4600 // out of bounds, a late MI-layer pass rewrites branches.
4601 // 403.gcc is an example that hits this case.
4602 if (LHS
.getOpcode() == ISD::AND
&&
4603 isa
<ConstantSDNode
>(LHS
.getOperand(1)) &&
4604 isPowerOf2_64(LHS
.getConstantOperandVal(1))) {
4605 SDValue Test
= LHS
.getOperand(0);
4606 uint64_t Mask
= LHS
.getConstantOperandVal(1);
4607 return DAG
.getNode(AArch64ISD::TBZ
, dl
, MVT::Other
, Chain
, Test
,
4608 DAG
.getConstant(Log2_64(Mask
), dl
, MVT::i64
),
4612 return DAG
.getNode(AArch64ISD::CBZ
, dl
, MVT::Other
, Chain
, LHS
, Dest
);
4613 } else if (CC
== ISD::SETNE
) {
4614 // See if we can use a TBZ to fold in an AND as well.
4615 // TBZ has a smaller branch displacement than CBZ. If the offset is
4616 // out of bounds, a late MI-layer pass rewrites branches.
4617 // 403.gcc is an example that hits this case.
4618 if (LHS
.getOpcode() == ISD::AND
&&
4619 isa
<ConstantSDNode
>(LHS
.getOperand(1)) &&
4620 isPowerOf2_64(LHS
.getConstantOperandVal(1))) {
4621 SDValue Test
= LHS
.getOperand(0);
4622 uint64_t Mask
= LHS
.getConstantOperandVal(1);
4623 return DAG
.getNode(AArch64ISD::TBNZ
, dl
, MVT::Other
, Chain
, Test
,
4624 DAG
.getConstant(Log2_64(Mask
), dl
, MVT::i64
),
4628 return DAG
.getNode(AArch64ISD::CBNZ
, dl
, MVT::Other
, Chain
, LHS
, Dest
);
4629 } else if (CC
== ISD::SETLT
&& LHS
.getOpcode() != ISD::AND
) {
4630 // Don't combine AND since emitComparison converts the AND to an ANDS
4631 // (a.k.a. TST) and the test in the test bit and branch instruction
4632 // becomes redundant. This would also increase register pressure.
4633 uint64_t Mask
= LHS
.getValueSizeInBits() - 1;
4634 return DAG
.getNode(AArch64ISD::TBNZ
, dl
, MVT::Other
, Chain
, LHS
,
4635 DAG
.getConstant(Mask
, dl
, MVT::i64
), Dest
);
4638 if (RHSC
&& RHSC
->getSExtValue() == -1 && CC
== ISD::SETGT
&&
4639 LHS
.getOpcode() != ISD::AND
&& ProduceNonFlagSettingCondBr
) {
4640 // Don't combine AND since emitComparison converts the AND to an ANDS
4641 // (a.k.a. TST) and the test in the test bit and branch instruction
4642 // becomes redundant. This would also increase register pressure.
4643 uint64_t Mask
= LHS
.getValueSizeInBits() - 1;
4644 return DAG
.getNode(AArch64ISD::TBZ
, dl
, MVT::Other
, Chain
, LHS
,
4645 DAG
.getConstant(Mask
, dl
, MVT::i64
), Dest
);
4649 SDValue Cmp
= getAArch64Cmp(LHS
, RHS
, CC
, CCVal
, DAG
, dl
);
4650 return DAG
.getNode(AArch64ISD::BRCOND
, dl
, MVT::Other
, Chain
, Dest
, CCVal
,
4654 assert(LHS
.getValueType() == MVT::f16
|| LHS
.getValueType() == MVT::f32
||
4655 LHS
.getValueType() == MVT::f64
);
4657 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4658 // clean. Some of them require two branches to implement.
4659 SDValue Cmp
= emitComparison(LHS
, RHS
, CC
, dl
, DAG
);
4660 AArch64CC::CondCode CC1
, CC2
;
4661 changeFPCCToAArch64CC(CC
, CC1
, CC2
);
4662 SDValue CC1Val
= DAG
.getConstant(CC1
, dl
, MVT::i32
);
4664 DAG
.getNode(AArch64ISD::BRCOND
, dl
, MVT::Other
, Chain
, Dest
, CC1Val
, Cmp
);
4665 if (CC2
!= AArch64CC::AL
) {
4666 SDValue CC2Val
= DAG
.getConstant(CC2
, dl
, MVT::i32
);
4667 return DAG
.getNode(AArch64ISD::BRCOND
, dl
, MVT::Other
, BR1
, Dest
, CC2Val
,
4674 SDValue
AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op
,
4675 SelectionDAG
&DAG
) const {
4676 EVT VT
= Op
.getValueType();
4679 SDValue In1
= Op
.getOperand(0);
4680 SDValue In2
= Op
.getOperand(1);
4681 EVT SrcVT
= In2
.getValueType();
4683 if (SrcVT
.bitsLT(VT
))
4684 In2
= DAG
.getNode(ISD::FP_EXTEND
, DL
, VT
, In2
);
4685 else if (SrcVT
.bitsGT(VT
))
4686 In2
= DAG
.getNode(ISD::FP_ROUND
, DL
, VT
, In2
, DAG
.getIntPtrConstant(0, DL
));
4690 SDValue VecVal1
, VecVal2
;
4692 auto setVecVal
= [&] (int Idx
) {
4693 if (!VT
.isVector()) {
4694 VecVal1
= DAG
.getTargetInsertSubreg(Idx
, DL
, VecVT
,
4695 DAG
.getUNDEF(VecVT
), In1
);
4696 VecVal2
= DAG
.getTargetInsertSubreg(Idx
, DL
, VecVT
,
4697 DAG
.getUNDEF(VecVT
), In2
);
4699 VecVal1
= DAG
.getNode(ISD::BITCAST
, DL
, VecVT
, In1
);
4700 VecVal2
= DAG
.getNode(ISD::BITCAST
, DL
, VecVT
, In2
);
4704 if (VT
== MVT::f32
|| VT
== MVT::v2f32
|| VT
== MVT::v4f32
) {
4705 VecVT
= (VT
== MVT::v2f32
? MVT::v2i32
: MVT::v4i32
);
4706 EltMask
= 0x80000000ULL
;
4707 setVecVal(AArch64::ssub
);
4708 } else if (VT
== MVT::f64
|| VT
== MVT::v2f64
) {
4711 // We want to materialize a mask with the high bit set, but the AdvSIMD
4712 // immediate moves cannot materialize that in a single instruction for
4713 // 64-bit elements. Instead, materialize zero and then negate it.
4716 setVecVal(AArch64::dsub
);
4717 } else if (VT
== MVT::f16
|| VT
== MVT::v4f16
|| VT
== MVT::v8f16
) {
4718 VecVT
= (VT
== MVT::v4f16
? MVT::v4i16
: MVT::v8i16
);
4719 EltMask
= 0x8000ULL
;
4720 setVecVal(AArch64::hsub
);
4722 llvm_unreachable("Invalid type for copysign!");
4725 SDValue BuildVec
= DAG
.getConstant(EltMask
, DL
, VecVT
);
4727 // If we couldn't materialize the mask above, then the mask vector will be
4728 // the zero vector, and we need to negate it here.
4729 if (VT
== MVT::f64
|| VT
== MVT::v2f64
) {
4730 BuildVec
= DAG
.getNode(ISD::BITCAST
, DL
, MVT::v2f64
, BuildVec
);
4731 BuildVec
= DAG
.getNode(ISD::FNEG
, DL
, MVT::v2f64
, BuildVec
);
4732 BuildVec
= DAG
.getNode(ISD::BITCAST
, DL
, MVT::v2i64
, BuildVec
);
4736 DAG
.getNode(AArch64ISD::BIT
, DL
, VecVT
, VecVal1
, VecVal2
, BuildVec
);
4739 return DAG
.getTargetExtractSubreg(AArch64::hsub
, DL
, VT
, Sel
);
4741 return DAG
.getTargetExtractSubreg(AArch64::ssub
, DL
, VT
, Sel
);
4742 else if (VT
== MVT::f64
)
4743 return DAG
.getTargetExtractSubreg(AArch64::dsub
, DL
, VT
, Sel
);
4745 return DAG
.getNode(ISD::BITCAST
, DL
, VT
, Sel
);
4748 SDValue
AArch64TargetLowering::LowerCTPOP(SDValue Op
, SelectionDAG
&DAG
) const {
4749 if (DAG
.getMachineFunction().getFunction().hasFnAttribute(
4750 Attribute::NoImplicitFloat
))
4753 if (!Subtarget
->hasNEON())
4756 // While there is no integer popcount instruction, it can
4757 // be more efficiently lowered to the following sequence that uses
4758 // AdvSIMD registers/instructions as long as the copies to/from
4759 // the AdvSIMD registers are cheap.
4760 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd
4761 // CNT V0.8B, V0.8B // 8xbyte pop-counts
4762 // ADDV B0, V0.8B // sum 8xbyte pop-counts
4763 // UMOV X0, V0.B[0] // copy byte result back to integer reg
4764 SDValue Val
= Op
.getOperand(0);
4766 EVT VT
= Op
.getValueType();
4768 if (VT
== MVT::i32
|| VT
== MVT::i64
) {
4770 Val
= DAG
.getNode(ISD::ZERO_EXTEND
, DL
, MVT::i64
, Val
);
4771 Val
= DAG
.getNode(ISD::BITCAST
, DL
, MVT::v8i8
, Val
);
4773 SDValue CtPop
= DAG
.getNode(ISD::CTPOP
, DL
, MVT::v8i8
, Val
);
4774 SDValue UaddLV
= DAG
.getNode(
4775 ISD::INTRINSIC_WO_CHAIN
, DL
, MVT::i32
,
4776 DAG
.getConstant(Intrinsic::aarch64_neon_uaddlv
, DL
, MVT::i32
), CtPop
);
4779 UaddLV
= DAG
.getNode(ISD::ZERO_EXTEND
, DL
, MVT::i64
, UaddLV
);
4783 assert((VT
== MVT::v1i64
|| VT
== MVT::v2i64
|| VT
== MVT::v2i32
||
4784 VT
== MVT::v4i32
|| VT
== MVT::v4i16
|| VT
== MVT::v8i16
) &&
4785 "Unexpected type for custom ctpop lowering");
4787 EVT VT8Bit
= VT
.is64BitVector() ? MVT::v8i8
: MVT::v16i8
;
4788 Val
= DAG
.getBitcast(VT8Bit
, Val
);
4789 Val
= DAG
.getNode(ISD::CTPOP
, DL
, VT8Bit
, Val
);
4791 // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
4792 unsigned EltSize
= 8;
4793 unsigned NumElts
= VT
.is64BitVector() ? 8 : 16;
4794 while (EltSize
!= VT
.getScalarSizeInBits()) {
4797 MVT WidenVT
= MVT::getVectorVT(MVT::getIntegerVT(EltSize
), NumElts
);
4799 ISD::INTRINSIC_WO_CHAIN
, DL
, WidenVT
,
4800 DAG
.getConstant(Intrinsic::aarch64_neon_uaddlp
, DL
, MVT::i32
), Val
);
4806 SDValue
AArch64TargetLowering::LowerSETCC(SDValue Op
, SelectionDAG
&DAG
) const {
4808 if (Op
.getValueType().isVector())
4809 return LowerVSETCC(Op
, DAG
);
4811 SDValue LHS
= Op
.getOperand(0);
4812 SDValue RHS
= Op
.getOperand(1);
4813 ISD::CondCode CC
= cast
<CondCodeSDNode
>(Op
.getOperand(2))->get();
4816 // We chose ZeroOrOneBooleanContents, so use zero and one.
4817 EVT VT
= Op
.getValueType();
4818 SDValue TVal
= DAG
.getConstant(1, dl
, VT
);
4819 SDValue FVal
= DAG
.getConstant(0, dl
, VT
);
4821 // Handle f128 first, since one possible outcome is a normal integer
4822 // comparison which gets picked up by the next if statement.
4823 if (LHS
.getValueType() == MVT::f128
) {
4824 softenSetCCOperands(DAG
, MVT::f128
, LHS
, RHS
, CC
, dl
, LHS
, RHS
);
4826 // If softenSetCCOperands returned a scalar, use it.
4827 if (!RHS
.getNode()) {
4828 assert(LHS
.getValueType() == Op
.getValueType() &&
4829 "Unexpected setcc expansion!");
4834 if (LHS
.getValueType().isInteger()) {
4837 getAArch64Cmp(LHS
, RHS
, ISD::getSetCCInverse(CC
, true), CCVal
, DAG
, dl
);
4839 // Note that we inverted the condition above, so we reverse the order of
4840 // the true and false operands here. This will allow the setcc to be
4841 // matched to a single CSINC instruction.
4842 return DAG
.getNode(AArch64ISD::CSEL
, dl
, VT
, FVal
, TVal
, CCVal
, Cmp
);
4845 // Now we know we're dealing with FP values.
4846 assert(LHS
.getValueType() == MVT::f16
|| LHS
.getValueType() == MVT::f32
||
4847 LHS
.getValueType() == MVT::f64
);
4849 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
4850 // and do the comparison.
4851 SDValue Cmp
= emitComparison(LHS
, RHS
, CC
, dl
, DAG
);
4853 AArch64CC::CondCode CC1
, CC2
;
4854 changeFPCCToAArch64CC(CC
, CC1
, CC2
);
4855 if (CC2
== AArch64CC::AL
) {
4856 changeFPCCToAArch64CC(ISD::getSetCCInverse(CC
, false), CC1
, CC2
);
4857 SDValue CC1Val
= DAG
.getConstant(CC1
, dl
, MVT::i32
);
4859 // Note that we inverted the condition above, so we reverse the order of
4860 // the true and false operands here. This will allow the setcc to be
4861 // matched to a single CSINC instruction.
4862 return DAG
.getNode(AArch64ISD::CSEL
, dl
, VT
, FVal
, TVal
, CC1Val
, Cmp
);
4864 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
4865 // totally clean. Some of them require two CSELs to implement. As is in
4866 // this case, we emit the first CSEL and then emit a second using the output
4867 // of the first as the RHS. We're effectively OR'ing the two CC's together.
4869 // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
4870 SDValue CC1Val
= DAG
.getConstant(CC1
, dl
, MVT::i32
);
4872 DAG
.getNode(AArch64ISD::CSEL
, dl
, VT
, TVal
, FVal
, CC1Val
, Cmp
);
4874 SDValue CC2Val
= DAG
.getConstant(CC2
, dl
, MVT::i32
);
4875 return DAG
.getNode(AArch64ISD::CSEL
, dl
, VT
, TVal
, CS1
, CC2Val
, Cmp
);
4879 SDValue
AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC
, SDValue LHS
,
4880 SDValue RHS
, SDValue TVal
,
4881 SDValue FVal
, const SDLoc
&dl
,
4882 SelectionDAG
&DAG
) const {
4883 // Handle f128 first, because it will result in a comparison of some RTLIB
4884 // call result against zero.
4885 if (LHS
.getValueType() == MVT::f128
) {
4886 softenSetCCOperands(DAG
, MVT::f128
, LHS
, RHS
, CC
, dl
, LHS
, RHS
);
4888 // If softenSetCCOperands returned a scalar, we need to compare the result
4889 // against zero to select between true and false values.
4890 if (!RHS
.getNode()) {
4891 RHS
= DAG
.getConstant(0, dl
, LHS
.getValueType());
4896 // Also handle f16, for which we need to do a f32 comparison.
4897 if (LHS
.getValueType() == MVT::f16
&& !Subtarget
->hasFullFP16()) {
4898 LHS
= DAG
.getNode(ISD::FP_EXTEND
, dl
, MVT::f32
, LHS
);
4899 RHS
= DAG
.getNode(ISD::FP_EXTEND
, dl
, MVT::f32
, RHS
);
4902 // Next, handle integers.
4903 if (LHS
.getValueType().isInteger()) {
4904 assert((LHS
.getValueType() == RHS
.getValueType()) &&
4905 (LHS
.getValueType() == MVT::i32
|| LHS
.getValueType() == MVT::i64
));
4907 unsigned Opcode
= AArch64ISD::CSEL
;
4909 // If both the TVal and the FVal are constants, see if we can swap them in
4910 // order to for a CSINV or CSINC out of them.
4911 ConstantSDNode
*CFVal
= dyn_cast
<ConstantSDNode
>(FVal
);
4912 ConstantSDNode
*CTVal
= dyn_cast
<ConstantSDNode
>(TVal
);
4914 if (CTVal
&& CFVal
&& CTVal
->isAllOnesValue() && CFVal
->isNullValue()) {
4915 std::swap(TVal
, FVal
);
4916 std::swap(CTVal
, CFVal
);
4917 CC
= ISD::getSetCCInverse(CC
, true);
4918 } else if (CTVal
&& CFVal
&& CTVal
->isOne() && CFVal
->isNullValue()) {
4919 std::swap(TVal
, FVal
);
4920 std::swap(CTVal
, CFVal
);
4921 CC
= ISD::getSetCCInverse(CC
, true);
4922 } else if (TVal
.getOpcode() == ISD::XOR
) {
4923 // If TVal is a NOT we want to swap TVal and FVal so that we can match
4924 // with a CSINV rather than a CSEL.
4925 if (isAllOnesConstant(TVal
.getOperand(1))) {
4926 std::swap(TVal
, FVal
);
4927 std::swap(CTVal
, CFVal
);
4928 CC
= ISD::getSetCCInverse(CC
, true);
4930 } else if (TVal
.getOpcode() == ISD::SUB
) {
4931 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
4932 // that we can match with a CSNEG rather than a CSEL.
4933 if (isNullConstant(TVal
.getOperand(0))) {
4934 std::swap(TVal
, FVal
);
4935 std::swap(CTVal
, CFVal
);
4936 CC
= ISD::getSetCCInverse(CC
, true);
4938 } else if (CTVal
&& CFVal
) {
4939 const int64_t TrueVal
= CTVal
->getSExtValue();
4940 const int64_t FalseVal
= CFVal
->getSExtValue();
4943 // If both TVal and FVal are constants, see if FVal is the
4944 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
4945 // instead of a CSEL in that case.
4946 if (TrueVal
== ~FalseVal
) {
4947 Opcode
= AArch64ISD::CSINV
;
4948 } else if (TrueVal
== -FalseVal
) {
4949 Opcode
= AArch64ISD::CSNEG
;
4950 } else if (TVal
.getValueType() == MVT::i32
) {
4951 // If our operands are only 32-bit wide, make sure we use 32-bit
4952 // arithmetic for the check whether we can use CSINC. This ensures that
4953 // the addition in the check will wrap around properly in case there is
4954 // an overflow (which would not be the case if we do the check with
4955 // 64-bit arithmetic).
4956 const uint32_t TrueVal32
= CTVal
->getZExtValue();
4957 const uint32_t FalseVal32
= CFVal
->getZExtValue();
4959 if ((TrueVal32
== FalseVal32
+ 1) || (TrueVal32
+ 1 == FalseVal32
)) {
4960 Opcode
= AArch64ISD::CSINC
;
4962 if (TrueVal32
> FalseVal32
) {
4966 // 64-bit check whether we can use CSINC.
4967 } else if ((TrueVal
== FalseVal
+ 1) || (TrueVal
+ 1 == FalseVal
)) {
4968 Opcode
= AArch64ISD::CSINC
;
4970 if (TrueVal
> FalseVal
) {
4975 // Swap TVal and FVal if necessary.
4977 std::swap(TVal
, FVal
);
4978 std::swap(CTVal
, CFVal
);
4979 CC
= ISD::getSetCCInverse(CC
, true);
4982 if (Opcode
!= AArch64ISD::CSEL
) {
4983 // Drop FVal since we can get its value by simply inverting/negating
4989 // Avoid materializing a constant when possible by reusing a known value in
4990 // a register. However, don't perform this optimization if the known value
4991 // is one, zero or negative one in the case of a CSEL. We can always
4992 // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the
4993 // FVal, respectively.
4994 ConstantSDNode
*RHSVal
= dyn_cast
<ConstantSDNode
>(RHS
);
4995 if (Opcode
== AArch64ISD::CSEL
&& RHSVal
&& !RHSVal
->isOne() &&
4996 !RHSVal
->isNullValue() && !RHSVal
->isAllOnesValue()) {
4997 AArch64CC::CondCode AArch64CC
= changeIntCCToAArch64CC(CC
);
4998 // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to
4999 // "a != C ? x : a" to avoid materializing C.
5000 if (CTVal
&& CTVal
== RHSVal
&& AArch64CC
== AArch64CC::EQ
)
5002 else if (CFVal
&& CFVal
== RHSVal
&& AArch64CC
== AArch64CC::NE
)
5004 } else if (Opcode
== AArch64ISD::CSNEG
&& RHSVal
&& RHSVal
->isOne()) {
5005 assert (CTVal
&& CFVal
&& "Expected constant operands for CSNEG.");
5006 // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to
5007 // avoid materializing C.
5008 AArch64CC::CondCode AArch64CC
= changeIntCCToAArch64CC(CC
);
5009 if (CTVal
== RHSVal
&& AArch64CC
== AArch64CC::EQ
) {
5010 Opcode
= AArch64ISD::CSINV
;
5012 FVal
= DAG
.getConstant(0, dl
, FVal
.getValueType());
5017 SDValue Cmp
= getAArch64Cmp(LHS
, RHS
, CC
, CCVal
, DAG
, dl
);
5018 EVT VT
= TVal
.getValueType();
5019 return DAG
.getNode(Opcode
, dl
, VT
, TVal
, FVal
, CCVal
, Cmp
);
5022 // Now we know we're dealing with FP values.
5023 assert(LHS
.getValueType() == MVT::f16
|| LHS
.getValueType() == MVT::f32
||
5024 LHS
.getValueType() == MVT::f64
);
5025 assert(LHS
.getValueType() == RHS
.getValueType());
5026 EVT VT
= TVal
.getValueType();
5027 SDValue Cmp
= emitComparison(LHS
, RHS
, CC
, dl
, DAG
);
5029 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
5030 // clean. Some of them require two CSELs to implement.
5031 AArch64CC::CondCode CC1
, CC2
;
5032 changeFPCCToAArch64CC(CC
, CC1
, CC2
);
5034 if (DAG
.getTarget().Options
.UnsafeFPMath
) {
5035 // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and
5036 // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0.
5037 ConstantFPSDNode
*RHSVal
= dyn_cast
<ConstantFPSDNode
>(RHS
);
5038 if (RHSVal
&& RHSVal
->isZero()) {
5039 ConstantFPSDNode
*CFVal
= dyn_cast
<ConstantFPSDNode
>(FVal
);
5040 ConstantFPSDNode
*CTVal
= dyn_cast
<ConstantFPSDNode
>(TVal
);
5042 if ((CC
== ISD::SETEQ
|| CC
== ISD::SETOEQ
|| CC
== ISD::SETUEQ
) &&
5043 CTVal
&& CTVal
->isZero() && TVal
.getValueType() == LHS
.getValueType())
5045 else if ((CC
== ISD::SETNE
|| CC
== ISD::SETONE
|| CC
== ISD::SETUNE
) &&
5046 CFVal
&& CFVal
->isZero() &&
5047 FVal
.getValueType() == LHS
.getValueType())
5052 // Emit first, and possibly only, CSEL.
5053 SDValue CC1Val
= DAG
.getConstant(CC1
, dl
, MVT::i32
);
5054 SDValue CS1
= DAG
.getNode(AArch64ISD::CSEL
, dl
, VT
, TVal
, FVal
, CC1Val
, Cmp
);
5056 // If we need a second CSEL, emit it, using the output of the first as the
5057 // RHS. We're effectively OR'ing the two CC's together.
5058 if (CC2
!= AArch64CC::AL
) {
5059 SDValue CC2Val
= DAG
.getConstant(CC2
, dl
, MVT::i32
);
5060 return DAG
.getNode(AArch64ISD::CSEL
, dl
, VT
, TVal
, CS1
, CC2Val
, Cmp
);
5063 // Otherwise, return the output of the first CSEL.
5067 SDValue
AArch64TargetLowering::LowerSELECT_CC(SDValue Op
,
5068 SelectionDAG
&DAG
) const {
5069 ISD::CondCode CC
= cast
<CondCodeSDNode
>(Op
.getOperand(4))->get();
5070 SDValue LHS
= Op
.getOperand(0);
5071 SDValue RHS
= Op
.getOperand(1);
5072 SDValue TVal
= Op
.getOperand(2);
5073 SDValue FVal
= Op
.getOperand(3);
5075 return LowerSELECT_CC(CC
, LHS
, RHS
, TVal
, FVal
, DL
, DAG
);
5078 SDValue
AArch64TargetLowering::LowerSELECT(SDValue Op
,
5079 SelectionDAG
&DAG
) const {
5080 SDValue CCVal
= Op
->getOperand(0);
5081 SDValue TVal
= Op
->getOperand(1);
5082 SDValue FVal
= Op
->getOperand(2);
5085 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
5087 if (isOverflowIntrOpRes(CCVal
)) {
5088 // Only lower legal XALUO ops.
5089 if (!DAG
.getTargetLoweringInfo().isTypeLegal(CCVal
->getValueType(0)))
5092 AArch64CC::CondCode OFCC
;
5093 SDValue Value
, Overflow
;
5094 std::tie(Value
, Overflow
) = getAArch64XALUOOp(OFCC
, CCVal
.getValue(0), DAG
);
5095 SDValue CCVal
= DAG
.getConstant(OFCC
, DL
, MVT::i32
);
5097 return DAG
.getNode(AArch64ISD::CSEL
, DL
, Op
.getValueType(), TVal
, FVal
,
5101 // Lower it the same way as we would lower a SELECT_CC node.
5104 if (CCVal
.getOpcode() == ISD::SETCC
) {
5105 LHS
= CCVal
.getOperand(0);
5106 RHS
= CCVal
.getOperand(1);
5107 CC
= cast
<CondCodeSDNode
>(CCVal
->getOperand(2))->get();
5110 RHS
= DAG
.getConstant(0, DL
, CCVal
.getValueType());
5113 return LowerSELECT_CC(CC
, LHS
, RHS
, TVal
, FVal
, DL
, DAG
);
5116 SDValue
AArch64TargetLowering::LowerJumpTable(SDValue Op
,
5117 SelectionDAG
&DAG
) const {
5118 // Jump table entries as PC relative offsets. No additional tweaking
5119 // is necessary here. Just get the address of the jump table.
5120 JumpTableSDNode
*JT
= cast
<JumpTableSDNode
>(Op
);
5122 if (getTargetMachine().getCodeModel() == CodeModel::Large
&&
5123 !Subtarget
->isTargetMachO()) {
5124 return getAddrLarge(JT
, DAG
);
5125 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny
) {
5126 return getAddrTiny(JT
, DAG
);
5128 return getAddr(JT
, DAG
);
5131 SDValue
AArch64TargetLowering::LowerBR_JT(SDValue Op
,
5132 SelectionDAG
&DAG
) const {
5133 // Jump table entries as PC relative offsets. No additional tweaking
5134 // is necessary here. Just get the address of the jump table.
5136 SDValue JT
= Op
.getOperand(1);
5137 SDValue Entry
= Op
.getOperand(2);
5138 int JTI
= cast
<JumpTableSDNode
>(JT
.getNode())->getIndex();
5141 DAG
.getMachineNode(AArch64::JumpTableDest32
, DL
, MVT::i64
, MVT::i64
, JT
,
5142 Entry
, DAG
.getTargetJumpTable(JTI
, MVT::i32
));
5143 return DAG
.getNode(ISD::BRIND
, DL
, MVT::Other
, Op
.getOperand(0),
5147 SDValue
AArch64TargetLowering::LowerConstantPool(SDValue Op
,
5148 SelectionDAG
&DAG
) const {
5149 ConstantPoolSDNode
*CP
= cast
<ConstantPoolSDNode
>(Op
);
5151 if (getTargetMachine().getCodeModel() == CodeModel::Large
) {
5152 // Use the GOT for the large code model on iOS.
5153 if (Subtarget
->isTargetMachO()) {
5154 return getGOT(CP
, DAG
);
5156 return getAddrLarge(CP
, DAG
);
5157 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny
) {
5158 return getAddrTiny(CP
, DAG
);
5160 return getAddr(CP
, DAG
);
5164 SDValue
AArch64TargetLowering::LowerBlockAddress(SDValue Op
,
5165 SelectionDAG
&DAG
) const {
5166 BlockAddressSDNode
*BA
= cast
<BlockAddressSDNode
>(Op
);
5167 if (getTargetMachine().getCodeModel() == CodeModel::Large
&&
5168 !Subtarget
->isTargetMachO()) {
5169 return getAddrLarge(BA
, DAG
);
5170 } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny
) {
5171 return getAddrTiny(BA
, DAG
);
5173 return getAddr(BA
, DAG
);
5176 SDValue
AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op
,
5177 SelectionDAG
&DAG
) const {
5178 AArch64FunctionInfo
*FuncInfo
=
5179 DAG
.getMachineFunction().getInfo
<AArch64FunctionInfo
>();
5182 SDValue FR
= DAG
.getFrameIndex(FuncInfo
->getVarArgsStackIndex(),
5183 getPointerTy(DAG
.getDataLayout()));
5184 const Value
*SV
= cast
<SrcValueSDNode
>(Op
.getOperand(2))->getValue();
5185 return DAG
.getStore(Op
.getOperand(0), DL
, FR
, Op
.getOperand(1),
5186 MachinePointerInfo(SV
));
5189 SDValue
AArch64TargetLowering::LowerWin64_VASTART(SDValue Op
,
5190 SelectionDAG
&DAG
) const {
5191 AArch64FunctionInfo
*FuncInfo
=
5192 DAG
.getMachineFunction().getInfo
<AArch64FunctionInfo
>();
5195 SDValue FR
= DAG
.getFrameIndex(FuncInfo
->getVarArgsGPRSize() > 0
5196 ? FuncInfo
->getVarArgsGPRIndex()
5197 : FuncInfo
->getVarArgsStackIndex(),
5198 getPointerTy(DAG
.getDataLayout()));
5199 const Value
*SV
= cast
<SrcValueSDNode
>(Op
.getOperand(2))->getValue();
5200 return DAG
.getStore(Op
.getOperand(0), DL
, FR
, Op
.getOperand(1),
5201 MachinePointerInfo(SV
));
5204 SDValue
AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op
,
5205 SelectionDAG
&DAG
) const {
5206 // The layout of the va_list struct is specified in the AArch64 Procedure Call
5207 // Standard, section B.3.
5208 MachineFunction
&MF
= DAG
.getMachineFunction();
5209 AArch64FunctionInfo
*FuncInfo
= MF
.getInfo
<AArch64FunctionInfo
>();
5210 auto PtrVT
= getPointerTy(DAG
.getDataLayout());
5213 SDValue Chain
= Op
.getOperand(0);
5214 SDValue VAList
= Op
.getOperand(1);
5215 const Value
*SV
= cast
<SrcValueSDNode
>(Op
.getOperand(2))->getValue();
5216 SmallVector
<SDValue
, 4> MemOps
;
5218 // void *__stack at offset 0
5219 SDValue Stack
= DAG
.getFrameIndex(FuncInfo
->getVarArgsStackIndex(), PtrVT
);
5220 MemOps
.push_back(DAG
.getStore(Chain
, DL
, Stack
, VAList
,
5221 MachinePointerInfo(SV
), /* Alignment = */ 8));
5223 // void *__gr_top at offset 8
5224 int GPRSize
= FuncInfo
->getVarArgsGPRSize();
5226 SDValue GRTop
, GRTopAddr
;
5229 DAG
.getNode(ISD::ADD
, DL
, PtrVT
, VAList
, DAG
.getConstant(8, DL
, PtrVT
));
5231 GRTop
= DAG
.getFrameIndex(FuncInfo
->getVarArgsGPRIndex(), PtrVT
);
5232 GRTop
= DAG
.getNode(ISD::ADD
, DL
, PtrVT
, GRTop
,
5233 DAG
.getConstant(GPRSize
, DL
, PtrVT
));
5235 MemOps
.push_back(DAG
.getStore(Chain
, DL
, GRTop
, GRTopAddr
,
5236 MachinePointerInfo(SV
, 8),
5237 /* Alignment = */ 8));
5240 // void *__vr_top at offset 16
5241 int FPRSize
= FuncInfo
->getVarArgsFPRSize();
5243 SDValue VRTop
, VRTopAddr
;
5244 VRTopAddr
= DAG
.getNode(ISD::ADD
, DL
, PtrVT
, VAList
,
5245 DAG
.getConstant(16, DL
, PtrVT
));
5247 VRTop
= DAG
.getFrameIndex(FuncInfo
->getVarArgsFPRIndex(), PtrVT
);
5248 VRTop
= DAG
.getNode(ISD::ADD
, DL
, PtrVT
, VRTop
,
5249 DAG
.getConstant(FPRSize
, DL
, PtrVT
));
5251 MemOps
.push_back(DAG
.getStore(Chain
, DL
, VRTop
, VRTopAddr
,
5252 MachinePointerInfo(SV
, 16),
5253 /* Alignment = */ 8));
5256 // int __gr_offs at offset 24
5257 SDValue GROffsAddr
=
5258 DAG
.getNode(ISD::ADD
, DL
, PtrVT
, VAList
, DAG
.getConstant(24, DL
, PtrVT
));
5259 MemOps
.push_back(DAG
.getStore(
5260 Chain
, DL
, DAG
.getConstant(-GPRSize
, DL
, MVT::i32
), GROffsAddr
,
5261 MachinePointerInfo(SV
, 24), /* Alignment = */ 4));
5263 // int __vr_offs at offset 28
5264 SDValue VROffsAddr
=
5265 DAG
.getNode(ISD::ADD
, DL
, PtrVT
, VAList
, DAG
.getConstant(28, DL
, PtrVT
));
5266 MemOps
.push_back(DAG
.getStore(
5267 Chain
, DL
, DAG
.getConstant(-FPRSize
, DL
, MVT::i32
), VROffsAddr
,
5268 MachinePointerInfo(SV
, 28), /* Alignment = */ 4));
5270 return DAG
.getNode(ISD::TokenFactor
, DL
, MVT::Other
, MemOps
);
5273 SDValue
AArch64TargetLowering::LowerVASTART(SDValue Op
,
5274 SelectionDAG
&DAG
) const {
5275 MachineFunction
&MF
= DAG
.getMachineFunction();
5277 if (Subtarget
->isCallingConvWin64(MF
.getFunction().getCallingConv()))
5278 return LowerWin64_VASTART(Op
, DAG
);
5279 else if (Subtarget
->isTargetDarwin())
5280 return LowerDarwin_VASTART(Op
, DAG
);
5282 return LowerAAPCS_VASTART(Op
, DAG
);
5285 SDValue
AArch64TargetLowering::LowerVACOPY(SDValue Op
,
5286 SelectionDAG
&DAG
) const {
5287 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
5290 unsigned VaListSize
=
5291 Subtarget
->isTargetDarwin() || Subtarget
->isTargetWindows() ? 8 : 32;
5292 const Value
*DestSV
= cast
<SrcValueSDNode
>(Op
.getOperand(3))->getValue();
5293 const Value
*SrcSV
= cast
<SrcValueSDNode
>(Op
.getOperand(4))->getValue();
5295 return DAG
.getMemcpy(Op
.getOperand(0), DL
, Op
.getOperand(1),
5297 DAG
.getConstant(VaListSize
, DL
, MVT::i32
),
5298 8, false, false, false, MachinePointerInfo(DestSV
),
5299 MachinePointerInfo(SrcSV
));
5302 SDValue
AArch64TargetLowering::LowerVAARG(SDValue Op
, SelectionDAG
&DAG
) const {
5303 assert(Subtarget
->isTargetDarwin() &&
5304 "automatic va_arg instruction only works on Darwin");
5306 const Value
*V
= cast
<SrcValueSDNode
>(Op
.getOperand(2))->getValue();
5307 EVT VT
= Op
.getValueType();
5309 SDValue Chain
= Op
.getOperand(0);
5310 SDValue Addr
= Op
.getOperand(1);
5311 unsigned Align
= Op
.getConstantOperandVal(3);
5312 auto PtrVT
= getPointerTy(DAG
.getDataLayout());
5314 SDValue VAList
= DAG
.getLoad(PtrVT
, DL
, Chain
, Addr
, MachinePointerInfo(V
));
5315 Chain
= VAList
.getValue(1);
5318 assert(((Align
& (Align
- 1)) == 0) && "Expected Align to be a power of 2");
5319 VAList
= DAG
.getNode(ISD::ADD
, DL
, PtrVT
, VAList
,
5320 DAG
.getConstant(Align
- 1, DL
, PtrVT
));
5321 VAList
= DAG
.getNode(ISD::AND
, DL
, PtrVT
, VAList
,
5322 DAG
.getConstant(-(int64_t)Align
, DL
, PtrVT
));
5325 Type
*ArgTy
= VT
.getTypeForEVT(*DAG
.getContext());
5326 uint64_t ArgSize
= DAG
.getDataLayout().getTypeAllocSize(ArgTy
);
5328 // Scalar integer and FP values smaller than 64 bits are implicitly extended
5329 // up to 64 bits. At the very least, we have to increase the striding of the
5330 // vaargs list to match this, and for FP values we need to introduce
5331 // FP_ROUND nodes as well.
5332 if (VT
.isInteger() && !VT
.isVector())
5334 bool NeedFPTrunc
= false;
5335 if (VT
.isFloatingPoint() && !VT
.isVector() && VT
!= MVT::f64
) {
5340 // Increment the pointer, VAList, to the next vaarg
5341 SDValue VANext
= DAG
.getNode(ISD::ADD
, DL
, PtrVT
, VAList
,
5342 DAG
.getConstant(ArgSize
, DL
, PtrVT
));
5343 // Store the incremented VAList to the legalized pointer
5345 DAG
.getStore(Chain
, DL
, VANext
, Addr
, MachinePointerInfo(V
));
5347 // Load the actual argument out of the pointer VAList
5349 // Load the value as an f64.
5351 DAG
.getLoad(MVT::f64
, DL
, APStore
, VAList
, MachinePointerInfo());
5352 // Round the value down to an f32.
5353 SDValue NarrowFP
= DAG
.getNode(ISD::FP_ROUND
, DL
, VT
, WideFP
.getValue(0),
5354 DAG
.getIntPtrConstant(1, DL
));
5355 SDValue Ops
[] = { NarrowFP
, WideFP
.getValue(1) };
5356 // Merge the rounded value with the chain output of the load.
5357 return DAG
.getMergeValues(Ops
, DL
);
5360 return DAG
.getLoad(VT
, DL
, APStore
, VAList
, MachinePointerInfo());
5363 SDValue
AArch64TargetLowering::LowerFRAMEADDR(SDValue Op
,
5364 SelectionDAG
&DAG
) const {
5365 MachineFrameInfo
&MFI
= DAG
.getMachineFunction().getFrameInfo();
5366 MFI
.setFrameAddressIsTaken(true);
5368 EVT VT
= Op
.getValueType();
5370 unsigned Depth
= cast
<ConstantSDNode
>(Op
.getOperand(0))->getZExtValue();
5372 DAG
.getCopyFromReg(DAG
.getEntryNode(), DL
, AArch64::FP
, VT
);
5374 FrameAddr
= DAG
.getLoad(VT
, DL
, DAG
.getEntryNode(), FrameAddr
,
5375 MachinePointerInfo());
5379 SDValue
AArch64TargetLowering::LowerSPONENTRY(SDValue Op
,
5380 SelectionDAG
&DAG
) const {
5381 MachineFrameInfo
&MFI
= DAG
.getMachineFunction().getFrameInfo();
5383 EVT VT
= getPointerTy(DAG
.getDataLayout());
5385 int FI
= MFI
.CreateFixedObject(4, 0, false);
5386 return DAG
.getFrameIndex(FI
, VT
);
5389 #define GET_REGISTER_MATCHER
5390 #include "AArch64GenAsmMatcher.inc"
5392 // FIXME? Maybe this could be a TableGen attribute on some registers and
5393 // this table could be generated automatically from RegInfo.
5394 unsigned AArch64TargetLowering::getRegisterByName(const char* RegName
, EVT VT
,
5395 SelectionDAG
&DAG
) const {
5396 unsigned Reg
= MatchRegisterName(RegName
);
5397 if (AArch64::X1
<= Reg
&& Reg
<= AArch64::X28
) {
5398 const MCRegisterInfo
*MRI
= Subtarget
->getRegisterInfo();
5399 unsigned DwarfRegNum
= MRI
->getDwarfRegNum(Reg
, false);
5400 if (!Subtarget
->isXRegisterReserved(DwarfRegNum
))
5405 report_fatal_error(Twine("Invalid register name \""
5406 + StringRef(RegName
) + "\"."));
5409 SDValue
AArch64TargetLowering::LowerADDROFRETURNADDR(SDValue Op
,
5410 SelectionDAG
&DAG
) const {
5411 DAG
.getMachineFunction().getFrameInfo().setFrameAddressIsTaken(true);
5413 EVT VT
= Op
.getValueType();
5417 DAG
.getCopyFromReg(DAG
.getEntryNode(), DL
, AArch64::FP
, VT
);
5418 SDValue Offset
= DAG
.getConstant(8, DL
, getPointerTy(DAG
.getDataLayout()));
5420 return DAG
.getNode(ISD::ADD
, DL
, VT
, FrameAddr
, Offset
);
5423 SDValue
AArch64TargetLowering::LowerRETURNADDR(SDValue Op
,
5424 SelectionDAG
&DAG
) const {
5425 MachineFunction
&MF
= DAG
.getMachineFunction();
5426 MachineFrameInfo
&MFI
= MF
.getFrameInfo();
5427 MFI
.setReturnAddressIsTaken(true);
5429 EVT VT
= Op
.getValueType();
5431 unsigned Depth
= cast
<ConstantSDNode
>(Op
.getOperand(0))->getZExtValue();
5433 SDValue FrameAddr
= LowerFRAMEADDR(Op
, DAG
);
5434 SDValue Offset
= DAG
.getConstant(8, DL
, getPointerTy(DAG
.getDataLayout()));
5435 return DAG
.getLoad(VT
, DL
, DAG
.getEntryNode(),
5436 DAG
.getNode(ISD::ADD
, DL
, VT
, FrameAddr
, Offset
),
5437 MachinePointerInfo());
5440 // Return LR, which contains the return address. Mark it an implicit live-in.
5441 unsigned Reg
= MF
.addLiveIn(AArch64::LR
, &AArch64::GPR64RegClass
);
5442 return DAG
.getCopyFromReg(DAG
.getEntryNode(), DL
, Reg
, VT
);
5445 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
5446 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
5447 SDValue
AArch64TargetLowering::LowerShiftRightParts(SDValue Op
,
5448 SelectionDAG
&DAG
) const {
5449 assert(Op
.getNumOperands() == 3 && "Not a double-shift!");
5450 EVT VT
= Op
.getValueType();
5451 unsigned VTBits
= VT
.getSizeInBits();
5453 SDValue ShOpLo
= Op
.getOperand(0);
5454 SDValue ShOpHi
= Op
.getOperand(1);
5455 SDValue ShAmt
= Op
.getOperand(2);
5456 unsigned Opc
= (Op
.getOpcode() == ISD::SRA_PARTS
) ? ISD::SRA
: ISD::SRL
;
5458 assert(Op
.getOpcode() == ISD::SRA_PARTS
|| Op
.getOpcode() == ISD::SRL_PARTS
);
5460 SDValue RevShAmt
= DAG
.getNode(ISD::SUB
, dl
, MVT::i64
,
5461 DAG
.getConstant(VTBits
, dl
, MVT::i64
), ShAmt
);
5462 SDValue HiBitsForLo
= DAG
.getNode(ISD::SHL
, dl
, VT
, ShOpHi
, RevShAmt
);
5464 // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
5465 // is "undef". We wanted 0, so CSEL it directly.
5466 SDValue Cmp
= emitComparison(ShAmt
, DAG
.getConstant(0, dl
, MVT::i64
),
5467 ISD::SETEQ
, dl
, DAG
);
5468 SDValue CCVal
= DAG
.getConstant(AArch64CC::EQ
, dl
, MVT::i32
);
5470 DAG
.getNode(AArch64ISD::CSEL
, dl
, VT
, DAG
.getConstant(0, dl
, MVT::i64
),
5471 HiBitsForLo
, CCVal
, Cmp
);
5473 SDValue ExtraShAmt
= DAG
.getNode(ISD::SUB
, dl
, MVT::i64
, ShAmt
,
5474 DAG
.getConstant(VTBits
, dl
, MVT::i64
));
5476 SDValue LoBitsForLo
= DAG
.getNode(ISD::SRL
, dl
, VT
, ShOpLo
, ShAmt
);
5477 SDValue LoForNormalShift
=
5478 DAG
.getNode(ISD::OR
, dl
, VT
, LoBitsForLo
, HiBitsForLo
);
5480 Cmp
= emitComparison(ExtraShAmt
, DAG
.getConstant(0, dl
, MVT::i64
), ISD::SETGE
,
5482 CCVal
= DAG
.getConstant(AArch64CC::GE
, dl
, MVT::i32
);
5483 SDValue LoForBigShift
= DAG
.getNode(Opc
, dl
, VT
, ShOpHi
, ExtraShAmt
);
5484 SDValue Lo
= DAG
.getNode(AArch64ISD::CSEL
, dl
, VT
, LoForBigShift
,
5485 LoForNormalShift
, CCVal
, Cmp
);
5487 // AArch64 shifts larger than the register width are wrapped rather than
5488 // clamped, so we can't just emit "hi >> x".
5489 SDValue HiForNormalShift
= DAG
.getNode(Opc
, dl
, VT
, ShOpHi
, ShAmt
);
5490 SDValue HiForBigShift
=
5492 ? DAG
.getNode(Opc
, dl
, VT
, ShOpHi
,
5493 DAG
.getConstant(VTBits
- 1, dl
, MVT::i64
))
5494 : DAG
.getConstant(0, dl
, VT
);
5495 SDValue Hi
= DAG
.getNode(AArch64ISD::CSEL
, dl
, VT
, HiForBigShift
,
5496 HiForNormalShift
, CCVal
, Cmp
);
5498 SDValue Ops
[2] = { Lo
, Hi
};
5499 return DAG
.getMergeValues(Ops
, dl
);
5502 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
5503 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
5504 SDValue
AArch64TargetLowering::LowerShiftLeftParts(SDValue Op
,
5505 SelectionDAG
&DAG
) const {
5506 assert(Op
.getNumOperands() == 3 && "Not a double-shift!");
5507 EVT VT
= Op
.getValueType();
5508 unsigned VTBits
= VT
.getSizeInBits();
5510 SDValue ShOpLo
= Op
.getOperand(0);
5511 SDValue ShOpHi
= Op
.getOperand(1);
5512 SDValue ShAmt
= Op
.getOperand(2);
5514 assert(Op
.getOpcode() == ISD::SHL_PARTS
);
5515 SDValue RevShAmt
= DAG
.getNode(ISD::SUB
, dl
, MVT::i64
,
5516 DAG
.getConstant(VTBits
, dl
, MVT::i64
), ShAmt
);
5517 SDValue LoBitsForHi
= DAG
.getNode(ISD::SRL
, dl
, VT
, ShOpLo
, RevShAmt
);
5519 // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
5520 // is "undef". We wanted 0, so CSEL it directly.
5521 SDValue Cmp
= emitComparison(ShAmt
, DAG
.getConstant(0, dl
, MVT::i64
),
5522 ISD::SETEQ
, dl
, DAG
);
5523 SDValue CCVal
= DAG
.getConstant(AArch64CC::EQ
, dl
, MVT::i32
);
5525 DAG
.getNode(AArch64ISD::CSEL
, dl
, VT
, DAG
.getConstant(0, dl
, MVT::i64
),
5526 LoBitsForHi
, CCVal
, Cmp
);
5528 SDValue ExtraShAmt
= DAG
.getNode(ISD::SUB
, dl
, MVT::i64
, ShAmt
,
5529 DAG
.getConstant(VTBits
, dl
, MVT::i64
));
5530 SDValue HiBitsForHi
= DAG
.getNode(ISD::SHL
, dl
, VT
, ShOpHi
, ShAmt
);
5531 SDValue HiForNormalShift
=
5532 DAG
.getNode(ISD::OR
, dl
, VT
, LoBitsForHi
, HiBitsForHi
);
5534 SDValue HiForBigShift
= DAG
.getNode(ISD::SHL
, dl
, VT
, ShOpLo
, ExtraShAmt
);
5536 Cmp
= emitComparison(ExtraShAmt
, DAG
.getConstant(0, dl
, MVT::i64
), ISD::SETGE
,
5538 CCVal
= DAG
.getConstant(AArch64CC::GE
, dl
, MVT::i32
);
5539 SDValue Hi
= DAG
.getNode(AArch64ISD::CSEL
, dl
, VT
, HiForBigShift
,
5540 HiForNormalShift
, CCVal
, Cmp
);
5542 // AArch64 shifts of larger than register sizes are wrapped rather than
5543 // clamped, so we can't just emit "lo << a" if a is too big.
5544 SDValue LoForBigShift
= DAG
.getConstant(0, dl
, VT
);
5545 SDValue LoForNormalShift
= DAG
.getNode(ISD::SHL
, dl
, VT
, ShOpLo
, ShAmt
);
5546 SDValue Lo
= DAG
.getNode(AArch64ISD::CSEL
, dl
, VT
, LoForBigShift
,
5547 LoForNormalShift
, CCVal
, Cmp
);
5549 SDValue Ops
[2] = { Lo
, Hi
};
5550 return DAG
.getMergeValues(Ops
, dl
);
5553 bool AArch64TargetLowering::isOffsetFoldingLegal(
5554 const GlobalAddressSDNode
*GA
) const {
5555 // Offsets are folded in the DAG combine rather than here so that we can
5556 // intelligently choose an offset based on the uses.
5560 bool AArch64TargetLowering::isFPImmLegal(const APFloat
&Imm
, EVT VT
,
5561 bool OptForSize
) const {
5562 bool IsLegal
= false;
5563 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit, 32-bit cases, and
5564 // 16-bit case when target has full fp16 support.
5565 // FIXME: We should be able to handle f128 as well with a clever lowering.
5566 const APInt ImmInt
= Imm
.bitcastToAPInt();
5568 IsLegal
= AArch64_AM::getFP64Imm(ImmInt
) != -1 || Imm
.isPosZero();
5569 else if (VT
== MVT::f32
)
5570 IsLegal
= AArch64_AM::getFP32Imm(ImmInt
) != -1 || Imm
.isPosZero();
5571 else if (VT
== MVT::f16
&& Subtarget
->hasFullFP16())
5572 IsLegal
= AArch64_AM::getFP16Imm(ImmInt
) != -1 || Imm
.isPosZero();
5573 // TODO: fmov h0, w0 is also legal, however on't have an isel pattern to
5574 // generate that fmov.
5576 // If we can not materialize in immediate field for fmov, check if the
5577 // value can be encoded as the immediate operand of a logical instruction.
5578 // The immediate value will be created with either MOVZ, MOVN, or ORR.
5579 if (!IsLegal
&& (VT
== MVT::f64
|| VT
== MVT::f32
)) {
5580 // The cost is actually exactly the same for mov+fmov vs. adrp+ldr;
5581 // however the mov+fmov sequence is always better because of the reduced
5582 // cache pressure. The timings are still the same if you consider
5583 // movw+movk+fmov vs. adrp+ldr (it's one instruction longer, but the
5584 // movw+movk is fused). So we limit up to 2 instrdduction at most.
5585 SmallVector
<AArch64_IMM::ImmInsnModel
, 4> Insn
;
5586 AArch64_IMM::expandMOVImm(ImmInt
.getZExtValue(), VT
.getSizeInBits(),
5588 unsigned Limit
= (OptForSize
? 1 : (Subtarget
->hasFuseLiterals() ? 5 : 2));
5589 IsLegal
= Insn
.size() <= Limit
;
5592 LLVM_DEBUG(dbgs() << (IsLegal
? "Legal " : "Illegal ") << VT
.getEVTString()
5593 << " imm value: "; Imm
.dump(););
5597 //===----------------------------------------------------------------------===//
5598 // AArch64 Optimization Hooks
5599 //===----------------------------------------------------------------------===//
5601 static SDValue
getEstimate(const AArch64Subtarget
*ST
, unsigned Opcode
,
5602 SDValue Operand
, SelectionDAG
&DAG
,
5604 EVT VT
= Operand
.getValueType();
5605 if (ST
->hasNEON() &&
5606 (VT
== MVT::f64
|| VT
== MVT::v1f64
|| VT
== MVT::v2f64
||
5607 VT
== MVT::f32
|| VT
== MVT::v1f32
||
5608 VT
== MVT::v2f32
|| VT
== MVT::v4f32
)) {
5609 if (ExtraSteps
== TargetLoweringBase::ReciprocalEstimate::Unspecified
)
5610 // For the reciprocal estimates, convergence is quadratic, so the number
5611 // of digits is doubled after each iteration. In ARMv8, the accuracy of
5612 // the initial estimate is 2^-8. Thus the number of extra steps to refine
5613 // the result for float (23 mantissa bits) is 2 and for double (52
5614 // mantissa bits) is 3.
5615 ExtraSteps
= VT
.getScalarType() == MVT::f64
? 3 : 2;
5617 return DAG
.getNode(Opcode
, SDLoc(Operand
), VT
, Operand
);
5623 SDValue
AArch64TargetLowering::getSqrtEstimate(SDValue Operand
,
5624 SelectionDAG
&DAG
, int Enabled
,
5627 bool Reciprocal
) const {
5628 if (Enabled
== ReciprocalEstimate::Enabled
||
5629 (Enabled
== ReciprocalEstimate::Unspecified
&& Subtarget
->useRSqrt()))
5630 if (SDValue Estimate
= getEstimate(Subtarget
, AArch64ISD::FRSQRTE
, Operand
,
5633 EVT VT
= Operand
.getValueType();
5636 Flags
.setAllowReassociation(true);
5638 // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2)
5639 // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N)
5640 for (int i
= ExtraSteps
; i
> 0; --i
) {
5641 SDValue Step
= DAG
.getNode(ISD::FMUL
, DL
, VT
, Estimate
, Estimate
,
5643 Step
= DAG
.getNode(AArch64ISD::FRSQRTS
, DL
, VT
, Operand
, Step
, Flags
);
5644 Estimate
= DAG
.getNode(ISD::FMUL
, DL
, VT
, Estimate
, Step
, Flags
);
5647 EVT CCVT
= getSetCCResultType(DAG
.getDataLayout(), *DAG
.getContext(),
5649 SDValue FPZero
= DAG
.getConstantFP(0.0, DL
, VT
);
5650 SDValue Eq
= DAG
.getSetCC(DL
, CCVT
, Operand
, FPZero
, ISD::SETEQ
);
5652 Estimate
= DAG
.getNode(ISD::FMUL
, DL
, VT
, Operand
, Estimate
, Flags
);
5653 // Correct the result if the operand is 0.0.
5654 Estimate
= DAG
.getNode(VT
.isVector() ? ISD::VSELECT
: ISD::SELECT
, DL
,
5655 VT
, Eq
, Operand
, Estimate
);
5665 SDValue
AArch64TargetLowering::getRecipEstimate(SDValue Operand
,
5666 SelectionDAG
&DAG
, int Enabled
,
5667 int &ExtraSteps
) const {
5668 if (Enabled
== ReciprocalEstimate::Enabled
)
5669 if (SDValue Estimate
= getEstimate(Subtarget
, AArch64ISD::FRECPE
, Operand
,
5672 EVT VT
= Operand
.getValueType();
5675 Flags
.setAllowReassociation(true);
5677 // Newton reciprocal iteration: E * (2 - X * E)
5678 // AArch64 reciprocal iteration instruction: (2 - M * N)
5679 for (int i
= ExtraSteps
; i
> 0; --i
) {
5680 SDValue Step
= DAG
.getNode(AArch64ISD::FRECPS
, DL
, VT
, Operand
,
5682 Estimate
= DAG
.getNode(ISD::FMUL
, DL
, VT
, Estimate
, Step
, Flags
);
5692 //===----------------------------------------------------------------------===//
5693 // AArch64 Inline Assembly Support
5694 //===----------------------------------------------------------------------===//
5696 // Table of Constraints
5697 // TODO: This is the current set of constraints supported by ARM for the
5698 // compiler, not all of them may make sense.
5700 // r - A general register
5701 // w - An FP/SIMD register of some size in the range v0-v31
5702 // x - An FP/SIMD register of some size in the range v0-v15
5703 // I - Constant that can be used with an ADD instruction
5704 // J - Constant that can be used with a SUB instruction
5705 // K - Constant that can be used with a 32-bit logical instruction
5706 // L - Constant that can be used with a 64-bit logical instruction
5707 // M - Constant that can be used as a 32-bit MOV immediate
5708 // N - Constant that can be used as a 64-bit MOV immediate
5709 // Q - A memory reference with base register and no offset
5710 // S - A symbolic address
5711 // Y - Floating point constant zero
5712 // Z - Integer constant zero
5714 // Note that general register operands will be output using their 64-bit x
5715 // register name, whatever the size of the variable, unless the asm operand
5716 // is prefixed by the %w modifier. Floating-point and SIMD register operands
5717 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
5719 const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT
) const {
5720 // At this point, we have to lower this constraint to something else, so we
5721 // lower it to an "r" or "w". However, by doing this we will force the result
5722 // to be in register, while the X constraint is much more permissive.
5724 // Although we are correct (we are free to emit anything, without
5725 // constraints), we might break use cases that would expect us to be more
5726 // efficient and emit something else.
5727 if (!Subtarget
->hasFPARMv8())
5730 if (ConstraintVT
.isFloatingPoint())
5733 if (ConstraintVT
.isVector() &&
5734 (ConstraintVT
.getSizeInBits() == 64 ||
5735 ConstraintVT
.getSizeInBits() == 128))
5741 /// getConstraintType - Given a constraint letter, return the type of
5742 /// constraint it is for this target.
5743 AArch64TargetLowering::ConstraintType
5744 AArch64TargetLowering::getConstraintType(StringRef Constraint
) const {
5745 if (Constraint
.size() == 1) {
5746 switch (Constraint
[0]) {
5752 return C_RegisterClass
;
5753 // An address with a single base register. Due to the way we
5754 // currently handle addresses it is the same as 'r'.
5767 case 'S': // A symbolic address
5771 return TargetLowering::getConstraintType(Constraint
);
5774 /// Examine constraint type and operand type and determine a weight value.
5775 /// This object must already have been set up with the operand type
5776 /// and the current alternative constraint selected.
5777 TargetLowering::ConstraintWeight
5778 AArch64TargetLowering::getSingleConstraintMatchWeight(
5779 AsmOperandInfo
&info
, const char *constraint
) const {
5780 ConstraintWeight weight
= CW_Invalid
;
5781 Value
*CallOperandVal
= info
.CallOperandVal
;
5782 // If we don't have a value, we can't do a match,
5783 // but allow it at the lowest weight.
5784 if (!CallOperandVal
)
5786 Type
*type
= CallOperandVal
->getType();
5787 // Look at the constraint type.
5788 switch (*constraint
) {
5790 weight
= TargetLowering::getSingleConstraintMatchWeight(info
, constraint
);
5795 if (type
->isFloatingPointTy() || type
->isVectorTy())
5796 weight
= CW_Register
;
5799 weight
= CW_Constant
;
5805 std::pair
<unsigned, const TargetRegisterClass
*>
5806 AArch64TargetLowering::getRegForInlineAsmConstraint(
5807 const TargetRegisterInfo
*TRI
, StringRef Constraint
, MVT VT
) const {
5808 if (Constraint
.size() == 1) {
5809 switch (Constraint
[0]) {
5811 if (VT
.getSizeInBits() == 64)
5812 return std::make_pair(0U, &AArch64::GPR64commonRegClass
);
5813 return std::make_pair(0U, &AArch64::GPR32commonRegClass
);
5815 if (!Subtarget
->hasFPARMv8())
5817 if (VT
.isScalableVector())
5818 return std::make_pair(0U, &AArch64::ZPRRegClass
);
5819 if (VT
.getSizeInBits() == 16)
5820 return std::make_pair(0U, &AArch64::FPR16RegClass
);
5821 if (VT
.getSizeInBits() == 32)
5822 return std::make_pair(0U, &AArch64::FPR32RegClass
);
5823 if (VT
.getSizeInBits() == 64)
5824 return std::make_pair(0U, &AArch64::FPR64RegClass
);
5825 if (VT
.getSizeInBits() == 128)
5826 return std::make_pair(0U, &AArch64::FPR128RegClass
);
5828 // The instructions that this constraint is designed for can
5829 // only take 128-bit registers so just use that regclass.
5831 if (!Subtarget
->hasFPARMv8())
5833 if (VT
.isScalableVector())
5834 return std::make_pair(0U, &AArch64::ZPR_4bRegClass
);
5835 if (VT
.getSizeInBits() == 128)
5836 return std::make_pair(0U, &AArch64::FPR128_loRegClass
);
5839 if (!Subtarget
->hasFPARMv8())
5841 if (VT
.isScalableVector())
5842 return std::make_pair(0U, &AArch64::ZPR_3bRegClass
);
5846 if (StringRef("{cc}").equals_lower(Constraint
))
5847 return std::make_pair(unsigned(AArch64::NZCV
), &AArch64::CCRRegClass
);
5849 // Use the default implementation in TargetLowering to convert the register
5850 // constraint into a member of a register class.
5851 std::pair
<unsigned, const TargetRegisterClass
*> Res
;
5852 Res
= TargetLowering::getRegForInlineAsmConstraint(TRI
, Constraint
, VT
);
5854 // Not found as a standard register?
5856 unsigned Size
= Constraint
.size();
5857 if ((Size
== 4 || Size
== 5) && Constraint
[0] == '{' &&
5858 tolower(Constraint
[1]) == 'v' && Constraint
[Size
- 1] == '}') {
5860 bool Failed
= Constraint
.slice(2, Size
- 1).getAsInteger(10, RegNo
);
5861 if (!Failed
&& RegNo
>= 0 && RegNo
<= 31) {
5862 // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size.
5863 // By default we'll emit v0-v31 for this unless there's a modifier where
5864 // we'll emit the correct register as well.
5865 if (VT
!= MVT::Other
&& VT
.getSizeInBits() == 64) {
5866 Res
.first
= AArch64::FPR64RegClass
.getRegister(RegNo
);
5867 Res
.second
= &AArch64::FPR64RegClass
;
5869 Res
.first
= AArch64::FPR128RegClass
.getRegister(RegNo
);
5870 Res
.second
= &AArch64::FPR128RegClass
;
5876 if (Res
.second
&& !Subtarget
->hasFPARMv8() &&
5877 !AArch64::GPR32allRegClass
.hasSubClassEq(Res
.second
) &&
5878 !AArch64::GPR64allRegClass
.hasSubClassEq(Res
.second
))
5879 return std::make_pair(0U, nullptr);
5884 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
5885 /// vector. If it is invalid, don't add anything to Ops.
5886 void AArch64TargetLowering::LowerAsmOperandForConstraint(
5887 SDValue Op
, std::string
&Constraint
, std::vector
<SDValue
> &Ops
,
5888 SelectionDAG
&DAG
) const {
5891 // Currently only support length 1 constraints.
5892 if (Constraint
.length() != 1)
5895 char ConstraintLetter
= Constraint
[0];
5896 switch (ConstraintLetter
) {
5900 // This set of constraints deal with valid constants for various instructions.
5901 // Validate and return a target constant for them if we can.
5903 // 'z' maps to xzr or wzr so it needs an input of 0.
5904 if (!isNullConstant(Op
))
5907 if (Op
.getValueType() == MVT::i64
)
5908 Result
= DAG
.getRegister(AArch64::XZR
, MVT::i64
);
5910 Result
= DAG
.getRegister(AArch64::WZR
, MVT::i32
);
5914 // An absolute symbolic address or label reference.
5915 if (const GlobalAddressSDNode
*GA
= dyn_cast
<GlobalAddressSDNode
>(Op
)) {
5916 Result
= DAG
.getTargetGlobalAddress(GA
->getGlobal(), SDLoc(Op
),
5917 GA
->getValueType(0));
5918 } else if (const BlockAddressSDNode
*BA
=
5919 dyn_cast
<BlockAddressSDNode
>(Op
)) {
5921 DAG
.getTargetBlockAddress(BA
->getBlockAddress(), BA
->getValueType(0));
5922 } else if (const ExternalSymbolSDNode
*ES
=
5923 dyn_cast
<ExternalSymbolSDNode
>(Op
)) {
5925 DAG
.getTargetExternalSymbol(ES
->getSymbol(), ES
->getValueType(0));
5937 ConstantSDNode
*C
= dyn_cast
<ConstantSDNode
>(Op
);
5941 // Grab the value and do some validation.
5942 uint64_t CVal
= C
->getZExtValue();
5943 switch (ConstraintLetter
) {
5944 // The I constraint applies only to simple ADD or SUB immediate operands:
5945 // i.e. 0 to 4095 with optional shift by 12
5946 // The J constraint applies only to ADD or SUB immediates that would be
5947 // valid when negated, i.e. if [an add pattern] were to be output as a SUB
5948 // instruction [or vice versa], in other words -1 to -4095 with optional
5949 // left shift by 12.
5951 if (isUInt
<12>(CVal
) || isShiftedUInt
<12, 12>(CVal
))
5955 uint64_t NVal
= -C
->getSExtValue();
5956 if (isUInt
<12>(NVal
) || isShiftedUInt
<12, 12>(NVal
)) {
5957 CVal
= C
->getSExtValue();
5962 // The K and L constraints apply *only* to logical immediates, including
5963 // what used to be the MOVI alias for ORR (though the MOVI alias has now
5964 // been removed and MOV should be used). So these constraints have to
5965 // distinguish between bit patterns that are valid 32-bit or 64-bit
5966 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
5967 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
5970 if (AArch64_AM::isLogicalImmediate(CVal
, 32))
5974 if (AArch64_AM::isLogicalImmediate(CVal
, 64))
5977 // The M and N constraints are a superset of K and L respectively, for use
5978 // with the MOV (immediate) alias. As well as the logical immediates they
5979 // also match 32 or 64-bit immediates that can be loaded either using a
5980 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
5981 // (M) or 64-bit 0x1234000000000000 (N) etc.
5982 // As a note some of this code is liberally stolen from the asm parser.
5984 if (!isUInt
<32>(CVal
))
5986 if (AArch64_AM::isLogicalImmediate(CVal
, 32))
5988 if ((CVal
& 0xFFFF) == CVal
)
5990 if ((CVal
& 0xFFFF0000ULL
) == CVal
)
5992 uint64_t NCVal
= ~(uint32_t)CVal
;
5993 if ((NCVal
& 0xFFFFULL
) == NCVal
)
5995 if ((NCVal
& 0xFFFF0000ULL
) == NCVal
)
6000 if (AArch64_AM::isLogicalImmediate(CVal
, 64))
6002 if ((CVal
& 0xFFFFULL
) == CVal
)
6004 if ((CVal
& 0xFFFF0000ULL
) == CVal
)
6006 if ((CVal
& 0xFFFF00000000ULL
) == CVal
)
6008 if ((CVal
& 0xFFFF000000000000ULL
) == CVal
)
6010 uint64_t NCVal
= ~CVal
;
6011 if ((NCVal
& 0xFFFFULL
) == NCVal
)
6013 if ((NCVal
& 0xFFFF0000ULL
) == NCVal
)
6015 if ((NCVal
& 0xFFFF00000000ULL
) == NCVal
)
6017 if ((NCVal
& 0xFFFF000000000000ULL
) == NCVal
)
6025 // All assembler immediates are 64-bit integers.
6026 Result
= DAG
.getTargetConstant(CVal
, SDLoc(Op
), MVT::i64
);
6030 if (Result
.getNode()) {
6031 Ops
.push_back(Result
);
6035 return TargetLowering::LowerAsmOperandForConstraint(Op
, Constraint
, Ops
, DAG
);
6038 //===----------------------------------------------------------------------===//
6039 // AArch64 Advanced SIMD Support
6040 //===----------------------------------------------------------------------===//
6042 /// WidenVector - Given a value in the V64 register class, produce the
6043 /// equivalent value in the V128 register class.
6044 static SDValue
WidenVector(SDValue V64Reg
, SelectionDAG
&DAG
) {
6045 EVT VT
= V64Reg
.getValueType();
6046 unsigned NarrowSize
= VT
.getVectorNumElements();
6047 MVT EltTy
= VT
.getVectorElementType().getSimpleVT();
6048 MVT WideTy
= MVT::getVectorVT(EltTy
, 2 * NarrowSize
);
6051 return DAG
.getNode(ISD::INSERT_SUBVECTOR
, DL
, WideTy
, DAG
.getUNDEF(WideTy
),
6052 V64Reg
, DAG
.getConstant(0, DL
, MVT::i32
));
6055 /// getExtFactor - Determine the adjustment factor for the position when
6056 /// generating an "extract from vector registers" instruction.
6057 static unsigned getExtFactor(SDValue
&V
) {
6058 EVT EltType
= V
.getValueType().getVectorElementType();
6059 return EltType
.getSizeInBits() / 8;
6062 /// NarrowVector - Given a value in the V128 register class, produce the
6063 /// equivalent value in the V64 register class.
6064 static SDValue
NarrowVector(SDValue V128Reg
, SelectionDAG
&DAG
) {
6065 EVT VT
= V128Reg
.getValueType();
6066 unsigned WideSize
= VT
.getVectorNumElements();
6067 MVT EltTy
= VT
.getVectorElementType().getSimpleVT();
6068 MVT NarrowTy
= MVT::getVectorVT(EltTy
, WideSize
/ 2);
6071 return DAG
.getTargetExtractSubreg(AArch64::dsub
, DL
, NarrowTy
, V128Reg
);
6074 // Gather data to see if the operation can be modelled as a
6075 // shuffle in combination with VEXTs.
6076 SDValue
AArch64TargetLowering::ReconstructShuffle(SDValue Op
,
6077 SelectionDAG
&DAG
) const {
6078 assert(Op
.getOpcode() == ISD::BUILD_VECTOR
&& "Unknown opcode!");
6079 LLVM_DEBUG(dbgs() << "AArch64TargetLowering::ReconstructShuffle\n");
6081 EVT VT
= Op
.getValueType();
6082 unsigned NumElts
= VT
.getVectorNumElements();
6084 struct ShuffleSourceInfo
{
6089 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
6090 // be compatible with the shuffle we intend to construct. As a result
6091 // ShuffleVec will be some sliding window into the original Vec.
6094 // Code should guarantee that element i in Vec starts at element "WindowBase
6095 // + i * WindowScale in ShuffleVec".
6099 ShuffleSourceInfo(SDValue Vec
)
6100 : Vec(Vec
), MinElt(std::numeric_limits
<unsigned>::max()), MaxElt(0),
6101 ShuffleVec(Vec
), WindowBase(0), WindowScale(1) {}
6103 bool operator ==(SDValue OtherVec
) { return Vec
== OtherVec
; }
6106 // First gather all vectors used as an immediate source for this BUILD_VECTOR
6108 SmallVector
<ShuffleSourceInfo
, 2> Sources
;
6109 for (unsigned i
= 0; i
< NumElts
; ++i
) {
6110 SDValue V
= Op
.getOperand(i
);
6113 else if (V
.getOpcode() != ISD::EXTRACT_VECTOR_ELT
||
6114 !isa
<ConstantSDNode
>(V
.getOperand(1))) {
6116 dbgs() << "Reshuffle failed: "
6117 "a shuffle can only come from building a vector from "
6118 "various elements of other vectors, provided their "
6119 "indices are constant\n");
6123 // Add this element source to the list if it's not already there.
6124 SDValue SourceVec
= V
.getOperand(0);
6125 auto Source
= find(Sources
, SourceVec
);
6126 if (Source
== Sources
.end())
6127 Source
= Sources
.insert(Sources
.end(), ShuffleSourceInfo(SourceVec
));
6129 // Update the minimum and maximum lane number seen.
6130 unsigned EltNo
= cast
<ConstantSDNode
>(V
.getOperand(1))->getZExtValue();
6131 Source
->MinElt
= std::min(Source
->MinElt
, EltNo
);
6132 Source
->MaxElt
= std::max(Source
->MaxElt
, EltNo
);
6135 if (Sources
.size() > 2) {
6137 dbgs() << "Reshuffle failed: currently only do something sane when at "
6138 "most two source vectors are involved\n");
6142 // Find out the smallest element size among result and two sources, and use
6143 // it as element size to build the shuffle_vector.
6144 EVT SmallestEltTy
= VT
.getVectorElementType();
6145 for (auto &Source
: Sources
) {
6146 EVT SrcEltTy
= Source
.Vec
.getValueType().getVectorElementType();
6147 if (SrcEltTy
.bitsLT(SmallestEltTy
)) {
6148 SmallestEltTy
= SrcEltTy
;
6151 unsigned ResMultiplier
=
6152 VT
.getScalarSizeInBits() / SmallestEltTy
.getSizeInBits();
6153 NumElts
= VT
.getSizeInBits() / SmallestEltTy
.getSizeInBits();
6154 EVT ShuffleVT
= EVT::getVectorVT(*DAG
.getContext(), SmallestEltTy
, NumElts
);
6156 // If the source vector is too wide or too narrow, we may nevertheless be able
6157 // to construct a compatible shuffle either by concatenating it with UNDEF or
6158 // extracting a suitable range of elements.
6159 for (auto &Src
: Sources
) {
6160 EVT SrcVT
= Src
.ShuffleVec
.getValueType();
6162 if (SrcVT
.getSizeInBits() == VT
.getSizeInBits())
6165 // This stage of the search produces a source with the same element type as
6166 // the original, but with a total width matching the BUILD_VECTOR output.
6167 EVT EltVT
= SrcVT
.getVectorElementType();
6168 unsigned NumSrcElts
= VT
.getSizeInBits() / EltVT
.getSizeInBits();
6169 EVT DestVT
= EVT::getVectorVT(*DAG
.getContext(), EltVT
, NumSrcElts
);
6171 if (SrcVT
.getSizeInBits() < VT
.getSizeInBits()) {
6172 assert(2 * SrcVT
.getSizeInBits() == VT
.getSizeInBits());
6173 // We can pad out the smaller vector for free, so if it's part of a
6176 DAG
.getNode(ISD::CONCAT_VECTORS
, dl
, DestVT
, Src
.ShuffleVec
,
6177 DAG
.getUNDEF(Src
.ShuffleVec
.getValueType()));
6181 assert(SrcVT
.getSizeInBits() == 2 * VT
.getSizeInBits());
6183 if (Src
.MaxElt
- Src
.MinElt
>= NumSrcElts
) {
6185 dbgs() << "Reshuffle failed: span too large for a VEXT to cope\n");
6189 if (Src
.MinElt
>= NumSrcElts
) {
6190 // The extraction can just take the second half
6192 DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, dl
, DestVT
, Src
.ShuffleVec
,
6193 DAG
.getConstant(NumSrcElts
, dl
, MVT::i64
));
6194 Src
.WindowBase
= -NumSrcElts
;
6195 } else if (Src
.MaxElt
< NumSrcElts
) {
6196 // The extraction can just take the first half
6198 DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, dl
, DestVT
, Src
.ShuffleVec
,
6199 DAG
.getConstant(0, dl
, MVT::i64
));
6201 // An actual VEXT is needed
6203 DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, dl
, DestVT
, Src
.ShuffleVec
,
6204 DAG
.getConstant(0, dl
, MVT::i64
));
6206 DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, dl
, DestVT
, Src
.ShuffleVec
,
6207 DAG
.getConstant(NumSrcElts
, dl
, MVT::i64
));
6208 unsigned Imm
= Src
.MinElt
* getExtFactor(VEXTSrc1
);
6210 Src
.ShuffleVec
= DAG
.getNode(AArch64ISD::EXT
, dl
, DestVT
, VEXTSrc1
,
6212 DAG
.getConstant(Imm
, dl
, MVT::i32
));
6213 Src
.WindowBase
= -Src
.MinElt
;
6217 // Another possible incompatibility occurs from the vector element types. We
6218 // can fix this by bitcasting the source vectors to the same type we intend
6220 for (auto &Src
: Sources
) {
6221 EVT SrcEltTy
= Src
.ShuffleVec
.getValueType().getVectorElementType();
6222 if (SrcEltTy
== SmallestEltTy
)
6224 assert(ShuffleVT
.getVectorElementType() == SmallestEltTy
);
6225 Src
.ShuffleVec
= DAG
.getNode(ISD::BITCAST
, dl
, ShuffleVT
, Src
.ShuffleVec
);
6226 Src
.WindowScale
= SrcEltTy
.getSizeInBits() / SmallestEltTy
.getSizeInBits();
6227 Src
.WindowBase
*= Src
.WindowScale
;
6230 // Final sanity check before we try to actually produce a shuffle.
6231 LLVM_DEBUG(for (auto Src
6233 assert(Src
.ShuffleVec
.getValueType() == ShuffleVT
););
6235 // The stars all align, our next step is to produce the mask for the shuffle.
6236 SmallVector
<int, 8> Mask(ShuffleVT
.getVectorNumElements(), -1);
6237 int BitsPerShuffleLane
= ShuffleVT
.getScalarSizeInBits();
6238 for (unsigned i
= 0; i
< VT
.getVectorNumElements(); ++i
) {
6239 SDValue Entry
= Op
.getOperand(i
);
6240 if (Entry
.isUndef())
6243 auto Src
= find(Sources
, Entry
.getOperand(0));
6244 int EltNo
= cast
<ConstantSDNode
>(Entry
.getOperand(1))->getSExtValue();
6246 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
6247 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
6249 EVT OrigEltTy
= Entry
.getOperand(0).getValueType().getVectorElementType();
6251 std::min(OrigEltTy
.getSizeInBits(), VT
.getScalarSizeInBits());
6252 int LanesDefined
= BitsDefined
/ BitsPerShuffleLane
;
6254 // This source is expected to fill ResMultiplier lanes of the final shuffle,
6255 // starting at the appropriate offset.
6256 int *LaneMask
= &Mask
[i
* ResMultiplier
];
6258 int ExtractBase
= EltNo
* Src
->WindowScale
+ Src
->WindowBase
;
6259 ExtractBase
+= NumElts
* (Src
- Sources
.begin());
6260 for (int j
= 0; j
< LanesDefined
; ++j
)
6261 LaneMask
[j
] = ExtractBase
+ j
;
6264 // Final check before we try to produce nonsense...
6265 if (!isShuffleMaskLegal(Mask
, ShuffleVT
)) {
6266 LLVM_DEBUG(dbgs() << "Reshuffle failed: illegal shuffle mask\n");
6270 SDValue ShuffleOps
[] = { DAG
.getUNDEF(ShuffleVT
), DAG
.getUNDEF(ShuffleVT
) };
6271 for (unsigned i
= 0; i
< Sources
.size(); ++i
)
6272 ShuffleOps
[i
] = Sources
[i
].ShuffleVec
;
6274 SDValue Shuffle
= DAG
.getVectorShuffle(ShuffleVT
, dl
, ShuffleOps
[0],
6275 ShuffleOps
[1], Mask
);
6276 SDValue V
= DAG
.getNode(ISD::BITCAST
, dl
, VT
, Shuffle
);
6278 LLVM_DEBUG(dbgs() << "Reshuffle, creating node: "; Shuffle
.dump();
6279 dbgs() << "Reshuffle, creating node: "; V
.dump(););
6284 // check if an EXT instruction can handle the shuffle mask when the
6285 // vector sources of the shuffle are the same.
6286 static bool isSingletonEXTMask(ArrayRef
<int> M
, EVT VT
, unsigned &Imm
) {
6287 unsigned NumElts
= VT
.getVectorNumElements();
6289 // Assume that the first shuffle index is not UNDEF. Fail if it is.
6295 // If this is a VEXT shuffle, the immediate value is the index of the first
6296 // element. The other shuffle indices must be the successive elements after
6298 unsigned ExpectedElt
= Imm
;
6299 for (unsigned i
= 1; i
< NumElts
; ++i
) {
6300 // Increment the expected index. If it wraps around, just follow it
6301 // back to index zero and keep going.
6303 if (ExpectedElt
== NumElts
)
6307 continue; // ignore UNDEF indices
6308 if (ExpectedElt
!= static_cast<unsigned>(M
[i
]))
6315 // check if an EXT instruction can handle the shuffle mask when the
6316 // vector sources of the shuffle are different.
6317 static bool isEXTMask(ArrayRef
<int> M
, EVT VT
, bool &ReverseEXT
,
6319 // Look for the first non-undef element.
6320 const int *FirstRealElt
= find_if(M
, [](int Elt
) { return Elt
>= 0; });
6322 // Benefit form APInt to handle overflow when calculating expected element.
6323 unsigned NumElts
= VT
.getVectorNumElements();
6324 unsigned MaskBits
= APInt(32, NumElts
* 2).logBase2();
6325 APInt ExpectedElt
= APInt(MaskBits
, *FirstRealElt
+ 1);
6326 // The following shuffle indices must be the successive elements after the
6327 // first real element.
6328 const int *FirstWrongElt
= std::find_if(FirstRealElt
+ 1, M
.end(),
6329 [&](int Elt
) {return Elt
!= ExpectedElt
++ && Elt
!= -1;});
6330 if (FirstWrongElt
!= M
.end())
6333 // The index of an EXT is the first element if it is not UNDEF.
6334 // Watch out for the beginning UNDEFs. The EXT index should be the expected
6335 // value of the first element. E.g.
6336 // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
6337 // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
6338 // ExpectedElt is the last mask index plus 1.
6339 Imm
= ExpectedElt
.getZExtValue();
6341 // There are two difference cases requiring to reverse input vectors.
6342 // For example, for vector <4 x i32> we have the following cases,
6343 // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
6344 // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
6345 // For both cases, we finally use mask <5, 6, 7, 0>, which requires
6346 // to reverse two input vectors.
6355 /// isREVMask - Check if a vector shuffle corresponds to a REV
6356 /// instruction with the specified blocksize. (The order of the elements
6357 /// within each block of the vector is reversed.)
6358 static bool isREVMask(ArrayRef
<int> M
, EVT VT
, unsigned BlockSize
) {
6359 assert((BlockSize
== 16 || BlockSize
== 32 || BlockSize
== 64) &&
6360 "Only possible block sizes for REV are: 16, 32, 64");
6362 unsigned EltSz
= VT
.getScalarSizeInBits();
6366 unsigned NumElts
= VT
.getVectorNumElements();
6367 unsigned BlockElts
= M
[0] + 1;
6368 // If the first shuffle index is UNDEF, be optimistic.
6370 BlockElts
= BlockSize
/ EltSz
;
6372 if (BlockSize
<= EltSz
|| BlockSize
!= BlockElts
* EltSz
)
6375 for (unsigned i
= 0; i
< NumElts
; ++i
) {
6377 continue; // ignore UNDEF indices
6378 if ((unsigned)M
[i
] != (i
- i
% BlockElts
) + (BlockElts
- 1 - i
% BlockElts
))
6385 static bool isZIPMask(ArrayRef
<int> M
, EVT VT
, unsigned &WhichResult
) {
6386 unsigned NumElts
= VT
.getVectorNumElements();
6387 if (NumElts
% 2 != 0)
6389 WhichResult
= (M
[0] == 0 ? 0 : 1);
6390 unsigned Idx
= WhichResult
* NumElts
/ 2;
6391 for (unsigned i
= 0; i
!= NumElts
; i
+= 2) {
6392 if ((M
[i
] >= 0 && (unsigned)M
[i
] != Idx
) ||
6393 (M
[i
+ 1] >= 0 && (unsigned)M
[i
+ 1] != Idx
+ NumElts
))
6401 static bool isUZPMask(ArrayRef
<int> M
, EVT VT
, unsigned &WhichResult
) {
6402 unsigned NumElts
= VT
.getVectorNumElements();
6403 WhichResult
= (M
[0] == 0 ? 0 : 1);
6404 for (unsigned i
= 0; i
!= NumElts
; ++i
) {
6406 continue; // ignore UNDEF indices
6407 if ((unsigned)M
[i
] != 2 * i
+ WhichResult
)
6414 static bool isTRNMask(ArrayRef
<int> M
, EVT VT
, unsigned &WhichResult
) {
6415 unsigned NumElts
= VT
.getVectorNumElements();
6416 if (NumElts
% 2 != 0)
6418 WhichResult
= (M
[0] == 0 ? 0 : 1);
6419 for (unsigned i
= 0; i
< NumElts
; i
+= 2) {
6420 if ((M
[i
] >= 0 && (unsigned)M
[i
] != i
+ WhichResult
) ||
6421 (M
[i
+ 1] >= 0 && (unsigned)M
[i
+ 1] != i
+ NumElts
+ WhichResult
))
6427 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
6428 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6429 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
6430 static bool isZIP_v_undef_Mask(ArrayRef
<int> M
, EVT VT
, unsigned &WhichResult
) {
6431 unsigned NumElts
= VT
.getVectorNumElements();
6432 if (NumElts
% 2 != 0)
6434 WhichResult
= (M
[0] == 0 ? 0 : 1);
6435 unsigned Idx
= WhichResult
* NumElts
/ 2;
6436 for (unsigned i
= 0; i
!= NumElts
; i
+= 2) {
6437 if ((M
[i
] >= 0 && (unsigned)M
[i
] != Idx
) ||
6438 (M
[i
+ 1] >= 0 && (unsigned)M
[i
+ 1] != Idx
))
6446 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
6447 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6448 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
6449 static bool isUZP_v_undef_Mask(ArrayRef
<int> M
, EVT VT
, unsigned &WhichResult
) {
6450 unsigned Half
= VT
.getVectorNumElements() / 2;
6451 WhichResult
= (M
[0] == 0 ? 0 : 1);
6452 for (unsigned j
= 0; j
!= 2; ++j
) {
6453 unsigned Idx
= WhichResult
;
6454 for (unsigned i
= 0; i
!= Half
; ++i
) {
6455 int MIdx
= M
[i
+ j
* Half
];
6456 if (MIdx
>= 0 && (unsigned)MIdx
!= Idx
)
6465 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
6466 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6467 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
6468 static bool isTRN_v_undef_Mask(ArrayRef
<int> M
, EVT VT
, unsigned &WhichResult
) {
6469 unsigned NumElts
= VT
.getVectorNumElements();
6470 if (NumElts
% 2 != 0)
6472 WhichResult
= (M
[0] == 0 ? 0 : 1);
6473 for (unsigned i
= 0; i
< NumElts
; i
+= 2) {
6474 if ((M
[i
] >= 0 && (unsigned)M
[i
] != i
+ WhichResult
) ||
6475 (M
[i
+ 1] >= 0 && (unsigned)M
[i
+ 1] != i
+ WhichResult
))
6481 static bool isINSMask(ArrayRef
<int> M
, int NumInputElements
,
6482 bool &DstIsLeft
, int &Anomaly
) {
6483 if (M
.size() != static_cast<size_t>(NumInputElements
))
6486 int NumLHSMatch
= 0, NumRHSMatch
= 0;
6487 int LastLHSMismatch
= -1, LastRHSMismatch
= -1;
6489 for (int i
= 0; i
< NumInputElements
; ++i
) {
6499 LastLHSMismatch
= i
;
6501 if (M
[i
] == i
+ NumInputElements
)
6504 LastRHSMismatch
= i
;
6507 if (NumLHSMatch
== NumInputElements
- 1) {
6509 Anomaly
= LastLHSMismatch
;
6511 } else if (NumRHSMatch
== NumInputElements
- 1) {
6513 Anomaly
= LastRHSMismatch
;
6520 static bool isConcatMask(ArrayRef
<int> Mask
, EVT VT
, bool SplitLHS
) {
6521 if (VT
.getSizeInBits() != 128)
6524 unsigned NumElts
= VT
.getVectorNumElements();
6526 for (int I
= 0, E
= NumElts
/ 2; I
!= E
; I
++) {
6531 int Offset
= NumElts
/ 2;
6532 for (int I
= NumElts
/ 2, E
= NumElts
; I
!= E
; I
++) {
6533 if (Mask
[I
] != I
+ SplitLHS
* Offset
)
6540 static SDValue
tryFormConcatFromShuffle(SDValue Op
, SelectionDAG
&DAG
) {
6542 EVT VT
= Op
.getValueType();
6543 SDValue V0
= Op
.getOperand(0);
6544 SDValue V1
= Op
.getOperand(1);
6545 ArrayRef
<int> Mask
= cast
<ShuffleVectorSDNode
>(Op
)->getMask();
6547 if (VT
.getVectorElementType() != V0
.getValueType().getVectorElementType() ||
6548 VT
.getVectorElementType() != V1
.getValueType().getVectorElementType())
6551 bool SplitV0
= V0
.getValueSizeInBits() == 128;
6553 if (!isConcatMask(Mask
, VT
, SplitV0
))
6556 EVT CastVT
= VT
.getHalfNumVectorElementsVT(*DAG
.getContext());
6558 V0
= DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, DL
, CastVT
, V0
,
6559 DAG
.getConstant(0, DL
, MVT::i64
));
6561 if (V1
.getValueSizeInBits() == 128) {
6562 V1
= DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, DL
, CastVT
, V1
,
6563 DAG
.getConstant(0, DL
, MVT::i64
));
6565 return DAG
.getNode(ISD::CONCAT_VECTORS
, DL
, VT
, V0
, V1
);
6568 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6569 /// the specified operations to build the shuffle.
6570 static SDValue
GeneratePerfectShuffle(unsigned PFEntry
, SDValue LHS
,
6571 SDValue RHS
, SelectionDAG
&DAG
,
6573 unsigned OpNum
= (PFEntry
>> 26) & 0x0F;
6574 unsigned LHSID
= (PFEntry
>> 13) & ((1 << 13) - 1);
6575 unsigned RHSID
= (PFEntry
>> 0) & ((1 << 13) - 1);
6578 OP_COPY
= 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6587 OP_VUZPL
, // VUZP, left result
6588 OP_VUZPR
, // VUZP, right result
6589 OP_VZIPL
, // VZIP, left result
6590 OP_VZIPR
, // VZIP, right result
6591 OP_VTRNL
, // VTRN, left result
6592 OP_VTRNR
// VTRN, right result
6595 if (OpNum
== OP_COPY
) {
6596 if (LHSID
== (1 * 9 + 2) * 9 + 3)
6598 assert(LHSID
== ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
6602 SDValue OpLHS
, OpRHS
;
6603 OpLHS
= GeneratePerfectShuffle(PerfectShuffleTable
[LHSID
], LHS
, RHS
, DAG
, dl
);
6604 OpRHS
= GeneratePerfectShuffle(PerfectShuffleTable
[RHSID
], LHS
, RHS
, DAG
, dl
);
6605 EVT VT
= OpLHS
.getValueType();
6609 llvm_unreachable("Unknown shuffle opcode!");
6611 // VREV divides the vector in half and swaps within the half.
6612 if (VT
.getVectorElementType() == MVT::i32
||
6613 VT
.getVectorElementType() == MVT::f32
)
6614 return DAG
.getNode(AArch64ISD::REV64
, dl
, VT
, OpLHS
);
6615 // vrev <4 x i16> -> REV32
6616 if (VT
.getVectorElementType() == MVT::i16
||
6617 VT
.getVectorElementType() == MVT::f16
)
6618 return DAG
.getNode(AArch64ISD::REV32
, dl
, VT
, OpLHS
);
6619 // vrev <4 x i8> -> REV16
6620 assert(VT
.getVectorElementType() == MVT::i8
);
6621 return DAG
.getNode(AArch64ISD::REV16
, dl
, VT
, OpLHS
);
6626 EVT EltTy
= VT
.getVectorElementType();
6628 if (EltTy
== MVT::i8
)
6629 Opcode
= AArch64ISD::DUPLANE8
;
6630 else if (EltTy
== MVT::i16
|| EltTy
== MVT::f16
)
6631 Opcode
= AArch64ISD::DUPLANE16
;
6632 else if (EltTy
== MVT::i32
|| EltTy
== MVT::f32
)
6633 Opcode
= AArch64ISD::DUPLANE32
;
6634 else if (EltTy
== MVT::i64
|| EltTy
== MVT::f64
)
6635 Opcode
= AArch64ISD::DUPLANE64
;
6637 llvm_unreachable("Invalid vector element type?");
6639 if (VT
.getSizeInBits() == 64)
6640 OpLHS
= WidenVector(OpLHS
, DAG
);
6641 SDValue Lane
= DAG
.getConstant(OpNum
- OP_VDUP0
, dl
, MVT::i64
);
6642 return DAG
.getNode(Opcode
, dl
, VT
, OpLHS
, Lane
);
6647 unsigned Imm
= (OpNum
- OP_VEXT1
+ 1) * getExtFactor(OpLHS
);
6648 return DAG
.getNode(AArch64ISD::EXT
, dl
, VT
, OpLHS
, OpRHS
,
6649 DAG
.getConstant(Imm
, dl
, MVT::i32
));
6652 return DAG
.getNode(AArch64ISD::UZP1
, dl
, DAG
.getVTList(VT
, VT
), OpLHS
,
6655 return DAG
.getNode(AArch64ISD::UZP2
, dl
, DAG
.getVTList(VT
, VT
), OpLHS
,
6658 return DAG
.getNode(AArch64ISD::ZIP1
, dl
, DAG
.getVTList(VT
, VT
), OpLHS
,
6661 return DAG
.getNode(AArch64ISD::ZIP2
, dl
, DAG
.getVTList(VT
, VT
), OpLHS
,
6664 return DAG
.getNode(AArch64ISD::TRN1
, dl
, DAG
.getVTList(VT
, VT
), OpLHS
,
6667 return DAG
.getNode(AArch64ISD::TRN2
, dl
, DAG
.getVTList(VT
, VT
), OpLHS
,
6672 static SDValue
GenerateTBL(SDValue Op
, ArrayRef
<int> ShuffleMask
,
6673 SelectionDAG
&DAG
) {
6674 // Check to see if we can use the TBL instruction.
6675 SDValue V1
= Op
.getOperand(0);
6676 SDValue V2
= Op
.getOperand(1);
6679 EVT EltVT
= Op
.getValueType().getVectorElementType();
6680 unsigned BytesPerElt
= EltVT
.getSizeInBits() / 8;
6682 SmallVector
<SDValue
, 8> TBLMask
;
6683 for (int Val
: ShuffleMask
) {
6684 for (unsigned Byte
= 0; Byte
< BytesPerElt
; ++Byte
) {
6685 unsigned Offset
= Byte
+ Val
* BytesPerElt
;
6686 TBLMask
.push_back(DAG
.getConstant(Offset
, DL
, MVT::i32
));
6690 MVT IndexVT
= MVT::v8i8
;
6691 unsigned IndexLen
= 8;
6692 if (Op
.getValueSizeInBits() == 128) {
6693 IndexVT
= MVT::v16i8
;
6697 SDValue V1Cst
= DAG
.getNode(ISD::BITCAST
, DL
, IndexVT
, V1
);
6698 SDValue V2Cst
= DAG
.getNode(ISD::BITCAST
, DL
, IndexVT
, V2
);
6701 if (V2
.getNode()->isUndef()) {
6703 V1Cst
= DAG
.getNode(ISD::CONCAT_VECTORS
, DL
, MVT::v16i8
, V1Cst
, V1Cst
);
6704 Shuffle
= DAG
.getNode(
6705 ISD::INTRINSIC_WO_CHAIN
, DL
, IndexVT
,
6706 DAG
.getConstant(Intrinsic::aarch64_neon_tbl1
, DL
, MVT::i32
), V1Cst
,
6707 DAG
.getBuildVector(IndexVT
, DL
,
6708 makeArrayRef(TBLMask
.data(), IndexLen
)));
6710 if (IndexLen
== 8) {
6711 V1Cst
= DAG
.getNode(ISD::CONCAT_VECTORS
, DL
, MVT::v16i8
, V1Cst
, V2Cst
);
6712 Shuffle
= DAG
.getNode(
6713 ISD::INTRINSIC_WO_CHAIN
, DL
, IndexVT
,
6714 DAG
.getConstant(Intrinsic::aarch64_neon_tbl1
, DL
, MVT::i32
), V1Cst
,
6715 DAG
.getBuildVector(IndexVT
, DL
,
6716 makeArrayRef(TBLMask
.data(), IndexLen
)));
6718 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
6719 // cannot currently represent the register constraints on the input
6721 // Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
6722 // DAG.getBuildVector(IndexVT, DL, &TBLMask[0],
6724 Shuffle
= DAG
.getNode(
6725 ISD::INTRINSIC_WO_CHAIN
, DL
, IndexVT
,
6726 DAG
.getConstant(Intrinsic::aarch64_neon_tbl2
, DL
, MVT::i32
), V1Cst
,
6727 V2Cst
, DAG
.getBuildVector(IndexVT
, DL
,
6728 makeArrayRef(TBLMask
.data(), IndexLen
)));
6731 return DAG
.getNode(ISD::BITCAST
, DL
, Op
.getValueType(), Shuffle
);
6734 static unsigned getDUPLANEOp(EVT EltType
) {
6735 if (EltType
== MVT::i8
)
6736 return AArch64ISD::DUPLANE8
;
6737 if (EltType
== MVT::i16
|| EltType
== MVT::f16
)
6738 return AArch64ISD::DUPLANE16
;
6739 if (EltType
== MVT::i32
|| EltType
== MVT::f32
)
6740 return AArch64ISD::DUPLANE32
;
6741 if (EltType
== MVT::i64
|| EltType
== MVT::f64
)
6742 return AArch64ISD::DUPLANE64
;
6744 llvm_unreachable("Invalid vector element type?");
6747 SDValue
AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op
,
6748 SelectionDAG
&DAG
) const {
6750 EVT VT
= Op
.getValueType();
6752 ShuffleVectorSDNode
*SVN
= cast
<ShuffleVectorSDNode
>(Op
.getNode());
6754 // Convert shuffles that are directly supported on NEON to target-specific
6755 // DAG nodes, instead of keeping them as shuffles and matching them again
6756 // during code selection. This is more efficient and avoids the possibility
6757 // of inconsistencies between legalization and selection.
6758 ArrayRef
<int> ShuffleMask
= SVN
->getMask();
6760 SDValue V1
= Op
.getOperand(0);
6761 SDValue V2
= Op
.getOperand(1);
6763 if (SVN
->isSplat()) {
6764 int Lane
= SVN
->getSplatIndex();
6765 // If this is undef splat, generate it via "just" vdup, if possible.
6769 if (Lane
== 0 && V1
.getOpcode() == ISD::SCALAR_TO_VECTOR
)
6770 return DAG
.getNode(AArch64ISD::DUP
, dl
, V1
.getValueType(),
6772 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
6773 // constant. If so, we can just reference the lane's definition directly.
6774 if (V1
.getOpcode() == ISD::BUILD_VECTOR
&&
6775 !isa
<ConstantSDNode
>(V1
.getOperand(Lane
)))
6776 return DAG
.getNode(AArch64ISD::DUP
, dl
, VT
, V1
.getOperand(Lane
));
6778 // Otherwise, duplicate from the lane of the input vector.
6779 unsigned Opcode
= getDUPLANEOp(V1
.getValueType().getVectorElementType());
6781 // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
6782 // to make a vector of the same size as this SHUFFLE. We can ignore the
6783 // extract entirely, and canonicalise the concat using WidenVector.
6784 if (V1
.getOpcode() == ISD::EXTRACT_SUBVECTOR
) {
6785 Lane
+= cast
<ConstantSDNode
>(V1
.getOperand(1))->getZExtValue();
6786 V1
= V1
.getOperand(0);
6787 } else if (V1
.getOpcode() == ISD::CONCAT_VECTORS
) {
6788 unsigned Idx
= Lane
>= (int)VT
.getVectorNumElements() / 2;
6789 Lane
-= Idx
* VT
.getVectorNumElements() / 2;
6790 V1
= WidenVector(V1
.getOperand(Idx
), DAG
);
6791 } else if (VT
.getSizeInBits() == 64)
6792 V1
= WidenVector(V1
, DAG
);
6794 return DAG
.getNode(Opcode
, dl
, VT
, V1
, DAG
.getConstant(Lane
, dl
, MVT::i64
));
6797 if (isREVMask(ShuffleMask
, VT
, 64))
6798 return DAG
.getNode(AArch64ISD::REV64
, dl
, V1
.getValueType(), V1
, V2
);
6799 if (isREVMask(ShuffleMask
, VT
, 32))
6800 return DAG
.getNode(AArch64ISD::REV32
, dl
, V1
.getValueType(), V1
, V2
);
6801 if (isREVMask(ShuffleMask
, VT
, 16))
6802 return DAG
.getNode(AArch64ISD::REV16
, dl
, V1
.getValueType(), V1
, V2
);
6804 bool ReverseEXT
= false;
6806 if (isEXTMask(ShuffleMask
, VT
, ReverseEXT
, Imm
)) {
6809 Imm
*= getExtFactor(V1
);
6810 return DAG
.getNode(AArch64ISD::EXT
, dl
, V1
.getValueType(), V1
, V2
,
6811 DAG
.getConstant(Imm
, dl
, MVT::i32
));
6812 } else if (V2
->isUndef() && isSingletonEXTMask(ShuffleMask
, VT
, Imm
)) {
6813 Imm
*= getExtFactor(V1
);
6814 return DAG
.getNode(AArch64ISD::EXT
, dl
, V1
.getValueType(), V1
, V1
,
6815 DAG
.getConstant(Imm
, dl
, MVT::i32
));
6818 unsigned WhichResult
;
6819 if (isZIPMask(ShuffleMask
, VT
, WhichResult
)) {
6820 unsigned Opc
= (WhichResult
== 0) ? AArch64ISD::ZIP1
: AArch64ISD::ZIP2
;
6821 return DAG
.getNode(Opc
, dl
, V1
.getValueType(), V1
, V2
);
6823 if (isUZPMask(ShuffleMask
, VT
, WhichResult
)) {
6824 unsigned Opc
= (WhichResult
== 0) ? AArch64ISD::UZP1
: AArch64ISD::UZP2
;
6825 return DAG
.getNode(Opc
, dl
, V1
.getValueType(), V1
, V2
);
6827 if (isTRNMask(ShuffleMask
, VT
, WhichResult
)) {
6828 unsigned Opc
= (WhichResult
== 0) ? AArch64ISD::TRN1
: AArch64ISD::TRN2
;
6829 return DAG
.getNode(Opc
, dl
, V1
.getValueType(), V1
, V2
);
6832 if (isZIP_v_undef_Mask(ShuffleMask
, VT
, WhichResult
)) {
6833 unsigned Opc
= (WhichResult
== 0) ? AArch64ISD::ZIP1
: AArch64ISD::ZIP2
;
6834 return DAG
.getNode(Opc
, dl
, V1
.getValueType(), V1
, V1
);
6836 if (isUZP_v_undef_Mask(ShuffleMask
, VT
, WhichResult
)) {
6837 unsigned Opc
= (WhichResult
== 0) ? AArch64ISD::UZP1
: AArch64ISD::UZP2
;
6838 return DAG
.getNode(Opc
, dl
, V1
.getValueType(), V1
, V1
);
6840 if (isTRN_v_undef_Mask(ShuffleMask
, VT
, WhichResult
)) {
6841 unsigned Opc
= (WhichResult
== 0) ? AArch64ISD::TRN1
: AArch64ISD::TRN2
;
6842 return DAG
.getNode(Opc
, dl
, V1
.getValueType(), V1
, V1
);
6845 if (SDValue Concat
= tryFormConcatFromShuffle(Op
, DAG
))
6850 int NumInputElements
= V1
.getValueType().getVectorNumElements();
6851 if (isINSMask(ShuffleMask
, NumInputElements
, DstIsLeft
, Anomaly
)) {
6852 SDValue DstVec
= DstIsLeft
? V1
: V2
;
6853 SDValue DstLaneV
= DAG
.getConstant(Anomaly
, dl
, MVT::i64
);
6855 SDValue SrcVec
= V1
;
6856 int SrcLane
= ShuffleMask
[Anomaly
];
6857 if (SrcLane
>= NumInputElements
) {
6859 SrcLane
-= VT
.getVectorNumElements();
6861 SDValue SrcLaneV
= DAG
.getConstant(SrcLane
, dl
, MVT::i64
);
6863 EVT ScalarVT
= VT
.getVectorElementType();
6865 if (ScalarVT
.getSizeInBits() < 32 && ScalarVT
.isInteger())
6866 ScalarVT
= MVT::i32
;
6869 ISD::INSERT_VECTOR_ELT
, dl
, VT
, DstVec
,
6870 DAG
.getNode(ISD::EXTRACT_VECTOR_ELT
, dl
, ScalarVT
, SrcVec
, SrcLaneV
),
6874 // If the shuffle is not directly supported and it has 4 elements, use
6875 // the PerfectShuffle-generated table to synthesize it from other shuffles.
6876 unsigned NumElts
= VT
.getVectorNumElements();
6878 unsigned PFIndexes
[4];
6879 for (unsigned i
= 0; i
!= 4; ++i
) {
6880 if (ShuffleMask
[i
] < 0)
6883 PFIndexes
[i
] = ShuffleMask
[i
];
6886 // Compute the index in the perfect shuffle table.
6887 unsigned PFTableIndex
= PFIndexes
[0] * 9 * 9 * 9 + PFIndexes
[1] * 9 * 9 +
6888 PFIndexes
[2] * 9 + PFIndexes
[3];
6889 unsigned PFEntry
= PerfectShuffleTable
[PFTableIndex
];
6890 unsigned Cost
= (PFEntry
>> 30);
6893 return GeneratePerfectShuffle(PFEntry
, V1
, V2
, DAG
, dl
);
6896 return GenerateTBL(Op
, ShuffleMask
, DAG
);
6899 static bool resolveBuildVector(BuildVectorSDNode
*BVN
, APInt
&CnstBits
,
6901 EVT VT
= BVN
->getValueType(0);
6902 APInt SplatBits
, SplatUndef
;
6903 unsigned SplatBitSize
;
6905 if (BVN
->isConstantSplat(SplatBits
, SplatUndef
, SplatBitSize
, HasAnyUndefs
)) {
6906 unsigned NumSplats
= VT
.getSizeInBits() / SplatBitSize
;
6908 for (unsigned i
= 0; i
< NumSplats
; ++i
) {
6909 CnstBits
<<= SplatBitSize
;
6910 UndefBits
<<= SplatBitSize
;
6911 CnstBits
|= SplatBits
.zextOrTrunc(VT
.getSizeInBits());
6912 UndefBits
|= (SplatBits
^ SplatUndef
).zextOrTrunc(VT
.getSizeInBits());
6921 // Try 64-bit splatted SIMD immediate.
6922 static SDValue
tryAdvSIMDModImm64(unsigned NewOp
, SDValue Op
, SelectionDAG
&DAG
,
6923 const APInt
&Bits
) {
6924 if (Bits
.getHiBits(64) == Bits
.getLoBits(64)) {
6925 uint64_t Value
= Bits
.zextOrTrunc(64).getZExtValue();
6926 EVT VT
= Op
.getValueType();
6927 MVT MovTy
= (VT
.getSizeInBits() == 128) ? MVT::v2i64
: MVT::f64
;
6929 if (AArch64_AM::isAdvSIMDModImmType10(Value
)) {
6930 Value
= AArch64_AM::encodeAdvSIMDModImmType10(Value
);
6933 SDValue Mov
= DAG
.getNode(NewOp
, dl
, MovTy
,
6934 DAG
.getConstant(Value
, dl
, MVT::i32
));
6935 return DAG
.getNode(AArch64ISD::NVCAST
, dl
, VT
, Mov
);
6942 // Try 32-bit splatted SIMD immediate.
6943 static SDValue
tryAdvSIMDModImm32(unsigned NewOp
, SDValue Op
, SelectionDAG
&DAG
,
6945 const SDValue
*LHS
= nullptr) {
6946 if (Bits
.getHiBits(64) == Bits
.getLoBits(64)) {
6947 uint64_t Value
= Bits
.zextOrTrunc(64).getZExtValue();
6948 EVT VT
= Op
.getValueType();
6949 MVT MovTy
= (VT
.getSizeInBits() == 128) ? MVT::v4i32
: MVT::v2i32
;
6950 bool isAdvSIMDModImm
= false;
6953 if ((isAdvSIMDModImm
= AArch64_AM::isAdvSIMDModImmType1(Value
))) {
6954 Value
= AArch64_AM::encodeAdvSIMDModImmType1(Value
);
6957 else if ((isAdvSIMDModImm
= AArch64_AM::isAdvSIMDModImmType2(Value
))) {
6958 Value
= AArch64_AM::encodeAdvSIMDModImmType2(Value
);
6961 else if ((isAdvSIMDModImm
= AArch64_AM::isAdvSIMDModImmType3(Value
))) {
6962 Value
= AArch64_AM::encodeAdvSIMDModImmType3(Value
);
6965 else if ((isAdvSIMDModImm
= AArch64_AM::isAdvSIMDModImmType4(Value
))) {
6966 Value
= AArch64_AM::encodeAdvSIMDModImmType4(Value
);
6970 if (isAdvSIMDModImm
) {
6975 Mov
= DAG
.getNode(NewOp
, dl
, MovTy
, *LHS
,
6976 DAG
.getConstant(Value
, dl
, MVT::i32
),
6977 DAG
.getConstant(Shift
, dl
, MVT::i32
));
6979 Mov
= DAG
.getNode(NewOp
, dl
, MovTy
,
6980 DAG
.getConstant(Value
, dl
, MVT::i32
),
6981 DAG
.getConstant(Shift
, dl
, MVT::i32
));
6983 return DAG
.getNode(AArch64ISD::NVCAST
, dl
, VT
, Mov
);
6990 // Try 16-bit splatted SIMD immediate.
6991 static SDValue
tryAdvSIMDModImm16(unsigned NewOp
, SDValue Op
, SelectionDAG
&DAG
,
6993 const SDValue
*LHS
= nullptr) {
6994 if (Bits
.getHiBits(64) == Bits
.getLoBits(64)) {
6995 uint64_t Value
= Bits
.zextOrTrunc(64).getZExtValue();
6996 EVT VT
= Op
.getValueType();
6997 MVT MovTy
= (VT
.getSizeInBits() == 128) ? MVT::v8i16
: MVT::v4i16
;
6998 bool isAdvSIMDModImm
= false;
7001 if ((isAdvSIMDModImm
= AArch64_AM::isAdvSIMDModImmType5(Value
))) {
7002 Value
= AArch64_AM::encodeAdvSIMDModImmType5(Value
);
7005 else if ((isAdvSIMDModImm
= AArch64_AM::isAdvSIMDModImmType6(Value
))) {
7006 Value
= AArch64_AM::encodeAdvSIMDModImmType6(Value
);
7010 if (isAdvSIMDModImm
) {
7015 Mov
= DAG
.getNode(NewOp
, dl
, MovTy
, *LHS
,
7016 DAG
.getConstant(Value
, dl
, MVT::i32
),
7017 DAG
.getConstant(Shift
, dl
, MVT::i32
));
7019 Mov
= DAG
.getNode(NewOp
, dl
, MovTy
,
7020 DAG
.getConstant(Value
, dl
, MVT::i32
),
7021 DAG
.getConstant(Shift
, dl
, MVT::i32
));
7023 return DAG
.getNode(AArch64ISD::NVCAST
, dl
, VT
, Mov
);
7030 // Try 32-bit splatted SIMD immediate with shifted ones.
7031 static SDValue
tryAdvSIMDModImm321s(unsigned NewOp
, SDValue Op
,
7032 SelectionDAG
&DAG
, const APInt
&Bits
) {
7033 if (Bits
.getHiBits(64) == Bits
.getLoBits(64)) {
7034 uint64_t Value
= Bits
.zextOrTrunc(64).getZExtValue();
7035 EVT VT
= Op
.getValueType();
7036 MVT MovTy
= (VT
.getSizeInBits() == 128) ? MVT::v4i32
: MVT::v2i32
;
7037 bool isAdvSIMDModImm
= false;
7040 if ((isAdvSIMDModImm
= AArch64_AM::isAdvSIMDModImmType7(Value
))) {
7041 Value
= AArch64_AM::encodeAdvSIMDModImmType7(Value
);
7044 else if ((isAdvSIMDModImm
= AArch64_AM::isAdvSIMDModImmType8(Value
))) {
7045 Value
= AArch64_AM::encodeAdvSIMDModImmType8(Value
);
7049 if (isAdvSIMDModImm
) {
7051 SDValue Mov
= DAG
.getNode(NewOp
, dl
, MovTy
,
7052 DAG
.getConstant(Value
, dl
, MVT::i32
),
7053 DAG
.getConstant(Shift
, dl
, MVT::i32
));
7054 return DAG
.getNode(AArch64ISD::NVCAST
, dl
, VT
, Mov
);
7061 // Try 8-bit splatted SIMD immediate.
7062 static SDValue
tryAdvSIMDModImm8(unsigned NewOp
, SDValue Op
, SelectionDAG
&DAG
,
7063 const APInt
&Bits
) {
7064 if (Bits
.getHiBits(64) == Bits
.getLoBits(64)) {
7065 uint64_t Value
= Bits
.zextOrTrunc(64).getZExtValue();
7066 EVT VT
= Op
.getValueType();
7067 MVT MovTy
= (VT
.getSizeInBits() == 128) ? MVT::v16i8
: MVT::v8i8
;
7069 if (AArch64_AM::isAdvSIMDModImmType9(Value
)) {
7070 Value
= AArch64_AM::encodeAdvSIMDModImmType9(Value
);
7073 SDValue Mov
= DAG
.getNode(NewOp
, dl
, MovTy
,
7074 DAG
.getConstant(Value
, dl
, MVT::i32
));
7075 return DAG
.getNode(AArch64ISD::NVCAST
, dl
, VT
, Mov
);
7082 // Try FP splatted SIMD immediate.
7083 static SDValue
tryAdvSIMDModImmFP(unsigned NewOp
, SDValue Op
, SelectionDAG
&DAG
,
7084 const APInt
&Bits
) {
7085 if (Bits
.getHiBits(64) == Bits
.getLoBits(64)) {
7086 uint64_t Value
= Bits
.zextOrTrunc(64).getZExtValue();
7087 EVT VT
= Op
.getValueType();
7088 bool isWide
= (VT
.getSizeInBits() == 128);
7090 bool isAdvSIMDModImm
= false;
7092 if ((isAdvSIMDModImm
= AArch64_AM::isAdvSIMDModImmType11(Value
))) {
7093 Value
= AArch64_AM::encodeAdvSIMDModImmType11(Value
);
7094 MovTy
= isWide
? MVT::v4f32
: MVT::v2f32
;
7097 (isAdvSIMDModImm
= AArch64_AM::isAdvSIMDModImmType12(Value
))) {
7098 Value
= AArch64_AM::encodeAdvSIMDModImmType12(Value
);
7102 if (isAdvSIMDModImm
) {
7104 SDValue Mov
= DAG
.getNode(NewOp
, dl
, MovTy
,
7105 DAG
.getConstant(Value
, dl
, MVT::i32
));
7106 return DAG
.getNode(AArch64ISD::NVCAST
, dl
, VT
, Mov
);
7113 // Specialized code to quickly find if PotentialBVec is a BuildVector that
7114 // consists of only the same constant int value, returned in reference arg
7116 static bool isAllConstantBuildVector(const SDValue
&PotentialBVec
,
7117 uint64_t &ConstVal
) {
7118 BuildVectorSDNode
*Bvec
= dyn_cast
<BuildVectorSDNode
>(PotentialBVec
);
7121 ConstantSDNode
*FirstElt
= dyn_cast
<ConstantSDNode
>(Bvec
->getOperand(0));
7124 EVT VT
= Bvec
->getValueType(0);
7125 unsigned NumElts
= VT
.getVectorNumElements();
7126 for (unsigned i
= 1; i
< NumElts
; ++i
)
7127 if (dyn_cast
<ConstantSDNode
>(Bvec
->getOperand(i
)) != FirstElt
)
7129 ConstVal
= FirstElt
->getZExtValue();
7133 static unsigned getIntrinsicID(const SDNode
*N
) {
7134 unsigned Opcode
= N
->getOpcode();
7137 return Intrinsic::not_intrinsic
;
7138 case ISD::INTRINSIC_WO_CHAIN
: {
7139 unsigned IID
= cast
<ConstantSDNode
>(N
->getOperand(0))->getZExtValue();
7140 if (IID
< Intrinsic::num_intrinsics
)
7142 return Intrinsic::not_intrinsic
;
7147 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
7148 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
7149 // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
7150 // Also, logical shift right -> sri, with the same structure.
7151 static SDValue
tryLowerToSLI(SDNode
*N
, SelectionDAG
&DAG
) {
7152 EVT VT
= N
->getValueType(0);
7159 // Is the first op an AND?
7160 const SDValue And
= N
->getOperand(0);
7161 if (And
.getOpcode() != ISD::AND
)
7164 // Is the second op an shl or lshr?
7165 SDValue Shift
= N
->getOperand(1);
7166 // This will have been turned into: AArch64ISD::VSHL vector, #shift
7167 // or AArch64ISD::VLSHR vector, #shift
7168 unsigned ShiftOpc
= Shift
.getOpcode();
7169 if ((ShiftOpc
!= AArch64ISD::VSHL
&& ShiftOpc
!= AArch64ISD::VLSHR
))
7171 bool IsShiftRight
= ShiftOpc
== AArch64ISD::VLSHR
;
7173 // Is the shift amount constant?
7174 ConstantSDNode
*C2node
= dyn_cast
<ConstantSDNode
>(Shift
.getOperand(1));
7178 // Is the and mask vector all constant?
7180 if (!isAllConstantBuildVector(And
.getOperand(1), C1
))
7183 // Is C1 == ~C2, taking into account how much one can shift elements of a
7185 uint64_t C2
= C2node
->getZExtValue();
7186 unsigned ElemSizeInBits
= VT
.getScalarSizeInBits();
7187 if (C2
> ElemSizeInBits
)
7189 unsigned ElemMask
= (1 << ElemSizeInBits
) - 1;
7190 if ((C1
& ElemMask
) != (~C2
& ElemMask
))
7193 SDValue X
= And
.getOperand(0);
7194 SDValue Y
= Shift
.getOperand(0);
7197 IsShiftRight
? Intrinsic::aarch64_neon_vsri
: Intrinsic::aarch64_neon_vsli
;
7199 DAG
.getNode(ISD::INTRINSIC_WO_CHAIN
, DL
, VT
,
7200 DAG
.getConstant(Intrin
, DL
, MVT::i32
), X
, Y
,
7201 Shift
.getOperand(1));
7203 LLVM_DEBUG(dbgs() << "aarch64-lower: transformed: \n");
7204 LLVM_DEBUG(N
->dump(&DAG
));
7205 LLVM_DEBUG(dbgs() << "into: \n");
7206 LLVM_DEBUG(ResultSLI
->dump(&DAG
));
7212 SDValue
AArch64TargetLowering::LowerVectorOR(SDValue Op
,
7213 SelectionDAG
&DAG
) const {
7214 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
7215 if (EnableAArch64SlrGeneration
) {
7216 if (SDValue Res
= tryLowerToSLI(Op
.getNode(), DAG
))
7220 EVT VT
= Op
.getValueType();
7222 SDValue LHS
= Op
.getOperand(0);
7223 BuildVectorSDNode
*BVN
=
7224 dyn_cast
<BuildVectorSDNode
>(Op
.getOperand(1).getNode());
7226 // OR commutes, so try swapping the operands.
7227 LHS
= Op
.getOperand(1);
7228 BVN
= dyn_cast
<BuildVectorSDNode
>(Op
.getOperand(0).getNode());
7233 APInt
DefBits(VT
.getSizeInBits(), 0);
7234 APInt
UndefBits(VT
.getSizeInBits(), 0);
7235 if (resolveBuildVector(BVN
, DefBits
, UndefBits
)) {
7238 if ((NewOp
= tryAdvSIMDModImm32(AArch64ISD::ORRi
, Op
, DAG
,
7240 (NewOp
= tryAdvSIMDModImm16(AArch64ISD::ORRi
, Op
, DAG
,
7244 if ((NewOp
= tryAdvSIMDModImm32(AArch64ISD::ORRi
, Op
, DAG
,
7245 UndefBits
, &LHS
)) ||
7246 (NewOp
= tryAdvSIMDModImm16(AArch64ISD::ORRi
, Op
, DAG
,
7251 // We can always fall back to a non-immediate OR.
7255 // Normalize the operands of BUILD_VECTOR. The value of constant operands will
7256 // be truncated to fit element width.
7257 static SDValue
NormalizeBuildVector(SDValue Op
,
7258 SelectionDAG
&DAG
) {
7259 assert(Op
.getOpcode() == ISD::BUILD_VECTOR
&& "Unknown opcode!");
7261 EVT VT
= Op
.getValueType();
7262 EVT EltTy
= VT
.getVectorElementType();
7264 if (EltTy
.isFloatingPoint() || EltTy
.getSizeInBits() > 16)
7267 SmallVector
<SDValue
, 16> Ops
;
7268 for (SDValue Lane
: Op
->ops()) {
7269 // For integer vectors, type legalization would have promoted the
7270 // operands already. Otherwise, if Op is a floating-point splat
7271 // (with operands cast to integers), then the only possibilities
7272 // are constants and UNDEFs.
7273 if (auto *CstLane
= dyn_cast
<ConstantSDNode
>(Lane
)) {
7274 APInt
LowBits(EltTy
.getSizeInBits(),
7275 CstLane
->getZExtValue());
7276 Lane
= DAG
.getConstant(LowBits
.getZExtValue(), dl
, MVT::i32
);
7277 } else if (Lane
.getNode()->isUndef()) {
7278 Lane
= DAG
.getUNDEF(MVT::i32
);
7280 assert(Lane
.getValueType() == MVT::i32
&&
7281 "Unexpected BUILD_VECTOR operand type");
7283 Ops
.push_back(Lane
);
7285 return DAG
.getBuildVector(VT
, dl
, Ops
);
7288 static SDValue
ConstantBuildVector(SDValue Op
, SelectionDAG
&DAG
) {
7289 EVT VT
= Op
.getValueType();
7291 APInt
DefBits(VT
.getSizeInBits(), 0);
7292 APInt
UndefBits(VT
.getSizeInBits(), 0);
7293 BuildVectorSDNode
*BVN
= cast
<BuildVectorSDNode
>(Op
.getNode());
7294 if (resolveBuildVector(BVN
, DefBits
, UndefBits
)) {
7296 if ((NewOp
= tryAdvSIMDModImm64(AArch64ISD::MOVIedit
, Op
, DAG
, DefBits
)) ||
7297 (NewOp
= tryAdvSIMDModImm32(AArch64ISD::MOVIshift
, Op
, DAG
, DefBits
)) ||
7298 (NewOp
= tryAdvSIMDModImm321s(AArch64ISD::MOVImsl
, Op
, DAG
, DefBits
)) ||
7299 (NewOp
= tryAdvSIMDModImm16(AArch64ISD::MOVIshift
, Op
, DAG
, DefBits
)) ||
7300 (NewOp
= tryAdvSIMDModImm8(AArch64ISD::MOVI
, Op
, DAG
, DefBits
)) ||
7301 (NewOp
= tryAdvSIMDModImmFP(AArch64ISD::FMOV
, Op
, DAG
, DefBits
)))
7305 if ((NewOp
= tryAdvSIMDModImm32(AArch64ISD::MVNIshift
, Op
, DAG
, DefBits
)) ||
7306 (NewOp
= tryAdvSIMDModImm321s(AArch64ISD::MVNImsl
, Op
, DAG
, DefBits
)) ||
7307 (NewOp
= tryAdvSIMDModImm16(AArch64ISD::MVNIshift
, Op
, DAG
, DefBits
)))
7310 DefBits
= UndefBits
;
7311 if ((NewOp
= tryAdvSIMDModImm64(AArch64ISD::MOVIedit
, Op
, DAG
, DefBits
)) ||
7312 (NewOp
= tryAdvSIMDModImm32(AArch64ISD::MOVIshift
, Op
, DAG
, DefBits
)) ||
7313 (NewOp
= tryAdvSIMDModImm321s(AArch64ISD::MOVImsl
, Op
, DAG
, DefBits
)) ||
7314 (NewOp
= tryAdvSIMDModImm16(AArch64ISD::MOVIshift
, Op
, DAG
, DefBits
)) ||
7315 (NewOp
= tryAdvSIMDModImm8(AArch64ISD::MOVI
, Op
, DAG
, DefBits
)) ||
7316 (NewOp
= tryAdvSIMDModImmFP(AArch64ISD::FMOV
, Op
, DAG
, DefBits
)))
7319 DefBits
= ~UndefBits
;
7320 if ((NewOp
= tryAdvSIMDModImm32(AArch64ISD::MVNIshift
, Op
, DAG
, DefBits
)) ||
7321 (NewOp
= tryAdvSIMDModImm321s(AArch64ISD::MVNImsl
, Op
, DAG
, DefBits
)) ||
7322 (NewOp
= tryAdvSIMDModImm16(AArch64ISD::MVNIshift
, Op
, DAG
, DefBits
)))
7329 SDValue
AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op
,
7330 SelectionDAG
&DAG
) const {
7331 EVT VT
= Op
.getValueType();
7333 // Try to build a simple constant vector.
7334 Op
= NormalizeBuildVector(Op
, DAG
);
7335 if (VT
.isInteger()) {
7336 // Certain vector constants, used to express things like logical NOT and
7337 // arithmetic NEG, are passed through unmodified. This allows special
7338 // patterns for these operations to match, which will lower these constants
7339 // to whatever is proven necessary.
7340 BuildVectorSDNode
*BVN
= cast
<BuildVectorSDNode
>(Op
.getNode());
7341 if (BVN
->isConstant())
7342 if (ConstantSDNode
*Const
= BVN
->getConstantSplatNode()) {
7343 unsigned BitSize
= VT
.getVectorElementType().getSizeInBits();
7345 Const
->getAPIntValue().zextOrTrunc(BitSize
).getZExtValue());
7346 if (Val
.isNullValue() || Val
.isAllOnesValue())
7351 if (SDValue V
= ConstantBuildVector(Op
, DAG
))
7354 // Scan through the operands to find some interesting properties we can
7356 // 1) If only one value is used, we can use a DUP, or
7357 // 2) if only the low element is not undef, we can just insert that, or
7358 // 3) if only one constant value is used (w/ some non-constant lanes),
7359 // we can splat the constant value into the whole vector then fill
7360 // in the non-constant lanes.
7361 // 4) FIXME: If different constant values are used, but we can intelligently
7362 // select the values we'll be overwriting for the non-constant
7363 // lanes such that we can directly materialize the vector
7364 // some other way (MOVI, e.g.), we can be sneaky.
7365 // 5) if all operands are EXTRACT_VECTOR_ELT, check for VUZP.
7367 unsigned NumElts
= VT
.getVectorNumElements();
7368 bool isOnlyLowElement
= true;
7369 bool usesOnlyOneValue
= true;
7370 bool usesOnlyOneConstantValue
= true;
7371 bool isConstant
= true;
7372 bool AllLanesExtractElt
= true;
7373 unsigned NumConstantLanes
= 0;
7375 SDValue ConstantValue
;
7376 for (unsigned i
= 0; i
< NumElts
; ++i
) {
7377 SDValue V
= Op
.getOperand(i
);
7378 if (V
.getOpcode() != ISD::EXTRACT_VECTOR_ELT
)
7379 AllLanesExtractElt
= false;
7383 isOnlyLowElement
= false;
7384 if (!isa
<ConstantFPSDNode
>(V
) && !isa
<ConstantSDNode
>(V
))
7387 if (isa
<ConstantSDNode
>(V
) || isa
<ConstantFPSDNode
>(V
)) {
7389 if (!ConstantValue
.getNode())
7391 else if (ConstantValue
!= V
)
7392 usesOnlyOneConstantValue
= false;
7395 if (!Value
.getNode())
7397 else if (V
!= Value
)
7398 usesOnlyOneValue
= false;
7401 if (!Value
.getNode()) {
7403 dbgs() << "LowerBUILD_VECTOR: value undefined, creating undef node\n");
7404 return DAG
.getUNDEF(VT
);
7407 // Convert BUILD_VECTOR where all elements but the lowest are undef into
7408 // SCALAR_TO_VECTOR, except for when we have a single-element constant vector
7409 // as SimplifyDemandedBits will just turn that back into BUILD_VECTOR.
7410 if (isOnlyLowElement
&& !(NumElts
== 1 && isa
<ConstantSDNode
>(Value
))) {
7411 LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: only low element used, creating 1 "
7412 "SCALAR_TO_VECTOR node\n");
7413 return DAG
.getNode(ISD::SCALAR_TO_VECTOR
, dl
, VT
, Value
);
7416 if (AllLanesExtractElt
) {
7417 SDNode
*Vector
= nullptr;
7420 // Check whether the extract elements match the Even pattern <0,2,4,...> or
7421 // the Odd pattern <1,3,5,...>.
7422 for (unsigned i
= 0; i
< NumElts
; ++i
) {
7423 SDValue V
= Op
.getOperand(i
);
7424 const SDNode
*N
= V
.getNode();
7425 if (!isa
<ConstantSDNode
>(N
->getOperand(1)))
7427 SDValue N0
= N
->getOperand(0);
7429 // All elements are extracted from the same vector.
7431 Vector
= N0
.getNode();
7432 // Check that the type of EXTRACT_VECTOR_ELT matches the type of
7434 if (VT
.getVectorElementType() !=
7435 N0
.getValueType().getVectorElementType())
7437 } else if (Vector
!= N0
.getNode()) {
7443 // Extracted values are either at Even indices <0,2,4,...> or at Odd
7444 // indices <1,3,5,...>.
7445 uint64_t Val
= N
->getConstantOperandVal(1);
7450 if (Val
- 1 == 2 * i
) {
7455 // Something does not match: abort.
7462 DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, dl
, VT
, SDValue(Vector
, 0),
7463 DAG
.getConstant(0, dl
, MVT::i64
));
7465 DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, dl
, VT
, SDValue(Vector
, 0),
7466 DAG
.getConstant(NumElts
, dl
, MVT::i64
));
7469 return DAG
.getNode(AArch64ISD::UZP1
, dl
, DAG
.getVTList(VT
, VT
), LHS
,
7472 return DAG
.getNode(AArch64ISD::UZP2
, dl
, DAG
.getVTList(VT
, VT
), LHS
,
7477 // Use DUP for non-constant splats. For f32 constant splats, reduce to
7478 // i32 and try again.
7479 if (usesOnlyOneValue
) {
7481 if (Value
.getOpcode() != ISD::EXTRACT_VECTOR_ELT
||
7482 Value
.getValueType() != VT
) {
7484 dbgs() << "LowerBUILD_VECTOR: use DUP for non-constant splats\n");
7485 return DAG
.getNode(AArch64ISD::DUP
, dl
, VT
, Value
);
7488 // This is actually a DUPLANExx operation, which keeps everything vectory.
7490 SDValue Lane
= Value
.getOperand(1);
7491 Value
= Value
.getOperand(0);
7492 if (Value
.getValueSizeInBits() == 64) {
7494 dbgs() << "LowerBUILD_VECTOR: DUPLANE works on 128-bit vectors, "
7496 Value
= WidenVector(Value
, DAG
);
7499 unsigned Opcode
= getDUPLANEOp(VT
.getVectorElementType());
7500 return DAG
.getNode(Opcode
, dl
, VT
, Value
, Lane
);
7503 if (VT
.getVectorElementType().isFloatingPoint()) {
7504 SmallVector
<SDValue
, 8> Ops
;
7505 EVT EltTy
= VT
.getVectorElementType();
7506 assert ((EltTy
== MVT::f16
|| EltTy
== MVT::f32
|| EltTy
== MVT::f64
) &&
7507 "Unsupported floating-point vector type");
7509 dbgs() << "LowerBUILD_VECTOR: float constant splats, creating int "
7510 "BITCASTS, and try again\n");
7511 MVT NewType
= MVT::getIntegerVT(EltTy
.getSizeInBits());
7512 for (unsigned i
= 0; i
< NumElts
; ++i
)
7513 Ops
.push_back(DAG
.getNode(ISD::BITCAST
, dl
, NewType
, Op
.getOperand(i
)));
7514 EVT VecVT
= EVT::getVectorVT(*DAG
.getContext(), NewType
, NumElts
);
7515 SDValue Val
= DAG
.getBuildVector(VecVT
, dl
, Ops
);
7516 LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: trying to lower new vector: ";
7518 Val
= LowerBUILD_VECTOR(Val
, DAG
);
7520 return DAG
.getNode(ISD::BITCAST
, dl
, VT
, Val
);
7524 // If there was only one constant value used and for more than one lane,
7525 // start by splatting that value, then replace the non-constant lanes. This
7526 // is better than the default, which will perform a separate initialization
7528 if (NumConstantLanes
> 0 && usesOnlyOneConstantValue
) {
7529 // Firstly, try to materialize the splat constant.
7530 SDValue Vec
= DAG
.getSplatBuildVector(VT
, dl
, ConstantValue
),
7531 Val
= ConstantBuildVector(Vec
, DAG
);
7533 // Otherwise, materialize the constant and splat it.
7534 Val
= DAG
.getNode(AArch64ISD::DUP
, dl
, VT
, ConstantValue
);
7535 DAG
.ReplaceAllUsesWith(Vec
.getNode(), &Val
);
7538 // Now insert the non-constant lanes.
7539 for (unsigned i
= 0; i
< NumElts
; ++i
) {
7540 SDValue V
= Op
.getOperand(i
);
7541 SDValue LaneIdx
= DAG
.getConstant(i
, dl
, MVT::i64
);
7542 if (!isa
<ConstantSDNode
>(V
) && !isa
<ConstantFPSDNode
>(V
))
7543 // Note that type legalization likely mucked about with the VT of the
7544 // source operand, so we may have to convert it here before inserting.
7545 Val
= DAG
.getNode(ISD::INSERT_VECTOR_ELT
, dl
, VT
, Val
, V
, LaneIdx
);
7550 // This will generate a load from the constant pool.
7553 dbgs() << "LowerBUILD_VECTOR: all elements are constant, use default "
7558 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
7560 if (SDValue shuffle
= ReconstructShuffle(Op
, DAG
))
7564 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
7565 // know the default expansion would otherwise fall back on something even
7566 // worse. For a vector with one or two non-undef values, that's
7567 // scalar_to_vector for the elements followed by a shuffle (provided the
7568 // shuffle is valid for the target) and materialization element by element
7569 // on the stack followed by a load for everything else.
7570 if (!isConstant
&& !usesOnlyOneValue
) {
7572 dbgs() << "LowerBUILD_VECTOR: alternatives failed, creating sequence "
7573 "of INSERT_VECTOR_ELT\n");
7575 SDValue Vec
= DAG
.getUNDEF(VT
);
7576 SDValue Op0
= Op
.getOperand(0);
7579 // Use SCALAR_TO_VECTOR for lane zero to
7580 // a) Avoid a RMW dependency on the full vector register, and
7581 // b) Allow the register coalescer to fold away the copy if the
7582 // value is already in an S or D register, and we're forced to emit an
7583 // INSERT_SUBREG that we can't fold anywhere.
7585 // We also allow types like i8 and i16 which are illegal scalar but legal
7586 // vector element types. After type-legalization the inserted value is
7587 // extended (i32) and it is safe to cast them to the vector type by ignoring
7588 // the upper bits of the lowest lane (e.g. v8i8, v4i16).
7589 if (!Op0
.isUndef()) {
7590 LLVM_DEBUG(dbgs() << "Creating node for op0, it is not undefined:\n");
7591 Vec
= DAG
.getNode(ISD::SCALAR_TO_VECTOR
, dl
, VT
, Op0
);
7594 LLVM_DEBUG(if (i
< NumElts
) dbgs()
7595 << "Creating nodes for the other vector elements:\n";);
7596 for (; i
< NumElts
; ++i
) {
7597 SDValue V
= Op
.getOperand(i
);
7600 SDValue LaneIdx
= DAG
.getConstant(i
, dl
, MVT::i64
);
7601 Vec
= DAG
.getNode(ISD::INSERT_VECTOR_ELT
, dl
, VT
, Vec
, V
, LaneIdx
);
7607 dbgs() << "LowerBUILD_VECTOR: use default expansion, failed to find "
7608 "better alternative\n");
7612 SDValue
AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op
,
7613 SelectionDAG
&DAG
) const {
7614 assert(Op
.getOpcode() == ISD::INSERT_VECTOR_ELT
&& "Unknown opcode!");
7616 // Check for non-constant or out of range lane.
7617 EVT VT
= Op
.getOperand(0).getValueType();
7618 ConstantSDNode
*CI
= dyn_cast
<ConstantSDNode
>(Op
.getOperand(2));
7619 if (!CI
|| CI
->getZExtValue() >= VT
.getVectorNumElements())
7623 // Insertion/extraction are legal for V128 types.
7624 if (VT
== MVT::v16i8
|| VT
== MVT::v8i16
|| VT
== MVT::v4i32
||
7625 VT
== MVT::v2i64
|| VT
== MVT::v4f32
|| VT
== MVT::v2f64
||
7629 if (VT
!= MVT::v8i8
&& VT
!= MVT::v4i16
&& VT
!= MVT::v2i32
&&
7630 VT
!= MVT::v1i64
&& VT
!= MVT::v2f32
&& VT
!= MVT::v4f16
)
7633 // For V64 types, we perform insertion by expanding the value
7634 // to a V128 type and perform the insertion on that.
7636 SDValue WideVec
= WidenVector(Op
.getOperand(0), DAG
);
7637 EVT WideTy
= WideVec
.getValueType();
7639 SDValue Node
= DAG
.getNode(ISD::INSERT_VECTOR_ELT
, DL
, WideTy
, WideVec
,
7640 Op
.getOperand(1), Op
.getOperand(2));
7641 // Re-narrow the resultant vector.
7642 return NarrowVector(Node
, DAG
);
7646 AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op
,
7647 SelectionDAG
&DAG
) const {
7648 assert(Op
.getOpcode() == ISD::EXTRACT_VECTOR_ELT
&& "Unknown opcode!");
7650 // Check for non-constant or out of range lane.
7651 EVT VT
= Op
.getOperand(0).getValueType();
7652 ConstantSDNode
*CI
= dyn_cast
<ConstantSDNode
>(Op
.getOperand(1));
7653 if (!CI
|| CI
->getZExtValue() >= VT
.getVectorNumElements())
7657 // Insertion/extraction are legal for V128 types.
7658 if (VT
== MVT::v16i8
|| VT
== MVT::v8i16
|| VT
== MVT::v4i32
||
7659 VT
== MVT::v2i64
|| VT
== MVT::v4f32
|| VT
== MVT::v2f64
||
7663 if (VT
!= MVT::v8i8
&& VT
!= MVT::v4i16
&& VT
!= MVT::v2i32
&&
7664 VT
!= MVT::v1i64
&& VT
!= MVT::v2f32
&& VT
!= MVT::v4f16
)
7667 // For V64 types, we perform extraction by expanding the value
7668 // to a V128 type and perform the extraction on that.
7670 SDValue WideVec
= WidenVector(Op
.getOperand(0), DAG
);
7671 EVT WideTy
= WideVec
.getValueType();
7673 EVT ExtrTy
= WideTy
.getVectorElementType();
7674 if (ExtrTy
== MVT::i16
|| ExtrTy
== MVT::i8
)
7677 // For extractions, we just return the result directly.
7678 return DAG
.getNode(ISD::EXTRACT_VECTOR_ELT
, DL
, ExtrTy
, WideVec
,
7682 SDValue
AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op
,
7683 SelectionDAG
&DAG
) const {
7684 EVT VT
= Op
.getOperand(0).getValueType();
7690 ConstantSDNode
*Cst
= dyn_cast
<ConstantSDNode
>(Op
.getOperand(1));
7693 unsigned Val
= Cst
->getZExtValue();
7695 unsigned Size
= Op
.getValueSizeInBits();
7697 // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
7701 // If this is extracting the upper 64-bits of a 128-bit vector, we match
7703 if (Size
== 64 && Val
* VT
.getScalarSizeInBits() == 64)
7709 bool AArch64TargetLowering::isShuffleMaskLegal(ArrayRef
<int> M
, EVT VT
) const {
7710 if (VT
.getVectorNumElements() == 4 &&
7711 (VT
.is128BitVector() || VT
.is64BitVector())) {
7712 unsigned PFIndexes
[4];
7713 for (unsigned i
= 0; i
!= 4; ++i
) {
7717 PFIndexes
[i
] = M
[i
];
7720 // Compute the index in the perfect shuffle table.
7721 unsigned PFTableIndex
= PFIndexes
[0] * 9 * 9 * 9 + PFIndexes
[1] * 9 * 9 +
7722 PFIndexes
[2] * 9 + PFIndexes
[3];
7723 unsigned PFEntry
= PerfectShuffleTable
[PFTableIndex
];
7724 unsigned Cost
= (PFEntry
>> 30);
7732 unsigned DummyUnsigned
;
7734 return (ShuffleVectorSDNode::isSplatMask(&M
[0], VT
) || isREVMask(M
, VT
, 64) ||
7735 isREVMask(M
, VT
, 32) || isREVMask(M
, VT
, 16) ||
7736 isEXTMask(M
, VT
, DummyBool
, DummyUnsigned
) ||
7737 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
7738 isTRNMask(M
, VT
, DummyUnsigned
) || isUZPMask(M
, VT
, DummyUnsigned
) ||
7739 isZIPMask(M
, VT
, DummyUnsigned
) ||
7740 isTRN_v_undef_Mask(M
, VT
, DummyUnsigned
) ||
7741 isUZP_v_undef_Mask(M
, VT
, DummyUnsigned
) ||
7742 isZIP_v_undef_Mask(M
, VT
, DummyUnsigned
) ||
7743 isINSMask(M
, VT
.getVectorNumElements(), DummyBool
, DummyInt
) ||
7744 isConcatMask(M
, VT
, VT
.getSizeInBits() == 128));
7747 /// getVShiftImm - Check if this is a valid build_vector for the immediate
7748 /// operand of a vector shift operation, where all the elements of the
7749 /// build_vector must have the same constant integer value.
7750 static bool getVShiftImm(SDValue Op
, unsigned ElementBits
, int64_t &Cnt
) {
7751 // Ignore bit_converts.
7752 while (Op
.getOpcode() == ISD::BITCAST
)
7753 Op
= Op
.getOperand(0);
7754 BuildVectorSDNode
*BVN
= dyn_cast
<BuildVectorSDNode
>(Op
.getNode());
7755 APInt SplatBits
, SplatUndef
;
7756 unsigned SplatBitSize
;
7758 if (!BVN
|| !BVN
->isConstantSplat(SplatBits
, SplatUndef
, SplatBitSize
,
7759 HasAnyUndefs
, ElementBits
) ||
7760 SplatBitSize
> ElementBits
)
7762 Cnt
= SplatBits
.getSExtValue();
7766 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
7767 /// operand of a vector shift left operation. That value must be in the range:
7768 /// 0 <= Value < ElementBits for a left shift; or
7769 /// 0 <= Value <= ElementBits for a long left shift.
7770 static bool isVShiftLImm(SDValue Op
, EVT VT
, bool isLong
, int64_t &Cnt
) {
7771 assert(VT
.isVector() && "vector shift count is not a vector type");
7772 int64_t ElementBits
= VT
.getScalarSizeInBits();
7773 if (!getVShiftImm(Op
, ElementBits
, Cnt
))
7775 return (Cnt
>= 0 && (isLong
? Cnt
- 1 : Cnt
) < ElementBits
);
7778 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
7779 /// operand of a vector shift right operation. The value must be in the range:
7780 /// 1 <= Value <= ElementBits for a right shift; or
7781 static bool isVShiftRImm(SDValue Op
, EVT VT
, bool isNarrow
, int64_t &Cnt
) {
7782 assert(VT
.isVector() && "vector shift count is not a vector type");
7783 int64_t ElementBits
= VT
.getScalarSizeInBits();
7784 if (!getVShiftImm(Op
, ElementBits
, Cnt
))
7786 return (Cnt
>= 1 && Cnt
<= (isNarrow
? ElementBits
/ 2 : ElementBits
));
7789 SDValue
AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op
,
7790 SelectionDAG
&DAG
) const {
7791 EVT VT
= Op
.getValueType();
7795 if (!Op
.getOperand(1).getValueType().isVector())
7797 unsigned EltSize
= VT
.getScalarSizeInBits();
7799 switch (Op
.getOpcode()) {
7801 llvm_unreachable("unexpected shift opcode");
7804 if (isVShiftLImm(Op
.getOperand(1), VT
, false, Cnt
) && Cnt
< EltSize
)
7805 return DAG
.getNode(AArch64ISD::VSHL
, DL
, VT
, Op
.getOperand(0),
7806 DAG
.getConstant(Cnt
, DL
, MVT::i32
));
7807 return DAG
.getNode(ISD::INTRINSIC_WO_CHAIN
, DL
, VT
,
7808 DAG
.getConstant(Intrinsic::aarch64_neon_ushl
, DL
,
7810 Op
.getOperand(0), Op
.getOperand(1));
7813 // Right shift immediate
7814 if (isVShiftRImm(Op
.getOperand(1), VT
, false, Cnt
) && Cnt
< EltSize
) {
7816 (Op
.getOpcode() == ISD::SRA
) ? AArch64ISD::VASHR
: AArch64ISD::VLSHR
;
7817 return DAG
.getNode(Opc
, DL
, VT
, Op
.getOperand(0),
7818 DAG
.getConstant(Cnt
, DL
, MVT::i32
));
7821 // Right shift register. Note, there is not a shift right register
7822 // instruction, but the shift left register instruction takes a signed
7823 // value, where negative numbers specify a right shift.
7824 unsigned Opc
= (Op
.getOpcode() == ISD::SRA
) ? Intrinsic::aarch64_neon_sshl
7825 : Intrinsic::aarch64_neon_ushl
;
7826 // negate the shift amount
7827 SDValue NegShift
= DAG
.getNode(AArch64ISD::NEG
, DL
, VT
, Op
.getOperand(1));
7828 SDValue NegShiftLeft
=
7829 DAG
.getNode(ISD::INTRINSIC_WO_CHAIN
, DL
, VT
,
7830 DAG
.getConstant(Opc
, DL
, MVT::i32
), Op
.getOperand(0),
7832 return NegShiftLeft
;
7838 static SDValue
EmitVectorComparison(SDValue LHS
, SDValue RHS
,
7839 AArch64CC::CondCode CC
, bool NoNans
, EVT VT
,
7840 const SDLoc
&dl
, SelectionDAG
&DAG
) {
7841 EVT SrcVT
= LHS
.getValueType();
7842 assert(VT
.getSizeInBits() == SrcVT
.getSizeInBits() &&
7843 "function only supposed to emit natural comparisons");
7845 BuildVectorSDNode
*BVN
= dyn_cast
<BuildVectorSDNode
>(RHS
.getNode());
7846 APInt
CnstBits(VT
.getSizeInBits(), 0);
7847 APInt
UndefBits(VT
.getSizeInBits(), 0);
7848 bool IsCnst
= BVN
&& resolveBuildVector(BVN
, CnstBits
, UndefBits
);
7849 bool IsZero
= IsCnst
&& (CnstBits
== 0);
7851 if (SrcVT
.getVectorElementType().isFloatingPoint()) {
7855 case AArch64CC::NE
: {
7858 Fcmeq
= DAG
.getNode(AArch64ISD::FCMEQz
, dl
, VT
, LHS
);
7860 Fcmeq
= DAG
.getNode(AArch64ISD::FCMEQ
, dl
, VT
, LHS
, RHS
);
7861 return DAG
.getNode(AArch64ISD::NOT
, dl
, VT
, Fcmeq
);
7865 return DAG
.getNode(AArch64ISD::FCMEQz
, dl
, VT
, LHS
);
7866 return DAG
.getNode(AArch64ISD::FCMEQ
, dl
, VT
, LHS
, RHS
);
7869 return DAG
.getNode(AArch64ISD::FCMGEz
, dl
, VT
, LHS
);
7870 return DAG
.getNode(AArch64ISD::FCMGE
, dl
, VT
, LHS
, RHS
);
7873 return DAG
.getNode(AArch64ISD::FCMGTz
, dl
, VT
, LHS
);
7874 return DAG
.getNode(AArch64ISD::FCMGT
, dl
, VT
, LHS
, RHS
);
7877 return DAG
.getNode(AArch64ISD::FCMLEz
, dl
, VT
, LHS
);
7878 return DAG
.getNode(AArch64ISD::FCMGE
, dl
, VT
, RHS
, LHS
);
7882 // If we ignore NaNs then we can use to the MI implementation.
7886 return DAG
.getNode(AArch64ISD::FCMLTz
, dl
, VT
, LHS
);
7887 return DAG
.getNode(AArch64ISD::FCMGT
, dl
, VT
, RHS
, LHS
);
7894 case AArch64CC::NE
: {
7897 Cmeq
= DAG
.getNode(AArch64ISD::CMEQz
, dl
, VT
, LHS
);
7899 Cmeq
= DAG
.getNode(AArch64ISD::CMEQ
, dl
, VT
, LHS
, RHS
);
7900 return DAG
.getNode(AArch64ISD::NOT
, dl
, VT
, Cmeq
);
7904 return DAG
.getNode(AArch64ISD::CMEQz
, dl
, VT
, LHS
);
7905 return DAG
.getNode(AArch64ISD::CMEQ
, dl
, VT
, LHS
, RHS
);
7908 return DAG
.getNode(AArch64ISD::CMGEz
, dl
, VT
, LHS
);
7909 return DAG
.getNode(AArch64ISD::CMGE
, dl
, VT
, LHS
, RHS
);
7912 return DAG
.getNode(AArch64ISD::CMGTz
, dl
, VT
, LHS
);
7913 return DAG
.getNode(AArch64ISD::CMGT
, dl
, VT
, LHS
, RHS
);
7916 return DAG
.getNode(AArch64ISD::CMLEz
, dl
, VT
, LHS
);
7917 return DAG
.getNode(AArch64ISD::CMGE
, dl
, VT
, RHS
, LHS
);
7919 return DAG
.getNode(AArch64ISD::CMHS
, dl
, VT
, RHS
, LHS
);
7921 return DAG
.getNode(AArch64ISD::CMHI
, dl
, VT
, RHS
, LHS
);
7924 return DAG
.getNode(AArch64ISD::CMLTz
, dl
, VT
, LHS
);
7925 return DAG
.getNode(AArch64ISD::CMGT
, dl
, VT
, RHS
, LHS
);
7927 return DAG
.getNode(AArch64ISD::CMHI
, dl
, VT
, LHS
, RHS
);
7929 return DAG
.getNode(AArch64ISD::CMHS
, dl
, VT
, LHS
, RHS
);
7933 SDValue
AArch64TargetLowering::LowerVSETCC(SDValue Op
,
7934 SelectionDAG
&DAG
) const {
7935 ISD::CondCode CC
= cast
<CondCodeSDNode
>(Op
.getOperand(2))->get();
7936 SDValue LHS
= Op
.getOperand(0);
7937 SDValue RHS
= Op
.getOperand(1);
7938 EVT CmpVT
= LHS
.getValueType().changeVectorElementTypeToInteger();
7941 if (LHS
.getValueType().getVectorElementType().isInteger()) {
7942 assert(LHS
.getValueType() == RHS
.getValueType());
7943 AArch64CC::CondCode AArch64CC
= changeIntCCToAArch64CC(CC
);
7945 EmitVectorComparison(LHS
, RHS
, AArch64CC
, false, CmpVT
, dl
, DAG
);
7946 return DAG
.getSExtOrTrunc(Cmp
, dl
, Op
.getValueType());
7949 const bool FullFP16
=
7950 static_cast<const AArch64Subtarget
&>(DAG
.getSubtarget()).hasFullFP16();
7952 // Make v4f16 (only) fcmp operations utilise vector instructions
7953 // v8f16 support will be a litle more complicated
7954 if (!FullFP16
&& LHS
.getValueType().getVectorElementType() == MVT::f16
) {
7955 if (LHS
.getValueType().getVectorNumElements() == 4) {
7956 LHS
= DAG
.getNode(ISD::FP_EXTEND
, dl
, MVT::v4f32
, LHS
);
7957 RHS
= DAG
.getNode(ISD::FP_EXTEND
, dl
, MVT::v4f32
, RHS
);
7958 SDValue NewSetcc
= DAG
.getSetCC(dl
, MVT::v4i16
, LHS
, RHS
, CC
);
7959 DAG
.ReplaceAllUsesWith(Op
, NewSetcc
);
7965 assert((!FullFP16
&& LHS
.getValueType().getVectorElementType() != MVT::f16
) ||
7966 LHS
.getValueType().getVectorElementType() != MVT::f128
);
7968 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
7969 // clean. Some of them require two branches to implement.
7970 AArch64CC::CondCode CC1
, CC2
;
7972 changeVectorFPCCToAArch64CC(CC
, CC1
, CC2
, ShouldInvert
);
7974 bool NoNaNs
= getTargetMachine().Options
.NoNaNsFPMath
;
7976 EmitVectorComparison(LHS
, RHS
, CC1
, NoNaNs
, CmpVT
, dl
, DAG
);
7980 if (CC2
!= AArch64CC::AL
) {
7982 EmitVectorComparison(LHS
, RHS
, CC2
, NoNaNs
, CmpVT
, dl
, DAG
);
7983 if (!Cmp2
.getNode())
7986 Cmp
= DAG
.getNode(ISD::OR
, dl
, CmpVT
, Cmp
, Cmp2
);
7989 Cmp
= DAG
.getSExtOrTrunc(Cmp
, dl
, Op
.getValueType());
7992 Cmp
= DAG
.getNOT(dl
, Cmp
, Cmp
.getValueType());
7997 static SDValue
getReductionSDNode(unsigned Op
, SDLoc DL
, SDValue ScalarOp
,
7998 SelectionDAG
&DAG
) {
7999 SDValue VecOp
= ScalarOp
.getOperand(0);
8000 auto Rdx
= DAG
.getNode(Op
, DL
, VecOp
.getSimpleValueType(), VecOp
);
8001 return DAG
.getNode(ISD::EXTRACT_VECTOR_ELT
, DL
, ScalarOp
.getValueType(), Rdx
,
8002 DAG
.getConstant(0, DL
, MVT::i64
));
8005 SDValue
AArch64TargetLowering::LowerVECREDUCE(SDValue Op
,
8006 SelectionDAG
&DAG
) const {
8008 switch (Op
.getOpcode()) {
8009 case ISD::VECREDUCE_ADD
:
8010 return getReductionSDNode(AArch64ISD::UADDV
, dl
, Op
, DAG
);
8011 case ISD::VECREDUCE_SMAX
:
8012 return getReductionSDNode(AArch64ISD::SMAXV
, dl
, Op
, DAG
);
8013 case ISD::VECREDUCE_SMIN
:
8014 return getReductionSDNode(AArch64ISD::SMINV
, dl
, Op
, DAG
);
8015 case ISD::VECREDUCE_UMAX
:
8016 return getReductionSDNode(AArch64ISD::UMAXV
, dl
, Op
, DAG
);
8017 case ISD::VECREDUCE_UMIN
:
8018 return getReductionSDNode(AArch64ISD::UMINV
, dl
, Op
, DAG
);
8019 case ISD::VECREDUCE_FMAX
: {
8020 assert(Op
->getFlags().hasNoNaNs() && "fmax vector reduction needs NoNaN flag");
8022 ISD::INTRINSIC_WO_CHAIN
, dl
, Op
.getValueType(),
8023 DAG
.getConstant(Intrinsic::aarch64_neon_fmaxnmv
, dl
, MVT::i32
),
8026 case ISD::VECREDUCE_FMIN
: {
8027 assert(Op
->getFlags().hasNoNaNs() && "fmin vector reduction needs NoNaN flag");
8029 ISD::INTRINSIC_WO_CHAIN
, dl
, Op
.getValueType(),
8030 DAG
.getConstant(Intrinsic::aarch64_neon_fminnmv
, dl
, MVT::i32
),
8034 llvm_unreachable("Unhandled reduction");
8038 SDValue
AArch64TargetLowering::LowerATOMIC_LOAD_SUB(SDValue Op
,
8039 SelectionDAG
&DAG
) const {
8040 auto &Subtarget
= static_cast<const AArch64Subtarget
&>(DAG
.getSubtarget());
8041 if (!Subtarget
.hasLSE())
8044 // LSE has an atomic load-add instruction, but not a load-sub.
8046 MVT VT
= Op
.getSimpleValueType();
8047 SDValue RHS
= Op
.getOperand(2);
8048 AtomicSDNode
*AN
= cast
<AtomicSDNode
>(Op
.getNode());
8049 RHS
= DAG
.getNode(ISD::SUB
, dl
, VT
, DAG
.getConstant(0, dl
, VT
), RHS
);
8050 return DAG
.getAtomic(ISD::ATOMIC_LOAD_ADD
, dl
, AN
->getMemoryVT(),
8051 Op
.getOperand(0), Op
.getOperand(1), RHS
,
8052 AN
->getMemOperand());
8055 SDValue
AArch64TargetLowering::LowerATOMIC_LOAD_AND(SDValue Op
,
8056 SelectionDAG
&DAG
) const {
8057 auto &Subtarget
= static_cast<const AArch64Subtarget
&>(DAG
.getSubtarget());
8058 if (!Subtarget
.hasLSE())
8061 // LSE has an atomic load-clear instruction, but not a load-and.
8063 MVT VT
= Op
.getSimpleValueType();
8064 SDValue RHS
= Op
.getOperand(2);
8065 AtomicSDNode
*AN
= cast
<AtomicSDNode
>(Op
.getNode());
8066 RHS
= DAG
.getNode(ISD::XOR
, dl
, VT
, DAG
.getConstant(-1ULL, dl
, VT
), RHS
);
8067 return DAG
.getAtomic(ISD::ATOMIC_LOAD_CLR
, dl
, AN
->getMemoryVT(),
8068 Op
.getOperand(0), Op
.getOperand(1), RHS
,
8069 AN
->getMemOperand());
8072 SDValue
AArch64TargetLowering::LowerWindowsDYNAMIC_STACKALLOC(
8073 SDValue Op
, SDValue Chain
, SDValue
&Size
, SelectionDAG
&DAG
) const {
8075 EVT PtrVT
= getPointerTy(DAG
.getDataLayout());
8076 SDValue Callee
= DAG
.getTargetExternalSymbol("__chkstk", PtrVT
, 0);
8078 const AArch64RegisterInfo
*TRI
= Subtarget
->getRegisterInfo();
8079 const uint32_t *Mask
= TRI
->getWindowsStackProbePreservedMask();
8080 if (Subtarget
->hasCustomCallingConv())
8081 TRI
->UpdateCustomCallPreservedMask(DAG
.getMachineFunction(), &Mask
);
8083 Size
= DAG
.getNode(ISD::SRL
, dl
, MVT::i64
, Size
,
8084 DAG
.getConstant(4, dl
, MVT::i64
));
8085 Chain
= DAG
.getCopyToReg(Chain
, dl
, AArch64::X15
, Size
, SDValue());
8087 DAG
.getNode(AArch64ISD::CALL
, dl
, DAG
.getVTList(MVT::Other
, MVT::Glue
),
8088 Chain
, Callee
, DAG
.getRegister(AArch64::X15
, MVT::i64
),
8089 DAG
.getRegisterMask(Mask
), Chain
.getValue(1));
8090 // To match the actual intent better, we should read the output from X15 here
8091 // again (instead of potentially spilling it to the stack), but rereading Size
8092 // from X15 here doesn't work at -O0, since it thinks that X15 is undefined
8095 Size
= DAG
.getNode(ISD::SHL
, dl
, MVT::i64
, Size
,
8096 DAG
.getConstant(4, dl
, MVT::i64
));
8101 AArch64TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op
,
8102 SelectionDAG
&DAG
) const {
8103 assert(Subtarget
->isTargetWindows() &&
8104 "Only Windows alloca probing supported");
8107 SDNode
*Node
= Op
.getNode();
8108 SDValue Chain
= Op
.getOperand(0);
8109 SDValue Size
= Op
.getOperand(1);
8110 unsigned Align
= cast
<ConstantSDNode
>(Op
.getOperand(2))->getZExtValue();
8111 EVT VT
= Node
->getValueType(0);
8113 if (DAG
.getMachineFunction().getFunction().hasFnAttribute(
8114 "no-stack-arg-probe")) {
8115 SDValue SP
= DAG
.getCopyFromReg(Chain
, dl
, AArch64::SP
, MVT::i64
);
8116 Chain
= SP
.getValue(1);
8117 SP
= DAG
.getNode(ISD::SUB
, dl
, MVT::i64
, SP
, Size
);
8119 SP
= DAG
.getNode(ISD::AND
, dl
, VT
, SP
.getValue(0),
8120 DAG
.getConstant(-(uint64_t)Align
, dl
, VT
));
8121 Chain
= DAG
.getCopyToReg(Chain
, dl
, AArch64::SP
, SP
);
8122 SDValue Ops
[2] = {SP
, Chain
};
8123 return DAG
.getMergeValues(Ops
, dl
);
8126 Chain
= DAG
.getCALLSEQ_START(Chain
, 0, 0, dl
);
8128 Chain
= LowerWindowsDYNAMIC_STACKALLOC(Op
, Chain
, Size
, DAG
);
8130 SDValue SP
= DAG
.getCopyFromReg(Chain
, dl
, AArch64::SP
, MVT::i64
);
8131 Chain
= SP
.getValue(1);
8132 SP
= DAG
.getNode(ISD::SUB
, dl
, MVT::i64
, SP
, Size
);
8134 SP
= DAG
.getNode(ISD::AND
, dl
, VT
, SP
.getValue(0),
8135 DAG
.getConstant(-(uint64_t)Align
, dl
, VT
));
8136 Chain
= DAG
.getCopyToReg(Chain
, dl
, AArch64::SP
, SP
);
8138 Chain
= DAG
.getCALLSEQ_END(Chain
, DAG
.getIntPtrConstant(0, dl
, true),
8139 DAG
.getIntPtrConstant(0, dl
, true), SDValue(), dl
);
8141 SDValue Ops
[2] = {SP
, Chain
};
8142 return DAG
.getMergeValues(Ops
, dl
);
8145 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
8146 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
8147 /// specified in the intrinsic calls.
8148 bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo
&Info
,
8150 MachineFunction
&MF
,
8151 unsigned Intrinsic
) const {
8152 auto &DL
= I
.getModule()->getDataLayout();
8153 switch (Intrinsic
) {
8154 case Intrinsic::aarch64_neon_ld2
:
8155 case Intrinsic::aarch64_neon_ld3
:
8156 case Intrinsic::aarch64_neon_ld4
:
8157 case Intrinsic::aarch64_neon_ld1x2
:
8158 case Intrinsic::aarch64_neon_ld1x3
:
8159 case Intrinsic::aarch64_neon_ld1x4
:
8160 case Intrinsic::aarch64_neon_ld2lane
:
8161 case Intrinsic::aarch64_neon_ld3lane
:
8162 case Intrinsic::aarch64_neon_ld4lane
:
8163 case Intrinsic::aarch64_neon_ld2r
:
8164 case Intrinsic::aarch64_neon_ld3r
:
8165 case Intrinsic::aarch64_neon_ld4r
: {
8166 Info
.opc
= ISD::INTRINSIC_W_CHAIN
;
8167 // Conservatively set memVT to the entire set of vectors loaded.
8168 uint64_t NumElts
= DL
.getTypeSizeInBits(I
.getType()) / 64;
8169 Info
.memVT
= EVT::getVectorVT(I
.getType()->getContext(), MVT::i64
, NumElts
);
8170 Info
.ptrVal
= I
.getArgOperand(I
.getNumArgOperands() - 1);
8173 // volatile loads with NEON intrinsics not supported
8174 Info
.flags
= MachineMemOperand::MOLoad
;
8177 case Intrinsic::aarch64_neon_st2
:
8178 case Intrinsic::aarch64_neon_st3
:
8179 case Intrinsic::aarch64_neon_st4
:
8180 case Intrinsic::aarch64_neon_st1x2
:
8181 case Intrinsic::aarch64_neon_st1x3
:
8182 case Intrinsic::aarch64_neon_st1x4
:
8183 case Intrinsic::aarch64_neon_st2lane
:
8184 case Intrinsic::aarch64_neon_st3lane
:
8185 case Intrinsic::aarch64_neon_st4lane
: {
8186 Info
.opc
= ISD::INTRINSIC_VOID
;
8187 // Conservatively set memVT to the entire set of vectors stored.
8188 unsigned NumElts
= 0;
8189 for (unsigned ArgI
= 0, ArgE
= I
.getNumArgOperands(); ArgI
< ArgE
; ++ArgI
) {
8190 Type
*ArgTy
= I
.getArgOperand(ArgI
)->getType();
8191 if (!ArgTy
->isVectorTy())
8193 NumElts
+= DL
.getTypeSizeInBits(ArgTy
) / 64;
8195 Info
.memVT
= EVT::getVectorVT(I
.getType()->getContext(), MVT::i64
, NumElts
);
8196 Info
.ptrVal
= I
.getArgOperand(I
.getNumArgOperands() - 1);
8199 // volatile stores with NEON intrinsics not supported
8200 Info
.flags
= MachineMemOperand::MOStore
;
8203 case Intrinsic::aarch64_ldaxr
:
8204 case Intrinsic::aarch64_ldxr
: {
8205 PointerType
*PtrTy
= cast
<PointerType
>(I
.getArgOperand(0)->getType());
8206 Info
.opc
= ISD::INTRINSIC_W_CHAIN
;
8207 Info
.memVT
= MVT::getVT(PtrTy
->getElementType());
8208 Info
.ptrVal
= I
.getArgOperand(0);
8210 Info
.align
= MaybeAlign(DL
.getABITypeAlignment(PtrTy
->getElementType()));
8211 Info
.flags
= MachineMemOperand::MOLoad
| MachineMemOperand::MOVolatile
;
8214 case Intrinsic::aarch64_stlxr
:
8215 case Intrinsic::aarch64_stxr
: {
8216 PointerType
*PtrTy
= cast
<PointerType
>(I
.getArgOperand(1)->getType());
8217 Info
.opc
= ISD::INTRINSIC_W_CHAIN
;
8218 Info
.memVT
= MVT::getVT(PtrTy
->getElementType());
8219 Info
.ptrVal
= I
.getArgOperand(1);
8221 Info
.align
= MaybeAlign(DL
.getABITypeAlignment(PtrTy
->getElementType()));
8222 Info
.flags
= MachineMemOperand::MOStore
| MachineMemOperand::MOVolatile
;
8225 case Intrinsic::aarch64_ldaxp
:
8226 case Intrinsic::aarch64_ldxp
:
8227 Info
.opc
= ISD::INTRINSIC_W_CHAIN
;
8228 Info
.memVT
= MVT::i128
;
8229 Info
.ptrVal
= I
.getArgOperand(0);
8231 Info
.align
= Align(16);
8232 Info
.flags
= MachineMemOperand::MOLoad
| MachineMemOperand::MOVolatile
;
8234 case Intrinsic::aarch64_stlxp
:
8235 case Intrinsic::aarch64_stxp
:
8236 Info
.opc
= ISD::INTRINSIC_W_CHAIN
;
8237 Info
.memVT
= MVT::i128
;
8238 Info
.ptrVal
= I
.getArgOperand(2);
8240 Info
.align
= Align(16);
8241 Info
.flags
= MachineMemOperand::MOStore
| MachineMemOperand::MOVolatile
;
8250 bool AArch64TargetLowering::shouldReduceLoadWidth(SDNode
*Load
,
8251 ISD::LoadExtType ExtTy
,
8253 // TODO: This may be worth removing. Check regression tests for diffs.
8254 if (!TargetLoweringBase::shouldReduceLoadWidth(Load
, ExtTy
, NewVT
))
8257 // If we're reducing the load width in order to avoid having to use an extra
8258 // instruction to do extension then it's probably a good idea.
8259 if (ExtTy
!= ISD::NON_EXTLOAD
)
8261 // Don't reduce load width if it would prevent us from combining a shift into
8263 MemSDNode
*Mem
= dyn_cast
<MemSDNode
>(Load
);
8265 const SDValue
&Base
= Mem
->getBasePtr();
8266 if (Base
.getOpcode() == ISD::ADD
&&
8267 Base
.getOperand(1).getOpcode() == ISD::SHL
&&
8268 Base
.getOperand(1).hasOneUse() &&
8269 Base
.getOperand(1).getOperand(1).getOpcode() == ISD::Constant
) {
8270 // The shift can be combined if it matches the size of the value being
8271 // loaded (and so reducing the width would make it not match).
8272 uint64_t ShiftAmount
= Base
.getOperand(1).getConstantOperandVal(1);
8273 uint64_t LoadBytes
= Mem
->getMemoryVT().getSizeInBits()/8;
8274 if (ShiftAmount
== Log2_32(LoadBytes
))
8277 // We have no reason to disallow reducing the load width, so allow it.
8281 // Truncations from 64-bit GPR to 32-bit GPR is free.
8282 bool AArch64TargetLowering::isTruncateFree(Type
*Ty1
, Type
*Ty2
) const {
8283 if (!Ty1
->isIntegerTy() || !Ty2
->isIntegerTy())
8285 unsigned NumBits1
= Ty1
->getPrimitiveSizeInBits();
8286 unsigned NumBits2
= Ty2
->getPrimitiveSizeInBits();
8287 return NumBits1
> NumBits2
;
8289 bool AArch64TargetLowering::isTruncateFree(EVT VT1
, EVT VT2
) const {
8290 if (VT1
.isVector() || VT2
.isVector() || !VT1
.isInteger() || !VT2
.isInteger())
8292 unsigned NumBits1
= VT1
.getSizeInBits();
8293 unsigned NumBits2
= VT2
.getSizeInBits();
8294 return NumBits1
> NumBits2
;
8297 /// Check if it is profitable to hoist instruction in then/else to if.
8298 /// Not profitable if I and it's user can form a FMA instruction
8299 /// because we prefer FMSUB/FMADD.
8300 bool AArch64TargetLowering::isProfitableToHoist(Instruction
*I
) const {
8301 if (I
->getOpcode() != Instruction::FMul
)
8304 if (!I
->hasOneUse())
8307 Instruction
*User
= I
->user_back();
8310 !(User
->getOpcode() == Instruction::FSub
||
8311 User
->getOpcode() == Instruction::FAdd
))
8314 const TargetOptions
&Options
= getTargetMachine().Options
;
8315 const DataLayout
&DL
= I
->getModule()->getDataLayout();
8316 EVT VT
= getValueType(DL
, User
->getOperand(0)->getType());
8318 return !(isFMAFasterThanFMulAndFAdd(VT
) &&
8319 isOperationLegalOrCustom(ISD::FMA
, VT
) &&
8320 (Options
.AllowFPOpFusion
== FPOpFusion::Fast
||
8321 Options
.UnsafeFPMath
));
8324 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
8326 bool AArch64TargetLowering::isZExtFree(Type
*Ty1
, Type
*Ty2
) const {
8327 if (!Ty1
->isIntegerTy() || !Ty2
->isIntegerTy())
8329 unsigned NumBits1
= Ty1
->getPrimitiveSizeInBits();
8330 unsigned NumBits2
= Ty2
->getPrimitiveSizeInBits();
8331 return NumBits1
== 32 && NumBits2
== 64;
8333 bool AArch64TargetLowering::isZExtFree(EVT VT1
, EVT VT2
) const {
8334 if (VT1
.isVector() || VT2
.isVector() || !VT1
.isInteger() || !VT2
.isInteger())
8336 unsigned NumBits1
= VT1
.getSizeInBits();
8337 unsigned NumBits2
= VT2
.getSizeInBits();
8338 return NumBits1
== 32 && NumBits2
== 64;
8341 bool AArch64TargetLowering::isZExtFree(SDValue Val
, EVT VT2
) const {
8342 EVT VT1
= Val
.getValueType();
8343 if (isZExtFree(VT1
, VT2
)) {
8347 if (Val
.getOpcode() != ISD::LOAD
)
8350 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
8351 return (VT1
.isSimple() && !VT1
.isVector() && VT1
.isInteger() &&
8352 VT2
.isSimple() && !VT2
.isVector() && VT2
.isInteger() &&
8353 VT1
.getSizeInBits() <= 32);
8356 bool AArch64TargetLowering::isExtFreeImpl(const Instruction
*Ext
) const {
8357 if (isa
<FPExtInst
>(Ext
))
8360 // Vector types are not free.
8361 if (Ext
->getType()->isVectorTy())
8364 for (const Use
&U
: Ext
->uses()) {
8365 // The extension is free if we can fold it with a left shift in an
8366 // addressing mode or an arithmetic operation: add, sub, and cmp.
8368 // Is there a shift?
8369 const Instruction
*Instr
= cast
<Instruction
>(U
.getUser());
8371 // Is this a constant shift?
8372 switch (Instr
->getOpcode()) {
8373 case Instruction::Shl
:
8374 if (!isa
<ConstantInt
>(Instr
->getOperand(1)))
8377 case Instruction::GetElementPtr
: {
8378 gep_type_iterator GTI
= gep_type_begin(Instr
);
8379 auto &DL
= Ext
->getModule()->getDataLayout();
8380 std::advance(GTI
, U
.getOperandNo()-1);
8381 Type
*IdxTy
= GTI
.getIndexedType();
8382 // This extension will end up with a shift because of the scaling factor.
8383 // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
8384 // Get the shift amount based on the scaling factor:
8385 // log2(sizeof(IdxTy)) - log2(8).
8387 countTrailingZeros(DL
.getTypeStoreSizeInBits(IdxTy
)) - 3;
8388 // Is the constant foldable in the shift of the addressing mode?
8389 // I.e., shift amount is between 1 and 4 inclusive.
8390 if (ShiftAmt
== 0 || ShiftAmt
> 4)
8394 case Instruction::Trunc
:
8395 // Check if this is a noop.
8396 // trunc(sext ty1 to ty2) to ty1.
8397 if (Instr
->getType() == Ext
->getOperand(0)->getType())
8404 // At this point we can use the bfm family, so this extension is free
8410 /// Check if both Op1 and Op2 are shufflevector extracts of either the lower
8411 /// or upper half of the vector elements.
8412 static bool areExtractShuffleVectors(Value
*Op1
, Value
*Op2
) {
8413 auto areTypesHalfed
= [](Value
*FullV
, Value
*HalfV
) {
8414 auto *FullVT
= cast
<VectorType
>(FullV
->getType());
8415 auto *HalfVT
= cast
<VectorType
>(HalfV
->getType());
8416 return FullVT
->getBitWidth() == 2 * HalfVT
->getBitWidth();
8419 auto extractHalf
= [](Value
*FullV
, Value
*HalfV
) {
8420 auto *FullVT
= cast
<VectorType
>(FullV
->getType());
8421 auto *HalfVT
= cast
<VectorType
>(HalfV
->getType());
8422 return FullVT
->getNumElements() == 2 * HalfVT
->getNumElements();
8426 Value
*S1Op1
, *S2Op1
;
8427 if (!match(Op1
, m_ShuffleVector(m_Value(S1Op1
), m_Undef(), m_Constant(M1
))) ||
8428 !match(Op2
, m_ShuffleVector(m_Value(S2Op1
), m_Undef(), m_Constant(M2
))))
8431 // Check that the operands are half as wide as the result and we extract
8432 // half of the elements of the input vectors.
8433 if (!areTypesHalfed(S1Op1
, Op1
) || !areTypesHalfed(S2Op1
, Op2
) ||
8434 !extractHalf(S1Op1
, Op1
) || !extractHalf(S2Op1
, Op2
))
8437 // Check the mask extracts either the lower or upper half of vector
8441 int NumElements
= cast
<VectorType
>(Op1
->getType())->getNumElements() * 2;
8442 if (!ShuffleVectorInst::isExtractSubvectorMask(M1
, NumElements
, M1Start
) ||
8443 !ShuffleVectorInst::isExtractSubvectorMask(M2
, NumElements
, M2Start
) ||
8444 M1Start
!= M2Start
|| (M1Start
!= 0 && M2Start
!= (NumElements
/ 2)))
8450 /// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth
8451 /// of the vector elements.
8452 static bool areExtractExts(Value
*Ext1
, Value
*Ext2
) {
8453 auto areExtDoubled
= [](Instruction
*Ext
) {
8454 return Ext
->getType()->getScalarSizeInBits() ==
8455 2 * Ext
->getOperand(0)->getType()->getScalarSizeInBits();
8458 if (!match(Ext1
, m_ZExtOrSExt(m_Value())) ||
8459 !match(Ext2
, m_ZExtOrSExt(m_Value())) ||
8460 !areExtDoubled(cast
<Instruction
>(Ext1
)) ||
8461 !areExtDoubled(cast
<Instruction
>(Ext2
)))
8467 /// Check if sinking \p I's operands to I's basic block is profitable, because
8468 /// the operands can be folded into a target instruction, e.g.
8469 /// shufflevectors extracts and/or sext/zext can be folded into (u,s)subl(2).
8470 bool AArch64TargetLowering::shouldSinkOperands(
8471 Instruction
*I
, SmallVectorImpl
<Use
*> &Ops
) const {
8472 if (!I
->getType()->isVectorTy())
8475 if (IntrinsicInst
*II
= dyn_cast
<IntrinsicInst
>(I
)) {
8476 switch (II
->getIntrinsicID()) {
8477 case Intrinsic::aarch64_neon_umull
:
8478 if (!areExtractShuffleVectors(II
->getOperand(0), II
->getOperand(1)))
8480 Ops
.push_back(&II
->getOperandUse(0));
8481 Ops
.push_back(&II
->getOperandUse(1));
8488 switch (I
->getOpcode()) {
8489 case Instruction::Sub
:
8490 case Instruction::Add
: {
8491 if (!areExtractExts(I
->getOperand(0), I
->getOperand(1)))
8494 // If the exts' operands extract either the lower or upper elements, we
8495 // can sink them too.
8496 auto Ext1
= cast
<Instruction
>(I
->getOperand(0));
8497 auto Ext2
= cast
<Instruction
>(I
->getOperand(1));
8498 if (areExtractShuffleVectors(Ext1
, Ext2
)) {
8499 Ops
.push_back(&Ext1
->getOperandUse(0));
8500 Ops
.push_back(&Ext2
->getOperandUse(0));
8503 Ops
.push_back(&I
->getOperandUse(0));
8504 Ops
.push_back(&I
->getOperandUse(1));
8514 bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType
,
8515 unsigned &RequiredAligment
) const {
8516 if (!LoadedType
.isSimple() ||
8517 (!LoadedType
.isInteger() && !LoadedType
.isFloatingPoint()))
8519 // Cyclone supports unaligned accesses.
8520 RequiredAligment
= 0;
8521 unsigned NumBits
= LoadedType
.getSizeInBits();
8522 return NumBits
== 32 || NumBits
== 64;
8525 /// A helper function for determining the number of interleaved accesses we
8526 /// will generate when lowering accesses of the given type.
8528 AArch64TargetLowering::getNumInterleavedAccesses(VectorType
*VecTy
,
8529 const DataLayout
&DL
) const {
8530 return (DL
.getTypeSizeInBits(VecTy
) + 127) / 128;
8533 MachineMemOperand::Flags
8534 AArch64TargetLowering::getMMOFlags(const Instruction
&I
) const {
8535 if (Subtarget
->getProcFamily() == AArch64Subtarget::Falkor
&&
8536 I
.getMetadata(FALKOR_STRIDED_ACCESS_MD
) != nullptr)
8537 return MOStridedAccess
;
8538 return MachineMemOperand::MONone
;
8541 bool AArch64TargetLowering::isLegalInterleavedAccessType(
8542 VectorType
*VecTy
, const DataLayout
&DL
) const {
8544 unsigned VecSize
= DL
.getTypeSizeInBits(VecTy
);
8545 unsigned ElSize
= DL
.getTypeSizeInBits(VecTy
->getElementType());
8547 // Ensure the number of vector elements is greater than 1.
8548 if (VecTy
->getNumElements() < 2)
8551 // Ensure the element type is legal.
8552 if (ElSize
!= 8 && ElSize
!= 16 && ElSize
!= 32 && ElSize
!= 64)
8555 // Ensure the total vector size is 64 or a multiple of 128. Types larger than
8556 // 128 will be split into multiple interleaved accesses.
8557 return VecSize
== 64 || VecSize
% 128 == 0;
8560 /// Lower an interleaved load into a ldN intrinsic.
8562 /// E.g. Lower an interleaved load (Factor = 2):
8563 /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr
8564 /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
8565 /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
8568 /// %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
8569 /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
8570 /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
8571 bool AArch64TargetLowering::lowerInterleavedLoad(
8572 LoadInst
*LI
, ArrayRef
<ShuffleVectorInst
*> Shuffles
,
8573 ArrayRef
<unsigned> Indices
, unsigned Factor
) const {
8574 assert(Factor
>= 2 && Factor
<= getMaxSupportedInterleaveFactor() &&
8575 "Invalid interleave factor");
8576 assert(!Shuffles
.empty() && "Empty shufflevector input");
8577 assert(Shuffles
.size() == Indices
.size() &&
8578 "Unmatched number of shufflevectors and indices");
8580 const DataLayout
&DL
= LI
->getModule()->getDataLayout();
8582 VectorType
*VecTy
= Shuffles
[0]->getType();
8584 // Skip if we do not have NEON and skip illegal vector types. We can
8585 // "legalize" wide vector types into multiple interleaved accesses as long as
8586 // the vector types are divisible by 128.
8587 if (!Subtarget
->hasNEON() || !isLegalInterleavedAccessType(VecTy
, DL
))
8590 unsigned NumLoads
= getNumInterleavedAccesses(VecTy
, DL
);
8592 // A pointer vector can not be the return type of the ldN intrinsics. Need to
8593 // load integer vectors first and then convert to pointer vectors.
8594 Type
*EltTy
= VecTy
->getVectorElementType();
8595 if (EltTy
->isPointerTy())
8597 VectorType::get(DL
.getIntPtrType(EltTy
), VecTy
->getVectorNumElements());
8599 IRBuilder
<> Builder(LI
);
8601 // The base address of the load.
8602 Value
*BaseAddr
= LI
->getPointerOperand();
8605 // If we're going to generate more than one load, reset the sub-vector type
8606 // to something legal.
8607 VecTy
= VectorType::get(VecTy
->getVectorElementType(),
8608 VecTy
->getVectorNumElements() / NumLoads
);
8610 // We will compute the pointer operand of each load from the original base
8611 // address using GEPs. Cast the base address to a pointer to the scalar
8613 BaseAddr
= Builder
.CreateBitCast(
8614 BaseAddr
, VecTy
->getVectorElementType()->getPointerTo(
8615 LI
->getPointerAddressSpace()));
8618 Type
*PtrTy
= VecTy
->getPointerTo(LI
->getPointerAddressSpace());
8619 Type
*Tys
[2] = {VecTy
, PtrTy
};
8620 static const Intrinsic::ID LoadInts
[3] = {Intrinsic::aarch64_neon_ld2
,
8621 Intrinsic::aarch64_neon_ld3
,
8622 Intrinsic::aarch64_neon_ld4
};
8624 Intrinsic::getDeclaration(LI
->getModule(), LoadInts
[Factor
- 2], Tys
);
8626 // Holds sub-vectors extracted from the load intrinsic return values. The
8627 // sub-vectors are associated with the shufflevector instructions they will
8629 DenseMap
<ShuffleVectorInst
*, SmallVector
<Value
*, 4>> SubVecs
;
8631 for (unsigned LoadCount
= 0; LoadCount
< NumLoads
; ++LoadCount
) {
8633 // If we're generating more than one load, compute the base address of
8634 // subsequent loads as an offset from the previous.
8637 Builder
.CreateConstGEP1_32(VecTy
->getVectorElementType(), BaseAddr
,
8638 VecTy
->getVectorNumElements() * Factor
);
8640 CallInst
*LdN
= Builder
.CreateCall(
8641 LdNFunc
, Builder
.CreateBitCast(BaseAddr
, PtrTy
), "ldN");
8643 // Extract and store the sub-vectors returned by the load intrinsic.
8644 for (unsigned i
= 0; i
< Shuffles
.size(); i
++) {
8645 ShuffleVectorInst
*SVI
= Shuffles
[i
];
8646 unsigned Index
= Indices
[i
];
8648 Value
*SubVec
= Builder
.CreateExtractValue(LdN
, Index
);
8650 // Convert the integer vector to pointer vector if the element is pointer.
8651 if (EltTy
->isPointerTy())
8652 SubVec
= Builder
.CreateIntToPtr(
8653 SubVec
, VectorType::get(SVI
->getType()->getVectorElementType(),
8654 VecTy
->getVectorNumElements()));
8655 SubVecs
[SVI
].push_back(SubVec
);
8659 // Replace uses of the shufflevector instructions with the sub-vectors
8660 // returned by the load intrinsic. If a shufflevector instruction is
8661 // associated with more than one sub-vector, those sub-vectors will be
8662 // concatenated into a single wide vector.
8663 for (ShuffleVectorInst
*SVI
: Shuffles
) {
8664 auto &SubVec
= SubVecs
[SVI
];
8666 SubVec
.size() > 1 ? concatenateVectors(Builder
, SubVec
) : SubVec
[0];
8667 SVI
->replaceAllUsesWith(WideVec
);
8673 /// Lower an interleaved store into a stN intrinsic.
8675 /// E.g. Lower an interleaved store (Factor = 3):
8676 /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
8677 /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
8678 /// store <12 x i32> %i.vec, <12 x i32>* %ptr
8681 /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
8682 /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
8683 /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
8684 /// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
8686 /// Note that the new shufflevectors will be removed and we'll only generate one
8687 /// st3 instruction in CodeGen.
8689 /// Example for a more general valid mask (Factor 3). Lower:
8690 /// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
8691 /// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
8692 /// store <12 x i32> %i.vec, <12 x i32>* %ptr
8695 /// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
8696 /// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
8697 /// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
8698 /// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
8699 bool AArch64TargetLowering::lowerInterleavedStore(StoreInst
*SI
,
8700 ShuffleVectorInst
*SVI
,
8701 unsigned Factor
) const {
8702 assert(Factor
>= 2 && Factor
<= getMaxSupportedInterleaveFactor() &&
8703 "Invalid interleave factor");
8705 VectorType
*VecTy
= SVI
->getType();
8706 assert(VecTy
->getVectorNumElements() % Factor
== 0 &&
8707 "Invalid interleaved store");
8709 unsigned LaneLen
= VecTy
->getVectorNumElements() / Factor
;
8710 Type
*EltTy
= VecTy
->getVectorElementType();
8711 VectorType
*SubVecTy
= VectorType::get(EltTy
, LaneLen
);
8713 const DataLayout
&DL
= SI
->getModule()->getDataLayout();
8715 // Skip if we do not have NEON and skip illegal vector types. We can
8716 // "legalize" wide vector types into multiple interleaved accesses as long as
8717 // the vector types are divisible by 128.
8718 if (!Subtarget
->hasNEON() || !isLegalInterleavedAccessType(SubVecTy
, DL
))
8721 unsigned NumStores
= getNumInterleavedAccesses(SubVecTy
, DL
);
8723 Value
*Op0
= SVI
->getOperand(0);
8724 Value
*Op1
= SVI
->getOperand(1);
8725 IRBuilder
<> Builder(SI
);
8727 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
8728 // vectors to integer vectors.
8729 if (EltTy
->isPointerTy()) {
8730 Type
*IntTy
= DL
.getIntPtrType(EltTy
);
8731 unsigned NumOpElts
= Op0
->getType()->getVectorNumElements();
8733 // Convert to the corresponding integer vector.
8734 Type
*IntVecTy
= VectorType::get(IntTy
, NumOpElts
);
8735 Op0
= Builder
.CreatePtrToInt(Op0
, IntVecTy
);
8736 Op1
= Builder
.CreatePtrToInt(Op1
, IntVecTy
);
8738 SubVecTy
= VectorType::get(IntTy
, LaneLen
);
8741 // The base address of the store.
8742 Value
*BaseAddr
= SI
->getPointerOperand();
8744 if (NumStores
> 1) {
8745 // If we're going to generate more than one store, reset the lane length
8746 // and sub-vector type to something legal.
8747 LaneLen
/= NumStores
;
8748 SubVecTy
= VectorType::get(SubVecTy
->getVectorElementType(), LaneLen
);
8750 // We will compute the pointer operand of each store from the original base
8751 // address using GEPs. Cast the base address to a pointer to the scalar
8753 BaseAddr
= Builder
.CreateBitCast(
8754 BaseAddr
, SubVecTy
->getVectorElementType()->getPointerTo(
8755 SI
->getPointerAddressSpace()));
8758 auto Mask
= SVI
->getShuffleMask();
8760 Type
*PtrTy
= SubVecTy
->getPointerTo(SI
->getPointerAddressSpace());
8761 Type
*Tys
[2] = {SubVecTy
, PtrTy
};
8762 static const Intrinsic::ID StoreInts
[3] = {Intrinsic::aarch64_neon_st2
,
8763 Intrinsic::aarch64_neon_st3
,
8764 Intrinsic::aarch64_neon_st4
};
8766 Intrinsic::getDeclaration(SI
->getModule(), StoreInts
[Factor
- 2], Tys
);
8768 for (unsigned StoreCount
= 0; StoreCount
< NumStores
; ++StoreCount
) {
8770 SmallVector
<Value
*, 5> Ops
;
8772 // Split the shufflevector operands into sub vectors for the new stN call.
8773 for (unsigned i
= 0; i
< Factor
; i
++) {
8774 unsigned IdxI
= StoreCount
* LaneLen
* Factor
+ i
;
8775 if (Mask
[IdxI
] >= 0) {
8776 Ops
.push_back(Builder
.CreateShuffleVector(
8777 Op0
, Op1
, createSequentialMask(Builder
, Mask
[IdxI
], LaneLen
, 0)));
8779 unsigned StartMask
= 0;
8780 for (unsigned j
= 1; j
< LaneLen
; j
++) {
8781 unsigned IdxJ
= StoreCount
* LaneLen
* Factor
+ j
;
8782 if (Mask
[IdxJ
* Factor
+ IdxI
] >= 0) {
8783 StartMask
= Mask
[IdxJ
* Factor
+ IdxI
] - IdxJ
;
8787 // Note: Filling undef gaps with random elements is ok, since
8788 // those elements were being written anyway (with undefs).
8789 // In the case of all undefs we're defaulting to using elems from 0
8790 // Note: StartMask cannot be negative, it's checked in
8791 // isReInterleaveMask
8792 Ops
.push_back(Builder
.CreateShuffleVector(
8793 Op0
, Op1
, createSequentialMask(Builder
, StartMask
, LaneLen
, 0)));
8797 // If we generating more than one store, we compute the base address of
8798 // subsequent stores as an offset from the previous.
8800 BaseAddr
= Builder
.CreateConstGEP1_32(SubVecTy
->getVectorElementType(),
8801 BaseAddr
, LaneLen
* Factor
);
8803 Ops
.push_back(Builder
.CreateBitCast(BaseAddr
, PtrTy
));
8804 Builder
.CreateCall(StNFunc
, Ops
);
8809 static bool memOpAlign(unsigned DstAlign
, unsigned SrcAlign
,
8810 unsigned AlignCheck
) {
8811 return ((SrcAlign
== 0 || SrcAlign
% AlignCheck
== 0) &&
8812 (DstAlign
== 0 || DstAlign
% AlignCheck
== 0));
8815 EVT
AArch64TargetLowering::getOptimalMemOpType(
8816 uint64_t Size
, unsigned DstAlign
, unsigned SrcAlign
, bool IsMemset
,
8817 bool ZeroMemset
, bool MemcpyStrSrc
,
8818 const AttributeList
&FuncAttributes
) const {
8819 bool CanImplicitFloat
=
8820 !FuncAttributes
.hasFnAttribute(Attribute::NoImplicitFloat
);
8821 bool CanUseNEON
= Subtarget
->hasNEON() && CanImplicitFloat
;
8822 bool CanUseFP
= Subtarget
->hasFPARMv8() && CanImplicitFloat
;
8823 // Only use AdvSIMD to implement memset of 32-byte and above. It would have
8824 // taken one instruction to materialize the v2i64 zero and one store (with
8825 // restrictive addressing mode). Just do i64 stores.
8826 bool IsSmallMemset
= IsMemset
&& Size
< 32;
8827 auto AlignmentIsAcceptable
= [&](EVT VT
, unsigned AlignCheck
) {
8828 if (memOpAlign(SrcAlign
, DstAlign
, AlignCheck
))
8831 return allowsMisalignedMemoryAccesses(VT
, 0, 1, MachineMemOperand::MONone
,
8836 if (CanUseNEON
&& IsMemset
&& !IsSmallMemset
&&
8837 AlignmentIsAcceptable(MVT::v2i64
, 16))
8839 if (CanUseFP
&& !IsSmallMemset
&& AlignmentIsAcceptable(MVT::f128
, 16))
8841 if (Size
>= 8 && AlignmentIsAcceptable(MVT::i64
, 8))
8843 if (Size
>= 4 && AlignmentIsAcceptable(MVT::i32
, 4))
8848 LLT
AArch64TargetLowering::getOptimalMemOpLLT(
8849 uint64_t Size
, unsigned DstAlign
, unsigned SrcAlign
, bool IsMemset
,
8850 bool ZeroMemset
, bool MemcpyStrSrc
,
8851 const AttributeList
&FuncAttributes
) const {
8852 bool CanImplicitFloat
=
8853 !FuncAttributes
.hasFnAttribute(Attribute::NoImplicitFloat
);
8854 bool CanUseNEON
= Subtarget
->hasNEON() && CanImplicitFloat
;
8855 bool CanUseFP
= Subtarget
->hasFPARMv8() && CanImplicitFloat
;
8856 // Only use AdvSIMD to implement memset of 32-byte and above. It would have
8857 // taken one instruction to materialize the v2i64 zero and one store (with
8858 // restrictive addressing mode). Just do i64 stores.
8859 bool IsSmallMemset
= IsMemset
&& Size
< 32;
8860 auto AlignmentIsAcceptable
= [&](EVT VT
, unsigned AlignCheck
) {
8861 if (memOpAlign(SrcAlign
, DstAlign
, AlignCheck
))
8864 return allowsMisalignedMemoryAccesses(VT
, 0, 1, MachineMemOperand::MONone
,
8869 if (CanUseNEON
&& IsMemset
&& !IsSmallMemset
&&
8870 AlignmentIsAcceptable(MVT::v2i64
, 16))
8871 return LLT::vector(2, 64);
8872 if (CanUseFP
&& !IsSmallMemset
&& AlignmentIsAcceptable(MVT::f128
, 16))
8873 return LLT::scalar(128);
8874 if (Size
>= 8 && AlignmentIsAcceptable(MVT::i64
, 8))
8875 return LLT::scalar(64);
8876 if (Size
>= 4 && AlignmentIsAcceptable(MVT::i32
, 4))
8877 return LLT::scalar(32);
8881 // 12-bit optionally shifted immediates are legal for adds.
8882 bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed
) const {
8883 if (Immed
== std::numeric_limits
<int64_t>::min()) {
8884 LLVM_DEBUG(dbgs() << "Illegal add imm " << Immed
8885 << ": avoid UB for INT64_MIN\n");
8888 // Same encoding for add/sub, just flip the sign.
8889 Immed
= std::abs(Immed
);
8890 bool IsLegal
= ((Immed
>> 12) == 0 ||
8891 ((Immed
& 0xfff) == 0 && Immed
>> 24 == 0));
8892 LLVM_DEBUG(dbgs() << "Is " << Immed
8893 << " legal add imm: " << (IsLegal
? "yes" : "no") << "\n");
8897 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
8898 // immediates is the same as for an add or a sub.
8899 bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed
) const {
8900 return isLegalAddImmediate(Immed
);
8903 /// isLegalAddressingMode - Return true if the addressing mode represented
8904 /// by AM is legal for this target, for a load/store of the specified type.
8905 bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout
&DL
,
8906 const AddrMode
&AM
, Type
*Ty
,
8907 unsigned AS
, Instruction
*I
) const {
8908 // AArch64 has five basic addressing modes:
8910 // reg + 9-bit signed offset
8911 // reg + SIZE_IN_BYTES * 12-bit unsigned offset
8913 // reg + SIZE_IN_BYTES * reg
8915 // No global is ever allowed as a base.
8919 // No reg+reg+imm addressing.
8920 if (AM
.HasBaseReg
&& AM
.BaseOffs
&& AM
.Scale
)
8923 // check reg + imm case:
8924 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
8925 uint64_t NumBytes
= 0;
8926 if (Ty
->isSized()) {
8927 uint64_t NumBits
= DL
.getTypeSizeInBits(Ty
);
8928 NumBytes
= NumBits
/ 8;
8929 if (!isPowerOf2_64(NumBits
))
8934 int64_t Offset
= AM
.BaseOffs
;
8936 // 9-bit signed offset
8937 if (isInt
<9>(Offset
))
8940 // 12-bit unsigned offset
8941 unsigned shift
= Log2_64(NumBytes
);
8942 if (NumBytes
&& Offset
> 0 && (Offset
/ NumBytes
) <= (1LL << 12) - 1 &&
8943 // Must be a multiple of NumBytes (NumBytes is a power of 2)
8944 (Offset
>> shift
) << shift
== Offset
)
8949 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
8951 return AM
.Scale
== 1 || (AM
.Scale
> 0 && (uint64_t)AM
.Scale
== NumBytes
);
8954 bool AArch64TargetLowering::shouldConsiderGEPOffsetSplit() const {
8955 // Consider splitting large offset of struct or array.
8959 int AArch64TargetLowering::getScalingFactorCost(const DataLayout
&DL
,
8960 const AddrMode
&AM
, Type
*Ty
,
8961 unsigned AS
) const {
8962 // Scaling factors are not free at all.
8963 // Operands | Rt Latency
8964 // -------------------------------------------
8966 // -------------------------------------------
8967 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5
8968 // Rt, [Xn, Wm, <extend> #imm] |
8969 if (isLegalAddressingMode(DL
, AM
, Ty
, AS
))
8970 // Scale represents reg2 * scale, thus account for 1 if
8971 // it is not equal to 0 or 1.
8972 return AM
.Scale
!= 0 && AM
.Scale
!= 1;
8976 bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT
) const {
8977 VT
= VT
.getScalarType();
8982 switch (VT
.getSimpleVT().SimpleTy
) {
8994 AArch64TargetLowering::getScratchRegisters(CallingConv::ID
) const {
8995 // LR is a callee-save register, but we must treat it as clobbered by any call
8996 // site. Hence we include LR in the scratch registers, which are in turn added
8997 // as implicit-defs for stackmaps and patchpoints.
8998 static const MCPhysReg ScratchRegs
[] = {
8999 AArch64::X16
, AArch64::X17
, AArch64::LR
, 0
9005 AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode
*N
,
9006 CombineLevel Level
) const {
9007 N
= N
->getOperand(0).getNode();
9008 EVT VT
= N
->getValueType(0);
9009 // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
9010 // it with shift to let it be lowered to UBFX.
9011 if (N
->getOpcode() == ISD::AND
&& (VT
== MVT::i32
|| VT
== MVT::i64
) &&
9012 isa
<ConstantSDNode
>(N
->getOperand(1))) {
9013 uint64_t TruncMask
= N
->getConstantOperandVal(1);
9014 if (isMask_64(TruncMask
) &&
9015 N
->getOperand(0).getOpcode() == ISD::SRL
&&
9016 isa
<ConstantSDNode
>(N
->getOperand(0)->getOperand(1)))
9022 bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt
&Imm
,
9024 assert(Ty
->isIntegerTy());
9026 unsigned BitSize
= Ty
->getPrimitiveSizeInBits();
9030 int64_t Val
= Imm
.getSExtValue();
9031 if (Val
== 0 || AArch64_AM::isLogicalImmediate(Val
, BitSize
))
9034 if ((int64_t)Val
< 0)
9037 Val
&= (1LL << 32) - 1;
9039 unsigned LZ
= countLeadingZeros((uint64_t)Val
);
9040 unsigned Shift
= (63 - LZ
) / 16;
9041 // MOVZ is free so return true for one or fewer MOVK.
9045 bool AArch64TargetLowering::isExtractSubvectorCheap(EVT ResVT
, EVT SrcVT
,
9046 unsigned Index
) const {
9047 if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR
, ResVT
))
9050 return (Index
== 0 || Index
== ResVT
.getVectorNumElements());
9053 /// Turn vector tests of the signbit in the form of:
9054 /// xor (sra X, elt_size(X)-1), -1
9057 static SDValue
foldVectorXorShiftIntoCmp(SDNode
*N
, SelectionDAG
&DAG
,
9058 const AArch64Subtarget
*Subtarget
) {
9059 EVT VT
= N
->getValueType(0);
9060 if (!Subtarget
->hasNEON() || !VT
.isVector())
9063 // There must be a shift right algebraic before the xor, and the xor must be a
9065 SDValue Shift
= N
->getOperand(0);
9066 SDValue Ones
= N
->getOperand(1);
9067 if (Shift
.getOpcode() != AArch64ISD::VASHR
|| !Shift
.hasOneUse() ||
9068 !ISD::isBuildVectorAllOnes(Ones
.getNode()))
9071 // The shift should be smearing the sign bit across each vector element.
9072 auto *ShiftAmt
= dyn_cast
<ConstantSDNode
>(Shift
.getOperand(1));
9073 EVT ShiftEltTy
= Shift
.getValueType().getVectorElementType();
9074 if (!ShiftAmt
|| ShiftAmt
->getZExtValue() != ShiftEltTy
.getSizeInBits() - 1)
9077 return DAG
.getNode(AArch64ISD::CMGEz
, SDLoc(N
), VT
, Shift
.getOperand(0));
9080 // Generate SUBS and CSEL for integer abs.
9081 static SDValue
performIntegerAbsCombine(SDNode
*N
, SelectionDAG
&DAG
) {
9082 EVT VT
= N
->getValueType(0);
9084 SDValue N0
= N
->getOperand(0);
9085 SDValue N1
= N
->getOperand(1);
9088 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
9089 // and change it to SUB and CSEL.
9090 if (VT
.isInteger() && N
->getOpcode() == ISD::XOR
&&
9091 N0
.getOpcode() == ISD::ADD
&& N0
.getOperand(1) == N1
&&
9092 N1
.getOpcode() == ISD::SRA
&& N1
.getOperand(0) == N0
.getOperand(0))
9093 if (ConstantSDNode
*Y1C
= dyn_cast
<ConstantSDNode
>(N1
.getOperand(1)))
9094 if (Y1C
->getAPIntValue() == VT
.getSizeInBits() - 1) {
9095 SDValue Neg
= DAG
.getNode(ISD::SUB
, DL
, VT
, DAG
.getConstant(0, DL
, VT
),
9097 // Generate SUBS & CSEL.
9099 DAG
.getNode(AArch64ISD::SUBS
, DL
, DAG
.getVTList(VT
, MVT::i32
),
9100 N0
.getOperand(0), DAG
.getConstant(0, DL
, VT
));
9101 return DAG
.getNode(AArch64ISD::CSEL
, DL
, VT
, N0
.getOperand(0), Neg
,
9102 DAG
.getConstant(AArch64CC::PL
, DL
, MVT::i32
),
9103 SDValue(Cmp
.getNode(), 1));
9108 static SDValue
performXorCombine(SDNode
*N
, SelectionDAG
&DAG
,
9109 TargetLowering::DAGCombinerInfo
&DCI
,
9110 const AArch64Subtarget
*Subtarget
) {
9111 if (DCI
.isBeforeLegalizeOps())
9114 if (SDValue Cmp
= foldVectorXorShiftIntoCmp(N
, DAG
, Subtarget
))
9117 return performIntegerAbsCombine(N
, DAG
);
9121 AArch64TargetLowering::BuildSDIVPow2(SDNode
*N
, const APInt
&Divisor
,
9123 SmallVectorImpl
<SDNode
*> &Created
) const {
9124 AttributeList Attr
= DAG
.getMachineFunction().getFunction().getAttributes();
9125 if (isIntDivCheap(N
->getValueType(0), Attr
))
9126 return SDValue(N
,0); // Lower SDIV as SDIV
9128 // fold (sdiv X, pow2)
9129 EVT VT
= N
->getValueType(0);
9130 if ((VT
!= MVT::i32
&& VT
!= MVT::i64
) ||
9131 !(Divisor
.isPowerOf2() || (-Divisor
).isPowerOf2()))
9135 SDValue N0
= N
->getOperand(0);
9136 unsigned Lg2
= Divisor
.countTrailingZeros();
9137 SDValue Zero
= DAG
.getConstant(0, DL
, VT
);
9138 SDValue Pow2MinusOne
= DAG
.getConstant((1ULL << Lg2
) - 1, DL
, VT
);
9140 // Add (N0 < 0) ? Pow2 - 1 : 0;
9142 SDValue Cmp
= getAArch64Cmp(N0
, Zero
, ISD::SETLT
, CCVal
, DAG
, DL
);
9143 SDValue Add
= DAG
.getNode(ISD::ADD
, DL
, VT
, N0
, Pow2MinusOne
);
9144 SDValue CSel
= DAG
.getNode(AArch64ISD::CSEL
, DL
, VT
, Add
, N0
, CCVal
, Cmp
);
9146 Created
.push_back(Cmp
.getNode());
9147 Created
.push_back(Add
.getNode());
9148 Created
.push_back(CSel
.getNode());
9152 DAG
.getNode(ISD::SRA
, DL
, VT
, CSel
, DAG
.getConstant(Lg2
, DL
, MVT::i64
));
9154 // If we're dividing by a positive value, we're done. Otherwise, we must
9155 // negate the result.
9156 if (Divisor
.isNonNegative())
9159 Created
.push_back(SRA
.getNode());
9160 return DAG
.getNode(ISD::SUB
, DL
, VT
, DAG
.getConstant(0, DL
, VT
), SRA
);
9163 static SDValue
performMulCombine(SDNode
*N
, SelectionDAG
&DAG
,
9164 TargetLowering::DAGCombinerInfo
&DCI
,
9165 const AArch64Subtarget
*Subtarget
) {
9166 if (DCI
.isBeforeLegalizeOps())
9169 // The below optimizations require a constant RHS.
9170 if (!isa
<ConstantSDNode
>(N
->getOperand(1)))
9173 ConstantSDNode
*C
= cast
<ConstantSDNode
>(N
->getOperand(1));
9174 const APInt
&ConstValue
= C
->getAPIntValue();
9176 // Multiplication of a power of two plus/minus one can be done more
9177 // cheaply as as shift+add/sub. For now, this is true unilaterally. If
9178 // future CPUs have a cheaper MADD instruction, this may need to be
9179 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
9180 // 64-bit is 5 cycles, so this is always a win.
9181 // More aggressively, some multiplications N0 * C can be lowered to
9182 // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M,
9183 // e.g. 6=3*2=(2+1)*2.
9184 // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45
9185 // which equals to (1+2)*16-(1+2).
9186 SDValue N0
= N
->getOperand(0);
9187 // TrailingZeroes is used to test if the mul can be lowered to
9189 unsigned TrailingZeroes
= ConstValue
.countTrailingZeros();
9190 if (TrailingZeroes
) {
9191 // Conservatively do not lower to shift+add+shift if the mul might be
9192 // folded into smul or umul.
9193 if (N0
->hasOneUse() && (isSignExtended(N0
.getNode(), DAG
) ||
9194 isZeroExtended(N0
.getNode(), DAG
)))
9196 // Conservatively do not lower to shift+add+shift if the mul might be
9197 // folded into madd or msub.
9198 if (N
->hasOneUse() && (N
->use_begin()->getOpcode() == ISD::ADD
||
9199 N
->use_begin()->getOpcode() == ISD::SUB
))
9202 // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub
9203 // and shift+add+shift.
9204 APInt ShiftedConstValue
= ConstValue
.ashr(TrailingZeroes
);
9206 unsigned ShiftAmt
, AddSubOpc
;
9207 // Is the shifted value the LHS operand of the add/sub?
9208 bool ShiftValUseIsN0
= true;
9209 // Do we need to negate the result?
9210 bool NegateResult
= false;
9212 if (ConstValue
.isNonNegative()) {
9213 // (mul x, 2^N + 1) => (add (shl x, N), x)
9214 // (mul x, 2^N - 1) => (sub (shl x, N), x)
9215 // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M)
9216 APInt SCVMinus1
= ShiftedConstValue
- 1;
9217 APInt CVPlus1
= ConstValue
+ 1;
9218 if (SCVMinus1
.isPowerOf2()) {
9219 ShiftAmt
= SCVMinus1
.logBase2();
9220 AddSubOpc
= ISD::ADD
;
9221 } else if (CVPlus1
.isPowerOf2()) {
9222 ShiftAmt
= CVPlus1
.logBase2();
9223 AddSubOpc
= ISD::SUB
;
9227 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
9228 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
9229 APInt CVNegPlus1
= -ConstValue
+ 1;
9230 APInt CVNegMinus1
= -ConstValue
- 1;
9231 if (CVNegPlus1
.isPowerOf2()) {
9232 ShiftAmt
= CVNegPlus1
.logBase2();
9233 AddSubOpc
= ISD::SUB
;
9234 ShiftValUseIsN0
= false;
9235 } else if (CVNegMinus1
.isPowerOf2()) {
9236 ShiftAmt
= CVNegMinus1
.logBase2();
9237 AddSubOpc
= ISD::ADD
;
9238 NegateResult
= true;
9244 EVT VT
= N
->getValueType(0);
9245 SDValue ShiftedVal
= DAG
.getNode(ISD::SHL
, DL
, VT
, N0
,
9246 DAG
.getConstant(ShiftAmt
, DL
, MVT::i64
));
9248 SDValue AddSubN0
= ShiftValUseIsN0
? ShiftedVal
: N0
;
9249 SDValue AddSubN1
= ShiftValUseIsN0
? N0
: ShiftedVal
;
9250 SDValue Res
= DAG
.getNode(AddSubOpc
, DL
, VT
, AddSubN0
, AddSubN1
);
9251 assert(!(NegateResult
&& TrailingZeroes
) &&
9252 "NegateResult and TrailingZeroes cannot both be true for now.");
9253 // Negate the result.
9255 return DAG
.getNode(ISD::SUB
, DL
, VT
, DAG
.getConstant(0, DL
, VT
), Res
);
9256 // Shift the result.
9258 return DAG
.getNode(ISD::SHL
, DL
, VT
, Res
,
9259 DAG
.getConstant(TrailingZeroes
, DL
, MVT::i64
));
9263 static SDValue
performVectorCompareAndMaskUnaryOpCombine(SDNode
*N
,
9264 SelectionDAG
&DAG
) {
9265 // Take advantage of vector comparisons producing 0 or -1 in each lane to
9266 // optimize away operation when it's from a constant.
9268 // The general transformation is:
9269 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
9270 // AND(VECTOR_CMP(x,y), constant2)
9271 // constant2 = UNARYOP(constant)
9273 // Early exit if this isn't a vector operation, the operand of the
9274 // unary operation isn't a bitwise AND, or if the sizes of the operations
9276 EVT VT
= N
->getValueType(0);
9277 if (!VT
.isVector() || N
->getOperand(0)->getOpcode() != ISD::AND
||
9278 N
->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC
||
9279 VT
.getSizeInBits() != N
->getOperand(0)->getValueType(0).getSizeInBits())
9282 // Now check that the other operand of the AND is a constant. We could
9283 // make the transformation for non-constant splats as well, but it's unclear
9284 // that would be a benefit as it would not eliminate any operations, just
9285 // perform one more step in scalar code before moving to the vector unit.
9286 if (BuildVectorSDNode
*BV
=
9287 dyn_cast
<BuildVectorSDNode
>(N
->getOperand(0)->getOperand(1))) {
9288 // Bail out if the vector isn't a constant.
9289 if (!BV
->isConstant())
9292 // Everything checks out. Build up the new and improved node.
9294 EVT IntVT
= BV
->getValueType(0);
9295 // Create a new constant of the appropriate type for the transformed
9297 SDValue SourceConst
= DAG
.getNode(N
->getOpcode(), DL
, VT
, SDValue(BV
, 0));
9298 // The AND node needs bitcasts to/from an integer vector type around it.
9299 SDValue MaskConst
= DAG
.getNode(ISD::BITCAST
, DL
, IntVT
, SourceConst
);
9300 SDValue NewAnd
= DAG
.getNode(ISD::AND
, DL
, IntVT
,
9301 N
->getOperand(0)->getOperand(0), MaskConst
);
9302 SDValue Res
= DAG
.getNode(ISD::BITCAST
, DL
, VT
, NewAnd
);
9309 static SDValue
performIntToFpCombine(SDNode
*N
, SelectionDAG
&DAG
,
9310 const AArch64Subtarget
*Subtarget
) {
9311 // First try to optimize away the conversion when it's conditionally from
9312 // a constant. Vectors only.
9313 if (SDValue Res
= performVectorCompareAndMaskUnaryOpCombine(N
, DAG
))
9316 EVT VT
= N
->getValueType(0);
9317 if (VT
!= MVT::f32
&& VT
!= MVT::f64
)
9320 // Only optimize when the source and destination types have the same width.
9321 if (VT
.getSizeInBits() != N
->getOperand(0).getValueSizeInBits())
9324 // If the result of an integer load is only used by an integer-to-float
9325 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
9326 // This eliminates an "integer-to-vector-move" UOP and improves throughput.
9327 SDValue N0
= N
->getOperand(0);
9328 if (Subtarget
->hasNEON() && ISD::isNormalLoad(N0
.getNode()) && N0
.hasOneUse() &&
9329 // Do not change the width of a volatile load.
9330 !cast
<LoadSDNode
>(N0
)->isVolatile()) {
9331 LoadSDNode
*LN0
= cast
<LoadSDNode
>(N0
);
9332 SDValue Load
= DAG
.getLoad(VT
, SDLoc(N
), LN0
->getChain(), LN0
->getBasePtr(),
9333 LN0
->getPointerInfo(), LN0
->getAlignment(),
9334 LN0
->getMemOperand()->getFlags());
9336 // Make sure successors of the original load stay after it by updating them
9337 // to use the new Chain.
9338 DAG
.ReplaceAllUsesOfValueWith(SDValue(LN0
, 1), Load
.getValue(1));
9341 (N
->getOpcode() == ISD::SINT_TO_FP
) ? AArch64ISD::SITOF
: AArch64ISD::UITOF
;
9342 return DAG
.getNode(Opcode
, SDLoc(N
), VT
, Load
);
9348 /// Fold a floating-point multiply by power of two into floating-point to
9349 /// fixed-point conversion.
9350 static SDValue
performFpToIntCombine(SDNode
*N
, SelectionDAG
&DAG
,
9351 TargetLowering::DAGCombinerInfo
&DCI
,
9352 const AArch64Subtarget
*Subtarget
) {
9353 if (!Subtarget
->hasNEON())
9356 if (!N
->getValueType(0).isSimple())
9359 SDValue Op
= N
->getOperand(0);
9360 if (!Op
.getValueType().isVector() || !Op
.getValueType().isSimple() ||
9361 Op
.getOpcode() != ISD::FMUL
)
9364 SDValue ConstVec
= Op
->getOperand(1);
9365 if (!isa
<BuildVectorSDNode
>(ConstVec
))
9368 MVT FloatTy
= Op
.getSimpleValueType().getVectorElementType();
9369 uint32_t FloatBits
= FloatTy
.getSizeInBits();
9370 if (FloatBits
!= 32 && FloatBits
!= 64)
9373 MVT IntTy
= N
->getSimpleValueType(0).getVectorElementType();
9374 uint32_t IntBits
= IntTy
.getSizeInBits();
9375 if (IntBits
!= 16 && IntBits
!= 32 && IntBits
!= 64)
9378 // Avoid conversions where iN is larger than the float (e.g., float -> i64).
9379 if (IntBits
> FloatBits
)
9382 BitVector UndefElements
;
9383 BuildVectorSDNode
*BV
= cast
<BuildVectorSDNode
>(ConstVec
);
9384 int32_t Bits
= IntBits
== 64 ? 64 : 32;
9385 int32_t C
= BV
->getConstantFPSplatPow2ToLog2Int(&UndefElements
, Bits
+ 1);
9386 if (C
== -1 || C
== 0 || C
> Bits
)
9390 unsigned NumLanes
= Op
.getValueType().getVectorNumElements();
9395 ResTy
= FloatBits
== 32 ? MVT::v2i32
: MVT::v2i64
;
9398 ResTy
= FloatBits
== 32 ? MVT::v4i32
: MVT::v4i64
;
9402 if (ResTy
== MVT::v4i64
&& DCI
.isBeforeLegalizeOps())
9405 assert((ResTy
!= MVT::v4i64
|| DCI
.isBeforeLegalizeOps()) &&
9406 "Illegal vector type after legalization");
9409 bool IsSigned
= N
->getOpcode() == ISD::FP_TO_SINT
;
9410 unsigned IntrinsicOpcode
= IsSigned
? Intrinsic::aarch64_neon_vcvtfp2fxs
9411 : Intrinsic::aarch64_neon_vcvtfp2fxu
;
9413 DAG
.getNode(ISD::INTRINSIC_WO_CHAIN
, DL
, ResTy
,
9414 DAG
.getConstant(IntrinsicOpcode
, DL
, MVT::i32
),
9415 Op
->getOperand(0), DAG
.getConstant(C
, DL
, MVT::i32
));
9416 // We can handle smaller integers by generating an extra trunc.
9417 if (IntBits
< FloatBits
)
9418 FixConv
= DAG
.getNode(ISD::TRUNCATE
, DL
, N
->getValueType(0), FixConv
);
9423 /// Fold a floating-point divide by power of two into fixed-point to
9424 /// floating-point conversion.
9425 static SDValue
performFDivCombine(SDNode
*N
, SelectionDAG
&DAG
,
9426 TargetLowering::DAGCombinerInfo
&DCI
,
9427 const AArch64Subtarget
*Subtarget
) {
9428 if (!Subtarget
->hasNEON())
9431 SDValue Op
= N
->getOperand(0);
9432 unsigned Opc
= Op
->getOpcode();
9433 if (!Op
.getValueType().isVector() || !Op
.getValueType().isSimple() ||
9434 !Op
.getOperand(0).getValueType().isSimple() ||
9435 (Opc
!= ISD::SINT_TO_FP
&& Opc
!= ISD::UINT_TO_FP
))
9438 SDValue ConstVec
= N
->getOperand(1);
9439 if (!isa
<BuildVectorSDNode
>(ConstVec
))
9442 MVT IntTy
= Op
.getOperand(0).getSimpleValueType().getVectorElementType();
9443 int32_t IntBits
= IntTy
.getSizeInBits();
9444 if (IntBits
!= 16 && IntBits
!= 32 && IntBits
!= 64)
9447 MVT FloatTy
= N
->getSimpleValueType(0).getVectorElementType();
9448 int32_t FloatBits
= FloatTy
.getSizeInBits();
9449 if (FloatBits
!= 32 && FloatBits
!= 64)
9452 // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
9453 if (IntBits
> FloatBits
)
9456 BitVector UndefElements
;
9457 BuildVectorSDNode
*BV
= cast
<BuildVectorSDNode
>(ConstVec
);
9458 int32_t C
= BV
->getConstantFPSplatPow2ToLog2Int(&UndefElements
, FloatBits
+ 1);
9459 if (C
== -1 || C
== 0 || C
> FloatBits
)
9463 unsigned NumLanes
= Op
.getValueType().getVectorNumElements();
9468 ResTy
= FloatBits
== 32 ? MVT::v2i32
: MVT::v2i64
;
9471 ResTy
= FloatBits
== 32 ? MVT::v4i32
: MVT::v4i64
;
9475 if (ResTy
== MVT::v4i64
&& DCI
.isBeforeLegalizeOps())
9479 SDValue ConvInput
= Op
.getOperand(0);
9480 bool IsSigned
= Opc
== ISD::SINT_TO_FP
;
9481 if (IntBits
< FloatBits
)
9482 ConvInput
= DAG
.getNode(IsSigned
? ISD::SIGN_EXTEND
: ISD::ZERO_EXTEND
, DL
,
9485 unsigned IntrinsicOpcode
= IsSigned
? Intrinsic::aarch64_neon_vcvtfxs2fp
9486 : Intrinsic::aarch64_neon_vcvtfxu2fp
;
9487 return DAG
.getNode(ISD::INTRINSIC_WO_CHAIN
, DL
, Op
.getValueType(),
9488 DAG
.getConstant(IntrinsicOpcode
, DL
, MVT::i32
), ConvInput
,
9489 DAG
.getConstant(C
, DL
, MVT::i32
));
9492 /// An EXTR instruction is made up of two shifts, ORed together. This helper
9493 /// searches for and classifies those shifts.
9494 static bool findEXTRHalf(SDValue N
, SDValue
&Src
, uint32_t &ShiftAmount
,
9496 if (N
.getOpcode() == ISD::SHL
)
9498 else if (N
.getOpcode() == ISD::SRL
)
9503 if (!isa
<ConstantSDNode
>(N
.getOperand(1)))
9506 ShiftAmount
= N
->getConstantOperandVal(1);
9507 Src
= N
->getOperand(0);
9511 /// EXTR instruction extracts a contiguous chunk of bits from two existing
9512 /// registers viewed as a high/low pair. This function looks for the pattern:
9513 /// <tt>(or (shl VAL1, \#N), (srl VAL2, \#RegWidth-N))</tt> and replaces it
9514 /// with an EXTR. Can't quite be done in TableGen because the two immediates
9515 /// aren't independent.
9516 static SDValue
tryCombineToEXTR(SDNode
*N
,
9517 TargetLowering::DAGCombinerInfo
&DCI
) {
9518 SelectionDAG
&DAG
= DCI
.DAG
;
9520 EVT VT
= N
->getValueType(0);
9522 assert(N
->getOpcode() == ISD::OR
&& "Unexpected root");
9524 if (VT
!= MVT::i32
&& VT
!= MVT::i64
)
9528 uint32_t ShiftLHS
= 0;
9529 bool LHSFromHi
= false;
9530 if (!findEXTRHalf(N
->getOperand(0), LHS
, ShiftLHS
, LHSFromHi
))
9534 uint32_t ShiftRHS
= 0;
9535 bool RHSFromHi
= false;
9536 if (!findEXTRHalf(N
->getOperand(1), RHS
, ShiftRHS
, RHSFromHi
))
9539 // If they're both trying to come from the high part of the register, they're
9540 // not really an EXTR.
9541 if (LHSFromHi
== RHSFromHi
)
9544 if (ShiftLHS
+ ShiftRHS
!= VT
.getSizeInBits())
9548 std::swap(LHS
, RHS
);
9549 std::swap(ShiftLHS
, ShiftRHS
);
9552 return DAG
.getNode(AArch64ISD::EXTR
, DL
, VT
, LHS
, RHS
,
9553 DAG
.getConstant(ShiftRHS
, DL
, MVT::i64
));
9556 static SDValue
tryCombineToBSL(SDNode
*N
,
9557 TargetLowering::DAGCombinerInfo
&DCI
) {
9558 EVT VT
= N
->getValueType(0);
9559 SelectionDAG
&DAG
= DCI
.DAG
;
9565 SDValue N0
= N
->getOperand(0);
9566 if (N0
.getOpcode() != ISD::AND
)
9569 SDValue N1
= N
->getOperand(1);
9570 if (N1
.getOpcode() != ISD::AND
)
9573 // We only have to look for constant vectors here since the general, variable
9574 // case can be handled in TableGen.
9575 unsigned Bits
= VT
.getScalarSizeInBits();
9576 uint64_t BitMask
= Bits
== 64 ? -1ULL : ((1ULL << Bits
) - 1);
9577 for (int i
= 1; i
>= 0; --i
)
9578 for (int j
= 1; j
>= 0; --j
) {
9579 BuildVectorSDNode
*BVN0
= dyn_cast
<BuildVectorSDNode
>(N0
->getOperand(i
));
9580 BuildVectorSDNode
*BVN1
= dyn_cast
<BuildVectorSDNode
>(N1
->getOperand(j
));
9584 bool FoundMatch
= true;
9585 for (unsigned k
= 0; k
< VT
.getVectorNumElements(); ++k
) {
9586 ConstantSDNode
*CN0
= dyn_cast
<ConstantSDNode
>(BVN0
->getOperand(k
));
9587 ConstantSDNode
*CN1
= dyn_cast
<ConstantSDNode
>(BVN1
->getOperand(k
));
9589 CN0
->getZExtValue() != (BitMask
& ~CN1
->getZExtValue())) {
9596 return DAG
.getNode(AArch64ISD::BSL
, DL
, VT
, SDValue(BVN0
, 0),
9597 N0
->getOperand(1 - i
), N1
->getOperand(1 - j
));
9603 static SDValue
performORCombine(SDNode
*N
, TargetLowering::DAGCombinerInfo
&DCI
,
9604 const AArch64Subtarget
*Subtarget
) {
9605 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
9606 SelectionDAG
&DAG
= DCI
.DAG
;
9607 EVT VT
= N
->getValueType(0);
9609 if (!DAG
.getTargetLoweringInfo().isTypeLegal(VT
))
9612 if (SDValue Res
= tryCombineToEXTR(N
, DCI
))
9615 if (SDValue Res
= tryCombineToBSL(N
, DCI
))
9621 static SDValue
performANDCombine(SDNode
*N
,
9622 TargetLowering::DAGCombinerInfo
&DCI
) {
9623 SelectionDAG
&DAG
= DCI
.DAG
;
9624 SDValue LHS
= N
->getOperand(0);
9625 EVT VT
= N
->getValueType(0);
9626 if (!VT
.isVector() || !DAG
.getTargetLoweringInfo().isTypeLegal(VT
))
9629 BuildVectorSDNode
*BVN
=
9630 dyn_cast
<BuildVectorSDNode
>(N
->getOperand(1).getNode());
9634 // AND does not accept an immediate, so check if we can use a BIC immediate
9635 // instruction instead. We do this here instead of using a (and x, (mvni imm))
9636 // pattern in isel, because some immediates may be lowered to the preferred
9637 // (and x, (movi imm)) form, even though an mvni representation also exists.
9638 APInt
DefBits(VT
.getSizeInBits(), 0);
9639 APInt
UndefBits(VT
.getSizeInBits(), 0);
9640 if (resolveBuildVector(BVN
, DefBits
, UndefBits
)) {
9644 if ((NewOp
= tryAdvSIMDModImm32(AArch64ISD::BICi
, SDValue(N
, 0), DAG
,
9646 (NewOp
= tryAdvSIMDModImm16(AArch64ISD::BICi
, SDValue(N
, 0), DAG
,
9650 UndefBits
= ~UndefBits
;
9651 if ((NewOp
= tryAdvSIMDModImm32(AArch64ISD::BICi
, SDValue(N
, 0), DAG
,
9652 UndefBits
, &LHS
)) ||
9653 (NewOp
= tryAdvSIMDModImm16(AArch64ISD::BICi
, SDValue(N
, 0), DAG
,
9661 static SDValue
performSRLCombine(SDNode
*N
,
9662 TargetLowering::DAGCombinerInfo
&DCI
) {
9663 SelectionDAG
&DAG
= DCI
.DAG
;
9664 EVT VT
= N
->getValueType(0);
9665 if (VT
!= MVT::i32
&& VT
!= MVT::i64
)
9668 // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the
9669 // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32)
9670 // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero.
9671 SDValue N0
= N
->getOperand(0);
9672 if (N0
.getOpcode() == ISD::BSWAP
) {
9674 SDValue N1
= N
->getOperand(1);
9675 SDValue N00
= N0
.getOperand(0);
9676 if (ConstantSDNode
*C
= dyn_cast
<ConstantSDNode
>(N1
)) {
9677 uint64_t ShiftAmt
= C
->getZExtValue();
9678 if (VT
== MVT::i32
&& ShiftAmt
== 16 &&
9679 DAG
.MaskedValueIsZero(N00
, APInt::getHighBitsSet(32, 16)))
9680 return DAG
.getNode(ISD::ROTR
, DL
, VT
, N0
, N1
);
9681 if (VT
== MVT::i64
&& ShiftAmt
== 32 &&
9682 DAG
.MaskedValueIsZero(N00
, APInt::getHighBitsSet(64, 32)))
9683 return DAG
.getNode(ISD::ROTR
, DL
, VT
, N0
, N1
);
9689 static SDValue
performBitcastCombine(SDNode
*N
,
9690 TargetLowering::DAGCombinerInfo
&DCI
,
9691 SelectionDAG
&DAG
) {
9692 // Wait 'til after everything is legalized to try this. That way we have
9693 // legal vector types and such.
9694 if (DCI
.isBeforeLegalizeOps())
9697 // Remove extraneous bitcasts around an extract_subvector.
9699 // (v4i16 (bitconvert
9700 // (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
9702 // (extract_subvector ((v8i16 ...), (i64 4)))
9704 // Only interested in 64-bit vectors as the ultimate result.
9705 EVT VT
= N
->getValueType(0);
9708 if (VT
.getSimpleVT().getSizeInBits() != 64)
9710 // Is the operand an extract_subvector starting at the beginning or halfway
9711 // point of the vector? A low half may also come through as an
9712 // EXTRACT_SUBREG, so look for that, too.
9713 SDValue Op0
= N
->getOperand(0);
9714 if (Op0
->getOpcode() != ISD::EXTRACT_SUBVECTOR
&&
9715 !(Op0
->isMachineOpcode() &&
9716 Op0
->getMachineOpcode() == AArch64::EXTRACT_SUBREG
))
9718 uint64_t idx
= cast
<ConstantSDNode
>(Op0
->getOperand(1))->getZExtValue();
9719 if (Op0
->getOpcode() == ISD::EXTRACT_SUBVECTOR
) {
9720 if (Op0
->getValueType(0).getVectorNumElements() != idx
&& idx
!= 0)
9722 } else if (Op0
->getMachineOpcode() == AArch64::EXTRACT_SUBREG
) {
9723 if (idx
!= AArch64::dsub
)
9725 // The dsub reference is equivalent to a lane zero subvector reference.
9728 // Look through the bitcast of the input to the extract.
9729 if (Op0
->getOperand(0)->getOpcode() != ISD::BITCAST
)
9731 SDValue Source
= Op0
->getOperand(0)->getOperand(0);
9732 // If the source type has twice the number of elements as our destination
9733 // type, we know this is an extract of the high or low half of the vector.
9734 EVT SVT
= Source
->getValueType(0);
9735 if (!SVT
.isVector() ||
9736 SVT
.getVectorNumElements() != VT
.getVectorNumElements() * 2)
9740 dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
9742 // Create the simplified form to just extract the low or high half of the
9743 // vector directly rather than bothering with the bitcasts.
9745 unsigned NumElements
= VT
.getVectorNumElements();
9747 SDValue HalfIdx
= DAG
.getConstant(NumElements
, dl
, MVT::i64
);
9748 return DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, dl
, VT
, Source
, HalfIdx
);
9750 SDValue SubReg
= DAG
.getTargetConstant(AArch64::dsub
, dl
, MVT::i32
);
9751 return SDValue(DAG
.getMachineNode(TargetOpcode::EXTRACT_SUBREG
, dl
, VT
,
9757 static SDValue
performConcatVectorsCombine(SDNode
*N
,
9758 TargetLowering::DAGCombinerInfo
&DCI
,
9759 SelectionDAG
&DAG
) {
9761 EVT VT
= N
->getValueType(0);
9762 SDValue N0
= N
->getOperand(0), N1
= N
->getOperand(1);
9764 // Optimize concat_vectors of truncated vectors, where the intermediate
9765 // type is illegal, to avoid said illegality, e.g.,
9766 // (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
9767 // (v2i16 (truncate (v2i64)))))
9769 // (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
9770 // (v4i32 (bitcast (v2i64))),
9772 // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
9773 // on both input and result type, so we might generate worse code.
9774 // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
9775 if (N
->getNumOperands() == 2 &&
9776 N0
->getOpcode() == ISD::TRUNCATE
&&
9777 N1
->getOpcode() == ISD::TRUNCATE
) {
9778 SDValue N00
= N0
->getOperand(0);
9779 SDValue N10
= N1
->getOperand(0);
9780 EVT N00VT
= N00
.getValueType();
9782 if (N00VT
== N10
.getValueType() &&
9783 (N00VT
== MVT::v2i64
|| N00VT
== MVT::v4i32
) &&
9784 N00VT
.getScalarSizeInBits() == 4 * VT
.getScalarSizeInBits()) {
9785 MVT MidVT
= (N00VT
== MVT::v2i64
? MVT::v4i32
: MVT::v8i16
);
9786 SmallVector
<int, 8> Mask(MidVT
.getVectorNumElements());
9787 for (size_t i
= 0; i
< Mask
.size(); ++i
)
9789 return DAG
.getNode(ISD::TRUNCATE
, dl
, VT
,
9790 DAG
.getVectorShuffle(
9792 DAG
.getNode(ISD::BITCAST
, dl
, MidVT
, N00
),
9793 DAG
.getNode(ISD::BITCAST
, dl
, MidVT
, N10
), Mask
));
9797 // Wait 'til after everything is legalized to try this. That way we have
9798 // legal vector types and such.
9799 if (DCI
.isBeforeLegalizeOps())
9802 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
9803 // splat. The indexed instructions are going to be expecting a DUPLANE64, so
9804 // canonicalise to that.
9805 if (N0
== N1
&& VT
.getVectorNumElements() == 2) {
9806 assert(VT
.getScalarSizeInBits() == 64);
9807 return DAG
.getNode(AArch64ISD::DUPLANE64
, dl
, VT
, WidenVector(N0
, DAG
),
9808 DAG
.getConstant(0, dl
, MVT::i64
));
9811 // Canonicalise concat_vectors so that the right-hand vector has as few
9812 // bit-casts as possible before its real operation. The primary matching
9813 // destination for these operations will be the narrowing "2" instructions,
9814 // which depend on the operation being performed on this right-hand vector.
9816 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS))))
9818 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
9820 if (N1
->getOpcode() != ISD::BITCAST
)
9822 SDValue RHS
= N1
->getOperand(0);
9823 MVT RHSTy
= RHS
.getValueType().getSimpleVT();
9824 // If the RHS is not a vector, this is not the pattern we're looking for.
9825 if (!RHSTy
.isVector())
9829 dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
9831 MVT ConcatTy
= MVT::getVectorVT(RHSTy
.getVectorElementType(),
9832 RHSTy
.getVectorNumElements() * 2);
9833 return DAG
.getNode(ISD::BITCAST
, dl
, VT
,
9834 DAG
.getNode(ISD::CONCAT_VECTORS
, dl
, ConcatTy
,
9835 DAG
.getNode(ISD::BITCAST
, dl
, RHSTy
, N0
),
9839 static SDValue
tryCombineFixedPointConvert(SDNode
*N
,
9840 TargetLowering::DAGCombinerInfo
&DCI
,
9841 SelectionDAG
&DAG
) {
9842 // Wait until after everything is legalized to try this. That way we have
9843 // legal vector types and such.
9844 if (DCI
.isBeforeLegalizeOps())
9846 // Transform a scalar conversion of a value from a lane extract into a
9847 // lane extract of a vector conversion. E.g., from foo1 to foo2:
9848 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
9849 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
9851 // The second form interacts better with instruction selection and the
9852 // register allocator to avoid cross-class register copies that aren't
9853 // coalescable due to a lane reference.
9855 // Check the operand and see if it originates from a lane extract.
9856 SDValue Op1
= N
->getOperand(1);
9857 if (Op1
.getOpcode() == ISD::EXTRACT_VECTOR_ELT
) {
9858 // Yep, no additional predication needed. Perform the transform.
9859 SDValue IID
= N
->getOperand(0);
9860 SDValue Shift
= N
->getOperand(2);
9861 SDValue Vec
= Op1
.getOperand(0);
9862 SDValue Lane
= Op1
.getOperand(1);
9863 EVT ResTy
= N
->getValueType(0);
9867 // The vector width should be 128 bits by the time we get here, even
9868 // if it started as 64 bits (the extract_vector handling will have
9870 assert(Vec
.getValueSizeInBits() == 128 &&
9871 "unexpected vector size on extract_vector_elt!");
9872 if (Vec
.getValueType() == MVT::v4i32
)
9873 VecResTy
= MVT::v4f32
;
9874 else if (Vec
.getValueType() == MVT::v2i64
)
9875 VecResTy
= MVT::v2f64
;
9877 llvm_unreachable("unexpected vector type!");
9880 DAG
.getNode(ISD::INTRINSIC_WO_CHAIN
, DL
, VecResTy
, IID
, Vec
, Shift
);
9881 return DAG
.getNode(ISD::EXTRACT_VECTOR_ELT
, DL
, ResTy
, Convert
, Lane
);
9886 // AArch64 high-vector "long" operations are formed by performing the non-high
9887 // version on an extract_subvector of each operand which gets the high half:
9889 // (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
9891 // However, there are cases which don't have an extract_high explicitly, but
9892 // have another operation that can be made compatible with one for free. For
9895 // (dupv64 scalar) --> (extract_high (dup128 scalar))
9897 // This routine does the actual conversion of such DUPs, once outer routines
9898 // have determined that everything else is in order.
9899 // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
9901 static SDValue
tryExtendDUPToExtractHigh(SDValue N
, SelectionDAG
&DAG
) {
9902 switch (N
.getOpcode()) {
9903 case AArch64ISD::DUP
:
9904 case AArch64ISD::DUPLANE8
:
9905 case AArch64ISD::DUPLANE16
:
9906 case AArch64ISD::DUPLANE32
:
9907 case AArch64ISD::DUPLANE64
:
9908 case AArch64ISD::MOVI
:
9909 case AArch64ISD::MOVIshift
:
9910 case AArch64ISD::MOVIedit
:
9911 case AArch64ISD::MOVImsl
:
9912 case AArch64ISD::MVNIshift
:
9913 case AArch64ISD::MVNImsl
:
9916 // FMOV could be supported, but isn't very useful, as it would only occur
9917 // if you passed a bitcast' floating point immediate to an eligible long
9918 // integer op (addl, smull, ...).
9922 MVT NarrowTy
= N
.getSimpleValueType();
9923 if (!NarrowTy
.is64BitVector())
9926 MVT ElementTy
= NarrowTy
.getVectorElementType();
9927 unsigned NumElems
= NarrowTy
.getVectorNumElements();
9928 MVT NewVT
= MVT::getVectorVT(ElementTy
, NumElems
* 2);
9931 return DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, dl
, NarrowTy
,
9932 DAG
.getNode(N
->getOpcode(), dl
, NewVT
, N
->ops()),
9933 DAG
.getConstant(NumElems
, dl
, MVT::i64
));
9936 static bool isEssentiallyExtractHighSubvector(SDValue N
) {
9937 if (N
.getOpcode() == ISD::BITCAST
)
9938 N
= N
.getOperand(0);
9939 if (N
.getOpcode() != ISD::EXTRACT_SUBVECTOR
)
9941 return cast
<ConstantSDNode
>(N
.getOperand(1))->getAPIntValue() ==
9942 N
.getOperand(0).getValueType().getVectorNumElements() / 2;
9945 /// Helper structure to keep track of ISD::SET_CC operands.
9946 struct GenericSetCCInfo
{
9947 const SDValue
*Opnd0
;
9948 const SDValue
*Opnd1
;
9952 /// Helper structure to keep track of a SET_CC lowered into AArch64 code.
9953 struct AArch64SetCCInfo
{
9955 AArch64CC::CondCode CC
;
9958 /// Helper structure to keep track of SetCC information.
9960 GenericSetCCInfo Generic
;
9961 AArch64SetCCInfo AArch64
;
9964 /// Helper structure to be able to read SetCC information. If set to
9965 /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
9966 /// GenericSetCCInfo.
9967 struct SetCCInfoAndKind
{
9972 /// Check whether or not \p Op is a SET_CC operation, either a generic or
9974 /// AArch64 lowered one.
9975 /// \p SetCCInfo is filled accordingly.
9976 /// \post SetCCInfo is meanginfull only when this function returns true.
9977 /// \return True when Op is a kind of SET_CC operation.
9978 static bool isSetCC(SDValue Op
, SetCCInfoAndKind
&SetCCInfo
) {
9979 // If this is a setcc, this is straight forward.
9980 if (Op
.getOpcode() == ISD::SETCC
) {
9981 SetCCInfo
.Info
.Generic
.Opnd0
= &Op
.getOperand(0);
9982 SetCCInfo
.Info
.Generic
.Opnd1
= &Op
.getOperand(1);
9983 SetCCInfo
.Info
.Generic
.CC
= cast
<CondCodeSDNode
>(Op
.getOperand(2))->get();
9984 SetCCInfo
.IsAArch64
= false;
9987 // Otherwise, check if this is a matching csel instruction.
9991 if (Op
.getOpcode() != AArch64ISD::CSEL
)
9993 // Set the information about the operands.
9994 // TODO: we want the operands of the Cmp not the csel
9995 SetCCInfo
.Info
.AArch64
.Cmp
= &Op
.getOperand(3);
9996 SetCCInfo
.IsAArch64
= true;
9997 SetCCInfo
.Info
.AArch64
.CC
= static_cast<AArch64CC::CondCode
>(
9998 cast
<ConstantSDNode
>(Op
.getOperand(2))->getZExtValue());
10000 // Check that the operands matches the constraints:
10001 // (1) Both operands must be constants.
10002 // (2) One must be 1 and the other must be 0.
10003 ConstantSDNode
*TValue
= dyn_cast
<ConstantSDNode
>(Op
.getOperand(0));
10004 ConstantSDNode
*FValue
= dyn_cast
<ConstantSDNode
>(Op
.getOperand(1));
10007 if (!TValue
|| !FValue
)
10011 if (!TValue
->isOne()) {
10012 // Update the comparison when we are interested in !cc.
10013 std::swap(TValue
, FValue
);
10014 SetCCInfo
.Info
.AArch64
.CC
=
10015 AArch64CC::getInvertedCondCode(SetCCInfo
.Info
.AArch64
.CC
);
10017 return TValue
->isOne() && FValue
->isNullValue();
10020 // Returns true if Op is setcc or zext of setcc.
10021 static bool isSetCCOrZExtSetCC(const SDValue
& Op
, SetCCInfoAndKind
&Info
) {
10022 if (isSetCC(Op
, Info
))
10024 return ((Op
.getOpcode() == ISD::ZERO_EXTEND
) &&
10025 isSetCC(Op
->getOperand(0), Info
));
10028 // The folding we want to perform is:
10029 // (add x, [zext] (setcc cc ...) )
10031 // (csel x, (add x, 1), !cc ...)
10033 // The latter will get matched to a CSINC instruction.
10034 static SDValue
performSetccAddFolding(SDNode
*Op
, SelectionDAG
&DAG
) {
10035 assert(Op
&& Op
->getOpcode() == ISD::ADD
&& "Unexpected operation!");
10036 SDValue LHS
= Op
->getOperand(0);
10037 SDValue RHS
= Op
->getOperand(1);
10038 SetCCInfoAndKind InfoAndKind
;
10040 // If neither operand is a SET_CC, give up.
10041 if (!isSetCCOrZExtSetCC(LHS
, InfoAndKind
)) {
10042 std::swap(LHS
, RHS
);
10043 if (!isSetCCOrZExtSetCC(LHS
, InfoAndKind
))
10047 // FIXME: This could be generatized to work for FP comparisons.
10048 EVT CmpVT
= InfoAndKind
.IsAArch64
10049 ? InfoAndKind
.Info
.AArch64
.Cmp
->getOperand(0).getValueType()
10050 : InfoAndKind
.Info
.Generic
.Opnd0
->getValueType();
10051 if (CmpVT
!= MVT::i32
&& CmpVT
!= MVT::i64
)
10057 if (InfoAndKind
.IsAArch64
) {
10058 CCVal
= DAG
.getConstant(
10059 AArch64CC::getInvertedCondCode(InfoAndKind
.Info
.AArch64
.CC
), dl
,
10061 Cmp
= *InfoAndKind
.Info
.AArch64
.Cmp
;
10063 Cmp
= getAArch64Cmp(*InfoAndKind
.Info
.Generic
.Opnd0
,
10064 *InfoAndKind
.Info
.Generic
.Opnd1
,
10065 ISD::getSetCCInverse(InfoAndKind
.Info
.Generic
.CC
, true),
10068 EVT VT
= Op
->getValueType(0);
10069 LHS
= DAG
.getNode(ISD::ADD
, dl
, VT
, RHS
, DAG
.getConstant(1, dl
, VT
));
10070 return DAG
.getNode(AArch64ISD::CSEL
, dl
, VT
, RHS
, LHS
, CCVal
, Cmp
);
10073 // The basic add/sub long vector instructions have variants with "2" on the end
10074 // which act on the high-half of their inputs. They are normally matched by
10077 // (add (zeroext (extract_high LHS)),
10078 // (zeroext (extract_high RHS)))
10079 // -> uaddl2 vD, vN, vM
10081 // However, if one of the extracts is something like a duplicate, this
10082 // instruction can still be used profitably. This function puts the DAG into a
10083 // more appropriate form for those patterns to trigger.
10084 static SDValue
performAddSubLongCombine(SDNode
*N
,
10085 TargetLowering::DAGCombinerInfo
&DCI
,
10086 SelectionDAG
&DAG
) {
10087 if (DCI
.isBeforeLegalizeOps())
10090 MVT VT
= N
->getSimpleValueType(0);
10091 if (!VT
.is128BitVector()) {
10092 if (N
->getOpcode() == ISD::ADD
)
10093 return performSetccAddFolding(N
, DAG
);
10097 // Make sure both branches are extended in the same way.
10098 SDValue LHS
= N
->getOperand(0);
10099 SDValue RHS
= N
->getOperand(1);
10100 if ((LHS
.getOpcode() != ISD::ZERO_EXTEND
&&
10101 LHS
.getOpcode() != ISD::SIGN_EXTEND
) ||
10102 LHS
.getOpcode() != RHS
.getOpcode())
10105 unsigned ExtType
= LHS
.getOpcode();
10107 // It's not worth doing if at least one of the inputs isn't already an
10108 // extract, but we don't know which it'll be so we have to try both.
10109 if (isEssentiallyExtractHighSubvector(LHS
.getOperand(0))) {
10110 RHS
= tryExtendDUPToExtractHigh(RHS
.getOperand(0), DAG
);
10111 if (!RHS
.getNode())
10114 RHS
= DAG
.getNode(ExtType
, SDLoc(N
), VT
, RHS
);
10115 } else if (isEssentiallyExtractHighSubvector(RHS
.getOperand(0))) {
10116 LHS
= tryExtendDUPToExtractHigh(LHS
.getOperand(0), DAG
);
10117 if (!LHS
.getNode())
10120 LHS
= DAG
.getNode(ExtType
, SDLoc(N
), VT
, LHS
);
10123 return DAG
.getNode(N
->getOpcode(), SDLoc(N
), VT
, LHS
, RHS
);
10126 // Massage DAGs which we can use the high-half "long" operations on into
10127 // something isel will recognize better. E.g.
10129 // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
10130 // (aarch64_neon_umull (extract_high (v2i64 vec)))
10131 // (extract_high (v2i64 (dup128 scalar)))))
10133 static SDValue
tryCombineLongOpWithDup(unsigned IID
, SDNode
*N
,
10134 TargetLowering::DAGCombinerInfo
&DCI
,
10135 SelectionDAG
&DAG
) {
10136 if (DCI
.isBeforeLegalizeOps())
10139 SDValue LHS
= N
->getOperand(1);
10140 SDValue RHS
= N
->getOperand(2);
10141 assert(LHS
.getValueType().is64BitVector() &&
10142 RHS
.getValueType().is64BitVector() &&
10143 "unexpected shape for long operation");
10145 // Either node could be a DUP, but it's not worth doing both of them (you'd
10146 // just as well use the non-high version) so look for a corresponding extract
10147 // operation on the other "wing".
10148 if (isEssentiallyExtractHighSubvector(LHS
)) {
10149 RHS
= tryExtendDUPToExtractHigh(RHS
, DAG
);
10150 if (!RHS
.getNode())
10152 } else if (isEssentiallyExtractHighSubvector(RHS
)) {
10153 LHS
= tryExtendDUPToExtractHigh(LHS
, DAG
);
10154 if (!LHS
.getNode())
10158 return DAG
.getNode(ISD::INTRINSIC_WO_CHAIN
, SDLoc(N
), N
->getValueType(0),
10159 N
->getOperand(0), LHS
, RHS
);
10162 static SDValue
tryCombineShiftImm(unsigned IID
, SDNode
*N
, SelectionDAG
&DAG
) {
10163 MVT ElemTy
= N
->getSimpleValueType(0).getScalarType();
10164 unsigned ElemBits
= ElemTy
.getSizeInBits();
10166 int64_t ShiftAmount
;
10167 if (BuildVectorSDNode
*BVN
= dyn_cast
<BuildVectorSDNode
>(N
->getOperand(2))) {
10168 APInt SplatValue
, SplatUndef
;
10169 unsigned SplatBitSize
;
10171 if (!BVN
->isConstantSplat(SplatValue
, SplatUndef
, SplatBitSize
,
10172 HasAnyUndefs
, ElemBits
) ||
10173 SplatBitSize
!= ElemBits
)
10176 ShiftAmount
= SplatValue
.getSExtValue();
10177 } else if (ConstantSDNode
*CVN
= dyn_cast
<ConstantSDNode
>(N
->getOperand(2))) {
10178 ShiftAmount
= CVN
->getSExtValue();
10186 llvm_unreachable("Unknown shift intrinsic");
10187 case Intrinsic::aarch64_neon_sqshl
:
10188 Opcode
= AArch64ISD::SQSHL_I
;
10189 IsRightShift
= false;
10191 case Intrinsic::aarch64_neon_uqshl
:
10192 Opcode
= AArch64ISD::UQSHL_I
;
10193 IsRightShift
= false;
10195 case Intrinsic::aarch64_neon_srshl
:
10196 Opcode
= AArch64ISD::SRSHR_I
;
10197 IsRightShift
= true;
10199 case Intrinsic::aarch64_neon_urshl
:
10200 Opcode
= AArch64ISD::URSHR_I
;
10201 IsRightShift
= true;
10203 case Intrinsic::aarch64_neon_sqshlu
:
10204 Opcode
= AArch64ISD::SQSHLU_I
;
10205 IsRightShift
= false;
10209 if (IsRightShift
&& ShiftAmount
<= -1 && ShiftAmount
>= -(int)ElemBits
) {
10211 return DAG
.getNode(Opcode
, dl
, N
->getValueType(0), N
->getOperand(1),
10212 DAG
.getConstant(-ShiftAmount
, dl
, MVT::i32
));
10213 } else if (!IsRightShift
&& ShiftAmount
>= 0 && ShiftAmount
< ElemBits
) {
10215 return DAG
.getNode(Opcode
, dl
, N
->getValueType(0), N
->getOperand(1),
10216 DAG
.getConstant(ShiftAmount
, dl
, MVT::i32
));
10222 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
10223 // the intrinsics must be legal and take an i32, this means there's almost
10224 // certainly going to be a zext in the DAG which we can eliminate.
10225 static SDValue
tryCombineCRC32(unsigned Mask
, SDNode
*N
, SelectionDAG
&DAG
) {
10226 SDValue AndN
= N
->getOperand(2);
10227 if (AndN
.getOpcode() != ISD::AND
)
10230 ConstantSDNode
*CMask
= dyn_cast
<ConstantSDNode
>(AndN
.getOperand(1));
10231 if (!CMask
|| CMask
->getZExtValue() != Mask
)
10234 return DAG
.getNode(ISD::INTRINSIC_WO_CHAIN
, SDLoc(N
), MVT::i32
,
10235 N
->getOperand(0), N
->getOperand(1), AndN
.getOperand(0));
10238 static SDValue
combineAcrossLanesIntrinsic(unsigned Opc
, SDNode
*N
,
10239 SelectionDAG
&DAG
) {
10241 return DAG
.getNode(ISD::EXTRACT_VECTOR_ELT
, dl
, N
->getValueType(0),
10242 DAG
.getNode(Opc
, dl
,
10243 N
->getOperand(1).getSimpleValueType(),
10245 DAG
.getConstant(0, dl
, MVT::i64
));
10248 static SDValue
performIntrinsicCombine(SDNode
*N
,
10249 TargetLowering::DAGCombinerInfo
&DCI
,
10250 const AArch64Subtarget
*Subtarget
) {
10251 SelectionDAG
&DAG
= DCI
.DAG
;
10252 unsigned IID
= getIntrinsicID(N
);
10256 case Intrinsic::aarch64_neon_vcvtfxs2fp
:
10257 case Intrinsic::aarch64_neon_vcvtfxu2fp
:
10258 return tryCombineFixedPointConvert(N
, DCI
, DAG
);
10259 case Intrinsic::aarch64_neon_saddv
:
10260 return combineAcrossLanesIntrinsic(AArch64ISD::SADDV
, N
, DAG
);
10261 case Intrinsic::aarch64_neon_uaddv
:
10262 return combineAcrossLanesIntrinsic(AArch64ISD::UADDV
, N
, DAG
);
10263 case Intrinsic::aarch64_neon_sminv
:
10264 return combineAcrossLanesIntrinsic(AArch64ISD::SMINV
, N
, DAG
);
10265 case Intrinsic::aarch64_neon_uminv
:
10266 return combineAcrossLanesIntrinsic(AArch64ISD::UMINV
, N
, DAG
);
10267 case Intrinsic::aarch64_neon_smaxv
:
10268 return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV
, N
, DAG
);
10269 case Intrinsic::aarch64_neon_umaxv
:
10270 return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV
, N
, DAG
);
10271 case Intrinsic::aarch64_neon_fmax
:
10272 return DAG
.getNode(ISD::FMAXIMUM
, SDLoc(N
), N
->getValueType(0),
10273 N
->getOperand(1), N
->getOperand(2));
10274 case Intrinsic::aarch64_neon_fmin
:
10275 return DAG
.getNode(ISD::FMINIMUM
, SDLoc(N
), N
->getValueType(0),
10276 N
->getOperand(1), N
->getOperand(2));
10277 case Intrinsic::aarch64_neon_fmaxnm
:
10278 return DAG
.getNode(ISD::FMAXNUM
, SDLoc(N
), N
->getValueType(0),
10279 N
->getOperand(1), N
->getOperand(2));
10280 case Intrinsic::aarch64_neon_fminnm
:
10281 return DAG
.getNode(ISD::FMINNUM
, SDLoc(N
), N
->getValueType(0),
10282 N
->getOperand(1), N
->getOperand(2));
10283 case Intrinsic::aarch64_neon_smull
:
10284 case Intrinsic::aarch64_neon_umull
:
10285 case Intrinsic::aarch64_neon_pmull
:
10286 case Intrinsic::aarch64_neon_sqdmull
:
10287 return tryCombineLongOpWithDup(IID
, N
, DCI
, DAG
);
10288 case Intrinsic::aarch64_neon_sqshl
:
10289 case Intrinsic::aarch64_neon_uqshl
:
10290 case Intrinsic::aarch64_neon_sqshlu
:
10291 case Intrinsic::aarch64_neon_srshl
:
10292 case Intrinsic::aarch64_neon_urshl
:
10293 return tryCombineShiftImm(IID
, N
, DAG
);
10294 case Intrinsic::aarch64_crc32b
:
10295 case Intrinsic::aarch64_crc32cb
:
10296 return tryCombineCRC32(0xff, N
, DAG
);
10297 case Intrinsic::aarch64_crc32h
:
10298 case Intrinsic::aarch64_crc32ch
:
10299 return tryCombineCRC32(0xffff, N
, DAG
);
10304 static SDValue
performExtendCombine(SDNode
*N
,
10305 TargetLowering::DAGCombinerInfo
&DCI
,
10306 SelectionDAG
&DAG
) {
10307 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
10308 // we can convert that DUP into another extract_high (of a bigger DUP), which
10309 // helps the backend to decide that an sabdl2 would be useful, saving a real
10310 // extract_high operation.
10311 if (!DCI
.isBeforeLegalizeOps() && N
->getOpcode() == ISD::ZERO_EXTEND
&&
10312 N
->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN
) {
10313 SDNode
*ABDNode
= N
->getOperand(0).getNode();
10314 unsigned IID
= getIntrinsicID(ABDNode
);
10315 if (IID
== Intrinsic::aarch64_neon_sabd
||
10316 IID
== Intrinsic::aarch64_neon_uabd
) {
10317 SDValue NewABD
= tryCombineLongOpWithDup(IID
, ABDNode
, DCI
, DAG
);
10318 if (!NewABD
.getNode())
10321 return DAG
.getNode(ISD::ZERO_EXTEND
, SDLoc(N
), N
->getValueType(0),
10326 // This is effectively a custom type legalization for AArch64.
10328 // Type legalization will split an extend of a small, legal, type to a larger
10329 // illegal type by first splitting the destination type, often creating
10330 // illegal source types, which then get legalized in isel-confusing ways,
10331 // leading to really terrible codegen. E.g.,
10332 // %result = v8i32 sext v8i8 %value
10334 // %losrc = extract_subreg %value, ...
10335 // %hisrc = extract_subreg %value, ...
10336 // %lo = v4i32 sext v4i8 %losrc
10337 // %hi = v4i32 sext v4i8 %hisrc
10338 // Things go rapidly downhill from there.
10340 // For AArch64, the [sz]ext vector instructions can only go up one element
10341 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
10342 // take two instructions.
10344 // This implies that the most efficient way to do the extend from v8i8
10345 // to two v4i32 values is to first extend the v8i8 to v8i16, then do
10346 // the normal splitting to happen for the v8i16->v8i32.
10348 // This is pre-legalization to catch some cases where the default
10349 // type legalization will create ill-tempered code.
10350 if (!DCI
.isBeforeLegalizeOps())
10353 // We're only interested in cleaning things up for non-legal vector types
10354 // here. If both the source and destination are legal, things will just
10355 // work naturally without any fiddling.
10356 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
10357 EVT ResVT
= N
->getValueType(0);
10358 if (!ResVT
.isVector() || TLI
.isTypeLegal(ResVT
))
10360 // If the vector type isn't a simple VT, it's beyond the scope of what
10361 // we're worried about here. Let legalization do its thing and hope for
10363 SDValue Src
= N
->getOperand(0);
10364 EVT SrcVT
= Src
->getValueType(0);
10365 if (!ResVT
.isSimple() || !SrcVT
.isSimple())
10368 // If the source VT is a 64-bit vector, we can play games and get the
10369 // better results we want.
10370 if (SrcVT
.getSizeInBits() != 64)
10373 unsigned SrcEltSize
= SrcVT
.getScalarSizeInBits();
10374 unsigned ElementCount
= SrcVT
.getVectorNumElements();
10375 SrcVT
= MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize
* 2), ElementCount
);
10377 Src
= DAG
.getNode(N
->getOpcode(), DL
, SrcVT
, Src
);
10379 // Now split the rest of the operation into two halves, each with a 64
10383 unsigned NumElements
= ResVT
.getVectorNumElements();
10384 assert(!(NumElements
& 1) && "Splitting vector, but not in half!");
10385 LoVT
= HiVT
= EVT::getVectorVT(*DAG
.getContext(),
10386 ResVT
.getVectorElementType(), NumElements
/ 2);
10388 EVT InNVT
= EVT::getVectorVT(*DAG
.getContext(), SrcVT
.getVectorElementType(),
10389 LoVT
.getVectorNumElements());
10390 Lo
= DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, DL
, InNVT
, Src
,
10391 DAG
.getConstant(0, DL
, MVT::i64
));
10392 Hi
= DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, DL
, InNVT
, Src
,
10393 DAG
.getConstant(InNVT
.getVectorNumElements(), DL
, MVT::i64
));
10394 Lo
= DAG
.getNode(N
->getOpcode(), DL
, LoVT
, Lo
);
10395 Hi
= DAG
.getNode(N
->getOpcode(), DL
, HiVT
, Hi
);
10397 // Now combine the parts back together so we still have a single result
10398 // like the combiner expects.
10399 return DAG
.getNode(ISD::CONCAT_VECTORS
, DL
, ResVT
, Lo
, Hi
);
10402 static SDValue
splitStoreSplat(SelectionDAG
&DAG
, StoreSDNode
&St
,
10403 SDValue SplatVal
, unsigned NumVecElts
) {
10404 assert(!St
.isTruncatingStore() && "cannot split truncating vector store");
10405 unsigned OrigAlignment
= St
.getAlignment();
10406 unsigned EltOffset
= SplatVal
.getValueType().getSizeInBits() / 8;
10408 // Create scalar stores. This is at least as good as the code sequence for a
10409 // split unaligned store which is a dup.s, ext.b, and two stores.
10410 // Most of the time the three stores should be replaced by store pair
10411 // instructions (stp).
10413 SDValue BasePtr
= St
.getBasePtr();
10414 uint64_t BaseOffset
= 0;
10416 const MachinePointerInfo
&PtrInfo
= St
.getPointerInfo();
10418 DAG
.getStore(St
.getChain(), DL
, SplatVal
, BasePtr
, PtrInfo
,
10419 OrigAlignment
, St
.getMemOperand()->getFlags());
10421 // As this in ISel, we will not merge this add which may degrade results.
10422 if (BasePtr
->getOpcode() == ISD::ADD
&&
10423 isa
<ConstantSDNode
>(BasePtr
->getOperand(1))) {
10424 BaseOffset
= cast
<ConstantSDNode
>(BasePtr
->getOperand(1))->getSExtValue();
10425 BasePtr
= BasePtr
->getOperand(0);
10428 unsigned Offset
= EltOffset
;
10429 while (--NumVecElts
) {
10430 unsigned Alignment
= MinAlign(OrigAlignment
, Offset
);
10431 SDValue OffsetPtr
=
10432 DAG
.getNode(ISD::ADD
, DL
, MVT::i64
, BasePtr
,
10433 DAG
.getConstant(BaseOffset
+ Offset
, DL
, MVT::i64
));
10434 NewST1
= DAG
.getStore(NewST1
.getValue(0), DL
, SplatVal
, OffsetPtr
,
10435 PtrInfo
.getWithOffset(Offset
), Alignment
,
10436 St
.getMemOperand()->getFlags());
10437 Offset
+= EltOffset
;
10442 /// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR. The
10443 /// load store optimizer pass will merge them to store pair stores. This should
10444 /// be better than a movi to create the vector zero followed by a vector store
10445 /// if the zero constant is not re-used, since one instructions and one register
10446 /// live range will be removed.
10448 /// For example, the final generated code should be:
10450 /// stp xzr, xzr, [x0]
10457 static SDValue
replaceZeroVectorStore(SelectionDAG
&DAG
, StoreSDNode
&St
) {
10458 SDValue StVal
= St
.getValue();
10459 EVT VT
= StVal
.getValueType();
10461 // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or
10462 // 2, 3 or 4 i32 elements.
10463 int NumVecElts
= VT
.getVectorNumElements();
10464 if (!(((NumVecElts
== 2 || NumVecElts
== 3) &&
10465 VT
.getVectorElementType().getSizeInBits() == 64) ||
10466 ((NumVecElts
== 2 || NumVecElts
== 3 || NumVecElts
== 4) &&
10467 VT
.getVectorElementType().getSizeInBits() == 32)))
10470 if (StVal
.getOpcode() != ISD::BUILD_VECTOR
)
10473 // If the zero constant has more than one use then the vector store could be
10474 // better since the constant mov will be amortized and stp q instructions
10475 // should be able to be formed.
10476 if (!StVal
.hasOneUse())
10479 // If the store is truncating then it's going down to i16 or smaller, which
10480 // means it can be implemented in a single store anyway.
10481 if (St
.isTruncatingStore())
10484 // If the immediate offset of the address operand is too large for the stp
10485 // instruction, then bail out.
10486 if (DAG
.isBaseWithConstantOffset(St
.getBasePtr())) {
10487 int64_t Offset
= St
.getBasePtr()->getConstantOperandVal(1);
10488 if (Offset
< -512 || Offset
> 504)
10492 for (int I
= 0; I
< NumVecElts
; ++I
) {
10493 SDValue EltVal
= StVal
.getOperand(I
);
10494 if (!isNullConstant(EltVal
) && !isNullFPConstant(EltVal
))
10498 // Use a CopyFromReg WZR/XZR here to prevent
10499 // DAGCombiner::MergeConsecutiveStores from undoing this transformation.
10503 if (VT
.getVectorElementType().getSizeInBits() == 32) {
10504 ZeroReg
= AArch64::WZR
;
10507 ZeroReg
= AArch64::XZR
;
10511 DAG
.getCopyFromReg(DAG
.getEntryNode(), DL
, ZeroReg
, ZeroVT
);
10512 return splitStoreSplat(DAG
, St
, SplatVal
, NumVecElts
);
10515 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
10516 /// value. The load store optimizer pass will merge them to store pair stores.
10517 /// This has better performance than a splat of the scalar followed by a split
10518 /// vector store. Even if the stores are not merged it is four stores vs a dup,
10519 /// followed by an ext.b and two stores.
10520 static SDValue
replaceSplatVectorStore(SelectionDAG
&DAG
, StoreSDNode
&St
) {
10521 SDValue StVal
= St
.getValue();
10522 EVT VT
= StVal
.getValueType();
10524 // Don't replace floating point stores, they possibly won't be transformed to
10525 // stp because of the store pair suppress pass.
10526 if (VT
.isFloatingPoint())
10529 // We can express a splat as store pair(s) for 2 or 4 elements.
10530 unsigned NumVecElts
= VT
.getVectorNumElements();
10531 if (NumVecElts
!= 4 && NumVecElts
!= 2)
10534 // If the store is truncating then it's going down to i16 or smaller, which
10535 // means it can be implemented in a single store anyway.
10536 if (St
.isTruncatingStore())
10539 // Check that this is a splat.
10540 // Make sure that each of the relevant vector element locations are inserted
10541 // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32.
10542 std::bitset
<4> IndexNotInserted((1 << NumVecElts
) - 1);
10544 for (unsigned I
= 0; I
< NumVecElts
; ++I
) {
10545 // Check for insert vector elements.
10546 if (StVal
.getOpcode() != ISD::INSERT_VECTOR_ELT
)
10549 // Check that same value is inserted at each vector element.
10551 SplatVal
= StVal
.getOperand(1);
10552 else if (StVal
.getOperand(1) != SplatVal
)
10555 // Check insert element index.
10556 ConstantSDNode
*CIndex
= dyn_cast
<ConstantSDNode
>(StVal
.getOperand(2));
10559 uint64_t IndexVal
= CIndex
->getZExtValue();
10560 if (IndexVal
>= NumVecElts
)
10562 IndexNotInserted
.reset(IndexVal
);
10564 StVal
= StVal
.getOperand(0);
10566 // Check that all vector element locations were inserted to.
10567 if (IndexNotInserted
.any())
10570 return splitStoreSplat(DAG
, St
, SplatVal
, NumVecElts
);
10573 static SDValue
splitStores(SDNode
*N
, TargetLowering::DAGCombinerInfo
&DCI
,
10575 const AArch64Subtarget
*Subtarget
) {
10577 StoreSDNode
*S
= cast
<StoreSDNode
>(N
);
10578 if (S
->isVolatile() || S
->isIndexed())
10581 SDValue StVal
= S
->getValue();
10582 EVT VT
= StVal
.getValueType();
10583 if (!VT
.isVector())
10586 // If we get a splat of zeros, convert this vector store to a store of
10587 // scalars. They will be merged into store pairs of xzr thereby removing one
10588 // instruction and one register.
10589 if (SDValue ReplacedZeroSplat
= replaceZeroVectorStore(DAG
, *S
))
10590 return ReplacedZeroSplat
;
10592 // FIXME: The logic for deciding if an unaligned store should be split should
10593 // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
10594 // a call to that function here.
10596 if (!Subtarget
->isMisaligned128StoreSlow())
10599 // Don't split at -Oz.
10600 if (DAG
.getMachineFunction().getFunction().hasMinSize())
10603 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
10604 // those up regresses performance on micro-benchmarks and olden/bh.
10605 if (VT
.getVectorNumElements() < 2 || VT
== MVT::v2i64
)
10608 // Split unaligned 16B stores. They are terrible for performance.
10609 // Don't split stores with alignment of 1 or 2. Code that uses clang vector
10610 // extensions can use this to mark that it does not want splitting to happen
10611 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
10612 // eliminating alignment hazards is only 1 in 8 for alignment of 2.
10613 if (VT
.getSizeInBits() != 128 || S
->getAlignment() >= 16 ||
10614 S
->getAlignment() <= 2)
10617 // If we get a splat of a scalar convert this vector store to a store of
10618 // scalars. They will be merged into store pairs thereby removing two
10620 if (SDValue ReplacedSplat
= replaceSplatVectorStore(DAG
, *S
))
10621 return ReplacedSplat
;
10625 // Split VT into two.
10626 EVT HalfVT
= VT
.getHalfNumVectorElementsVT(*DAG
.getContext());
10627 unsigned NumElts
= HalfVT
.getVectorNumElements();
10628 SDValue SubVector0
= DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, DL
, HalfVT
, StVal
,
10629 DAG
.getConstant(0, DL
, MVT::i64
));
10630 SDValue SubVector1
= DAG
.getNode(ISD::EXTRACT_SUBVECTOR
, DL
, HalfVT
, StVal
,
10631 DAG
.getConstant(NumElts
, DL
, MVT::i64
));
10632 SDValue BasePtr
= S
->getBasePtr();
10634 DAG
.getStore(S
->getChain(), DL
, SubVector0
, BasePtr
, S
->getPointerInfo(),
10635 S
->getAlignment(), S
->getMemOperand()->getFlags());
10636 SDValue OffsetPtr
= DAG
.getNode(ISD::ADD
, DL
, MVT::i64
, BasePtr
,
10637 DAG
.getConstant(8, DL
, MVT::i64
));
10638 return DAG
.getStore(NewST1
.getValue(0), DL
, SubVector1
, OffsetPtr
,
10639 S
->getPointerInfo(), S
->getAlignment(),
10640 S
->getMemOperand()->getFlags());
10643 /// Target-specific DAG combine function for post-increment LD1 (lane) and
10644 /// post-increment LD1R.
10645 static SDValue
performPostLD1Combine(SDNode
*N
,
10646 TargetLowering::DAGCombinerInfo
&DCI
,
10648 if (DCI
.isBeforeLegalizeOps())
10651 SelectionDAG
&DAG
= DCI
.DAG
;
10652 EVT VT
= N
->getValueType(0);
10654 unsigned LoadIdx
= IsLaneOp
? 1 : 0;
10655 SDNode
*LD
= N
->getOperand(LoadIdx
).getNode();
10656 // If it is not LOAD, can not do such combine.
10657 if (LD
->getOpcode() != ISD::LOAD
)
10660 // The vector lane must be a constant in the LD1LANE opcode.
10663 Lane
= N
->getOperand(2);
10664 auto *LaneC
= dyn_cast
<ConstantSDNode
>(Lane
);
10665 if (!LaneC
|| LaneC
->getZExtValue() >= VT
.getVectorNumElements())
10669 LoadSDNode
*LoadSDN
= cast
<LoadSDNode
>(LD
);
10670 EVT MemVT
= LoadSDN
->getMemoryVT();
10671 // Check if memory operand is the same type as the vector element.
10672 if (MemVT
!= VT
.getVectorElementType())
10675 // Check if there are other uses. If so, do not combine as it will introduce
10677 for (SDNode::use_iterator UI
= LD
->use_begin(), UE
= LD
->use_end(); UI
!= UE
;
10679 if (UI
.getUse().getResNo() == 1) // Ignore uses of the chain result.
10685 SDValue Addr
= LD
->getOperand(1);
10686 SDValue Vector
= N
->getOperand(0);
10687 // Search for a use of the address operand that is an increment.
10688 for (SDNode::use_iterator UI
= Addr
.getNode()->use_begin(), UE
=
10689 Addr
.getNode()->use_end(); UI
!= UE
; ++UI
) {
10690 SDNode
*User
= *UI
;
10691 if (User
->getOpcode() != ISD::ADD
10692 || UI
.getUse().getResNo() != Addr
.getResNo())
10695 // If the increment is a constant, it must match the memory ref size.
10696 SDValue Inc
= User
->getOperand(User
->getOperand(0) == Addr
? 1 : 0);
10697 if (ConstantSDNode
*CInc
= dyn_cast
<ConstantSDNode
>(Inc
.getNode())) {
10698 uint32_t IncVal
= CInc
->getZExtValue();
10699 unsigned NumBytes
= VT
.getScalarSizeInBits() / 8;
10700 if (IncVal
!= NumBytes
)
10702 Inc
= DAG
.getRegister(AArch64::XZR
, MVT::i64
);
10705 // To avoid cycle construction make sure that neither the load nor the add
10706 // are predecessors to each other or the Vector.
10707 SmallPtrSet
<const SDNode
*, 32> Visited
;
10708 SmallVector
<const SDNode
*, 16> Worklist
;
10709 Visited
.insert(Addr
.getNode());
10710 Worklist
.push_back(User
);
10711 Worklist
.push_back(LD
);
10712 Worklist
.push_back(Vector
.getNode());
10713 if (SDNode::hasPredecessorHelper(LD
, Visited
, Worklist
) ||
10714 SDNode::hasPredecessorHelper(User
, Visited
, Worklist
))
10717 SmallVector
<SDValue
, 8> Ops
;
10718 Ops
.push_back(LD
->getOperand(0)); // Chain
10720 Ops
.push_back(Vector
); // The vector to be inserted
10721 Ops
.push_back(Lane
); // The lane to be inserted in the vector
10723 Ops
.push_back(Addr
);
10724 Ops
.push_back(Inc
);
10726 EVT Tys
[3] = { VT
, MVT::i64
, MVT::Other
};
10727 SDVTList SDTys
= DAG
.getVTList(Tys
);
10728 unsigned NewOp
= IsLaneOp
? AArch64ISD::LD1LANEpost
: AArch64ISD::LD1DUPpost
;
10729 SDValue UpdN
= DAG
.getMemIntrinsicNode(NewOp
, SDLoc(N
), SDTys
, Ops
,
10731 LoadSDN
->getMemOperand());
10733 // Update the uses.
10734 SDValue NewResults
[] = {
10735 SDValue(LD
, 0), // The result of load
10736 SDValue(UpdN
.getNode(), 2) // Chain
10738 DCI
.CombineTo(LD
, NewResults
);
10739 DCI
.CombineTo(N
, SDValue(UpdN
.getNode(), 0)); // Dup/Inserted Result
10740 DCI
.CombineTo(User
, SDValue(UpdN
.getNode(), 1)); // Write back register
10747 /// Simplify ``Addr`` given that the top byte of it is ignored by HW during
10748 /// address translation.
10749 static bool performTBISimplification(SDValue Addr
,
10750 TargetLowering::DAGCombinerInfo
&DCI
,
10751 SelectionDAG
&DAG
) {
10752 APInt DemandedMask
= APInt::getLowBitsSet(64, 56);
10754 TargetLowering::TargetLoweringOpt
TLO(DAG
, !DCI
.isBeforeLegalize(),
10755 !DCI
.isBeforeLegalizeOps());
10756 const TargetLowering
&TLI
= DAG
.getTargetLoweringInfo();
10757 if (TLI
.SimplifyDemandedBits(Addr
, DemandedMask
, Known
, TLO
)) {
10758 DCI
.CommitTargetLoweringOpt(TLO
);
10764 static SDValue
performSTORECombine(SDNode
*N
,
10765 TargetLowering::DAGCombinerInfo
&DCI
,
10767 const AArch64Subtarget
*Subtarget
) {
10768 if (SDValue Split
= splitStores(N
, DCI
, DAG
, Subtarget
))
10771 if (Subtarget
->supportsAddressTopByteIgnored() &&
10772 performTBISimplification(N
->getOperand(2), DCI
, DAG
))
10773 return SDValue(N
, 0);
10779 /// Target-specific DAG combine function for NEON load/store intrinsics
10780 /// to merge base address updates.
10781 static SDValue
performNEONPostLDSTCombine(SDNode
*N
,
10782 TargetLowering::DAGCombinerInfo
&DCI
,
10783 SelectionDAG
&DAG
) {
10784 if (DCI
.isBeforeLegalize() || DCI
.isCalledByLegalizer())
10787 unsigned AddrOpIdx
= N
->getNumOperands() - 1;
10788 SDValue Addr
= N
->getOperand(AddrOpIdx
);
10790 // Search for a use of the address operand that is an increment.
10791 for (SDNode::use_iterator UI
= Addr
.getNode()->use_begin(),
10792 UE
= Addr
.getNode()->use_end(); UI
!= UE
; ++UI
) {
10793 SDNode
*User
= *UI
;
10794 if (User
->getOpcode() != ISD::ADD
||
10795 UI
.getUse().getResNo() != Addr
.getResNo())
10798 // Check that the add is independent of the load/store. Otherwise, folding
10799 // it would create a cycle.
10800 SmallPtrSet
<const SDNode
*, 32> Visited
;
10801 SmallVector
<const SDNode
*, 16> Worklist
;
10802 Visited
.insert(Addr
.getNode());
10803 Worklist
.push_back(N
);
10804 Worklist
.push_back(User
);
10805 if (SDNode::hasPredecessorHelper(N
, Visited
, Worklist
) ||
10806 SDNode::hasPredecessorHelper(User
, Visited
, Worklist
))
10809 // Find the new opcode for the updating load/store.
10810 bool IsStore
= false;
10811 bool IsLaneOp
= false;
10812 bool IsDupOp
= false;
10813 unsigned NewOpc
= 0;
10814 unsigned NumVecs
= 0;
10815 unsigned IntNo
= cast
<ConstantSDNode
>(N
->getOperand(1))->getZExtValue();
10817 default: llvm_unreachable("unexpected intrinsic for Neon base update");
10818 case Intrinsic::aarch64_neon_ld2
: NewOpc
= AArch64ISD::LD2post
;
10819 NumVecs
= 2; break;
10820 case Intrinsic::aarch64_neon_ld3
: NewOpc
= AArch64ISD::LD3post
;
10821 NumVecs
= 3; break;
10822 case Intrinsic::aarch64_neon_ld4
: NewOpc
= AArch64ISD::LD4post
;
10823 NumVecs
= 4; break;
10824 case Intrinsic::aarch64_neon_st2
: NewOpc
= AArch64ISD::ST2post
;
10825 NumVecs
= 2; IsStore
= true; break;
10826 case Intrinsic::aarch64_neon_st3
: NewOpc
= AArch64ISD::ST3post
;
10827 NumVecs
= 3; IsStore
= true; break;
10828 case Intrinsic::aarch64_neon_st4
: NewOpc
= AArch64ISD::ST4post
;
10829 NumVecs
= 4; IsStore
= true; break;
10830 case Intrinsic::aarch64_neon_ld1x2
: NewOpc
= AArch64ISD::LD1x2post
;
10831 NumVecs
= 2; break;
10832 case Intrinsic::aarch64_neon_ld1x3
: NewOpc
= AArch64ISD::LD1x3post
;
10833 NumVecs
= 3; break;
10834 case Intrinsic::aarch64_neon_ld1x4
: NewOpc
= AArch64ISD::LD1x4post
;
10835 NumVecs
= 4; break;
10836 case Intrinsic::aarch64_neon_st1x2
: NewOpc
= AArch64ISD::ST1x2post
;
10837 NumVecs
= 2; IsStore
= true; break;
10838 case Intrinsic::aarch64_neon_st1x3
: NewOpc
= AArch64ISD::ST1x3post
;
10839 NumVecs
= 3; IsStore
= true; break;
10840 case Intrinsic::aarch64_neon_st1x4
: NewOpc
= AArch64ISD::ST1x4post
;
10841 NumVecs
= 4; IsStore
= true; break;
10842 case Intrinsic::aarch64_neon_ld2r
: NewOpc
= AArch64ISD::LD2DUPpost
;
10843 NumVecs
= 2; IsDupOp
= true; break;
10844 case Intrinsic::aarch64_neon_ld3r
: NewOpc
= AArch64ISD::LD3DUPpost
;
10845 NumVecs
= 3; IsDupOp
= true; break;
10846 case Intrinsic::aarch64_neon_ld4r
: NewOpc
= AArch64ISD::LD4DUPpost
;
10847 NumVecs
= 4; IsDupOp
= true; break;
10848 case Intrinsic::aarch64_neon_ld2lane
: NewOpc
= AArch64ISD::LD2LANEpost
;
10849 NumVecs
= 2; IsLaneOp
= true; break;
10850 case Intrinsic::aarch64_neon_ld3lane
: NewOpc
= AArch64ISD::LD3LANEpost
;
10851 NumVecs
= 3; IsLaneOp
= true; break;
10852 case Intrinsic::aarch64_neon_ld4lane
: NewOpc
= AArch64ISD::LD4LANEpost
;
10853 NumVecs
= 4; IsLaneOp
= true; break;
10854 case Intrinsic::aarch64_neon_st2lane
: NewOpc
= AArch64ISD::ST2LANEpost
;
10855 NumVecs
= 2; IsStore
= true; IsLaneOp
= true; break;
10856 case Intrinsic::aarch64_neon_st3lane
: NewOpc
= AArch64ISD::ST3LANEpost
;
10857 NumVecs
= 3; IsStore
= true; IsLaneOp
= true; break;
10858 case Intrinsic::aarch64_neon_st4lane
: NewOpc
= AArch64ISD::ST4LANEpost
;
10859 NumVecs
= 4; IsStore
= true; IsLaneOp
= true; break;
10864 VecTy
= N
->getOperand(2).getValueType();
10866 VecTy
= N
->getValueType(0);
10868 // If the increment is a constant, it must match the memory ref size.
10869 SDValue Inc
= User
->getOperand(User
->getOperand(0) == Addr
? 1 : 0);
10870 if (ConstantSDNode
*CInc
= dyn_cast
<ConstantSDNode
>(Inc
.getNode())) {
10871 uint32_t IncVal
= CInc
->getZExtValue();
10872 unsigned NumBytes
= NumVecs
* VecTy
.getSizeInBits() / 8;
10873 if (IsLaneOp
|| IsDupOp
)
10874 NumBytes
/= VecTy
.getVectorNumElements();
10875 if (IncVal
!= NumBytes
)
10877 Inc
= DAG
.getRegister(AArch64::XZR
, MVT::i64
);
10879 SmallVector
<SDValue
, 8> Ops
;
10880 Ops
.push_back(N
->getOperand(0)); // Incoming chain
10881 // Load lane and store have vector list as input.
10882 if (IsLaneOp
|| IsStore
)
10883 for (unsigned i
= 2; i
< AddrOpIdx
; ++i
)
10884 Ops
.push_back(N
->getOperand(i
));
10885 Ops
.push_back(Addr
); // Base register
10886 Ops
.push_back(Inc
);
10890 unsigned NumResultVecs
= (IsStore
? 0 : NumVecs
);
10892 for (n
= 0; n
< NumResultVecs
; ++n
)
10894 Tys
[n
++] = MVT::i64
; // Type of write back register
10895 Tys
[n
] = MVT::Other
; // Type of the chain
10896 SDVTList SDTys
= DAG
.getVTList(makeArrayRef(Tys
, NumResultVecs
+ 2));
10898 MemIntrinsicSDNode
*MemInt
= cast
<MemIntrinsicSDNode
>(N
);
10899 SDValue UpdN
= DAG
.getMemIntrinsicNode(NewOpc
, SDLoc(N
), SDTys
, Ops
,
10900 MemInt
->getMemoryVT(),
10901 MemInt
->getMemOperand());
10903 // Update the uses.
10904 std::vector
<SDValue
> NewResults
;
10905 for (unsigned i
= 0; i
< NumResultVecs
; ++i
) {
10906 NewResults
.push_back(SDValue(UpdN
.getNode(), i
));
10908 NewResults
.push_back(SDValue(UpdN
.getNode(), NumResultVecs
+ 1));
10909 DCI
.CombineTo(N
, NewResults
);
10910 DCI
.CombineTo(User
, SDValue(UpdN
.getNode(), NumResultVecs
));
10917 // Checks to see if the value is the prescribed width and returns information
10918 // about its extension mode.
10920 bool checkValueWidth(SDValue V
, unsigned width
, ISD::LoadExtType
&ExtType
) {
10921 ExtType
= ISD::NON_EXTLOAD
;
10922 switch(V
.getNode()->getOpcode()) {
10926 LoadSDNode
*LoadNode
= cast
<LoadSDNode
>(V
.getNode());
10927 if ((LoadNode
->getMemoryVT() == MVT::i8
&& width
== 8)
10928 || (LoadNode
->getMemoryVT() == MVT::i16
&& width
== 16)) {
10929 ExtType
= LoadNode
->getExtensionType();
10934 case ISD::AssertSext
: {
10935 VTSDNode
*TypeNode
= cast
<VTSDNode
>(V
.getNode()->getOperand(1));
10936 if ((TypeNode
->getVT() == MVT::i8
&& width
== 8)
10937 || (TypeNode
->getVT() == MVT::i16
&& width
== 16)) {
10938 ExtType
= ISD::SEXTLOAD
;
10943 case ISD::AssertZext
: {
10944 VTSDNode
*TypeNode
= cast
<VTSDNode
>(V
.getNode()->getOperand(1));
10945 if ((TypeNode
->getVT() == MVT::i8
&& width
== 8)
10946 || (TypeNode
->getVT() == MVT::i16
&& width
== 16)) {
10947 ExtType
= ISD::ZEXTLOAD
;
10952 case ISD::Constant
:
10953 case ISD::TargetConstant
: {
10954 return std::abs(cast
<ConstantSDNode
>(V
.getNode())->getSExtValue()) <
10955 1LL << (width
- 1);
10962 // This function does a whole lot of voodoo to determine if the tests are
10963 // equivalent without and with a mask. Essentially what happens is that given a
10966 // +-------------+ +-------------+ +-------------+ +-------------+
10967 // | Input | | AddConstant | | CompConstant| | CC |
10968 // +-------------+ +-------------+ +-------------+ +-------------+
10970 // V V | +----------+
10971 // +-------------+ +----+ | |
10972 // | ADD | |0xff| | |
10973 // +-------------+ +----+ | |
10976 // +-------------+ | |
10978 // +-------------+ | |
10987 // The AND node may be safely removed for some combinations of inputs. In
10988 // particular we need to take into account the extension type of the Input,
10989 // the exact values of AddConstant, CompConstant, and CC, along with the nominal
10990 // width of the input (this can work for any width inputs, the above graph is
10991 // specific to 8 bits.
10993 // The specific equations were worked out by generating output tables for each
10994 // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
10995 // problem was simplified by working with 4 bit inputs, which means we only
10996 // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
10997 // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
10998 // patterns present in both extensions (0,7). For every distinct set of
10999 // AddConstant and CompConstants bit patterns we can consider the masked and
11000 // unmasked versions to be equivalent if the result of this function is true for
11001 // all 16 distinct bit patterns of for the current extension type of Input (w0).
11004 // and w10, w8, #0x0f
11006 // cset w9, AArch64CC
11008 // cset w11, AArch64CC
11013 // Since the above function shows when the outputs are equivalent it defines
11014 // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
11015 // would be expensive to run during compiles. The equations below were written
11016 // in a test harness that confirmed they gave equivalent outputs to the above
11017 // for all inputs function, so they can be used determine if the removal is
11020 // isEquivalentMaskless() is the code for testing if the AND can be removed
11021 // factored out of the DAG recognition as the DAG can take several forms.
11023 static bool isEquivalentMaskless(unsigned CC
, unsigned width
,
11024 ISD::LoadExtType ExtType
, int AddConstant
,
11025 int CompConstant
) {
11026 // By being careful about our equations and only writing the in term
11027 // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
11028 // make them generally applicable to all bit widths.
11029 int MaxUInt
= (1 << width
);
11031 // For the purposes of these comparisons sign extending the type is
11032 // equivalent to zero extending the add and displacing it by half the integer
11033 // width. Provided we are careful and make sure our equations are valid over
11034 // the whole range we can just adjust the input and avoid writing equations
11035 // for sign extended inputs.
11036 if (ExtType
== ISD::SEXTLOAD
)
11037 AddConstant
-= (1 << (width
-1));
11040 case AArch64CC::LE
:
11041 case AArch64CC::GT
:
11042 if ((AddConstant
== 0) ||
11043 (CompConstant
== MaxUInt
- 1 && AddConstant
< 0) ||
11044 (AddConstant
>= 0 && CompConstant
< 0) ||
11045 (AddConstant
<= 0 && CompConstant
<= 0 && CompConstant
< AddConstant
))
11048 case AArch64CC::LT
:
11049 case AArch64CC::GE
:
11050 if ((AddConstant
== 0) ||
11051 (AddConstant
>= 0 && CompConstant
<= 0) ||
11052 (AddConstant
<= 0 && CompConstant
<= 0 && CompConstant
<= AddConstant
))
11055 case AArch64CC::HI
:
11056 case AArch64CC::LS
:
11057 if ((AddConstant
>= 0 && CompConstant
< 0) ||
11058 (AddConstant
<= 0 && CompConstant
>= -1 &&
11059 CompConstant
< AddConstant
+ MaxUInt
))
11062 case AArch64CC::PL
:
11063 case AArch64CC::MI
:
11064 if ((AddConstant
== 0) ||
11065 (AddConstant
> 0 && CompConstant
<= 0) ||
11066 (AddConstant
< 0 && CompConstant
<= AddConstant
))
11069 case AArch64CC::LO
:
11070 case AArch64CC::HS
:
11071 if ((AddConstant
>= 0 && CompConstant
<= 0) ||
11072 (AddConstant
<= 0 && CompConstant
>= 0 &&
11073 CompConstant
<= AddConstant
+ MaxUInt
))
11076 case AArch64CC::EQ
:
11077 case AArch64CC::NE
:
11078 if ((AddConstant
> 0 && CompConstant
< 0) ||
11079 (AddConstant
< 0 && CompConstant
>= 0 &&
11080 CompConstant
< AddConstant
+ MaxUInt
) ||
11081 (AddConstant
>= 0 && CompConstant
>= 0 &&
11082 CompConstant
>= AddConstant
) ||
11083 (AddConstant
<= 0 && CompConstant
< 0 && CompConstant
< AddConstant
))
11086 case AArch64CC::VS
:
11087 case AArch64CC::VC
:
11088 case AArch64CC::AL
:
11089 case AArch64CC::NV
:
11091 case AArch64CC::Invalid
:
11099 SDValue
performCONDCombine(SDNode
*N
,
11100 TargetLowering::DAGCombinerInfo
&DCI
,
11101 SelectionDAG
&DAG
, unsigned CCIndex
,
11102 unsigned CmpIndex
) {
11103 unsigned CC
= cast
<ConstantSDNode
>(N
->getOperand(CCIndex
))->getSExtValue();
11104 SDNode
*SubsNode
= N
->getOperand(CmpIndex
).getNode();
11105 unsigned CondOpcode
= SubsNode
->getOpcode();
11107 if (CondOpcode
!= AArch64ISD::SUBS
)
11110 // There is a SUBS feeding this condition. Is it fed by a mask we can
11113 SDNode
*AndNode
= SubsNode
->getOperand(0).getNode();
11114 unsigned MaskBits
= 0;
11116 if (AndNode
->getOpcode() != ISD::AND
)
11119 if (ConstantSDNode
*CN
= dyn_cast
<ConstantSDNode
>(AndNode
->getOperand(1))) {
11120 uint32_t CNV
= CN
->getZExtValue();
11123 else if (CNV
== 65535)
11130 SDValue AddValue
= AndNode
->getOperand(0);
11132 if (AddValue
.getOpcode() != ISD::ADD
)
11135 // The basic dag structure is correct, grab the inputs and validate them.
11137 SDValue AddInputValue1
= AddValue
.getNode()->getOperand(0);
11138 SDValue AddInputValue2
= AddValue
.getNode()->getOperand(1);
11139 SDValue SubsInputValue
= SubsNode
->getOperand(1);
11141 // The mask is present and the provenance of all the values is a smaller type,
11142 // lets see if the mask is superfluous.
11144 if (!isa
<ConstantSDNode
>(AddInputValue2
.getNode()) ||
11145 !isa
<ConstantSDNode
>(SubsInputValue
.getNode()))
11148 ISD::LoadExtType ExtType
;
11150 if (!checkValueWidth(SubsInputValue
, MaskBits
, ExtType
) ||
11151 !checkValueWidth(AddInputValue2
, MaskBits
, ExtType
) ||
11152 !checkValueWidth(AddInputValue1
, MaskBits
, ExtType
) )
11155 if(!isEquivalentMaskless(CC
, MaskBits
, ExtType
,
11156 cast
<ConstantSDNode
>(AddInputValue2
.getNode())->getSExtValue(),
11157 cast
<ConstantSDNode
>(SubsInputValue
.getNode())->getSExtValue()))
11160 // The AND is not necessary, remove it.
11162 SDVTList VTs
= DAG
.getVTList(SubsNode
->getValueType(0),
11163 SubsNode
->getValueType(1));
11164 SDValue Ops
[] = { AddValue
, SubsNode
->getOperand(1) };
11166 SDValue NewValue
= DAG
.getNode(CondOpcode
, SDLoc(SubsNode
), VTs
, Ops
);
11167 DAG
.ReplaceAllUsesWith(SubsNode
, NewValue
.getNode());
11169 return SDValue(N
, 0);
11172 // Optimize compare with zero and branch.
11173 static SDValue
performBRCONDCombine(SDNode
*N
,
11174 TargetLowering::DAGCombinerInfo
&DCI
,
11175 SelectionDAG
&DAG
) {
11176 MachineFunction
&MF
= DAG
.getMachineFunction();
11177 // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
11178 // will not be produced, as they are conditional branch instructions that do
11180 if (MF
.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening
))
11183 if (SDValue NV
= performCONDCombine(N
, DCI
, DAG
, 2, 3))
11185 SDValue Chain
= N
->getOperand(0);
11186 SDValue Dest
= N
->getOperand(1);
11187 SDValue CCVal
= N
->getOperand(2);
11188 SDValue Cmp
= N
->getOperand(3);
11190 assert(isa
<ConstantSDNode
>(CCVal
) && "Expected a ConstantSDNode here!");
11191 unsigned CC
= cast
<ConstantSDNode
>(CCVal
)->getZExtValue();
11192 if (CC
!= AArch64CC::EQ
&& CC
!= AArch64CC::NE
)
11195 unsigned CmpOpc
= Cmp
.getOpcode();
11196 if (CmpOpc
!= AArch64ISD::ADDS
&& CmpOpc
!= AArch64ISD::SUBS
)
11199 // Only attempt folding if there is only one use of the flag and no use of the
11201 if (!Cmp
->hasNUsesOfValue(0, 0) || !Cmp
->hasNUsesOfValue(1, 1))
11204 SDValue LHS
= Cmp
.getOperand(0);
11205 SDValue RHS
= Cmp
.getOperand(1);
11207 assert(LHS
.getValueType() == RHS
.getValueType() &&
11208 "Expected the value type to be the same for both operands!");
11209 if (LHS
.getValueType() != MVT::i32
&& LHS
.getValueType() != MVT::i64
)
11212 if (isNullConstant(LHS
))
11213 std::swap(LHS
, RHS
);
11215 if (!isNullConstant(RHS
))
11218 if (LHS
.getOpcode() == ISD::SHL
|| LHS
.getOpcode() == ISD::SRA
||
11219 LHS
.getOpcode() == ISD::SRL
)
11222 // Fold the compare into the branch instruction.
11224 if (CC
== AArch64CC::EQ
)
11225 BR
= DAG
.getNode(AArch64ISD::CBZ
, SDLoc(N
), MVT::Other
, Chain
, LHS
, Dest
);
11227 BR
= DAG
.getNode(AArch64ISD::CBNZ
, SDLoc(N
), MVT::Other
, Chain
, LHS
, Dest
);
11229 // Do not add new nodes to DAG combiner worklist.
11230 DCI
.CombineTo(N
, BR
, false);
11235 // Optimize some simple tbz/tbnz cases. Returns the new operand and bit to test
11236 // as well as whether the test should be inverted. This code is required to
11237 // catch these cases (as opposed to standard dag combines) because
11238 // AArch64ISD::TBZ is matched during legalization.
11239 static SDValue
getTestBitOperand(SDValue Op
, unsigned &Bit
, bool &Invert
,
11240 SelectionDAG
&DAG
) {
11242 if (!Op
->hasOneUse())
11245 // We don't handle undef/constant-fold cases below, as they should have
11246 // already been taken care of (e.g. and of 0, test of undefined shifted bits,
11249 // (tbz (trunc x), b) -> (tbz x, b)
11250 // This case is just here to enable more of the below cases to be caught.
11251 if (Op
->getOpcode() == ISD::TRUNCATE
&&
11252 Bit
< Op
->getValueType(0).getSizeInBits()) {
11253 return getTestBitOperand(Op
->getOperand(0), Bit
, Invert
, DAG
);
11256 // (tbz (any_ext x), b) -> (tbz x, b) if we don't use the extended bits.
11257 if (Op
->getOpcode() == ISD::ANY_EXTEND
&&
11258 Bit
< Op
->getOperand(0).getValueSizeInBits()) {
11259 return getTestBitOperand(Op
->getOperand(0), Bit
, Invert
, DAG
);
11262 if (Op
->getNumOperands() != 2)
11265 auto *C
= dyn_cast
<ConstantSDNode
>(Op
->getOperand(1));
11269 switch (Op
->getOpcode()) {
11273 // (tbz (and x, m), b) -> (tbz x, b)
11275 if ((C
->getZExtValue() >> Bit
) & 1)
11276 return getTestBitOperand(Op
->getOperand(0), Bit
, Invert
, DAG
);
11279 // (tbz (shl x, c), b) -> (tbz x, b-c)
11281 if (C
->getZExtValue() <= Bit
&&
11282 (Bit
- C
->getZExtValue()) < Op
->getValueType(0).getSizeInBits()) {
11283 Bit
= Bit
- C
->getZExtValue();
11284 return getTestBitOperand(Op
->getOperand(0), Bit
, Invert
, DAG
);
11288 // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
11290 Bit
= Bit
+ C
->getZExtValue();
11291 if (Bit
>= Op
->getValueType(0).getSizeInBits())
11292 Bit
= Op
->getValueType(0).getSizeInBits() - 1;
11293 return getTestBitOperand(Op
->getOperand(0), Bit
, Invert
, DAG
);
11295 // (tbz (srl x, c), b) -> (tbz x, b+c)
11297 if ((Bit
+ C
->getZExtValue()) < Op
->getValueType(0).getSizeInBits()) {
11298 Bit
= Bit
+ C
->getZExtValue();
11299 return getTestBitOperand(Op
->getOperand(0), Bit
, Invert
, DAG
);
11303 // (tbz (xor x, -1), b) -> (tbnz x, b)
11305 if ((C
->getZExtValue() >> Bit
) & 1)
11307 return getTestBitOperand(Op
->getOperand(0), Bit
, Invert
, DAG
);
11311 // Optimize test single bit zero/non-zero and branch.
11312 static SDValue
performTBZCombine(SDNode
*N
,
11313 TargetLowering::DAGCombinerInfo
&DCI
,
11314 SelectionDAG
&DAG
) {
11315 unsigned Bit
= cast
<ConstantSDNode
>(N
->getOperand(2))->getZExtValue();
11316 bool Invert
= false;
11317 SDValue TestSrc
= N
->getOperand(1);
11318 SDValue NewTestSrc
= getTestBitOperand(TestSrc
, Bit
, Invert
, DAG
);
11320 if (TestSrc
== NewTestSrc
)
11323 unsigned NewOpc
= N
->getOpcode();
11325 if (NewOpc
== AArch64ISD::TBZ
)
11326 NewOpc
= AArch64ISD::TBNZ
;
11328 assert(NewOpc
== AArch64ISD::TBNZ
);
11329 NewOpc
= AArch64ISD::TBZ
;
11334 return DAG
.getNode(NewOpc
, DL
, MVT::Other
, N
->getOperand(0), NewTestSrc
,
11335 DAG
.getConstant(Bit
, DL
, MVT::i64
), N
->getOperand(3));
11338 // vselect (v1i1 setcc) ->
11339 // vselect (v1iXX setcc) (XX is the size of the compared operand type)
11340 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
11341 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
11343 static SDValue
performVSelectCombine(SDNode
*N
, SelectionDAG
&DAG
) {
11344 SDValue N0
= N
->getOperand(0);
11345 EVT CCVT
= N0
.getValueType();
11347 if (N0
.getOpcode() != ISD::SETCC
|| CCVT
.getVectorNumElements() != 1 ||
11348 CCVT
.getVectorElementType() != MVT::i1
)
11351 EVT ResVT
= N
->getValueType(0);
11352 EVT CmpVT
= N0
.getOperand(0).getValueType();
11353 // Only combine when the result type is of the same size as the compared
11355 if (ResVT
.getSizeInBits() != CmpVT
.getSizeInBits())
11358 SDValue IfTrue
= N
->getOperand(1);
11359 SDValue IfFalse
= N
->getOperand(2);
11361 DAG
.getSetCC(SDLoc(N
), CmpVT
.changeVectorElementTypeToInteger(),
11362 N0
.getOperand(0), N0
.getOperand(1),
11363 cast
<CondCodeSDNode
>(N0
.getOperand(2))->get());
11364 return DAG
.getNode(ISD::VSELECT
, SDLoc(N
), ResVT
, SetCC
,
11368 /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
11369 /// the compare-mask instructions rather than going via NZCV, even if LHS and
11370 /// RHS are really scalar. This replaces any scalar setcc in the above pattern
11371 /// with a vector one followed by a DUP shuffle on the result.
11372 static SDValue
performSelectCombine(SDNode
*N
,
11373 TargetLowering::DAGCombinerInfo
&DCI
) {
11374 SelectionDAG
&DAG
= DCI
.DAG
;
11375 SDValue N0
= N
->getOperand(0);
11376 EVT ResVT
= N
->getValueType(0);
11378 if (N0
.getOpcode() != ISD::SETCC
)
11381 // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
11382 // scalar SetCCResultType. We also don't expect vectors, because we assume
11383 // that selects fed by vector SETCCs are canonicalized to VSELECT.
11384 assert((N0
.getValueType() == MVT::i1
|| N0
.getValueType() == MVT::i32
) &&
11385 "Scalar-SETCC feeding SELECT has unexpected result type!");
11387 // If NumMaskElts == 0, the comparison is larger than select result. The
11388 // largest real NEON comparison is 64-bits per lane, which means the result is
11389 // at most 32-bits and an illegal vector. Just bail out for now.
11390 EVT SrcVT
= N0
.getOperand(0).getValueType();
11392 // Don't try to do this optimization when the setcc itself has i1 operands.
11393 // There are no legal vectors of i1, so this would be pointless.
11394 if (SrcVT
== MVT::i1
)
11397 int NumMaskElts
= ResVT
.getSizeInBits() / SrcVT
.getSizeInBits();
11398 if (!ResVT
.isVector() || NumMaskElts
== 0)
11401 SrcVT
= EVT::getVectorVT(*DAG
.getContext(), SrcVT
, NumMaskElts
);
11402 EVT CCVT
= SrcVT
.changeVectorElementTypeToInteger();
11404 // Also bail out if the vector CCVT isn't the same size as ResVT.
11405 // This can happen if the SETCC operand size doesn't divide the ResVT size
11406 // (e.g., f64 vs v3f32).
11407 if (CCVT
.getSizeInBits() != ResVT
.getSizeInBits())
11410 // Make sure we didn't create illegal types, if we're not supposed to.
11411 assert(DCI
.isBeforeLegalize() ||
11412 DAG
.getTargetLoweringInfo().isTypeLegal(SrcVT
));
11414 // First perform a vector comparison, where lane 0 is the one we're interested
11418 DAG
.getNode(ISD::SCALAR_TO_VECTOR
, DL
, SrcVT
, N0
.getOperand(0));
11420 DAG
.getNode(ISD::SCALAR_TO_VECTOR
, DL
, SrcVT
, N0
.getOperand(1));
11421 SDValue SetCC
= DAG
.getNode(ISD::SETCC
, DL
, CCVT
, LHS
, RHS
, N0
.getOperand(2));
11423 // Now duplicate the comparison mask we want across all other lanes.
11424 SmallVector
<int, 8> DUPMask(CCVT
.getVectorNumElements(), 0);
11425 SDValue Mask
= DAG
.getVectorShuffle(CCVT
, DL
, SetCC
, SetCC
, DUPMask
);
11426 Mask
= DAG
.getNode(ISD::BITCAST
, DL
,
11427 ResVT
.changeVectorElementTypeToInteger(), Mask
);
11429 return DAG
.getSelect(DL
, ResVT
, Mask
, N
->getOperand(1), N
->getOperand(2));
11432 /// Get rid of unnecessary NVCASTs (that don't change the type).
11433 static SDValue
performNVCASTCombine(SDNode
*N
) {
11434 if (N
->getValueType(0) == N
->getOperand(0).getValueType())
11435 return N
->getOperand(0);
11440 // If all users of the globaladdr are of the form (globaladdr + constant), find
11441 // the smallest constant, fold it into the globaladdr's offset and rewrite the
11442 // globaladdr as (globaladdr + constant) - constant.
11443 static SDValue
performGlobalAddressCombine(SDNode
*N
, SelectionDAG
&DAG
,
11444 const AArch64Subtarget
*Subtarget
,
11445 const TargetMachine
&TM
) {
11446 auto *GN
= cast
<GlobalAddressSDNode
>(N
);
11447 if (Subtarget
->ClassifyGlobalReference(GN
->getGlobal(), TM
) !=
11448 AArch64II::MO_NO_FLAG
)
11451 uint64_t MinOffset
= -1ull;
11452 for (SDNode
*N
: GN
->uses()) {
11453 if (N
->getOpcode() != ISD::ADD
)
11455 auto *C
= dyn_cast
<ConstantSDNode
>(N
->getOperand(0));
11457 C
= dyn_cast
<ConstantSDNode
>(N
->getOperand(1));
11460 MinOffset
= std::min(MinOffset
, C
->getZExtValue());
11462 uint64_t Offset
= MinOffset
+ GN
->getOffset();
11464 // Require that the new offset is larger than the existing one. Otherwise, we
11465 // can end up oscillating between two possible DAGs, for example,
11466 // (add (add globaladdr + 10, -1), 1) and (add globaladdr + 9, 1).
11467 if (Offset
<= uint64_t(GN
->getOffset()))
11470 // Check whether folding this offset is legal. It must not go out of bounds of
11471 // the referenced object to avoid violating the code model, and must be
11472 // smaller than 2^21 because this is the largest offset expressible in all
11475 // This check also prevents us from folding negative offsets, which will end
11476 // up being treated in the same way as large positive ones. They could also
11477 // cause code model violations, and aren't really common enough to matter.
11478 if (Offset
>= (1 << 21))
11481 const GlobalValue
*GV
= GN
->getGlobal();
11482 Type
*T
= GV
->getValueType();
11483 if (!T
->isSized() ||
11484 Offset
> GV
->getParent()->getDataLayout().getTypeAllocSize(T
))
11488 SDValue Result
= DAG
.getGlobalAddress(GV
, DL
, MVT::i64
, Offset
);
11489 return DAG
.getNode(ISD::SUB
, DL
, MVT::i64
, Result
,
11490 DAG
.getConstant(MinOffset
, DL
, MVT::i64
));
11493 SDValue
AArch64TargetLowering::PerformDAGCombine(SDNode
*N
,
11494 DAGCombinerInfo
&DCI
) const {
11495 SelectionDAG
&DAG
= DCI
.DAG
;
11496 switch (N
->getOpcode()) {
11498 LLVM_DEBUG(dbgs() << "Custom combining: skipping\n");
11502 return performAddSubLongCombine(N
, DCI
, DAG
);
11504 return performXorCombine(N
, DAG
, DCI
, Subtarget
);
11506 return performMulCombine(N
, DAG
, DCI
, Subtarget
);
11507 case ISD::SINT_TO_FP
:
11508 case ISD::UINT_TO_FP
:
11509 return performIntToFpCombine(N
, DAG
, Subtarget
);
11510 case ISD::FP_TO_SINT
:
11511 case ISD::FP_TO_UINT
:
11512 return performFpToIntCombine(N
, DAG
, DCI
, Subtarget
);
11514 return performFDivCombine(N
, DAG
, DCI
, Subtarget
);
11516 return performORCombine(N
, DCI
, Subtarget
);
11518 return performANDCombine(N
, DCI
);
11520 return performSRLCombine(N
, DCI
);
11521 case ISD::INTRINSIC_WO_CHAIN
:
11522 return performIntrinsicCombine(N
, DCI
, Subtarget
);
11523 case ISD::ANY_EXTEND
:
11524 case ISD::ZERO_EXTEND
:
11525 case ISD::SIGN_EXTEND
:
11526 return performExtendCombine(N
, DCI
, DAG
);
11528 return performBitcastCombine(N
, DCI
, DAG
);
11529 case ISD::CONCAT_VECTORS
:
11530 return performConcatVectorsCombine(N
, DCI
, DAG
);
11532 return performSelectCombine(N
, DCI
);
11534 return performVSelectCombine(N
, DCI
.DAG
);
11536 if (performTBISimplification(N
->getOperand(1), DCI
, DAG
))
11537 return SDValue(N
, 0);
11540 return performSTORECombine(N
, DCI
, DAG
, Subtarget
);
11541 case AArch64ISD::BRCOND
:
11542 return performBRCONDCombine(N
, DCI
, DAG
);
11543 case AArch64ISD::TBNZ
:
11544 case AArch64ISD::TBZ
:
11545 return performTBZCombine(N
, DCI
, DAG
);
11546 case AArch64ISD::CSEL
:
11547 return performCONDCombine(N
, DCI
, DAG
, 2, 3);
11548 case AArch64ISD::DUP
:
11549 return performPostLD1Combine(N
, DCI
, false);
11550 case AArch64ISD::NVCAST
:
11551 return performNVCASTCombine(N
);
11552 case ISD::INSERT_VECTOR_ELT
:
11553 return performPostLD1Combine(N
, DCI
, true);
11554 case ISD::INTRINSIC_VOID
:
11555 case ISD::INTRINSIC_W_CHAIN
:
11556 switch (cast
<ConstantSDNode
>(N
->getOperand(1))->getZExtValue()) {
11557 case Intrinsic::aarch64_neon_ld2
:
11558 case Intrinsic::aarch64_neon_ld3
:
11559 case Intrinsic::aarch64_neon_ld4
:
11560 case Intrinsic::aarch64_neon_ld1x2
:
11561 case Intrinsic::aarch64_neon_ld1x3
:
11562 case Intrinsic::aarch64_neon_ld1x4
:
11563 case Intrinsic::aarch64_neon_ld2lane
:
11564 case Intrinsic::aarch64_neon_ld3lane
:
11565 case Intrinsic::aarch64_neon_ld4lane
:
11566 case Intrinsic::aarch64_neon_ld2r
:
11567 case Intrinsic::aarch64_neon_ld3r
:
11568 case Intrinsic::aarch64_neon_ld4r
:
11569 case Intrinsic::aarch64_neon_st2
:
11570 case Intrinsic::aarch64_neon_st3
:
11571 case Intrinsic::aarch64_neon_st4
:
11572 case Intrinsic::aarch64_neon_st1x2
:
11573 case Intrinsic::aarch64_neon_st1x3
:
11574 case Intrinsic::aarch64_neon_st1x4
:
11575 case Intrinsic::aarch64_neon_st2lane
:
11576 case Intrinsic::aarch64_neon_st3lane
:
11577 case Intrinsic::aarch64_neon_st4lane
:
11578 return performNEONPostLDSTCombine(N
, DCI
, DAG
);
11583 case ISD::GlobalAddress
:
11584 return performGlobalAddressCombine(N
, DAG
, Subtarget
, getTargetMachine());
11589 // Check if the return value is used as only a return value, as otherwise
11590 // we can't perform a tail-call. In particular, we need to check for
11591 // target ISD nodes that are returns and any other "odd" constructs
11592 // that the generic analysis code won't necessarily catch.
11593 bool AArch64TargetLowering::isUsedByReturnOnly(SDNode
*N
,
11594 SDValue
&Chain
) const {
11595 if (N
->getNumValues() != 1)
11597 if (!N
->hasNUsesOfValue(1, 0))
11600 SDValue TCChain
= Chain
;
11601 SDNode
*Copy
= *N
->use_begin();
11602 if (Copy
->getOpcode() == ISD::CopyToReg
) {
11603 // If the copy has a glue operand, we conservatively assume it isn't safe to
11604 // perform a tail call.
11605 if (Copy
->getOperand(Copy
->getNumOperands() - 1).getValueType() ==
11608 TCChain
= Copy
->getOperand(0);
11609 } else if (Copy
->getOpcode() != ISD::FP_EXTEND
)
11612 bool HasRet
= false;
11613 for (SDNode
*Node
: Copy
->uses()) {
11614 if (Node
->getOpcode() != AArch64ISD::RET_FLAG
)
11626 // Return whether the an instruction can potentially be optimized to a tail
11627 // call. This will cause the optimizers to attempt to move, or duplicate,
11628 // return instructions to help enable tail call optimizations for this
11630 bool AArch64TargetLowering::mayBeEmittedAsTailCall(const CallInst
*CI
) const {
11631 return CI
->isTailCall();
11634 bool AArch64TargetLowering::getIndexedAddressParts(SDNode
*Op
, SDValue
&Base
,
11636 ISD::MemIndexedMode
&AM
,
11638 SelectionDAG
&DAG
) const {
11639 if (Op
->getOpcode() != ISD::ADD
&& Op
->getOpcode() != ISD::SUB
)
11642 Base
= Op
->getOperand(0);
11643 // All of the indexed addressing mode instructions take a signed
11644 // 9 bit immediate offset.
11645 if (ConstantSDNode
*RHS
= dyn_cast
<ConstantSDNode
>(Op
->getOperand(1))) {
11646 int64_t RHSC
= RHS
->getSExtValue();
11647 if (Op
->getOpcode() == ISD::SUB
)
11648 RHSC
= -(uint64_t)RHSC
;
11649 if (!isInt
<9>(RHSC
))
11651 IsInc
= (Op
->getOpcode() == ISD::ADD
);
11652 Offset
= Op
->getOperand(1);
11658 bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode
*N
, SDValue
&Base
,
11660 ISD::MemIndexedMode
&AM
,
11661 SelectionDAG
&DAG
) const {
11664 if (LoadSDNode
*LD
= dyn_cast
<LoadSDNode
>(N
)) {
11665 VT
= LD
->getMemoryVT();
11666 Ptr
= LD
->getBasePtr();
11667 } else if (StoreSDNode
*ST
= dyn_cast
<StoreSDNode
>(N
)) {
11668 VT
= ST
->getMemoryVT();
11669 Ptr
= ST
->getBasePtr();
11674 if (!getIndexedAddressParts(Ptr
.getNode(), Base
, Offset
, AM
, IsInc
, DAG
))
11676 AM
= IsInc
? ISD::PRE_INC
: ISD::PRE_DEC
;
11680 bool AArch64TargetLowering::getPostIndexedAddressParts(
11681 SDNode
*N
, SDNode
*Op
, SDValue
&Base
, SDValue
&Offset
,
11682 ISD::MemIndexedMode
&AM
, SelectionDAG
&DAG
) const {
11685 if (LoadSDNode
*LD
= dyn_cast
<LoadSDNode
>(N
)) {
11686 VT
= LD
->getMemoryVT();
11687 Ptr
= LD
->getBasePtr();
11688 } else if (StoreSDNode
*ST
= dyn_cast
<StoreSDNode
>(N
)) {
11689 VT
= ST
->getMemoryVT();
11690 Ptr
= ST
->getBasePtr();
11695 if (!getIndexedAddressParts(Op
, Base
, Offset
, AM
, IsInc
, DAG
))
11697 // Post-indexing updates the base, so it's not a valid transform
11698 // if that's not the same as the load's pointer.
11701 AM
= IsInc
? ISD::POST_INC
: ISD::POST_DEC
;
11705 static void ReplaceBITCASTResults(SDNode
*N
, SmallVectorImpl
<SDValue
> &Results
,
11706 SelectionDAG
&DAG
) {
11708 SDValue Op
= N
->getOperand(0);
11710 if (N
->getValueType(0) != MVT::i16
|| Op
.getValueType() != MVT::f16
)
11714 DAG
.getMachineNode(TargetOpcode::INSERT_SUBREG
, DL
, MVT::f32
,
11715 DAG
.getUNDEF(MVT::i32
), Op
,
11716 DAG
.getTargetConstant(AArch64::hsub
, DL
, MVT::i32
)),
11718 Op
= DAG
.getNode(ISD::BITCAST
, DL
, MVT::i32
, Op
);
11719 Results
.push_back(DAG
.getNode(ISD::TRUNCATE
, DL
, MVT::i16
, Op
));
11722 static void ReplaceReductionResults(SDNode
*N
,
11723 SmallVectorImpl
<SDValue
> &Results
,
11724 SelectionDAG
&DAG
, unsigned InterOp
,
11725 unsigned AcrossOp
) {
11729 std::tie(LoVT
, HiVT
) = DAG
.GetSplitDestVTs(N
->getValueType(0));
11730 std::tie(Lo
, Hi
) = DAG
.SplitVectorOperand(N
, 0);
11731 SDValue InterVal
= DAG
.getNode(InterOp
, dl
, LoVT
, Lo
, Hi
);
11732 SDValue SplitVal
= DAG
.getNode(AcrossOp
, dl
, LoVT
, InterVal
);
11733 Results
.push_back(SplitVal
);
11736 static std::pair
<SDValue
, SDValue
> splitInt128(SDValue N
, SelectionDAG
&DAG
) {
11738 SDValue Lo
= DAG
.getNode(ISD::TRUNCATE
, DL
, MVT::i64
, N
);
11739 SDValue Hi
= DAG
.getNode(ISD::TRUNCATE
, DL
, MVT::i64
,
11740 DAG
.getNode(ISD::SRL
, DL
, MVT::i128
, N
,
11741 DAG
.getConstant(64, DL
, MVT::i64
)));
11742 return std::make_pair(Lo
, Hi
);
11745 // Create an even/odd pair of X registers holding integer value V.
11746 static SDValue
createGPRPairNode(SelectionDAG
&DAG
, SDValue V
) {
11747 SDLoc
dl(V
.getNode());
11748 SDValue VLo
= DAG
.getAnyExtOrTrunc(V
, dl
, MVT::i64
);
11749 SDValue VHi
= DAG
.getAnyExtOrTrunc(
11750 DAG
.getNode(ISD::SRL
, dl
, MVT::i128
, V
, DAG
.getConstant(64, dl
, MVT::i64
)),
11752 if (DAG
.getDataLayout().isBigEndian())
11753 std::swap (VLo
, VHi
);
11755 DAG
.getTargetConstant(AArch64::XSeqPairsClassRegClassID
, dl
, MVT::i32
);
11756 SDValue SubReg0
= DAG
.getTargetConstant(AArch64::sube64
, dl
, MVT::i32
);
11757 SDValue SubReg1
= DAG
.getTargetConstant(AArch64::subo64
, dl
, MVT::i32
);
11758 const SDValue Ops
[] = { RegClass
, VLo
, SubReg0
, VHi
, SubReg1
};
11760 DAG
.getMachineNode(TargetOpcode::REG_SEQUENCE
, dl
, MVT::Untyped
, Ops
), 0);
11763 static void ReplaceCMP_SWAP_128Results(SDNode
*N
,
11764 SmallVectorImpl
<SDValue
> &Results
,
11766 const AArch64Subtarget
*Subtarget
) {
11767 assert(N
->getValueType(0) == MVT::i128
&&
11768 "AtomicCmpSwap on types less than 128 should be legal");
11770 if (Subtarget
->hasLSE()) {
11771 // LSE has a 128-bit compare and swap (CASP), but i128 is not a legal type,
11772 // so lower it here, wrapped in REG_SEQUENCE and EXTRACT_SUBREG.
11774 createGPRPairNode(DAG
, N
->getOperand(2)), // Compare value
11775 createGPRPairNode(DAG
, N
->getOperand(3)), // Store value
11776 N
->getOperand(1), // Ptr
11777 N
->getOperand(0), // Chain in
11780 MachineMemOperand
*MemOp
= cast
<MemSDNode
>(N
)->getMemOperand();
11783 switch (MemOp
->getOrdering()) {
11784 case AtomicOrdering::Monotonic
:
11785 Opcode
= AArch64::CASPX
;
11787 case AtomicOrdering::Acquire
:
11788 Opcode
= AArch64::CASPAX
;
11790 case AtomicOrdering::Release
:
11791 Opcode
= AArch64::CASPLX
;
11793 case AtomicOrdering::AcquireRelease
:
11794 case AtomicOrdering::SequentiallyConsistent
:
11795 Opcode
= AArch64::CASPALX
;
11798 llvm_unreachable("Unexpected ordering!");
11801 MachineSDNode
*CmpSwap
= DAG
.getMachineNode(
11802 Opcode
, SDLoc(N
), DAG
.getVTList(MVT::Untyped
, MVT::Other
), Ops
);
11803 DAG
.setNodeMemRefs(CmpSwap
, {MemOp
});
11805 unsigned SubReg1
= AArch64::sube64
, SubReg2
= AArch64::subo64
;
11806 if (DAG
.getDataLayout().isBigEndian())
11807 std::swap(SubReg1
, SubReg2
);
11808 Results
.push_back(DAG
.getTargetExtractSubreg(SubReg1
, SDLoc(N
), MVT::i64
,
11809 SDValue(CmpSwap
, 0)));
11810 Results
.push_back(DAG
.getTargetExtractSubreg(SubReg2
, SDLoc(N
), MVT::i64
,
11811 SDValue(CmpSwap
, 0)));
11812 Results
.push_back(SDValue(CmpSwap
, 1)); // Chain out
11816 auto Desired
= splitInt128(N
->getOperand(2), DAG
);
11817 auto New
= splitInt128(N
->getOperand(3), DAG
);
11818 SDValue Ops
[] = {N
->getOperand(1), Desired
.first
, Desired
.second
,
11819 New
.first
, New
.second
, N
->getOperand(0)};
11820 SDNode
*CmpSwap
= DAG
.getMachineNode(
11821 AArch64::CMP_SWAP_128
, SDLoc(N
),
11822 DAG
.getVTList(MVT::i64
, MVT::i64
, MVT::i32
, MVT::Other
), Ops
);
11824 MachineMemOperand
*MemOp
= cast
<MemSDNode
>(N
)->getMemOperand();
11825 DAG
.setNodeMemRefs(cast
<MachineSDNode
>(CmpSwap
), {MemOp
});
11827 Results
.push_back(SDValue(CmpSwap
, 0));
11828 Results
.push_back(SDValue(CmpSwap
, 1));
11829 Results
.push_back(SDValue(CmpSwap
, 3));
11832 void AArch64TargetLowering::ReplaceNodeResults(
11833 SDNode
*N
, SmallVectorImpl
<SDValue
> &Results
, SelectionDAG
&DAG
) const {
11834 switch (N
->getOpcode()) {
11836 llvm_unreachable("Don't know how to custom expand this");
11838 ReplaceBITCASTResults(N
, Results
, DAG
);
11840 case ISD::VECREDUCE_ADD
:
11841 case ISD::VECREDUCE_SMAX
:
11842 case ISD::VECREDUCE_SMIN
:
11843 case ISD::VECREDUCE_UMAX
:
11844 case ISD::VECREDUCE_UMIN
:
11845 Results
.push_back(LowerVECREDUCE(SDValue(N
, 0), DAG
));
11848 case AArch64ISD::SADDV
:
11849 ReplaceReductionResults(N
, Results
, DAG
, ISD::ADD
, AArch64ISD::SADDV
);
11851 case AArch64ISD::UADDV
:
11852 ReplaceReductionResults(N
, Results
, DAG
, ISD::ADD
, AArch64ISD::UADDV
);
11854 case AArch64ISD::SMINV
:
11855 ReplaceReductionResults(N
, Results
, DAG
, ISD::SMIN
, AArch64ISD::SMINV
);
11857 case AArch64ISD::UMINV
:
11858 ReplaceReductionResults(N
, Results
, DAG
, ISD::UMIN
, AArch64ISD::UMINV
);
11860 case AArch64ISD::SMAXV
:
11861 ReplaceReductionResults(N
, Results
, DAG
, ISD::SMAX
, AArch64ISD::SMAXV
);
11863 case AArch64ISD::UMAXV
:
11864 ReplaceReductionResults(N
, Results
, DAG
, ISD::UMAX
, AArch64ISD::UMAXV
);
11866 case ISD::FP_TO_UINT
:
11867 case ISD::FP_TO_SINT
:
11868 assert(N
->getValueType(0) == MVT::i128
&& "unexpected illegal conversion");
11869 // Let normal code take care of it by not adding anything to Results.
11871 case ISD::ATOMIC_CMP_SWAP
:
11872 ReplaceCMP_SWAP_128Results(N
, Results
, DAG
, Subtarget
);
11877 bool AArch64TargetLowering::useLoadStackGuardNode() const {
11878 if (Subtarget
->isTargetAndroid() || Subtarget
->isTargetFuchsia())
11879 return TargetLowering::useLoadStackGuardNode();
11883 unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
11884 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
11885 // reciprocal if there are three or more FDIVs.
11889 TargetLoweringBase::LegalizeTypeAction
11890 AArch64TargetLowering::getPreferredVectorAction(MVT VT
) const {
11891 // During type legalization, we prefer to widen v1i8, v1i16, v1i32 to v8i8,
11892 // v4i16, v2i32 instead of to promote.
11893 if (VT
== MVT::v1i8
|| VT
== MVT::v1i16
|| VT
== MVT::v1i32
||
11895 return TypeWidenVector
;
11897 return TargetLoweringBase::getPreferredVectorAction(VT
);
11900 // Loads and stores less than 128-bits are already atomic; ones above that
11901 // are doomed anyway, so defer to the default libcall and blame the OS when
11902 // things go wrong.
11903 bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst
*SI
) const {
11904 unsigned Size
= SI
->getValueOperand()->getType()->getPrimitiveSizeInBits();
11905 return Size
== 128;
11908 // Loads and stores less than 128-bits are already atomic; ones above that
11909 // are doomed anyway, so defer to the default libcall and blame the OS when
11910 // things go wrong.
11911 TargetLowering::AtomicExpansionKind
11912 AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst
*LI
) const {
11913 unsigned Size
= LI
->getType()->getPrimitiveSizeInBits();
11914 return Size
== 128 ? AtomicExpansionKind::LLSC
: AtomicExpansionKind::None
;
11917 // For the real atomic operations, we have ldxr/stxr up to 128 bits,
11918 TargetLowering::AtomicExpansionKind
11919 AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst
*AI
) const {
11920 if (AI
->isFloatingPointOperation())
11921 return AtomicExpansionKind::CmpXChg
;
11923 unsigned Size
= AI
->getType()->getPrimitiveSizeInBits();
11924 if (Size
> 128) return AtomicExpansionKind::None
;
11925 // Nand not supported in LSE.
11926 if (AI
->getOperation() == AtomicRMWInst::Nand
) return AtomicExpansionKind::LLSC
;
11927 // Leave 128 bits to LLSC.
11928 return (Subtarget
->hasLSE() && Size
< 128) ? AtomicExpansionKind::None
: AtomicExpansionKind::LLSC
;
11931 TargetLowering::AtomicExpansionKind
11932 AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
11933 AtomicCmpXchgInst
*AI
) const {
11934 // If subtarget has LSE, leave cmpxchg intact for codegen.
11935 if (Subtarget
->hasLSE())
11936 return AtomicExpansionKind::None
;
11937 // At -O0, fast-regalloc cannot cope with the live vregs necessary to
11938 // implement cmpxchg without spilling. If the address being exchanged is also
11939 // on the stack and close enough to the spill slot, this can lead to a
11940 // situation where the monitor always gets cleared and the atomic operation
11941 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
11942 if (getTargetMachine().getOptLevel() == 0)
11943 return AtomicExpansionKind::None
;
11944 return AtomicExpansionKind::LLSC
;
11947 Value
*AArch64TargetLowering::emitLoadLinked(IRBuilder
<> &Builder
, Value
*Addr
,
11948 AtomicOrdering Ord
) const {
11949 Module
*M
= Builder
.GetInsertBlock()->getParent()->getParent();
11950 Type
*ValTy
= cast
<PointerType
>(Addr
->getType())->getElementType();
11951 bool IsAcquire
= isAcquireOrStronger(Ord
);
11953 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
11954 // intrinsic must return {i64, i64} and we have to recombine them into a
11955 // single i128 here.
11956 if (ValTy
->getPrimitiveSizeInBits() == 128) {
11957 Intrinsic::ID Int
=
11958 IsAcquire
? Intrinsic::aarch64_ldaxp
: Intrinsic::aarch64_ldxp
;
11959 Function
*Ldxr
= Intrinsic::getDeclaration(M
, Int
);
11961 Addr
= Builder
.CreateBitCast(Addr
, Type::getInt8PtrTy(M
->getContext()));
11962 Value
*LoHi
= Builder
.CreateCall(Ldxr
, Addr
, "lohi");
11964 Value
*Lo
= Builder
.CreateExtractValue(LoHi
, 0, "lo");
11965 Value
*Hi
= Builder
.CreateExtractValue(LoHi
, 1, "hi");
11966 Lo
= Builder
.CreateZExt(Lo
, ValTy
, "lo64");
11967 Hi
= Builder
.CreateZExt(Hi
, ValTy
, "hi64");
11968 return Builder
.CreateOr(
11969 Lo
, Builder
.CreateShl(Hi
, ConstantInt::get(ValTy
, 64)), "val64");
11972 Type
*Tys
[] = { Addr
->getType() };
11973 Intrinsic::ID Int
=
11974 IsAcquire
? Intrinsic::aarch64_ldaxr
: Intrinsic::aarch64_ldxr
;
11975 Function
*Ldxr
= Intrinsic::getDeclaration(M
, Int
, Tys
);
11977 Type
*EltTy
= cast
<PointerType
>(Addr
->getType())->getElementType();
11979 const DataLayout
&DL
= M
->getDataLayout();
11980 IntegerType
*IntEltTy
= Builder
.getIntNTy(DL
.getTypeSizeInBits(EltTy
));
11981 Value
*Trunc
= Builder
.CreateTrunc(Builder
.CreateCall(Ldxr
, Addr
), IntEltTy
);
11983 return Builder
.CreateBitCast(Trunc
, EltTy
);
11986 void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
11987 IRBuilder
<> &Builder
) const {
11988 Module
*M
= Builder
.GetInsertBlock()->getParent()->getParent();
11989 Builder
.CreateCall(Intrinsic::getDeclaration(M
, Intrinsic::aarch64_clrex
));
11992 Value
*AArch64TargetLowering::emitStoreConditional(IRBuilder
<> &Builder
,
11993 Value
*Val
, Value
*Addr
,
11994 AtomicOrdering Ord
) const {
11995 Module
*M
= Builder
.GetInsertBlock()->getParent()->getParent();
11996 bool IsRelease
= isReleaseOrStronger(Ord
);
11998 // Since the intrinsics must have legal type, the i128 intrinsics take two
11999 // parameters: "i64, i64". We must marshal Val into the appropriate form
12000 // before the call.
12001 if (Val
->getType()->getPrimitiveSizeInBits() == 128) {
12002 Intrinsic::ID Int
=
12003 IsRelease
? Intrinsic::aarch64_stlxp
: Intrinsic::aarch64_stxp
;
12004 Function
*Stxr
= Intrinsic::getDeclaration(M
, Int
);
12005 Type
*Int64Ty
= Type::getInt64Ty(M
->getContext());
12007 Value
*Lo
= Builder
.CreateTrunc(Val
, Int64Ty
, "lo");
12008 Value
*Hi
= Builder
.CreateTrunc(Builder
.CreateLShr(Val
, 64), Int64Ty
, "hi");
12009 Addr
= Builder
.CreateBitCast(Addr
, Type::getInt8PtrTy(M
->getContext()));
12010 return Builder
.CreateCall(Stxr
, {Lo
, Hi
, Addr
});
12013 Intrinsic::ID Int
=
12014 IsRelease
? Intrinsic::aarch64_stlxr
: Intrinsic::aarch64_stxr
;
12015 Type
*Tys
[] = { Addr
->getType() };
12016 Function
*Stxr
= Intrinsic::getDeclaration(M
, Int
, Tys
);
12018 const DataLayout
&DL
= M
->getDataLayout();
12019 IntegerType
*IntValTy
= Builder
.getIntNTy(DL
.getTypeSizeInBits(Val
->getType()));
12020 Val
= Builder
.CreateBitCast(Val
, IntValTy
);
12022 return Builder
.CreateCall(Stxr
,
12023 {Builder
.CreateZExtOrBitCast(
12024 Val
, Stxr
->getFunctionType()->getParamType(0)),
12028 bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
12029 Type
*Ty
, CallingConv::ID CallConv
, bool isVarArg
) const {
12030 return Ty
->isArrayTy();
12033 bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext
&,
12038 static Value
*UseTlsOffset(IRBuilder
<> &IRB
, unsigned Offset
) {
12039 Module
*M
= IRB
.GetInsertBlock()->getParent()->getParent();
12040 Function
*ThreadPointerFunc
=
12041 Intrinsic::getDeclaration(M
, Intrinsic::thread_pointer
);
12042 return IRB
.CreatePointerCast(
12043 IRB
.CreateConstGEP1_32(IRB
.getInt8Ty(), IRB
.CreateCall(ThreadPointerFunc
),
12045 IRB
.getInt8PtrTy()->getPointerTo(0));
12048 Value
*AArch64TargetLowering::getIRStackGuard(IRBuilder
<> &IRB
) const {
12049 // Android provides a fixed TLS slot for the stack cookie. See the definition
12050 // of TLS_SLOT_STACK_GUARD in
12051 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
12052 if (Subtarget
->isTargetAndroid())
12053 return UseTlsOffset(IRB
, 0x28);
12055 // Fuchsia is similar.
12056 // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value.
12057 if (Subtarget
->isTargetFuchsia())
12058 return UseTlsOffset(IRB
, -0x10);
12060 return TargetLowering::getIRStackGuard(IRB
);
12063 void AArch64TargetLowering::insertSSPDeclarations(Module
&M
) const {
12064 // MSVC CRT provides functionalities for stack protection.
12065 if (Subtarget
->getTargetTriple().isWindowsMSVCEnvironment()) {
12066 // MSVC CRT has a global variable holding security cookie.
12067 M
.getOrInsertGlobal("__security_cookie",
12068 Type::getInt8PtrTy(M
.getContext()));
12070 // MSVC CRT has a function to validate security cookie.
12071 FunctionCallee SecurityCheckCookie
= M
.getOrInsertFunction(
12072 "__security_check_cookie", Type::getVoidTy(M
.getContext()),
12073 Type::getInt8PtrTy(M
.getContext()));
12074 if (Function
*F
= dyn_cast
<Function
>(SecurityCheckCookie
.getCallee())) {
12075 F
->setCallingConv(CallingConv::Win64
);
12076 F
->addAttribute(1, Attribute::AttrKind::InReg
);
12080 TargetLowering::insertSSPDeclarations(M
);
12083 Value
*AArch64TargetLowering::getSDagStackGuard(const Module
&M
) const {
12084 // MSVC CRT has a global variable holding security cookie.
12085 if (Subtarget
->getTargetTriple().isWindowsMSVCEnvironment())
12086 return M
.getGlobalVariable("__security_cookie");
12087 return TargetLowering::getSDagStackGuard(M
);
12090 Function
*AArch64TargetLowering::getSSPStackGuardCheck(const Module
&M
) const {
12091 // MSVC CRT has a function to validate security cookie.
12092 if (Subtarget
->getTargetTriple().isWindowsMSVCEnvironment())
12093 return M
.getFunction("__security_check_cookie");
12094 return TargetLowering::getSSPStackGuardCheck(M
);
12097 Value
*AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder
<> &IRB
) const {
12098 // Android provides a fixed TLS slot for the SafeStack pointer. See the
12099 // definition of TLS_SLOT_SAFESTACK in
12100 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
12101 if (Subtarget
->isTargetAndroid())
12102 return UseTlsOffset(IRB
, 0x48);
12104 // Fuchsia is similar.
12105 // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value.
12106 if (Subtarget
->isTargetFuchsia())
12107 return UseTlsOffset(IRB
, -0x8);
12109 return TargetLowering::getSafeStackPointerLocation(IRB
);
12112 bool AArch64TargetLowering::isMaskAndCmp0FoldingBeneficial(
12113 const Instruction
&AndI
) const {
12114 // Only sink 'and' mask to cmp use block if it is masking a single bit, since
12115 // this is likely to be fold the and/cmp/br into a single tbz instruction. It
12116 // may be beneficial to sink in other cases, but we would have to check that
12117 // the cmp would not get folded into the br to form a cbz for these to be
12119 ConstantInt
* Mask
= dyn_cast
<ConstantInt
>(AndI
.getOperand(1));
12122 return Mask
->getValue().isPowerOf2();
12125 bool AArch64TargetLowering::
12126 shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
12127 SDValue X
, ConstantSDNode
*XC
, ConstantSDNode
*CC
, SDValue Y
,
12128 unsigned OldShiftOpcode
, unsigned NewShiftOpcode
,
12129 SelectionDAG
&DAG
) const {
12130 // Does baseline recommend not to perform the fold by default?
12131 if (!TargetLowering::shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
12132 X
, XC
, CC
, Y
, OldShiftOpcode
, NewShiftOpcode
, DAG
))
12134 // Else, if this is a vector shift, prefer 'shl'.
12135 return X
.getValueType().isScalarInteger() || NewShiftOpcode
== ISD::SHL
;
12138 bool AArch64TargetLowering::shouldExpandShift(SelectionDAG
&DAG
,
12140 if (DAG
.getMachineFunction().getFunction().hasMinSize() &&
12141 !Subtarget
->isTargetWindows())
12146 void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock
*Entry
) const {
12147 // Update IsSplitCSR in AArch64unctionInfo.
12148 AArch64FunctionInfo
*AFI
= Entry
->getParent()->getInfo
<AArch64FunctionInfo
>();
12149 AFI
->setIsSplitCSR(true);
12152 void AArch64TargetLowering::insertCopiesSplitCSR(
12153 MachineBasicBlock
*Entry
,
12154 const SmallVectorImpl
<MachineBasicBlock
*> &Exits
) const {
12155 const AArch64RegisterInfo
*TRI
= Subtarget
->getRegisterInfo();
12156 const MCPhysReg
*IStart
= TRI
->getCalleeSavedRegsViaCopy(Entry
->getParent());
12160 const TargetInstrInfo
*TII
= Subtarget
->getInstrInfo();
12161 MachineRegisterInfo
*MRI
= &Entry
->getParent()->getRegInfo();
12162 MachineBasicBlock::iterator MBBI
= Entry
->begin();
12163 for (const MCPhysReg
*I
= IStart
; *I
; ++I
) {
12164 const TargetRegisterClass
*RC
= nullptr;
12165 if (AArch64::GPR64RegClass
.contains(*I
))
12166 RC
= &AArch64::GPR64RegClass
;
12167 else if (AArch64::FPR64RegClass
.contains(*I
))
12168 RC
= &AArch64::FPR64RegClass
;
12170 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
12172 Register NewVR
= MRI
->createVirtualRegister(RC
);
12173 // Create copy from CSR to a virtual register.
12174 // FIXME: this currently does not emit CFI pseudo-instructions, it works
12175 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
12176 // nounwind. If we want to generalize this later, we may need to emit
12177 // CFI pseudo-instructions.
12178 assert(Entry
->getParent()->getFunction().hasFnAttribute(
12179 Attribute::NoUnwind
) &&
12180 "Function should be nounwind in insertCopiesSplitCSR!");
12181 Entry
->addLiveIn(*I
);
12182 BuildMI(*Entry
, MBBI
, DebugLoc(), TII
->get(TargetOpcode::COPY
), NewVR
)
12185 // Insert the copy-back instructions right before the terminator.
12186 for (auto *Exit
: Exits
)
12187 BuildMI(*Exit
, Exit
->getFirstTerminator(), DebugLoc(),
12188 TII
->get(TargetOpcode::COPY
), *I
)
12193 bool AArch64TargetLowering::isIntDivCheap(EVT VT
, AttributeList Attr
) const {
12194 // Integer division on AArch64 is expensive. However, when aggressively
12195 // optimizing for code size, we prefer to use a div instruction, as it is
12196 // usually smaller than the alternative sequence.
12197 // The exception to this is vector division. Since AArch64 doesn't have vector
12198 // integer division, leaving the division as-is is a loss even in terms of
12199 // size, because it will have to be scalarized, while the alternative code
12200 // sequence can be performed in vector form.
12202 Attr
.hasAttribute(AttributeList::FunctionIndex
, Attribute::MinSize
);
12203 return OptSize
&& !VT
.isVector();
12206 bool AArch64TargetLowering::preferIncOfAddToSubOfNot(EVT VT
) const {
12207 // We want inc-of-add for scalars and sub-of-not for vectors.
12208 return VT
.isScalarInteger();
12211 bool AArch64TargetLowering::enableAggressiveFMAFusion(EVT VT
) const {
12212 return Subtarget
->hasAggressiveFMA() && VT
.isFloatingPoint();
12216 AArch64TargetLowering::getVaListSizeInBits(const DataLayout
&DL
) const {
12217 if (Subtarget
->isTargetDarwin() || Subtarget
->isTargetWindows())
12218 return getPointerTy(DL
).getSizeInBits();
12220 return 3 * getPointerTy(DL
).getSizeInBits() + 2 * 32;
12223 void AArch64TargetLowering::finalizeLowering(MachineFunction
&MF
) const {
12224 MF
.getFrameInfo().computeMaxCallFrameSize(MF
);
12225 TargetLoweringBase::finalizeLowering(MF
);
12228 // Unlike X86, we let frame lowering assign offsets to all catch objects.
12229 bool AArch64TargetLowering::needsFixedCatchObjects() const {