1 //===-- ARM64ISelLowering.cpp - ARM64 DAG Lowering Implementation --------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the ARM64TargetLowering class.
12 //===----------------------------------------------------------------------===//
14 #include "ARM64ISelLowering.h"
15 #include "ARM64PerfectShuffle.h"
16 #include "ARM64Subtarget.h"
17 #include "ARM64CallingConv.h"
18 #include "ARM64MachineFunctionInfo.h"
19 #include "ARM64TargetMachine.h"
20 #include "ARM64TargetObjectFile.h"
21 #include "MCTargetDesc/ARM64AddressingModes.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/CodeGen/CallingConvLower.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineInstrBuilder.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/Intrinsics.h"
29 #include "llvm/IR/Type.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Target/TargetOptions.h"
37 #define DEBUG_TYPE "arm64-lower"
39 STATISTIC(NumTailCalls, "Number of tail calls");
40 STATISTIC(NumShiftInserts, "Number of vector shift inserts");
42 // This option should go away when tail calls fully work.
44 EnableARM64TailCalls("arm64-tail-calls", cl::Hidden,
45 cl::desc("Generate ARM64 tail calls (TEMPORARY OPTION)."),
53 static cl::opt<AlignMode>
54 Align(cl::desc("Load/store alignment support"),
55 cl::Hidden, cl::init(NoStrictAlign),
57 clEnumValN(StrictAlign, "arm64-strict-align",
58 "Disallow all unaligned memory accesses"),
59 clEnumValN(NoStrictAlign, "arm64-no-strict-align",
60 "Allow unaligned memory accesses"),
63 // Place holder until extr generation is tested fully.
65 EnableARM64ExtrGeneration("arm64-extr-generation", cl::Hidden,
66 cl::desc("Allow ARM64 (or (shift)(shift))->extract"),
70 EnableARM64SlrGeneration("arm64-shift-insert-generation", cl::Hidden,
71 cl::desc("Allow ARM64 SLI/SRI formation"),
74 //===----------------------------------------------------------------------===//
75 // ARM64 Lowering public interface.
76 //===----------------------------------------------------------------------===//
77 static TargetLoweringObjectFile *createTLOF(TargetMachine &TM) {
78 if (TM.getSubtarget<ARM64Subtarget>().isTargetDarwin())
79 return new ARM64_MachoTargetObjectFile();
81 return new ARM64_ELFTargetObjectFile();
84 ARM64TargetLowering::ARM64TargetLowering(ARM64TargetMachine &TM)
85 : TargetLowering(TM, createTLOF(TM)) {
86 Subtarget = &TM.getSubtarget<ARM64Subtarget>();
88 // ARM64 doesn't have comparisons which set GPRs or setcc instructions, so
89 // we have to make something up. Arbitrarily, choose ZeroOrOne.
90 setBooleanContents(ZeroOrOneBooleanContent);
91 // When comparing vectors the result sets the different elements in the
92 // vector to all-one or all-zero.
93 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
95 // Set up the register classes.
96 addRegisterClass(MVT::i32, &ARM64::GPR32allRegClass);
97 addRegisterClass(MVT::i64, &ARM64::GPR64allRegClass);
99 if (Subtarget->hasFPARMv8()) {
100 addRegisterClass(MVT::f16, &ARM64::FPR16RegClass);
101 addRegisterClass(MVT::f32, &ARM64::FPR32RegClass);
102 addRegisterClass(MVT::f64, &ARM64::FPR64RegClass);
103 addRegisterClass(MVT::f128, &ARM64::FPR128RegClass);
106 if (Subtarget->hasNEON()) {
107 addRegisterClass(MVT::v16i8, &ARM64::FPR8RegClass);
108 addRegisterClass(MVT::v8i16, &ARM64::FPR16RegClass);
109 // Someone set us up the NEON.
110 addDRTypeForNEON(MVT::v2f32);
111 addDRTypeForNEON(MVT::v8i8);
112 addDRTypeForNEON(MVT::v4i16);
113 addDRTypeForNEON(MVT::v2i32);
114 addDRTypeForNEON(MVT::v1i64);
115 addDRTypeForNEON(MVT::v1f64);
117 addQRTypeForNEON(MVT::v4f32);
118 addQRTypeForNEON(MVT::v2f64);
119 addQRTypeForNEON(MVT::v16i8);
120 addQRTypeForNEON(MVT::v8i16);
121 addQRTypeForNEON(MVT::v4i32);
122 addQRTypeForNEON(MVT::v2i64);
125 // Compute derived properties from the register classes
126 computeRegisterProperties();
128 // Provide all sorts of operation actions
129 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
130 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
131 setOperationAction(ISD::SETCC, MVT::i32, Custom);
132 setOperationAction(ISD::SETCC, MVT::i64, Custom);
133 setOperationAction(ISD::SETCC, MVT::f32, Custom);
134 setOperationAction(ISD::SETCC, MVT::f64, Custom);
135 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
136 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
137 setOperationAction(ISD::BR_CC, MVT::i64, Custom);
138 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
139 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
140 setOperationAction(ISD::SELECT, MVT::i32, Custom);
141 setOperationAction(ISD::SELECT, MVT::i64, Custom);
142 setOperationAction(ISD::SELECT, MVT::f32, Custom);
143 setOperationAction(ISD::SELECT, MVT::f64, Custom);
144 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
145 setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
146 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
147 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
148 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
149 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
151 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
152 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
153 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
155 setOperationAction(ISD::FREM, MVT::f32, Expand);
156 setOperationAction(ISD::FREM, MVT::f64, Expand);
157 setOperationAction(ISD::FREM, MVT::f80, Expand);
159 // Custom lowering hooks are needed for XOR
160 // to fold it into CSINC/CSINV.
161 setOperationAction(ISD::XOR, MVT::i32, Custom);
162 setOperationAction(ISD::XOR, MVT::i64, Custom);
164 // Virtually no operation on f128 is legal, but LLVM can't expand them when
165 // there's a valid register class, so we need custom operations in most cases.
166 setOperationAction(ISD::FABS, MVT::f128, Expand);
167 setOperationAction(ISD::FADD, MVT::f128, Custom);
168 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
169 setOperationAction(ISD::FCOS, MVT::f128, Expand);
170 setOperationAction(ISD::FDIV, MVT::f128, Custom);
171 setOperationAction(ISD::FMA, MVT::f128, Expand);
172 setOperationAction(ISD::FMUL, MVT::f128, Custom);
173 setOperationAction(ISD::FNEG, MVT::f128, Expand);
174 setOperationAction(ISD::FPOW, MVT::f128, Expand);
175 setOperationAction(ISD::FREM, MVT::f128, Expand);
176 setOperationAction(ISD::FRINT, MVT::f128, Expand);
177 setOperationAction(ISD::FSIN, MVT::f128, Expand);
178 setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
179 setOperationAction(ISD::FSQRT, MVT::f128, Expand);
180 setOperationAction(ISD::FSUB, MVT::f128, Custom);
181 setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
182 setOperationAction(ISD::SETCC, MVT::f128, Custom);
183 setOperationAction(ISD::BR_CC, MVT::f128, Custom);
184 setOperationAction(ISD::SELECT, MVT::f128, Custom);
185 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
186 setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
188 // Lowering for many of the conversions is actually specified by the non-f128
189 // type. The LowerXXX function will be trivial when f128 isn't involved.
190 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
191 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
192 setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
193 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
194 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
195 setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
196 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
197 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
198 setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
199 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
200 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
201 setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
202 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
203 setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
205 // Variable arguments.
206 setOperationAction(ISD::VASTART, MVT::Other, Custom);
207 setOperationAction(ISD::VAARG, MVT::Other, Custom);
208 setOperationAction(ISD::VACOPY, MVT::Other, Custom);
209 setOperationAction(ISD::VAEND, MVT::Other, Expand);
211 // Variable-sized objects.
212 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
213 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
214 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
216 // Exception handling.
217 // FIXME: These are guesses. Has this been defined yet?
218 setExceptionPointerRegister(ARM64::X0);
219 setExceptionSelectorRegister(ARM64::X1);
221 // Constant pool entries
222 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
225 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
227 // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
228 setOperationAction(ISD::ADDC, MVT::i32, Custom);
229 setOperationAction(ISD::ADDE, MVT::i32, Custom);
230 setOperationAction(ISD::SUBC, MVT::i32, Custom);
231 setOperationAction(ISD::SUBE, MVT::i32, Custom);
232 setOperationAction(ISD::ADDC, MVT::i64, Custom);
233 setOperationAction(ISD::ADDE, MVT::i64, Custom);
234 setOperationAction(ISD::SUBC, MVT::i64, Custom);
235 setOperationAction(ISD::SUBE, MVT::i64, Custom);
237 // ARM64 lacks both left-rotate and popcount instructions.
238 setOperationAction(ISD::ROTL, MVT::i32, Expand);
239 setOperationAction(ISD::ROTL, MVT::i64, Expand);
241 // ARM64 doesn't have {U|S}MUL_LOHI.
242 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
243 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
246 // Expand the undefined-at-zero variants to cttz/ctlz to their defined-at-zero
247 // counterparts, which ARM64 supports directly.
248 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
249 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
250 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
251 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
253 setOperationAction(ISD::CTPOP, MVT::i32, Custom);
254 setOperationAction(ISD::CTPOP, MVT::i64, Custom);
256 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
257 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
258 setOperationAction(ISD::SREM, MVT::i32, Expand);
259 setOperationAction(ISD::SREM, MVT::i64, Expand);
260 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
261 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
262 setOperationAction(ISD::UREM, MVT::i32, Expand);
263 setOperationAction(ISD::UREM, MVT::i64, Expand);
265 // Custom lower Add/Sub/Mul with overflow.
266 setOperationAction(ISD::SADDO, MVT::i32, Custom);
267 setOperationAction(ISD::SADDO, MVT::i64, Custom);
268 setOperationAction(ISD::UADDO, MVT::i32, Custom);
269 setOperationAction(ISD::UADDO, MVT::i64, Custom);
270 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
271 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
272 setOperationAction(ISD::USUBO, MVT::i32, Custom);
273 setOperationAction(ISD::USUBO, MVT::i64, Custom);
274 setOperationAction(ISD::SMULO, MVT::i32, Custom);
275 setOperationAction(ISD::SMULO, MVT::i64, Custom);
276 setOperationAction(ISD::UMULO, MVT::i32, Custom);
277 setOperationAction(ISD::UMULO, MVT::i64, Custom);
279 setOperationAction(ISD::FSIN, MVT::f32, Expand);
280 setOperationAction(ISD::FSIN, MVT::f64, Expand);
281 setOperationAction(ISD::FCOS, MVT::f32, Expand);
282 setOperationAction(ISD::FCOS, MVT::f64, Expand);
283 setOperationAction(ISD::FPOW, MVT::f32, Expand);
284 setOperationAction(ISD::FPOW, MVT::f64, Expand);
285 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
286 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
288 // ARM64 has implementations of a lot of rounding-like FP operations.
289 static MVT RoundingTypes[] = { MVT::f32, MVT::f64};
290 for (unsigned I = 0; I < array_lengthof(RoundingTypes); ++I) {
291 MVT Ty = RoundingTypes[I];
292 setOperationAction(ISD::FFLOOR, Ty, Legal);
293 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
294 setOperationAction(ISD::FCEIL, Ty, Legal);
295 setOperationAction(ISD::FRINT, Ty, Legal);
296 setOperationAction(ISD::FTRUNC, Ty, Legal);
297 setOperationAction(ISD::FROUND, Ty, Legal);
300 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
302 if (Subtarget->isTargetMachO()) {
303 // For iOS, we don't want to the normal expansion of a libcall to
304 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
306 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
307 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
309 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
310 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
313 // ARM64 does not have floating-point extending loads, i1 sign-extending load,
314 // floating-point truncating stores, or v2i32->v2i16 truncating store.
315 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
316 setLoadExtAction(ISD::EXTLOAD, MVT::f64, Expand);
317 setLoadExtAction(ISD::EXTLOAD, MVT::f80, Expand);
318 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Expand);
319 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
320 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
321 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
322 setTruncStoreAction(MVT::f128, MVT::f80, Expand);
323 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
324 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
325 setTruncStoreAction(MVT::f128, MVT::f16, Expand);
326 // Indexed loads and stores are supported.
327 for (unsigned im = (unsigned)ISD::PRE_INC;
328 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
329 setIndexedLoadAction(im, MVT::i8, Legal);
330 setIndexedLoadAction(im, MVT::i16, Legal);
331 setIndexedLoadAction(im, MVT::i32, Legal);
332 setIndexedLoadAction(im, MVT::i64, Legal);
333 setIndexedLoadAction(im, MVT::f64, Legal);
334 setIndexedLoadAction(im, MVT::f32, Legal);
335 setIndexedStoreAction(im, MVT::i8, Legal);
336 setIndexedStoreAction(im, MVT::i16, Legal);
337 setIndexedStoreAction(im, MVT::i32, Legal);
338 setIndexedStoreAction(im, MVT::i64, Legal);
339 setIndexedStoreAction(im, MVT::f64, Legal);
340 setIndexedStoreAction(im, MVT::f32, Legal);
344 setOperationAction(ISD::TRAP, MVT::Other, Legal);
346 // We combine OR nodes for bitfield operations.
347 setTargetDAGCombine(ISD::OR);
349 // Vector add and sub nodes may conceal a high-half opportunity.
350 // Also, try to fold ADD into CSINC/CSINV..
351 setTargetDAGCombine(ISD::ADD);
352 setTargetDAGCombine(ISD::SUB);
354 setTargetDAGCombine(ISD::XOR);
355 setTargetDAGCombine(ISD::SINT_TO_FP);
356 setTargetDAGCombine(ISD::UINT_TO_FP);
358 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
360 setTargetDAGCombine(ISD::ANY_EXTEND);
361 setTargetDAGCombine(ISD::ZERO_EXTEND);
362 setTargetDAGCombine(ISD::SIGN_EXTEND);
363 setTargetDAGCombine(ISD::BITCAST);
364 setTargetDAGCombine(ISD::CONCAT_VECTORS);
365 setTargetDAGCombine(ISD::STORE);
367 setTargetDAGCombine(ISD::MUL);
369 setTargetDAGCombine(ISD::VSELECT);
371 MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 8;
372 MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 4;
373 MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = 4;
375 setStackPointerRegisterToSaveRestore(ARM64::SP);
377 setSchedulingPreference(Sched::Hybrid);
380 MaskAndBranchFoldingIsLegal = true;
382 setMinFunctionAlignment(2);
384 RequireStrictAlign = (Align == StrictAlign);
386 setHasExtractBitsInsn(true);
388 if (Subtarget->hasNEON()) {
389 // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
390 // silliness like this:
391 setOperationAction(ISD::FABS, MVT::v1f64, Expand);
392 setOperationAction(ISD::FADD, MVT::v1f64, Expand);
393 setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
394 setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
395 setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
396 setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
397 setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
398 setOperationAction(ISD::FMA, MVT::v1f64, Expand);
399 setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
400 setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
401 setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
402 setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
403 setOperationAction(ISD::FREM, MVT::v1f64, Expand);
404 setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
405 setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
406 setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
407 setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
408 setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
409 setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
410 setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
411 setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
412 setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
413 setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
414 setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
415 setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
417 setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
418 setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
419 setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
420 setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
421 setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
423 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
425 // ARM64 doesn't have a direct vector ->f32 conversion instructions for
426 // elements smaller than i32, so promote the input to i32 first.
427 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Promote);
428 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Promote);
429 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Promote);
430 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Promote);
431 // Similarly, there is no direct i32 -> f64 vector conversion instruction.
432 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
433 setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
434 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
435 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
437 // ARM64 doesn't have MUL.2d:
438 setOperationAction(ISD::MUL, MVT::v2i64, Expand);
439 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
440 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
441 // Likewise, narrowing and extending vector loads/stores aren't handled
443 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
444 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
446 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
449 setOperationAction(ISD::MULHS, (MVT::SimpleValueType)VT, Expand);
450 setOperationAction(ISD::SMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
451 setOperationAction(ISD::MULHU, (MVT::SimpleValueType)VT, Expand);
452 setOperationAction(ISD::UMUL_LOHI, (MVT::SimpleValueType)VT, Expand);
454 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
455 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
456 setTruncStoreAction((MVT::SimpleValueType)VT,
457 (MVT::SimpleValueType)InnerVT, Expand);
458 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
459 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
460 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
463 // ARM64 has implementations of a lot of rounding-like FP operations.
464 static MVT RoundingVecTypes[] = {MVT::v2f32, MVT::v4f32, MVT::v2f64 };
465 for (unsigned I = 0; I < array_lengthof(RoundingVecTypes); ++I) {
466 MVT Ty = RoundingVecTypes[I];
467 setOperationAction(ISD::FFLOOR, Ty, Legal);
468 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
469 setOperationAction(ISD::FCEIL, Ty, Legal);
470 setOperationAction(ISD::FRINT, Ty, Legal);
471 setOperationAction(ISD::FTRUNC, Ty, Legal);
472 setOperationAction(ISD::FROUND, Ty, Legal);
477 void ARM64TargetLowering::addTypeForNEON(EVT VT, EVT PromotedBitwiseVT) {
478 if (VT == MVT::v2f32) {
479 setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
480 AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i32);
482 setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
483 AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i32);
484 } else if (VT == MVT::v2f64 || VT == MVT::v4f32) {
485 setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
486 AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i64);
488 setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
489 AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i64);
492 // Mark vector float intrinsics as expand.
493 if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
494 setOperationAction(ISD::FSIN, VT.getSimpleVT(), Expand);
495 setOperationAction(ISD::FCOS, VT.getSimpleVT(), Expand);
496 setOperationAction(ISD::FPOWI, VT.getSimpleVT(), Expand);
497 setOperationAction(ISD::FPOW, VT.getSimpleVT(), Expand);
498 setOperationAction(ISD::FLOG, VT.getSimpleVT(), Expand);
499 setOperationAction(ISD::FLOG2, VT.getSimpleVT(), Expand);
500 setOperationAction(ISD::FLOG10, VT.getSimpleVT(), Expand);
501 setOperationAction(ISD::FEXP, VT.getSimpleVT(), Expand);
502 setOperationAction(ISD::FEXP2, VT.getSimpleVT(), Expand);
505 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT.getSimpleVT(), Custom);
506 setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getSimpleVT(), Custom);
507 setOperationAction(ISD::BUILD_VECTOR, VT.getSimpleVT(), Custom);
508 setOperationAction(ISD::VECTOR_SHUFFLE, VT.getSimpleVT(), Custom);
509 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT.getSimpleVT(), Custom);
510 setOperationAction(ISD::SRA, VT.getSimpleVT(), Custom);
511 setOperationAction(ISD::SRL, VT.getSimpleVT(), Custom);
512 setOperationAction(ISD::SHL, VT.getSimpleVT(), Custom);
513 setOperationAction(ISD::AND, VT.getSimpleVT(), Custom);
514 setOperationAction(ISD::OR, VT.getSimpleVT(), Custom);
515 setOperationAction(ISD::SETCC, VT.getSimpleVT(), Custom);
516 setOperationAction(ISD::CONCAT_VECTORS, VT.getSimpleVT(), Legal);
518 setOperationAction(ISD::SELECT, VT.getSimpleVT(), Expand);
519 setOperationAction(ISD::SELECT_CC, VT.getSimpleVT(), Expand);
520 setOperationAction(ISD::VSELECT, VT.getSimpleVT(), Expand);
521 setLoadExtAction(ISD::EXTLOAD, VT.getSimpleVT(), Expand);
523 // CNT supports only B element sizes.
524 if (VT != MVT::v8i8 && VT != MVT::v16i8)
525 setOperationAction(ISD::CTPOP, VT.getSimpleVT(), Expand);
527 setOperationAction(ISD::UDIV, VT.getSimpleVT(), Expand);
528 setOperationAction(ISD::SDIV, VT.getSimpleVT(), Expand);
529 setOperationAction(ISD::UREM, VT.getSimpleVT(), Expand);
530 setOperationAction(ISD::SREM, VT.getSimpleVT(), Expand);
531 setOperationAction(ISD::FREM, VT.getSimpleVT(), Expand);
533 setOperationAction(ISD::FP_TO_SINT, VT.getSimpleVT(), Custom);
534 setOperationAction(ISD::FP_TO_UINT, VT.getSimpleVT(), Custom);
536 if (Subtarget->isLittleEndian()) {
537 for (unsigned im = (unsigned)ISD::PRE_INC;
538 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
539 setIndexedLoadAction(im, VT.getSimpleVT(), Legal);
540 setIndexedStoreAction(im, VT.getSimpleVT(), Legal);
545 void ARM64TargetLowering::addDRTypeForNEON(MVT VT) {
546 addRegisterClass(VT, &ARM64::FPR64RegClass);
547 addTypeForNEON(VT, MVT::v2i32);
550 void ARM64TargetLowering::addQRTypeForNEON(MVT VT) {
551 addRegisterClass(VT, &ARM64::FPR128RegClass);
552 addTypeForNEON(VT, MVT::v4i32);
555 EVT ARM64TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
558 return VT.changeVectorElementTypeToInteger();
561 /// computeMaskedBitsForTargetNode - Determine which of the bits specified in
562 /// Mask are known to be either zero or one and return them in the
563 /// KnownZero/KnownOne bitsets.
564 void ARM64TargetLowering::computeMaskedBitsForTargetNode(
565 const SDValue Op, APInt &KnownZero, APInt &KnownOne,
566 const SelectionDAG &DAG, unsigned Depth) const {
567 switch (Op.getOpcode()) {
570 case ARM64ISD::CSEL: {
571 APInt KnownZero2, KnownOne2;
572 DAG.ComputeMaskedBits(Op->getOperand(0), KnownZero, KnownOne, Depth + 1);
573 DAG.ComputeMaskedBits(Op->getOperand(1), KnownZero2, KnownOne2, Depth + 1);
574 KnownZero &= KnownZero2;
575 KnownOne &= KnownOne2;
578 case ISD::INTRINSIC_W_CHAIN: {
579 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
580 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
583 case Intrinsic::arm64_ldaxr:
584 case Intrinsic::arm64_ldxr: {
585 unsigned BitWidth = KnownOne.getBitWidth();
586 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
587 unsigned MemBits = VT.getScalarType().getSizeInBits();
588 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
594 case ISD::INTRINSIC_WO_CHAIN:
595 case ISD::INTRINSIC_VOID: {
596 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
600 case Intrinsic::arm64_neon_umaxv:
601 case Intrinsic::arm64_neon_uminv: {
602 // Figure out the datatype of the vector operand. The UMINV instruction
603 // will zero extend the result, so we can mark as known zero all the
604 // bits larger than the element datatype. 32-bit or larget doesn't need
605 // this as those are legal types and will be handled by isel directly.
606 MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
607 unsigned BitWidth = KnownZero.getBitWidth();
608 if (VT == MVT::v8i8 || VT == MVT::v16i8) {
609 assert(BitWidth >= 8 && "Unexpected width!");
610 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
612 } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
613 assert(BitWidth >= 16 && "Unexpected width!");
614 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
624 MVT ARM64TargetLowering::getScalarShiftAmountTy(EVT LHSTy) const {
628 unsigned ARM64TargetLowering::getMaximalGlobalOffset() const {
629 // FIXME: On ARM64, this depends on the type.
630 // Basically, the addressable offsets are o to 4095 * Ty.getSizeInBytes().
631 // and the offset has to be a multiple of the related size in bytes.
636 ARM64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
637 const TargetLibraryInfo *libInfo) const {
638 return ARM64::createFastISel(funcInfo, libInfo);
641 const char *ARM64TargetLowering::getTargetNodeName(unsigned Opcode) const {
645 case ARM64ISD::CALL: return "ARM64ISD::CALL";
646 case ARM64ISD::ADRP: return "ARM64ISD::ADRP";
647 case ARM64ISD::ADDlow: return "ARM64ISD::ADDlow";
648 case ARM64ISD::LOADgot: return "ARM64ISD::LOADgot";
649 case ARM64ISD::RET_FLAG: return "ARM64ISD::RET_FLAG";
650 case ARM64ISD::BRCOND: return "ARM64ISD::BRCOND";
651 case ARM64ISD::CSEL: return "ARM64ISD::CSEL";
652 case ARM64ISD::FCSEL: return "ARM64ISD::FCSEL";
653 case ARM64ISD::CSINV: return "ARM64ISD::CSINV";
654 case ARM64ISD::CSNEG: return "ARM64ISD::CSNEG";
655 case ARM64ISD::CSINC: return "ARM64ISD::CSINC";
656 case ARM64ISD::THREAD_POINTER: return "ARM64ISD::THREAD_POINTER";
657 case ARM64ISD::TLSDESC_CALL: return "ARM64ISD::TLSDESC_CALL";
658 case ARM64ISD::ADC: return "ARM64ISD::ADC";
659 case ARM64ISD::SBC: return "ARM64ISD::SBC";
660 case ARM64ISD::ADDS: return "ARM64ISD::ADDS";
661 case ARM64ISD::SUBS: return "ARM64ISD::SUBS";
662 case ARM64ISD::ADCS: return "ARM64ISD::ADCS";
663 case ARM64ISD::SBCS: return "ARM64ISD::SBCS";
664 case ARM64ISD::ANDS: return "ARM64ISD::ANDS";
665 case ARM64ISD::FCMP: return "ARM64ISD::FCMP";
666 case ARM64ISD::FMIN: return "ARM64ISD::FMIN";
667 case ARM64ISD::FMAX: return "ARM64ISD::FMAX";
668 case ARM64ISD::DUP: return "ARM64ISD::DUP";
669 case ARM64ISD::DUPLANE8: return "ARM64ISD::DUPLANE8";
670 case ARM64ISD::DUPLANE16: return "ARM64ISD::DUPLANE16";
671 case ARM64ISD::DUPLANE32: return "ARM64ISD::DUPLANE32";
672 case ARM64ISD::DUPLANE64: return "ARM64ISD::DUPLANE64";
673 case ARM64ISD::MOVI: return "ARM64ISD::MOVI";
674 case ARM64ISD::MOVIshift: return "ARM64ISD::MOVIshift";
675 case ARM64ISD::MOVIedit: return "ARM64ISD::MOVIedit";
676 case ARM64ISD::MOVImsl: return "ARM64ISD::MOVImsl";
677 case ARM64ISD::FMOV: return "ARM64ISD::FMOV";
678 case ARM64ISD::MVNIshift: return "ARM64ISD::MVNIshift";
679 case ARM64ISD::MVNImsl: return "ARM64ISD::MVNImsl";
680 case ARM64ISD::BICi: return "ARM64ISD::BICi";
681 case ARM64ISD::ORRi: return "ARM64ISD::ORRi";
682 case ARM64ISD::BSL: return "ARM64ISD::BSL";
683 case ARM64ISD::NEG: return "ARM64ISD::NEG";
684 case ARM64ISD::EXTR: return "ARM64ISD::EXTR";
685 case ARM64ISD::ZIP1: return "ARM64ISD::ZIP1";
686 case ARM64ISD::ZIP2: return "ARM64ISD::ZIP2";
687 case ARM64ISD::UZP1: return "ARM64ISD::UZP1";
688 case ARM64ISD::UZP2: return "ARM64ISD::UZP2";
689 case ARM64ISD::TRN1: return "ARM64ISD::TRN1";
690 case ARM64ISD::TRN2: return "ARM64ISD::TRN2";
691 case ARM64ISD::REV16: return "ARM64ISD::REV16";
692 case ARM64ISD::REV32: return "ARM64ISD::REV32";
693 case ARM64ISD::REV64: return "ARM64ISD::REV64";
694 case ARM64ISD::EXT: return "ARM64ISD::EXT";
695 case ARM64ISD::VSHL: return "ARM64ISD::VSHL";
696 case ARM64ISD::VLSHR: return "ARM64ISD::VLSHR";
697 case ARM64ISD::VASHR: return "ARM64ISD::VASHR";
698 case ARM64ISD::CMEQ: return "ARM64ISD::CMEQ";
699 case ARM64ISD::CMGE: return "ARM64ISD::CMGE";
700 case ARM64ISD::CMGT: return "ARM64ISD::CMGT";
701 case ARM64ISD::CMHI: return "ARM64ISD::CMHI";
702 case ARM64ISD::CMHS: return "ARM64ISD::CMHS";
703 case ARM64ISD::FCMEQ: return "ARM64ISD::FCMEQ";
704 case ARM64ISD::FCMGE: return "ARM64ISD::FCMGE";
705 case ARM64ISD::FCMGT: return "ARM64ISD::FCMGT";
706 case ARM64ISD::CMEQz: return "ARM64ISD::CMEQz";
707 case ARM64ISD::CMGEz: return "ARM64ISD::CMGEz";
708 case ARM64ISD::CMGTz: return "ARM64ISD::CMGTz";
709 case ARM64ISD::CMLEz: return "ARM64ISD::CMLEz";
710 case ARM64ISD::CMLTz: return "ARM64ISD::CMLTz";
711 case ARM64ISD::FCMEQz: return "ARM64ISD::FCMEQz";
712 case ARM64ISD::FCMGEz: return "ARM64ISD::FCMGEz";
713 case ARM64ISD::FCMGTz: return "ARM64ISD::FCMGTz";
714 case ARM64ISD::FCMLEz: return "ARM64ISD::FCMLEz";
715 case ARM64ISD::FCMLTz: return "ARM64ISD::FCMLTz";
716 case ARM64ISD::NOT: return "ARM64ISD::NOT";
717 case ARM64ISD::BIT: return "ARM64ISD::BIT";
718 case ARM64ISD::CBZ: return "ARM64ISD::CBZ";
719 case ARM64ISD::CBNZ: return "ARM64ISD::CBNZ";
720 case ARM64ISD::TBZ: return "ARM64ISD::TBZ";
721 case ARM64ISD::TBNZ: return "ARM64ISD::TBNZ";
722 case ARM64ISD::TC_RETURN: return "ARM64ISD::TC_RETURN";
723 case ARM64ISD::SITOF: return "ARM64ISD::SITOF";
724 case ARM64ISD::UITOF: return "ARM64ISD::UITOF";
725 case ARM64ISD::SQSHL_I: return "ARM64ISD::SQSHL_I";
726 case ARM64ISD::UQSHL_I: return "ARM64ISD::UQSHL_I";
727 case ARM64ISD::SRSHR_I: return "ARM64ISD::SRSHR_I";
728 case ARM64ISD::URSHR_I: return "ARM64ISD::URSHR_I";
729 case ARM64ISD::SQSHLU_I: return "ARM64ISD::SQSHLU_I";
730 case ARM64ISD::WrapperLarge: return "ARM64ISD::WrapperLarge";
735 ARM64TargetLowering::EmitF128CSEL(MachineInstr *MI,
736 MachineBasicBlock *MBB) const {
737 // We materialise the F128CSEL pseudo-instruction as some control flow and a
741 // [... previous instrs leading to comparison ...]
747 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
749 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
750 MachineFunction *MF = MBB->getParent();
751 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
752 DebugLoc DL = MI->getDebugLoc();
753 MachineFunction::iterator It = MBB;
756 unsigned DestReg = MI->getOperand(0).getReg();
757 unsigned IfTrueReg = MI->getOperand(1).getReg();
758 unsigned IfFalseReg = MI->getOperand(2).getReg();
759 unsigned CondCode = MI->getOperand(3).getImm();
760 bool NZCVKilled = MI->getOperand(4).isKill();
762 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
763 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
764 MF->insert(It, TrueBB);
765 MF->insert(It, EndBB);
767 // Transfer rest of current basic-block to EndBB
768 EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
770 EndBB->transferSuccessorsAndUpdatePHIs(MBB);
772 BuildMI(MBB, DL, TII->get(ARM64::Bcc)).addImm(CondCode).addMBB(TrueBB);
773 BuildMI(MBB, DL, TII->get(ARM64::B)).addMBB(EndBB);
774 MBB->addSuccessor(TrueBB);
775 MBB->addSuccessor(EndBB);
777 // TrueBB falls through to the end.
778 TrueBB->addSuccessor(EndBB);
781 TrueBB->addLiveIn(ARM64::NZCV);
782 EndBB->addLiveIn(ARM64::NZCV);
785 BuildMI(*EndBB, EndBB->begin(), DL, TII->get(ARM64::PHI), DestReg)
791 MI->eraseFromParent();
796 ARM64TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
797 MachineBasicBlock *BB) const {
798 switch (MI->getOpcode()) {
803 assert(0 && "Unexpected instruction for custom inserter!");
806 case ARM64::F128CSEL:
807 return EmitF128CSEL(MI, BB);
809 case TargetOpcode::STACKMAP:
810 case TargetOpcode::PATCHPOINT:
811 return emitPatchPoint(MI, BB);
813 llvm_unreachable("Unexpected instruction for custom inserter!");
816 //===----------------------------------------------------------------------===//
817 // ARM64 Lowering private implementation.
818 //===----------------------------------------------------------------------===//
820 //===----------------------------------------------------------------------===//
822 //===----------------------------------------------------------------------===//
824 /// changeIntCCToARM64CC - Convert a DAG integer condition code to an ARM64 CC
825 static ARM64CC::CondCode changeIntCCToARM64CC(ISD::CondCode CC) {
828 llvm_unreachable("Unknown condition code!");
852 /// changeFPCCToARM64CC - Convert a DAG fp condition code to an ARM64 CC.
853 static void changeFPCCToARM64CC(ISD::CondCode CC, ARM64CC::CondCode &CondCode,
854 ARM64CC::CondCode &CondCode2) {
855 CondCode2 = ARM64CC::AL;
858 llvm_unreachable("Unknown FP condition!");
861 CondCode = ARM64CC::EQ;
865 CondCode = ARM64CC::GT;
869 CondCode = ARM64CC::GE;
872 CondCode = ARM64CC::MI;
875 CondCode = ARM64CC::LS;
878 CondCode = ARM64CC::MI;
879 CondCode2 = ARM64CC::GT;
882 CondCode = ARM64CC::VC;
885 CondCode = ARM64CC::VS;
888 CondCode = ARM64CC::EQ;
889 CondCode2 = ARM64CC::VS;
892 CondCode = ARM64CC::HI;
895 CondCode = ARM64CC::PL;
899 CondCode = ARM64CC::LT;
903 CondCode = ARM64CC::LE;
907 CondCode = ARM64CC::NE;
912 /// changeVectorFPCCToARM64CC - Convert a DAG fp condition code to an ARM64 CC
913 /// usable with the vector instructions. Fewer operations are available without
914 /// a real NZCV register, so we have to use less efficient combinations to get
916 static void changeVectorFPCCToARM64CC(ISD::CondCode CC,
917 ARM64CC::CondCode &CondCode,
918 ARM64CC::CondCode &CondCode2,
923 // Mostly the scalar mappings work fine.
924 changeFPCCToARM64CC(CC, CondCode, CondCode2);
927 Invert = true; // Fallthrough
929 CondCode = ARM64CC::MI;
930 CondCode2 = ARM64CC::GE;
937 // All of the compare-mask comparisons are ordered, but we can switch
938 // between the two by a double inversion. E.g. ULE == !OGT.
940 changeFPCCToARM64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
945 static bool isLegalArithImmed(uint64_t C) {
946 // Matches ARM64DAGToDAGISel::SelectArithImmed().
947 return (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
950 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
951 SDLoc dl, SelectionDAG &DAG) {
952 EVT VT = LHS.getValueType();
954 if (VT.isFloatingPoint())
955 return DAG.getNode(ARM64ISD::FCMP, dl, VT, LHS, RHS);
957 // The CMP instruction is just an alias for SUBS, and representing it as
958 // SUBS means that it's possible to get CSE with subtract operations.
959 // A later phase can perform the optimization of setting the destination
960 // register to WZR/XZR if it ends up being unused.
961 unsigned Opcode = ARM64ISD::SUBS;
963 if (RHS.getOpcode() == ISD::SUB && isa<ConstantSDNode>(RHS.getOperand(0)) &&
964 cast<ConstantSDNode>(RHS.getOperand(0))->getZExtValue() == 0 &&
965 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
966 // We'd like to combine a (CMP op1, (sub 0, op2) into a CMN instruction on
967 // the grounds that "op1 - (-op2) == op1 + op2". However, the C and V flags
968 // can be set differently by this operation. It comes down to whether
969 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
970 // everything is fine. If not then the optimization is wrong. Thus general
971 // comparisons are only valid if op2 != 0.
973 // So, finally, the only LLVM-native comparisons that don't mention C and V
974 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
975 // the absence of information about op2.
976 Opcode = ARM64ISD::ADDS;
977 RHS = RHS.getOperand(1);
978 } else if (LHS.getOpcode() == ISD::AND && isa<ConstantSDNode>(RHS) &&
979 cast<ConstantSDNode>(RHS)->getZExtValue() == 0 &&
980 !isUnsignedIntSetCC(CC)) {
981 // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
982 // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
983 // of the signed comparisons.
984 Opcode = ARM64ISD::ANDS;
985 RHS = LHS.getOperand(1);
986 LHS = LHS.getOperand(0);
989 return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS)
993 static SDValue getARM64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
994 SDValue &ARM64cc, SelectionDAG &DAG, SDLoc dl) {
995 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
996 EVT VT = RHS.getValueType();
997 uint64_t C = RHSC->getZExtValue();
998 if (!isLegalArithImmed(C)) {
999 // Constant does not fit, try adjusting it by one?
1005 if ((VT == MVT::i32 && C != 0x80000000 &&
1006 isLegalArithImmed((uint32_t)(C - 1))) ||
1007 (VT == MVT::i64 && C != 0x80000000ULL &&
1008 isLegalArithImmed(C - 1ULL))) {
1009 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1010 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1011 RHS = DAG.getConstant(C, VT);
1016 if ((VT == MVT::i32 && C != 0 &&
1017 isLegalArithImmed((uint32_t)(C - 1))) ||
1018 (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1019 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1020 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
1021 RHS = DAG.getConstant(C, VT);
1026 if ((VT == MVT::i32 && C != 0x7fffffff &&
1027 isLegalArithImmed((uint32_t)(C + 1))) ||
1028 (VT == MVT::i64 && C != 0x7ffffffffffffffULL &&
1029 isLegalArithImmed(C + 1ULL))) {
1030 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1031 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1032 RHS = DAG.getConstant(C, VT);
1037 if ((VT == MVT::i32 && C != 0xffffffff &&
1038 isLegalArithImmed((uint32_t)(C + 1))) ||
1039 (VT == MVT::i64 && C != 0xfffffffffffffffULL &&
1040 isLegalArithImmed(C + 1ULL))) {
1041 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1042 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
1043 RHS = DAG.getConstant(C, VT);
1050 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
1051 ARM64CC::CondCode ARM64CC = changeIntCCToARM64CC(CC);
1052 ARM64cc = DAG.getConstant(ARM64CC, MVT::i32);
1056 static std::pair<SDValue, SDValue>
1057 getARM64XALUOOp(ARM64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
1058 assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
1059 "Unsupported value type");
1060 SDValue Value, Overflow;
1062 SDValue LHS = Op.getOperand(0);
1063 SDValue RHS = Op.getOperand(1);
1065 switch (Op.getOpcode()) {
1067 llvm_unreachable("Unknown overflow instruction!");
1069 Opc = ARM64ISD::ADDS;
1073 Opc = ARM64ISD::ADDS;
1077 Opc = ARM64ISD::SUBS;
1081 Opc = ARM64ISD::SUBS;
1084 // Multiply needs a little bit extra work.
1088 bool IsSigned = (Op.getOpcode() == ISD::SMULO) ? true : false;
1089 if (Op.getValueType() == MVT::i32) {
1090 unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1091 // For a 32 bit multiply with overflow check we want the instruction
1092 // selector to generate a widening multiply (SMADDL/UMADDL). For that we
1093 // need to generate the following pattern:
1094 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
1095 LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
1096 RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
1097 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1098 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
1099 DAG.getConstant(0, MVT::i64));
1100 // On ARM64 the upper 32 bits are always zero extended for a 32 bit
1101 // operation. We need to clear out the upper 32 bits, because we used a
1102 // widening multiply that wrote all 64 bits. In the end this should be a
1104 Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
1106 // The signed overflow check requires more than just a simple check for
1107 // any bit set in the upper 32 bits of the result. These bits could be
1108 // just the sign bits of a negative number. To perform the overflow
1109 // check we have to arithmetic shift right the 32nd bit of the result by
1110 // 31 bits. Then we compare the result to the upper 32 bits.
1111 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
1112 DAG.getConstant(32, MVT::i64));
1113 UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
1114 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
1115 DAG.getConstant(31, MVT::i64));
1116 // It is important that LowerBits is last, otherwise the arithmetic
1117 // shift will not be folded into the compare (SUBS).
1118 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
1119 Overflow = DAG.getNode(ARM64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1122 // The overflow check for unsigned multiply is easy. We only need to
1123 // check if any of the upper 32 bits are set. This can be done with a
1124 // CMP (shifted register). For that we need to generate the following
1126 // (i64 ARM64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
1127 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
1128 DAG.getConstant(32, MVT::i64));
1129 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1131 DAG.getNode(ARM64ISD::SUBS, DL, VTs, DAG.getConstant(0, MVT::i64),
1132 UpperBits).getValue(1);
1136 assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
1137 // For the 64 bit multiply
1138 Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1140 SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
1141 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
1142 DAG.getConstant(63, MVT::i64));
1143 // It is important that LowerBits is last, otherwise the arithmetic
1144 // shift will not be folded into the compare (SUBS).
1145 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1146 Overflow = DAG.getNode(ARM64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1149 SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
1150 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1152 DAG.getNode(ARM64ISD::SUBS, DL, VTs, DAG.getConstant(0, MVT::i64),
1153 UpperBits).getValue(1);
1160 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
1162 // Emit the ARM64 operation with overflow check.
1163 Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
1164 Overflow = Value.getValue(1);
1166 return std::make_pair(Value, Overflow);
1169 SDValue ARM64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
1170 RTLIB::Libcall Call) const {
1171 SmallVector<SDValue, 2> Ops;
1172 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i)
1173 Ops.push_back(Op.getOperand(i));
1175 return makeLibCall(DAG, Call, MVT::f128, &Ops[0], Ops.size(), false,
1179 static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
1180 SDValue Sel = Op.getOperand(0);
1181 SDValue Other = Op.getOperand(1);
1183 // If neither operand is a SELECT_CC, give up.
1184 if (Sel.getOpcode() != ISD::SELECT_CC)
1185 std::swap(Sel, Other);
1186 if (Sel.getOpcode() != ISD::SELECT_CC)
1189 // The folding we want to perform is:
1190 // (xor x, (select_cc a, b, cc, 0, -1) )
1192 // (csel x, (xor x, -1), cc ...)
1194 // The latter will get matched to a CSINV instruction.
1196 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
1197 SDValue LHS = Sel.getOperand(0);
1198 SDValue RHS = Sel.getOperand(1);
1199 SDValue TVal = Sel.getOperand(2);
1200 SDValue FVal = Sel.getOperand(3);
1203 // FIXME: This could be generalized to non-integer comparisons.
1204 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
1207 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
1208 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
1210 // The the values aren't constants, this isn't the pattern we're looking for.
1211 if (!CFVal || !CTVal)
1214 // We can commute the SELECT_CC by inverting the condition. This
1215 // might be needed to make this fit into a CSINV pattern.
1216 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
1217 std::swap(TVal, FVal);
1218 std::swap(CTVal, CFVal);
1219 CC = ISD::getSetCCInverse(CC, true);
1222 // If the constants line up, perform the transform!
1223 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
1225 SDValue Cmp = getARM64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
1228 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
1229 DAG.getConstant(-1ULL, Other.getValueType()));
1231 return DAG.getNode(ARM64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
1238 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
1239 EVT VT = Op.getValueType();
1241 // Let legalize expand this if it isn't a legal type yet.
1242 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
1245 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
1248 bool ExtraOp = false;
1249 switch (Op.getOpcode()) {
1251 assert(0 && "Invalid code");
1253 Opc = ARM64ISD::ADDS;
1256 Opc = ARM64ISD::SUBS;
1259 Opc = ARM64ISD::ADCS;
1263 Opc = ARM64ISD::SBCS;
1269 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
1270 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
1274 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
1275 // Let legalize expand this if it isn't a legal type yet.
1276 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
1279 ARM64CC::CondCode CC;
1280 // The actual operation that sets the overflow or carry flag.
1281 SDValue Value, Overflow;
1282 std::tie(Value, Overflow) = getARM64XALUOOp(CC, Op, DAG);
1284 // We use 0 and 1 as false and true values.
1285 SDValue TVal = DAG.getConstant(1, MVT::i32);
1286 SDValue FVal = DAG.getConstant(0, MVT::i32);
1288 // We use an inverted condition, because the conditional select is inverted
1289 // too. This will allow it to be selected to a single instruction:
1290 // CSINC Wd, WZR, WZR, invert(cond).
1291 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), MVT::i32);
1292 Overflow = DAG.getNode(ARM64ISD::CSEL, SDLoc(Op), MVT::i32, FVal, TVal, CCVal,
1295 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
1296 return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), VTs, Value, Overflow);
1299 // Prefetch operands are:
1300 // 1: Address to prefetch
1302 // 3: int locality (0 = no locality ... 3 = extreme locality)
1303 // 4: bool isDataCache
1304 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
1306 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
1307 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
1308 // The data thing is not used.
1309 // unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
1311 bool IsStream = !Locality;
1312 // When the locality number is set
1314 // The front-end should have filtered out the out-of-range values
1315 assert(Locality <= 3 && "Prefetch locality out-of-range");
1316 // The locality degree is the opposite of the cache speed.
1317 // Put the number the other way around.
1318 // The encoding starts at 0 for level 1
1319 Locality = 3 - Locality;
1322 // built the mask value encoding the expected behavior.
1323 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit
1324 (Locality << 1) | // Cache level bits
1325 (unsigned)IsStream; // Stream bit
1326 return DAG.getNode(ARM64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
1327 DAG.getConstant(PrfOp, MVT::i32), Op.getOperand(1));
1330 SDValue ARM64TargetLowering::LowerFP_EXTEND(SDValue Op,
1331 SelectionDAG &DAG) const {
1332 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
1335 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
1337 return LowerF128Call(Op, DAG, LC);
1340 SDValue ARM64TargetLowering::LowerFP_ROUND(SDValue Op,
1341 SelectionDAG &DAG) const {
1342 if (Op.getOperand(0).getValueType() != MVT::f128) {
1343 // It's legal except when f128 is involved
1348 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
1350 // FP_ROUND node has a second operand indicating whether it is known to be
1351 // precise. That doesn't take part in the LibCall so we can't directly use
1353 SDValue SrcVal = Op.getOperand(0);
1354 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
1355 /*isSigned*/ false, SDLoc(Op)).first;
1358 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
1359 // Warning: We maintain cost tables in ARM64TargetTransformInfo.cpp.
1360 // Any additional optimization in this function should be recorded
1361 // in the cost tables.
1362 EVT InVT = Op.getOperand(0).getValueType();
1363 EVT VT = Op.getValueType();
1365 // FP_TO_XINT conversion from the same type are legal.
1366 if (VT.getSizeInBits() == InVT.getSizeInBits())
1369 if (InVT == MVT::v2f64 || InVT == MVT::v4f32) {
1372 DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
1374 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
1375 } else if (InVT == MVT::v2f32) {
1377 SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v2f64, Op.getOperand(0));
1378 return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
1381 // Type changing conversions are illegal.
1385 SDValue ARM64TargetLowering::LowerFP_TO_INT(SDValue Op,
1386 SelectionDAG &DAG) const {
1387 if (Op.getOperand(0).getValueType().isVector())
1388 return LowerVectorFP_TO_INT(Op, DAG);
1390 if (Op.getOperand(0).getValueType() != MVT::f128) {
1391 // It's legal except when f128 is involved
1396 if (Op.getOpcode() == ISD::FP_TO_SINT)
1397 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
1399 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
1401 SmallVector<SDValue, 2> Ops;
1402 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i)
1403 Ops.push_back(Op.getOperand(i));
1405 return makeLibCall(DAG, LC, Op.getValueType(), &Ops[0], Ops.size(), false,
1409 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
1410 // Warning: We maintain cost tables in ARM64TargetTransformInfo.cpp.
1411 // Any additional optimization in this function should be recorded
1412 // in the cost tables.
1413 EVT VT = Op.getValueType();
1415 SDValue In = Op.getOperand(0);
1416 EVT InVT = In.getValueType();
1418 // v2i32 to v2f32 is legal.
1419 if (VT == MVT::v2f32 && InVT == MVT::v2i32)
1422 // This function only handles v2f64 outputs.
1423 if (VT == MVT::v2f64) {
1424 // Extend the input argument to a v2i64 that we can feed into the
1425 // floating point conversion. Zero or sign extend based on whether
1426 // we're doing a signed or unsigned float conversion.
1428 Op.getOpcode() == ISD::UINT_TO_FP ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
1429 assert(Op.getNumOperands() == 1 && "FP conversions take one argument");
1430 SDValue Promoted = DAG.getNode(Opc, dl, MVT::v2i64, Op.getOperand(0));
1431 return DAG.getNode(Op.getOpcode(), dl, Op.getValueType(), Promoted);
1434 // Scalarize v2i64 to v2f32 conversions.
1435 std::vector<SDValue> BuildVectorOps;
1436 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
1437 SDValue Sclr = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, In,
1438 DAG.getConstant(i, MVT::i64));
1439 Sclr = DAG.getNode(Op->getOpcode(), dl, MVT::f32, Sclr);
1440 BuildVectorOps.push_back(Sclr);
1443 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, BuildVectorOps);
1446 SDValue ARM64TargetLowering::LowerINT_TO_FP(SDValue Op,
1447 SelectionDAG &DAG) const {
1448 if (Op.getValueType().isVector())
1449 return LowerVectorINT_TO_FP(Op, DAG);
1451 // i128 conversions are libcalls.
1452 if (Op.getOperand(0).getValueType() == MVT::i128)
1455 // Other conversions are legal, unless it's to the completely software-based
1457 if (Op.getValueType() != MVT::f128)
1461 if (Op.getOpcode() == ISD::SINT_TO_FP)
1462 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
1464 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
1466 return LowerF128Call(Op, DAG, LC);
1469 SDValue ARM64TargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
1470 // For iOS, we want to call an alternative entry point: __sincos_stret,
1471 // which returns the values in two S / D registers.
1473 SDValue Arg = Op.getOperand(0);
1474 EVT ArgVT = Arg.getValueType();
1475 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
1482 Entry.isSExt = false;
1483 Entry.isZExt = false;
1484 Args.push_back(Entry);
1486 const char *LibcallName =
1487 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
1488 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
1490 StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL);
1491 TargetLowering::CallLoweringInfo CLI(
1492 DAG.getEntryNode(), RetTy, false, false, false, false, 0,
1493 CallingConv::Fast, /*isTaillCall=*/false,
1494 /*doesNotRet=*/false, /*isReturnValueUsed*/ true, Callee, Args, DAG, dl);
1495 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1496 return CallResult.first;
1499 SDValue ARM64TargetLowering::LowerOperation(SDValue Op,
1500 SelectionDAG &DAG) const {
1501 switch (Op.getOpcode()) {
1503 llvm_unreachable("unimplemented operand");
1505 case ISD::GlobalAddress:
1506 return LowerGlobalAddress(Op, DAG);
1507 case ISD::GlobalTLSAddress:
1508 return LowerGlobalTLSAddress(Op, DAG);
1510 return LowerSETCC(Op, DAG);
1512 return LowerBR_CC(Op, DAG);
1514 return LowerSELECT(Op, DAG);
1515 case ISD::SELECT_CC:
1516 return LowerSELECT_CC(Op, DAG);
1517 case ISD::JumpTable:
1518 return LowerJumpTable(Op, DAG);
1519 case ISD::ConstantPool:
1520 return LowerConstantPool(Op, DAG);
1521 case ISD::BlockAddress:
1522 return LowerBlockAddress(Op, DAG);
1524 return LowerVASTART(Op, DAG);
1526 return LowerVACOPY(Op, DAG);
1528 return LowerVAARG(Op, DAG);
1533 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
1540 return LowerXALUO(Op, DAG);
1542 return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
1544 return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
1546 return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
1548 return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
1550 return LowerFP_ROUND(Op, DAG);
1551 case ISD::FP_EXTEND:
1552 return LowerFP_EXTEND(Op, DAG);
1553 case ISD::FRAMEADDR:
1554 return LowerFRAMEADDR(Op, DAG);
1555 case ISD::RETURNADDR:
1556 return LowerRETURNADDR(Op, DAG);
1557 case ISD::INSERT_VECTOR_ELT:
1558 return LowerINSERT_VECTOR_ELT(Op, DAG);
1559 case ISD::EXTRACT_VECTOR_ELT:
1560 return LowerEXTRACT_VECTOR_ELT(Op, DAG);
1561 case ISD::BUILD_VECTOR:
1562 return LowerBUILD_VECTOR(Op, DAG);
1563 case ISD::VECTOR_SHUFFLE:
1564 return LowerVECTOR_SHUFFLE(Op, DAG);
1565 case ISD::EXTRACT_SUBVECTOR:
1566 return LowerEXTRACT_SUBVECTOR(Op, DAG);
1570 return LowerVectorSRA_SRL_SHL(Op, DAG);
1571 case ISD::SHL_PARTS:
1572 return LowerShiftLeftParts(Op, DAG);
1573 case ISD::SRL_PARTS:
1574 case ISD::SRA_PARTS:
1575 return LowerShiftRightParts(Op, DAG);
1577 return LowerCTPOP(Op, DAG);
1578 case ISD::FCOPYSIGN:
1579 return LowerFCOPYSIGN(Op, DAG);
1581 return LowerVectorAND(Op, DAG);
1583 return LowerVectorOR(Op, DAG);
1585 return LowerXOR(Op, DAG);
1587 return LowerPREFETCH(Op, DAG);
1588 case ISD::SINT_TO_FP:
1589 case ISD::UINT_TO_FP:
1590 return LowerINT_TO_FP(Op, DAG);
1591 case ISD::FP_TO_SINT:
1592 case ISD::FP_TO_UINT:
1593 return LowerFP_TO_INT(Op, DAG);
1595 return LowerFSINCOS(Op, DAG);
1599 /// getFunctionAlignment - Return the Log2 alignment of this function.
1600 unsigned ARM64TargetLowering::getFunctionAlignment(const Function *F) const {
1604 //===----------------------------------------------------------------------===//
1605 // Calling Convention Implementation
1606 //===----------------------------------------------------------------------===//
1608 #include "ARM64GenCallingConv.inc"
1610 /// Selects the correct CCAssignFn for a the given CallingConvention
1612 CCAssignFn *ARM64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
1613 bool IsVarArg) const {
1616 llvm_unreachable("Unsupported calling convention.");
1617 case CallingConv::WebKit_JS:
1618 return CC_ARM64_WebKit_JS;
1619 case CallingConv::C:
1620 case CallingConv::Fast:
1621 if (!Subtarget->isTargetDarwin())
1622 return CC_ARM64_AAPCS;
1623 return IsVarArg ? CC_ARM64_DarwinPCS_VarArg : CC_ARM64_DarwinPCS;
1627 SDValue ARM64TargetLowering::LowerFormalArguments(
1628 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
1629 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
1630 SmallVectorImpl<SDValue> &InVals) const {
1631 MachineFunction &MF = DAG.getMachineFunction();
1632 MachineFrameInfo *MFI = MF.getFrameInfo();
1634 // Assign locations to all of the incoming arguments.
1635 SmallVector<CCValAssign, 16> ArgLocs;
1636 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1637 getTargetMachine(), ArgLocs, *DAG.getContext());
1639 // At this point, Ins[].VT may already be promoted to i32. To correctly
1640 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
1641 // i8 to CC_ARM64_AAPCS with i32 being ValVT and i8 being LocVT.
1642 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
1643 // we use a special version of AnalyzeFormalArguments to pass in ValVT and
1645 unsigned NumArgs = Ins.size();
1646 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
1647 unsigned CurArgIdx = 0;
1648 for (unsigned i = 0; i != NumArgs; ++i) {
1649 MVT ValVT = Ins[i].VT;
1650 std::advance(CurOrigArg, Ins[i].OrigArgIndex - CurArgIdx);
1651 CurArgIdx = Ins[i].OrigArgIndex;
1653 // Get type of the original argument.
1654 EVT ActualVT = getValueType(CurOrigArg->getType(), /*AllowUnknown*/ true);
1655 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
1656 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
1658 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
1660 else if (ActualMVT == MVT::i16)
1663 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
1665 AssignFn(i, ValVT, LocVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
1666 assert(!Res && "Call operand has unhandled type");
1669 assert(ArgLocs.size() == Ins.size());
1670 SmallVector<SDValue, 16> ArgValues;
1671 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1672 CCValAssign &VA = ArgLocs[i];
1674 if (Ins[i].Flags.isByVal()) {
1675 // Byval is used for HFAs in the PCS, but the system should work in a
1676 // non-compliant manner for larger structs.
1677 EVT PtrTy = getPointerTy();
1678 int Size = Ins[i].Flags.getByValSize();
1679 unsigned NumRegs = (Size + 7) / 8;
1682 MFI->CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
1683 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrTy);
1684 InVals.push_back(FrameIdxN);
1687 } if (VA.isRegLoc()) {
1688 // Arguments stored in registers.
1689 EVT RegVT = VA.getLocVT();
1692 const TargetRegisterClass *RC;
1694 if (RegVT == MVT::i32)
1695 RC = &ARM64::GPR32RegClass;
1696 else if (RegVT == MVT::i64)
1697 RC = &ARM64::GPR64RegClass;
1698 else if (RegVT == MVT::f32)
1699 RC = &ARM64::FPR32RegClass;
1700 else if (RegVT == MVT::f64 || RegVT.is64BitVector())
1701 RC = &ARM64::FPR64RegClass;
1702 else if (RegVT == MVT::f128 || RegVT.is128BitVector())
1703 RC = &ARM64::FPR128RegClass;
1705 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
1707 // Transform the arguments in physical registers into virtual ones.
1708 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1709 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
1711 // If this is an 8, 16 or 32-bit value, it is really passed promoted
1712 // to 64 bits. Insert an assert[sz]ext to capture this, then
1713 // truncate to the right size.
1714 switch (VA.getLocInfo()) {
1716 llvm_unreachable("Unknown loc info!");
1717 case CCValAssign::Full:
1719 case CCValAssign::BCvt:
1720 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
1722 case CCValAssign::SExt:
1723 ArgValue = DAG.getNode(ISD::AssertSext, DL, RegVT, ArgValue,
1724 DAG.getValueType(VA.getValVT()));
1725 ArgValue = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), ArgValue);
1727 case CCValAssign::ZExt:
1728 ArgValue = DAG.getNode(ISD::AssertZext, DL, RegVT, ArgValue,
1729 DAG.getValueType(VA.getValVT()));
1730 ArgValue = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), ArgValue);
1734 InVals.push_back(ArgValue);
1736 } else { // VA.isRegLoc()
1737 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
1738 unsigned ArgOffset = VA.getLocMemOffset();
1739 unsigned ArgSize = VA.getLocVT().getSizeInBits() / 8;
1740 int FI = MFI->CreateFixedObject(ArgSize, ArgOffset, true);
1742 // Create load nodes to retrieve arguments from the stack.
1743 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1744 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, FIN,
1745 MachinePointerInfo::getFixedStack(FI), false,
1752 if (!Subtarget->isTargetDarwin()) {
1753 // The AAPCS variadic function ABI is identical to the non-variadic
1754 // one. As a result there may be more arguments in registers and we should
1755 // save them for future reference.
1756 saveVarArgRegisters(CCInfo, DAG, DL, Chain);
1759 ARM64FunctionInfo *AFI = MF.getInfo<ARM64FunctionInfo>();
1760 // This will point to the next argument passed via stack.
1761 unsigned StackOffset = CCInfo.getNextStackOffset();
1762 // We currently pass all varargs at 8-byte alignment.
1763 StackOffset = ((StackOffset + 7) & ~7);
1764 AFI->setVarArgsStackIndex(MFI->CreateFixedObject(4, StackOffset, true));
1770 void ARM64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
1771 SelectionDAG &DAG, SDLoc DL,
1772 SDValue &Chain) const {
1773 MachineFunction &MF = DAG.getMachineFunction();
1774 MachineFrameInfo *MFI = MF.getFrameInfo();
1775 ARM64FunctionInfo *FuncInfo = MF.getInfo<ARM64FunctionInfo>();
1777 SmallVector<SDValue, 8> MemOps;
1779 static const MCPhysReg GPRArgRegs[] = { ARM64::X0, ARM64::X1, ARM64::X2,
1780 ARM64::X3, ARM64::X4, ARM64::X5,
1781 ARM64::X6, ARM64::X7 };
1782 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
1783 unsigned FirstVariadicGPR =
1784 CCInfo.getFirstUnallocated(GPRArgRegs, NumGPRArgRegs);
1786 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
1788 if (GPRSaveSize != 0) {
1789 GPRIdx = MFI->CreateStackObject(GPRSaveSize, 8, false);
1791 SDValue FIN = DAG.getFrameIndex(GPRIdx, getPointerTy());
1793 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
1794 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &ARM64::GPR64RegClass);
1795 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
1797 DAG.getStore(Val.getValue(1), DL, Val, FIN,
1798 MachinePointerInfo::getStack(i * 8), false, false, 0);
1799 MemOps.push_back(Store);
1800 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), FIN,
1801 DAG.getConstant(8, getPointerTy()));
1804 FuncInfo->setVarArgsGPRIndex(GPRIdx);
1805 FuncInfo->setVarArgsGPRSize(GPRSaveSize);
1807 if (Subtarget->hasFPARMv8()) {
1808 static const MCPhysReg FPRArgRegs[] = { ARM64::Q0, ARM64::Q1, ARM64::Q2,
1809 ARM64::Q3, ARM64::Q4, ARM64::Q5,
1810 ARM64::Q6, ARM64::Q7 };
1811 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
1812 unsigned FirstVariadicFPR =
1813 CCInfo.getFirstUnallocated(FPRArgRegs, NumFPRArgRegs);
1815 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
1817 if (FPRSaveSize != 0) {
1818 FPRIdx = MFI->CreateStackObject(FPRSaveSize, 16, false);
1820 SDValue FIN = DAG.getFrameIndex(FPRIdx, getPointerTy());
1822 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
1823 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &ARM64::FPR128RegClass);
1824 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::v2i64);
1826 DAG.getStore(Val.getValue(1), DL, Val, FIN,
1827 MachinePointerInfo::getStack(i * 16), false, false, 0);
1828 MemOps.push_back(Store);
1829 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), FIN,
1830 DAG.getConstant(16, getPointerTy()));
1833 FuncInfo->setVarArgsFPRIndex(FPRIdx);
1834 FuncInfo->setVarArgsFPRSize(FPRSaveSize);
1837 if (!MemOps.empty()) {
1838 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
1842 /// LowerCallResult - Lower the result values of a call into the
1843 /// appropriate copies out of appropriate physical registers.
1844 SDValue ARM64TargetLowering::LowerCallResult(
1845 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
1846 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
1847 SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
1848 SDValue ThisVal) const {
1849 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS ? RetCC_ARM64_WebKit_JS
1850 : RetCC_ARM64_AAPCS;
1851 // Assign locations to each value returned by this call.
1852 SmallVector<CCValAssign, 16> RVLocs;
1853 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1854 getTargetMachine(), RVLocs, *DAG.getContext());
1855 CCInfo.AnalyzeCallResult(Ins, RetCC);
1857 // Copy all of the result registers out of their specified physreg.
1858 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1859 CCValAssign VA = RVLocs[i];
1861 // Pass 'this' value directly from the argument to return value, to avoid
1862 // reg unit interference
1863 if (i == 0 && isThisReturn) {
1864 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
1865 "unexpected return calling convention register assignment");
1866 InVals.push_back(ThisVal);
1871 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
1872 Chain = Val.getValue(1);
1873 InFlag = Val.getValue(2);
1875 switch (VA.getLocInfo()) {
1877 llvm_unreachable("Unknown loc info!");
1878 case CCValAssign::Full:
1880 case CCValAssign::BCvt:
1881 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
1885 InVals.push_back(Val);
1891 bool ARM64TargetLowering::isEligibleForTailCallOptimization(
1892 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
1893 bool isCalleeStructRet, bool isCallerStructRet,
1894 const SmallVectorImpl<ISD::OutputArg> &Outs,
1895 const SmallVectorImpl<SDValue> &OutVals,
1896 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
1897 // Look for obvious safe cases to perform tail call optimization that do not
1898 // require ABI changes. This is what gcc calls sibcall.
1900 // Do not sibcall optimize vararg calls unless the call site is not passing
1902 if (isVarArg && !Outs.empty())
1905 // Also avoid sibcall optimization if either caller or callee uses struct
1906 // return semantics.
1907 if (isCalleeStructRet || isCallerStructRet)
1910 // Note that currently ARM64 "C" calling convention and "Fast" calling
1911 // convention are compatible. If/when that ever changes, we'll need to
1912 // add checks here to make sure any interactions are OK.
1914 // If the callee takes no arguments then go on to check the results of the
1916 if (!Outs.empty()) {
1917 // Check if stack adjustment is needed. For now, do not do this if any
1918 // argument is passed on the stack.
1919 SmallVector<CCValAssign, 16> ArgLocs;
1920 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
1921 getTargetMachine(), ArgLocs, *DAG.getContext());
1922 CCAssignFn *AssignFn = CCAssignFnForCall(CalleeCC, /*IsVarArg=*/false);
1923 CCInfo.AnalyzeCallOperands(Outs, AssignFn);
1924 if (CCInfo.getNextStackOffset()) {
1925 // Check if the arguments are already laid out in the right way as
1926 // the caller's fixed stack objects.
1927 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
1928 ++i, ++realArgIdx) {
1929 CCValAssign &VA = ArgLocs[i];
1930 if (VA.getLocInfo() == CCValAssign::Indirect)
1932 if (VA.needsCustom()) {
1933 // Just don't handle anything that needs custom adjustments for now.
1934 // If need be, we can revisit later, but we shouldn't ever end up
1937 } else if (!VA.isRegLoc()) {
1938 // Likewise, don't try to handle stack based arguments for the
1948 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
1949 /// and add input and output parameter nodes.
1950 SDValue ARM64TargetLowering::LowerCall(CallLoweringInfo &CLI,
1951 SmallVectorImpl<SDValue> &InVals) const {
1952 SelectionDAG &DAG = CLI.DAG;
1954 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
1955 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
1956 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
1957 SDValue Chain = CLI.Chain;
1958 SDValue Callee = CLI.Callee;
1959 bool &IsTailCall = CLI.IsTailCall;
1960 CallingConv::ID CallConv = CLI.CallConv;
1961 bool IsVarArg = CLI.IsVarArg;
1963 MachineFunction &MF = DAG.getMachineFunction();
1964 bool IsStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1965 bool IsThisReturn = false;
1967 // If tail calls are explicitly disabled, make sure not to use them.
1968 if (!EnableARM64TailCalls)
1972 // Check if it's really possible to do a tail call.
1973 IsTailCall = isEligibleForTailCallOptimization(
1974 Callee, CallConv, IsVarArg, IsStructRet,
1975 MF.getFunction()->hasStructRetAttr(), Outs, OutVals, Ins, DAG);
1976 if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
1977 report_fatal_error("failed to perform tail call elimination on a call "
1978 "site marked musttail");
1979 // We don't support GuaranteedTailCallOpt, only automatically
1980 // detected sibcalls.
1981 // FIXME: Re-evaluate. Is this true? Should it be true?
1986 // Analyze operands of the call, assigning locations to each operand.
1987 SmallVector<CCValAssign, 16> ArgLocs;
1988 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
1989 getTargetMachine(), ArgLocs, *DAG.getContext());
1992 // Handle fixed and variable vector arguments differently.
1993 // Variable vector arguments always go into memory.
1994 unsigned NumArgs = Outs.size();
1996 for (unsigned i = 0; i != NumArgs; ++i) {
1997 MVT ArgVT = Outs[i].VT;
1998 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
1999 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
2000 /*IsVarArg=*/ !Outs[i].IsFixed);
2001 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
2002 assert(!Res && "Call operand has unhandled type");
2006 // At this point, Outs[].VT may already be promoted to i32. To correctly
2007 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2008 // i8 to CC_ARM64_AAPCS with i32 being ValVT and i8 being LocVT.
2009 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
2010 // we use a special version of AnalyzeCallOperands to pass in ValVT and
2012 unsigned NumArgs = Outs.size();
2013 for (unsigned i = 0; i != NumArgs; ++i) {
2014 MVT ValVT = Outs[i].VT;
2015 // Get type of the original argument.
2016 EVT ActualVT = getValueType(CLI.Args[Outs[i].OrigArgIndex].Ty,
2017 /*AllowUnknown*/ true);
2018 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
2019 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2020 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2022 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2024 else if (ActualMVT == MVT::i16)
2027 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2028 bool Res = AssignFn(i, ValVT, LocVT, CCValAssign::Full, ArgFlags, CCInfo);
2029 assert(!Res && "Call operand has unhandled type");
2034 // Get a count of how many bytes are to be pushed on the stack.
2035 unsigned NumBytes = CCInfo.getNextStackOffset();
2037 // Adjust the stack pointer for the new arguments...
2038 // These operations are automatically eliminated by the prolog/epilog pass
2041 DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true), DL);
2043 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, ARM64::SP, getPointerTy());
2045 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2046 SmallVector<SDValue, 8> MemOpChains;
2048 // Walk the register/memloc assignments, inserting copies/loads.
2049 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
2050 ++i, ++realArgIdx) {
2051 CCValAssign &VA = ArgLocs[i];
2052 SDValue Arg = OutVals[realArgIdx];
2053 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2055 // Promote the value if needed.
2056 switch (VA.getLocInfo()) {
2058 llvm_unreachable("Unknown loc info!");
2059 case CCValAssign::Full:
2061 case CCValAssign::SExt:
2062 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2064 case CCValAssign::ZExt:
2065 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2067 case CCValAssign::AExt:
2068 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2070 case CCValAssign::BCvt:
2071 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2073 case CCValAssign::FPExt:
2074 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
2078 if (VA.isRegLoc()) {
2079 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i64) {
2080 assert(VA.getLocVT() == MVT::i64 &&
2081 "unexpected calling convention register assignment");
2082 assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
2083 "unexpected use of 'returned'");
2084 IsThisReturn = true;
2086 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2088 assert(VA.isMemLoc());
2089 // There's no reason we can't support stack args w/ tailcall, but
2090 // we currently don't, so assert if we see one.
2091 assert(!IsTailCall && "stack argument with tail call!?");
2092 unsigned LocMemOffset = VA.getLocMemOffset();
2093 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2094 PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr, PtrOff);
2096 if (Outs[i].Flags.isByVal()) {
2098 DAG.getConstant(Outs[i].Flags.getByValSize(), MVT::i64);
2099 SDValue Cpy = DAG.getMemcpy(
2100 Chain, DL, PtrOff, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
2101 /*isVolatile = */ false,
2102 /*alwaysInline = */ false,
2103 MachinePointerInfo::getStack(LocMemOffset), MachinePointerInfo());
2105 MemOpChains.push_back(Cpy);
2107 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
2108 // promoted to a legal register type i32, we should truncate Arg back to
2110 if (Arg.getValueType().isSimple() &&
2111 Arg.getValueType().getSimpleVT() == MVT::i32 &&
2112 (VA.getLocVT() == MVT::i1 || VA.getLocVT() == MVT::i8 ||
2113 VA.getLocVT() == MVT::i16))
2114 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getLocVT(), Arg);
2116 SDValue Store = DAG.getStore(Chain, DL, Arg, PtrOff,
2117 MachinePointerInfo::getStack(LocMemOffset),
2119 MemOpChains.push_back(Store);
2124 if (!MemOpChains.empty())
2125 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2127 // Build a sequence of copy-to-reg nodes chained together with token chain
2128 // and flag operands which copy the outgoing args into the appropriate regs.
2130 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2131 Chain = DAG.getCopyToReg(Chain, DL, RegsToPass[i].first,
2132 RegsToPass[i].second, InFlag);
2133 InFlag = Chain.getValue(1);
2136 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2137 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2138 // node so that legalize doesn't hack it.
2139 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
2140 Subtarget->isTargetMachO()) {
2141 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2142 const GlobalValue *GV = G->getGlobal();
2143 bool InternalLinkage = GV->hasInternalLinkage();
2144 if (InternalLinkage)
2145 Callee = DAG.getTargetGlobalAddress(GV, DL, getPointerTy(), 0, 0);
2147 Callee = DAG.getTargetGlobalAddress(GV, DL, getPointerTy(), 0,
2149 Callee = DAG.getNode(ARM64ISD::LOADgot, DL, getPointerTy(), Callee);
2151 } else if (ExternalSymbolSDNode *S =
2152 dyn_cast<ExternalSymbolSDNode>(Callee)) {
2153 const char *Sym = S->getSymbol();
2155 DAG.getTargetExternalSymbol(Sym, getPointerTy(), ARM64II::MO_GOT);
2156 Callee = DAG.getNode(ARM64ISD::LOADgot, DL, getPointerTy(), Callee);
2158 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2159 const GlobalValue *GV = G->getGlobal();
2160 Callee = DAG.getTargetGlobalAddress(GV, DL, getPointerTy(), 0, 0);
2161 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2162 const char *Sym = S->getSymbol();
2163 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), 0);
2166 std::vector<SDValue> Ops;
2167 Ops.push_back(Chain);
2168 Ops.push_back(Callee);
2170 // Add argument registers to the end of the list so that they are known live
2172 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2173 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2174 RegsToPass[i].second.getValueType()));
2176 // Add a register mask operand representing the call-preserved registers.
2177 const uint32_t *Mask;
2178 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2179 const ARM64RegisterInfo *ARI = static_cast<const ARM64RegisterInfo *>(TRI);
2181 // For 'this' returns, use the X0-preserving mask if applicable
2182 Mask = ARI->getThisReturnPreservedMask(CallConv);
2184 IsThisReturn = false;
2185 Mask = ARI->getCallPreservedMask(CallConv);
2188 Mask = ARI->getCallPreservedMask(CallConv);
2190 assert(Mask && "Missing call preserved mask for calling convention");
2191 Ops.push_back(DAG.getRegisterMask(Mask));
2193 if (InFlag.getNode())
2194 Ops.push_back(InFlag);
2196 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2198 // If we're doing a tall call, use a TC_RETURN here rather than an
2199 // actual call instruction.
2201 return DAG.getNode(ARM64ISD::TC_RETURN, DL, NodeTys, Ops);
2203 // Returns a chain and a flag for retval copy to use.
2204 Chain = DAG.getNode(ARM64ISD::CALL, DL, NodeTys, Ops);
2205 InFlag = Chain.getValue(1);
2207 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2208 DAG.getIntPtrConstant(0, true), InFlag, DL);
2210 InFlag = Chain.getValue(1);
2212 // Handle result values, copying them out of physregs into vregs that we
2214 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
2215 InVals, IsThisReturn,
2216 IsThisReturn ? OutVals[0] : SDValue());
2219 bool ARM64TargetLowering::CanLowerReturn(
2220 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
2221 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
2222 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS ? RetCC_ARM64_WebKit_JS
2223 : RetCC_ARM64_AAPCS;
2224 SmallVector<CCValAssign, 16> RVLocs;
2225 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
2226 return CCInfo.CheckReturn(Outs, RetCC);
2230 ARM64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2232 const SmallVectorImpl<ISD::OutputArg> &Outs,
2233 const SmallVectorImpl<SDValue> &OutVals,
2234 SDLoc DL, SelectionDAG &DAG) const {
2235 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS ? RetCC_ARM64_WebKit_JS
2236 : RetCC_ARM64_AAPCS;
2237 SmallVector<CCValAssign, 16> RVLocs;
2238 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2239 getTargetMachine(), RVLocs, *DAG.getContext());
2240 CCInfo.AnalyzeReturn(Outs, RetCC);
2242 // Copy the result values into the output registers.
2244 SmallVector<SDValue, 4> RetOps(1, Chain);
2245 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
2246 ++i, ++realRVLocIdx) {
2247 CCValAssign &VA = RVLocs[i];
2248 assert(VA.isRegLoc() && "Can only return in registers!");
2249 SDValue Arg = OutVals[realRVLocIdx];
2251 switch (VA.getLocInfo()) {
2253 llvm_unreachable("Unknown loc info!");
2254 case CCValAssign::Full:
2256 case CCValAssign::BCvt:
2257 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2261 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2262 Flag = Chain.getValue(1);
2263 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2266 RetOps[0] = Chain; // Update chain.
2268 // Add the flag if we have it.
2270 RetOps.push_back(Flag);
2272 return DAG.getNode(ARM64ISD::RET_FLAG, DL, MVT::Other, RetOps);
2275 //===----------------------------------------------------------------------===//
2276 // Other Lowering Code
2277 //===----------------------------------------------------------------------===//
2279 SDValue ARM64TargetLowering::LowerGlobalAddress(SDValue Op,
2280 SelectionDAG &DAG) const {
2281 EVT PtrVT = getPointerTy();
2283 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2284 unsigned char OpFlags =
2285 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
2287 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
2288 "unexpected offset in global node");
2290 // This also catched the large code model case for Darwin.
2291 if ((OpFlags & ARM64II::MO_GOT) != 0) {
2292 SDValue GotAddr = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
2293 // FIXME: Once remat is capable of dealing with instructions with register
2294 // operands, expand this into two nodes instead of using a wrapper node.
2295 return DAG.getNode(ARM64ISD::LOADgot, DL, PtrVT, GotAddr);
2298 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2299 const unsigned char MO_NC = ARM64II::MO_NC;
2301 ARM64ISD::WrapperLarge, DL, PtrVT,
2302 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ARM64II::MO_G3),
2303 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ARM64II::MO_G2 | MO_NC),
2304 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ARM64II::MO_G1 | MO_NC),
2305 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ARM64II::MO_G0 | MO_NC));
2307 // Use ADRP/ADD or ADRP/LDR for everything else: the small model on ELF and
2308 // the only correct model on Darwin.
2309 SDValue Hi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2310 OpFlags | ARM64II::MO_PAGE);
2311 unsigned char LoFlags = OpFlags | ARM64II::MO_PAGEOFF | ARM64II::MO_NC;
2312 SDValue Lo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, LoFlags);
2314 SDValue ADRP = DAG.getNode(ARM64ISD::ADRP, DL, PtrVT, Hi);
2315 return DAG.getNode(ARM64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
2319 /// \brief Convert a TLS address reference into the correct sequence of loads
2320 /// and calls to compute the variable's address (for Darwin, currently) and
2321 /// return an SDValue containing the final node.
2323 /// Darwin only has one TLS scheme which must be capable of dealing with the
2324 /// fully general situation, in the worst case. This means:
2325 /// + "extern __thread" declaration.
2326 /// + Defined in a possibly unknown dynamic library.
2328 /// The general system is that each __thread variable has a [3 x i64] descriptor
2329 /// which contains information used by the runtime to calculate the address. The
2330 /// only part of this the compiler needs to know about is the first xword, which
2331 /// contains a function pointer that must be called with the address of the
2332 /// entire descriptor in "x0".
2334 /// Since this descriptor may be in a different unit, in general even the
2335 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
2337 /// adrp x0, _var@TLVPPAGE
2338 /// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor
2339 /// ldr x1, [x0] ; x1 contains 1st entry of descriptor,
2340 /// ; the function pointer
2341 /// blr x1 ; Uses descriptor address in x0
2342 /// ; Address of _var is now in x0.
2344 /// If the address of _var's descriptor *is* known to the linker, then it can
2345 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
2346 /// a slight efficiency gain.
2348 ARM64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
2349 SelectionDAG &DAG) const {
2350 assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
2353 MVT PtrVT = getPointerTy();
2354 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2357 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ARM64II::MO_TLS);
2358 SDValue DescAddr = DAG.getNode(ARM64ISD::LOADgot, DL, PtrVT, TLVPAddr);
2360 // The first entry in the descriptor is a function pointer that we must call
2361 // to obtain the address of the variable.
2362 SDValue Chain = DAG.getEntryNode();
2363 SDValue FuncTLVGet =
2364 DAG.getLoad(MVT::i64, DL, Chain, DescAddr, MachinePointerInfo::getGOT(),
2365 false, true, true, 8);
2366 Chain = FuncTLVGet.getValue(1);
2368 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2369 MFI->setAdjustsStack(true);
2371 // TLS calls preserve all registers except those that absolutely must be
2372 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
2374 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2375 const ARM64RegisterInfo *ARI = static_cast<const ARM64RegisterInfo *>(TRI);
2376 const uint32_t *Mask = ARI->getTLSCallPreservedMask();
2378 // Finally, we can make the call. This is just a degenerate version of a
2379 // normal ARM64 call node: x0 takes the address of the descriptor, and returns
2380 // the address of the variable in this thread.
2381 Chain = DAG.getCopyToReg(Chain, DL, ARM64::X0, DescAddr, SDValue());
2382 Chain = DAG.getNode(ARM64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
2383 Chain, FuncTLVGet, DAG.getRegister(ARM64::X0, MVT::i64),
2384 DAG.getRegisterMask(Mask), Chain.getValue(1));
2385 return DAG.getCopyFromReg(Chain, DL, ARM64::X0, PtrVT, Chain.getValue(1));
2388 /// When accessing thread-local variables under either the general-dynamic or
2389 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
2390 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
2391 /// is a function pointer to carry out the resolution. This function takes the
2392 /// address of the descriptor in X0 and returns the TPIDR_EL0 offset in X0. All
2393 /// other registers (except LR, NZCV) are preserved.
2395 /// Thus, the ideal call sequence on AArch64 is:
2397 /// adrp x0, :tlsdesc:thread_var
2398 /// ldr x8, [x0, :tlsdesc_lo12:thread_var]
2399 /// add x0, x0, :tlsdesc_lo12:thread_var
2400 /// .tlsdesccall thread_var
2402 /// (TPIDR_EL0 offset now in x0).
2404 /// The ".tlsdesccall" directive instructs the assembler to insert a particular
2405 /// relocation to help the linker relax this sequence if it turns out to be too
2408 /// FIXME: we currently produce an extra, duplicated, ADRP instruction, but this
2410 SDValue ARM64TargetLowering::LowerELFTLSDescCall(SDValue SymAddr,
2411 SDValue DescAddr, SDLoc DL,
2412 SelectionDAG &DAG) const {
2413 EVT PtrVT = getPointerTy();
2415 // The function we need to call is simply the first entry in the GOT for this
2416 // descriptor, load it in preparation.
2417 SDValue Func = DAG.getNode(ARM64ISD::LOADgot, DL, PtrVT, SymAddr);
2419 // TLS calls preserve all registers except those that absolutely must be
2420 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
2422 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2423 const ARM64RegisterInfo *ARI = static_cast<const ARM64RegisterInfo *>(TRI);
2424 const uint32_t *Mask = ARI->getTLSCallPreservedMask();
2426 // The function takes only one argument: the address of the descriptor itself
2428 SDValue Glue, Chain;
2429 Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM64::X0, DescAddr, Glue);
2430 Glue = Chain.getValue(1);
2432 // We're now ready to populate the argument list, as with a normal call:
2433 SmallVector<SDValue, 6> Ops;
2434 Ops.push_back(Chain);
2435 Ops.push_back(Func);
2436 Ops.push_back(SymAddr);
2437 Ops.push_back(DAG.getRegister(ARM64::X0, PtrVT));
2438 Ops.push_back(DAG.getRegisterMask(Mask));
2439 Ops.push_back(Glue);
2441 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2442 Chain = DAG.getNode(ARM64ISD::TLSDESC_CALL, DL, NodeTys, Ops);
2443 Glue = Chain.getValue(1);
2445 return DAG.getCopyFromReg(Chain, DL, ARM64::X0, PtrVT, Glue);
2448 SDValue ARM64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
2449 SelectionDAG &DAG) const {
2450 assert(Subtarget->isTargetELF() && "This function expects an ELF target");
2451 assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
2452 "ELF TLS only supported in small memory model");
2453 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2455 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
2458 EVT PtrVT = getPointerTy();
2460 const GlobalValue *GV = GA->getGlobal();
2462 SDValue ThreadBase = DAG.getNode(ARM64ISD::THREAD_POINTER, DL, PtrVT);
2464 if (Model == TLSModel::LocalExec) {
2465 SDValue HiVar = DAG.getTargetGlobalAddress(
2466 GV, DL, PtrVT, 0, ARM64II::MO_TLS | ARM64II::MO_G1);
2467 SDValue LoVar = DAG.getTargetGlobalAddress(
2468 GV, DL, PtrVT, 0, ARM64II::MO_TLS | ARM64II::MO_G0 | ARM64II::MO_NC);
2470 TPOff = SDValue(DAG.getMachineNode(ARM64::MOVZXi, DL, PtrVT, HiVar,
2471 DAG.getTargetConstant(16, MVT::i32)),
2473 TPOff = SDValue(DAG.getMachineNode(ARM64::MOVKXi, DL, PtrVT, TPOff, LoVar,
2474 DAG.getTargetConstant(0, MVT::i32)),
2476 } else if (Model == TLSModel::InitialExec) {
2477 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ARM64II::MO_TLS);
2478 TPOff = DAG.getNode(ARM64ISD::LOADgot, DL, PtrVT, TPOff);
2479 } else if (Model == TLSModel::LocalDynamic) {
2480 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
2481 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
2482 // the beginning of the module's TLS region, followed by a DTPREL offset
2485 // These accesses will need deduplicating if there's more than one.
2486 ARM64FunctionInfo *MFI =
2487 DAG.getMachineFunction().getInfo<ARM64FunctionInfo>();
2488 MFI->incNumLocalDynamicTLSAccesses();
2490 // Accesses used in this sequence go via the TLS descriptor which lives in
2491 // the GOT. Prepare an address we can use to handle this.
2492 SDValue HiDesc = DAG.getTargetExternalSymbol(
2493 "_TLS_MODULE_BASE_", PtrVT, ARM64II::MO_TLS | ARM64II::MO_PAGE);
2494 SDValue LoDesc = DAG.getTargetExternalSymbol(
2495 "_TLS_MODULE_BASE_", PtrVT,
2496 ARM64II::MO_TLS | ARM64II::MO_PAGEOFF | ARM64II::MO_NC);
2498 // First argument to the descriptor call is the address of the descriptor
2500 SDValue DescAddr = DAG.getNode(ARM64ISD::ADRP, DL, PtrVT, HiDesc);
2501 DescAddr = DAG.getNode(ARM64ISD::ADDlow, DL, PtrVT, DescAddr, LoDesc);
2503 // The call needs a relocation too for linker relaxation. It doesn't make
2504 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
2506 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
2509 // Now we can calculate the offset from TPIDR_EL0 to this module's
2510 // thread-local area.
2511 TPOff = LowerELFTLSDescCall(SymAddr, DescAddr, DL, DAG);
2513 // Now use :dtprel_whatever: operations to calculate this variable's offset
2514 // in its thread-storage area.
2515 SDValue HiVar = DAG.getTargetGlobalAddress(
2516 GV, DL, MVT::i64, 0, ARM64II::MO_TLS | ARM64II::MO_G1);
2517 SDValue LoVar = DAG.getTargetGlobalAddress(
2518 GV, DL, MVT::i64, 0, ARM64II::MO_TLS | ARM64II::MO_G0 | ARM64II::MO_NC);
2521 SDValue(DAG.getMachineNode(ARM64::MOVZXi, DL, PtrVT, HiVar,
2522 DAG.getTargetConstant(16, MVT::i32)),
2524 DTPOff = SDValue(DAG.getMachineNode(ARM64::MOVKXi, DL, PtrVT, DTPOff, LoVar,
2525 DAG.getTargetConstant(0, MVT::i32)),
2528 TPOff = DAG.getNode(ISD::ADD, DL, PtrVT, TPOff, DTPOff);
2529 } else if (Model == TLSModel::GeneralDynamic) {
2530 // Accesses used in this sequence go via the TLS descriptor which lives in
2531 // the GOT. Prepare an address we can use to handle this.
2532 SDValue HiDesc = DAG.getTargetGlobalAddress(
2533 GV, DL, PtrVT, 0, ARM64II::MO_TLS | ARM64II::MO_PAGE);
2534 SDValue LoDesc = DAG.getTargetGlobalAddress(
2536 ARM64II::MO_TLS | ARM64II::MO_PAGEOFF | ARM64II::MO_NC);
2538 // First argument to the descriptor call is the address of the descriptor
2540 SDValue DescAddr = DAG.getNode(ARM64ISD::ADRP, DL, PtrVT, HiDesc);
2541 DescAddr = DAG.getNode(ARM64ISD::ADDlow, DL, PtrVT, DescAddr, LoDesc);
2543 // The call needs a relocation too for linker relaxation. It doesn't make
2544 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
2547 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ARM64II::MO_TLS);
2549 // Finally we can make a call to calculate the offset from tpidr_el0.
2550 TPOff = LowerELFTLSDescCall(SymAddr, DescAddr, DL, DAG);
2552 llvm_unreachable("Unsupported ELF TLS access model");
2554 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
2557 SDValue ARM64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
2558 SelectionDAG &DAG) const {
2559 if (Subtarget->isTargetDarwin())
2560 return LowerDarwinGlobalTLSAddress(Op, DAG);
2561 else if (Subtarget->isTargetELF())
2562 return LowerELFGlobalTLSAddress(Op, DAG);
2564 llvm_unreachable("Unexpected platform trying to use TLS");
2566 SDValue ARM64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
2567 SDValue Chain = Op.getOperand(0);
2568 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
2569 SDValue LHS = Op.getOperand(2);
2570 SDValue RHS = Op.getOperand(3);
2571 SDValue Dest = Op.getOperand(4);
2574 // Handle f128 first, since lowering it will result in comparing the return
2575 // value of a libcall against zero, which is just what the rest of LowerBR_CC
2576 // is expecting to deal with.
2577 if (LHS.getValueType() == MVT::f128) {
2578 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
2580 // If softenSetCCOperands returned a scalar, we need to compare the result
2581 // against zero to select between true and false values.
2582 if (!RHS.getNode()) {
2583 RHS = DAG.getConstant(0, LHS.getValueType());
2588 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
2590 unsigned Opc = LHS.getOpcode();
2591 if (LHS.getResNo() == 1 && isa<ConstantSDNode>(RHS) &&
2592 cast<ConstantSDNode>(RHS)->isOne() &&
2593 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
2594 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
2595 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
2596 "Unexpected condition code.");
2597 // Only lower legal XALUO ops.
2598 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
2601 // The actual operation with overflow check.
2602 ARM64CC::CondCode OFCC;
2603 SDValue Value, Overflow;
2604 std::tie(Value, Overflow) = getARM64XALUOOp(OFCC, LHS.getValue(0), DAG);
2606 if (CC == ISD::SETNE)
2607 OFCC = getInvertedCondCode(OFCC);
2608 SDValue CCVal = DAG.getConstant(OFCC, MVT::i32);
2610 return DAG.getNode(ARM64ISD::BRCOND, SDLoc(LHS), MVT::Other, Chain, Dest,
2614 if (LHS.getValueType().isInteger()) {
2615 assert((LHS.getValueType() == RHS.getValueType()) &&
2616 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
2618 // If the RHS of the comparison is zero, we can potentially fold this
2619 // to a specialized branch.
2620 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
2621 if (RHSC && RHSC->getZExtValue() == 0) {
2622 if (CC == ISD::SETEQ) {
2623 // See if we can use a TBZ to fold in an AND as well.
2624 // TBZ has a smaller branch displacement than CBZ. If the offset is
2625 // out of bounds, a late MI-layer pass rewrites branches.
2626 // 403.gcc is an example that hits this case.
2627 if (LHS.getOpcode() == ISD::AND &&
2628 isa<ConstantSDNode>(LHS.getOperand(1)) &&
2629 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
2630 SDValue Test = LHS.getOperand(0);
2631 uint64_t Mask = LHS.getConstantOperandVal(1);
2633 // TBZ only operates on i64's, but the ext should be free.
2634 if (Test.getValueType() == MVT::i32)
2635 Test = DAG.getAnyExtOrTrunc(Test, dl, MVT::i64);
2637 return DAG.getNode(ARM64ISD::TBZ, dl, MVT::Other, Chain, Test,
2638 DAG.getConstant(Log2_64(Mask), MVT::i64), Dest);
2641 return DAG.getNode(ARM64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
2642 } else if (CC == ISD::SETNE) {
2643 // See if we can use a TBZ to fold in an AND as well.
2644 // TBZ has a smaller branch displacement than CBZ. If the offset is
2645 // out of bounds, a late MI-layer pass rewrites branches.
2646 // 403.gcc is an example that hits this case.
2647 if (LHS.getOpcode() == ISD::AND &&
2648 isa<ConstantSDNode>(LHS.getOperand(1)) &&
2649 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
2650 SDValue Test = LHS.getOperand(0);
2651 uint64_t Mask = LHS.getConstantOperandVal(1);
2653 // TBNZ only operates on i64's, but the ext should be free.
2654 if (Test.getValueType() == MVT::i32)
2655 Test = DAG.getAnyExtOrTrunc(Test, dl, MVT::i64);
2657 return DAG.getNode(ARM64ISD::TBNZ, dl, MVT::Other, Chain, Test,
2658 DAG.getConstant(Log2_64(Mask), MVT::i64), Dest);
2661 return DAG.getNode(ARM64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
2666 SDValue Cmp = getARM64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
2667 return DAG.getNode(ARM64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
2671 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
2673 // Unfortunately, the mapping of LLVM FP CC's onto ARM64 CC's isn't totally
2674 // clean. Some of them require two branches to implement.
2675 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
2676 ARM64CC::CondCode CC1, CC2;
2677 changeFPCCToARM64CC(CC, CC1, CC2);
2678 SDValue CC1Val = DAG.getConstant(CC1, MVT::i32);
2680 DAG.getNode(ARM64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
2681 if (CC2 != ARM64CC::AL) {
2682 SDValue CC2Val = DAG.getConstant(CC2, MVT::i32);
2683 return DAG.getNode(ARM64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
2690 SDValue ARM64TargetLowering::LowerFCOPYSIGN(SDValue Op,
2691 SelectionDAG &DAG) const {
2692 EVT VT = Op.getValueType();
2695 SDValue In1 = Op.getOperand(0);
2696 SDValue In2 = Op.getOperand(1);
2697 EVT SrcVT = In2.getValueType();
2699 if (SrcVT == MVT::f32 && VT == MVT::f64)
2700 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
2701 else if (SrcVT == MVT::f64 && VT == MVT::f32)
2702 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0));
2704 // FIXME: Src type is different, bail out for now. Can VT really be a
2711 SDValue EltMask, VecVal1, VecVal2;
2712 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
2715 EltMask = DAG.getConstant(0x80000000ULL, EltVT);
2717 if (!VT.isVector()) {
2718 VecVal1 = DAG.getTargetInsertSubreg(ARM64::ssub, DL, VecVT,
2719 DAG.getUNDEF(VecVT), In1);
2720 VecVal2 = DAG.getTargetInsertSubreg(ARM64::ssub, DL, VecVT,
2721 DAG.getUNDEF(VecVT), In2);
2723 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
2724 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
2726 } else if (VT == MVT::f64 || VT == MVT::v2f64) {
2730 // We want to materialize a mask with the the high bit set, but the AdvSIMD
2731 // immediate moves cannot materialize that in a single instruction for
2732 // 64-bit elements. Instead, materialize zero and then negate it.
2733 EltMask = DAG.getConstant(0, EltVT);
2735 if (!VT.isVector()) {
2736 VecVal1 = DAG.getTargetInsertSubreg(ARM64::dsub, DL, VecVT,
2737 DAG.getUNDEF(VecVT), In1);
2738 VecVal2 = DAG.getTargetInsertSubreg(ARM64::dsub, DL, VecVT,
2739 DAG.getUNDEF(VecVT), In2);
2741 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
2742 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
2745 llvm_unreachable("Invalid type for copysign!");
2748 std::vector<SDValue> BuildVectorOps;
2749 for (unsigned i = 0; i < VecVT.getVectorNumElements(); ++i)
2750 BuildVectorOps.push_back(EltMask);
2752 SDValue BuildVec = DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, BuildVectorOps);
2754 // If we couldn't materialize the mask above, then the mask vector will be
2755 // the zero vector, and we need to negate it here.
2756 if (VT == MVT::f64 || VT == MVT::v2f64) {
2757 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
2758 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
2759 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
2763 DAG.getNode(ARM64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
2766 return DAG.getTargetExtractSubreg(ARM64::ssub, DL, VT, Sel);
2767 else if (VT == MVT::f64)
2768 return DAG.getTargetExtractSubreg(ARM64::dsub, DL, VT, Sel);
2770 return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
2773 SDValue ARM64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
2774 if (DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
2775 AttributeSet::FunctionIndex, Attribute::NoImplicitFloat))
2778 // While there is no integer popcount instruction, it can
2779 // be more efficiently lowered to the following sequence that uses
2780 // AdvSIMD registers/instructions as long as the copies to/from
2781 // the AdvSIMD registers are cheap.
2782 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd
2783 // CNT V0.8B, V0.8B // 8xbyte pop-counts
2784 // ADDV B0, V0.8B // sum 8xbyte pop-counts
2785 // UMOV X0, V0.B[0] // copy byte result back to integer reg
2786 SDValue Val = Op.getOperand(0);
2788 EVT VT = Op.getValueType();
2789 SDValue ZeroVec = DAG.getUNDEF(MVT::v8i8);
2792 if (VT == MVT::i32) {
2793 VecVal = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val);
2795 DAG.getTargetInsertSubreg(ARM64::ssub, DL, MVT::v8i8, ZeroVec, VecVal);
2797 VecVal = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
2800 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, VecVal);
2801 SDValue UaddLV = DAG.getNode(
2802 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
2803 DAG.getConstant(Intrinsic::arm64_neon_uaddlv, MVT::i32), CtPop);
2806 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
2810 SDValue ARM64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2812 if (Op.getValueType().isVector())
2813 return LowerVSETCC(Op, DAG);
2815 SDValue LHS = Op.getOperand(0);
2816 SDValue RHS = Op.getOperand(1);
2817 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2820 // We chose ZeroOrOneBooleanContents, so use zero and one.
2821 EVT VT = Op.getValueType();
2822 SDValue TVal = DAG.getConstant(1, VT);
2823 SDValue FVal = DAG.getConstant(0, VT);
2825 // Handle f128 first, since one possible outcome is a normal integer
2826 // comparison which gets picked up by the next if statement.
2827 if (LHS.getValueType() == MVT::f128) {
2828 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
2830 // If softenSetCCOperands returned a scalar, use it.
2831 if (!RHS.getNode()) {
2832 assert(LHS.getValueType() == Op.getValueType() &&
2833 "Unexpected setcc expansion!");
2838 if (LHS.getValueType().isInteger()) {
2841 getARM64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
2843 // Note that we inverted the condition above, so we reverse the order of
2844 // the true and false operands here. This will allow the setcc to be
2845 // matched to a single CSINC instruction.
2846 return DAG.getNode(ARM64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
2849 // Now we know we're dealing with FP values.
2850 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
2852 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
2853 // and do the comparison.
2854 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
2856 ARM64CC::CondCode CC1, CC2;
2857 changeFPCCToARM64CC(CC, CC1, CC2);
2858 if (CC2 == ARM64CC::AL) {
2859 changeFPCCToARM64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
2860 SDValue CC1Val = DAG.getConstant(CC1, MVT::i32);
2862 // Note that we inverted the condition above, so we reverse the order of
2863 // the true and false operands here. This will allow the setcc to be
2864 // matched to a single CSINC instruction.
2865 return DAG.getNode(ARM64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
2867 // Unfortunately, the mapping of LLVM FP CC's onto ARM64 CC's isn't totally
2868 // clean. Some of them require two CSELs to implement. As is in this case,
2869 // we emit the first CSEL and then emit a second using the output of the
2870 // first as the RHS. We're effectively OR'ing the two CC's together.
2872 // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
2873 SDValue CC1Val = DAG.getConstant(CC1, MVT::i32);
2874 SDValue CS1 = DAG.getNode(ARM64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
2876 SDValue CC2Val = DAG.getConstant(CC2, MVT::i32);
2877 return DAG.getNode(ARM64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
2881 /// A SELECT_CC operation is really some kind of max or min if both values being
2882 /// compared are, in some sense, equal to the results in either case. However,
2883 /// it is permissible to compare f32 values and produce directly extended f64
2886 /// Extending the comparison operands would also be allowed, but is less likely
2887 /// to happen in practice since their use is right here. Note that truncate
2888 /// operations would *not* be semantically equivalent.
2889 static bool selectCCOpsAreFMaxCompatible(SDValue Cmp, SDValue Result) {
2893 ConstantFPSDNode *CCmp = dyn_cast<ConstantFPSDNode>(Cmp);
2894 ConstantFPSDNode *CResult = dyn_cast<ConstantFPSDNode>(Result);
2895 if (CCmp && CResult && Cmp.getValueType() == MVT::f32 &&
2896 Result.getValueType() == MVT::f64) {
2898 APFloat CmpVal = CCmp->getValueAPF();
2899 CmpVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &Lossy);
2900 return CResult->getValueAPF().bitwiseIsEqual(CmpVal);
2903 return Result->getOpcode() == ISD::FP_EXTEND && Result->getOperand(0) == Cmp;
2906 SDValue ARM64TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
2907 SDValue CC = Op->getOperand(0);
2908 SDValue TVal = Op->getOperand(1);
2909 SDValue FVal = Op->getOperand(2);
2912 unsigned Opc = CC.getOpcode();
2913 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
2915 if (CC.getResNo() == 1 &&
2916 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
2917 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
2918 // Only lower legal XALUO ops.
2919 if (!DAG.getTargetLoweringInfo().isTypeLegal(CC->getValueType(0)))
2922 ARM64CC::CondCode OFCC;
2923 SDValue Value, Overflow;
2924 std::tie(Value, Overflow) = getARM64XALUOOp(OFCC, CC.getValue(0), DAG);
2925 SDValue CCVal = DAG.getConstant(OFCC, MVT::i32);
2927 return DAG.getNode(ARM64ISD::CSEL, DL, Op.getValueType(), TVal, FVal, CCVal,
2931 if (CC.getOpcode() == ISD::SETCC)
2932 return DAG.getSelectCC(DL, CC.getOperand(0), CC.getOperand(1), TVal, FVal,
2933 cast<CondCodeSDNode>(CC.getOperand(2))->get());
2935 return DAG.getSelectCC(DL, CC, DAG.getConstant(0, CC.getValueType()), TVal,
2939 SDValue ARM64TargetLowering::LowerSELECT_CC(SDValue Op,
2940 SelectionDAG &DAG) const {
2941 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
2942 SDValue LHS = Op.getOperand(0);
2943 SDValue RHS = Op.getOperand(1);
2944 SDValue TVal = Op.getOperand(2);
2945 SDValue FVal = Op.getOperand(3);
2948 // Handle f128 first, because it will result in a comparison of some RTLIB
2949 // call result against zero.
2950 if (LHS.getValueType() == MVT::f128) {
2951 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
2953 // If softenSetCCOperands returned a scalar, we need to compare the result
2954 // against zero to select between true and false values.
2955 if (!RHS.getNode()) {
2956 RHS = DAG.getConstant(0, LHS.getValueType());
2961 // Handle integers first.
2962 if (LHS.getValueType().isInteger()) {
2963 assert((LHS.getValueType() == RHS.getValueType()) &&
2964 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
2966 unsigned Opcode = ARM64ISD::CSEL;
2968 // If both the TVal and the FVal are constants, see if we can swap them in
2969 // order to for a CSINV or CSINC out of them.
2970 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
2971 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
2973 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
2974 std::swap(TVal, FVal);
2975 std::swap(CTVal, CFVal);
2976 CC = ISD::getSetCCInverse(CC, true);
2977 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
2978 std::swap(TVal, FVal);
2979 std::swap(CTVal, CFVal);
2980 CC = ISD::getSetCCInverse(CC, true);
2981 } else if (TVal.getOpcode() == ISD::XOR) {
2982 // If TVal is a NOT we want to swap TVal and FVal so that we can match
2983 // with a CSINV rather than a CSEL.
2984 ConstantSDNode *CVal = dyn_cast<ConstantSDNode>(TVal.getOperand(1));
2986 if (CVal && CVal->isAllOnesValue()) {
2987 std::swap(TVal, FVal);
2988 std::swap(CTVal, CFVal);
2989 CC = ISD::getSetCCInverse(CC, true);
2991 } else if (TVal.getOpcode() == ISD::SUB) {
2992 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
2993 // that we can match with a CSNEG rather than a CSEL.
2994 ConstantSDNode *CVal = dyn_cast<ConstantSDNode>(TVal.getOperand(0));
2996 if (CVal && CVal->isNullValue()) {
2997 std::swap(TVal, FVal);
2998 std::swap(CTVal, CFVal);
2999 CC = ISD::getSetCCInverse(CC, true);
3001 } else if (CTVal && CFVal) {
3002 const int64_t TrueVal = CTVal->getSExtValue();
3003 const int64_t FalseVal = CFVal->getSExtValue();
3006 // If both TVal and FVal are constants, see if FVal is the
3007 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
3008 // instead of a CSEL in that case.
3009 if (TrueVal == ~FalseVal) {
3010 Opcode = ARM64ISD::CSINV;
3011 } else if (TrueVal == -FalseVal) {
3012 Opcode = ARM64ISD::CSNEG;
3013 } else if (TVal.getValueType() == MVT::i32) {
3014 // If our operands are only 32-bit wide, make sure we use 32-bit
3015 // arithmetic for the check whether we can use CSINC. This ensures that
3016 // the addition in the check will wrap around properly in case there is
3017 // an overflow (which would not be the case if we do the check with
3018 // 64-bit arithmetic).
3019 const uint32_t TrueVal32 = CTVal->getZExtValue();
3020 const uint32_t FalseVal32 = CFVal->getZExtValue();
3022 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
3023 Opcode = ARM64ISD::CSINC;
3025 if (TrueVal32 > FalseVal32) {
3029 // 64-bit check whether we can use CSINC.
3030 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
3031 Opcode = ARM64ISD::CSINC;
3033 if (TrueVal > FalseVal) {
3038 // Swap TVal and FVal if necessary.
3040 std::swap(TVal, FVal);
3041 std::swap(CTVal, CFVal);
3042 CC = ISD::getSetCCInverse(CC, true);
3045 if (Opcode != ARM64ISD::CSEL) {
3046 // Drop FVal since we can get its value by simply inverting/negating
3053 SDValue Cmp = getARM64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3055 EVT VT = Op.getValueType();
3056 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
3059 // Now we know we're dealing with FP values.
3060 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3061 assert(LHS.getValueType() == RHS.getValueType());
3062 EVT VT = Op.getValueType();
3064 // Try to match this select into a max/min operation, which have dedicated
3065 // opcode in the instruction set.
3066 // NOTE: This is not correct in the presence of NaNs, so we only enable this
3068 if (getTargetMachine().Options.NoNaNsFPMath) {
3069 if (selectCCOpsAreFMaxCompatible(LHS, FVal) &&
3070 selectCCOpsAreFMaxCompatible(RHS, TVal)) {
3071 CC = ISD::getSetCCSwappedOperands(CC);
3072 std::swap(TVal, FVal);
3075 if (selectCCOpsAreFMaxCompatible(LHS, TVal) &&
3076 selectCCOpsAreFMaxCompatible(RHS, FVal)) {
3086 return DAG.getNode(ARM64ISD::FMAX, dl, VT, TVal, FVal);
3094 return DAG.getNode(ARM64ISD::FMIN, dl, VT, TVal, FVal);
3100 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
3101 // and do the comparison.
3102 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3104 // Unfortunately, the mapping of LLVM FP CC's onto ARM64 CC's isn't totally
3105 // clean. Some of them require two CSELs to implement.
3106 ARM64CC::CondCode CC1, CC2;
3107 changeFPCCToARM64CC(CC, CC1, CC2);
3108 SDValue CC1Val = DAG.getConstant(CC1, MVT::i32);
3109 SDValue CS1 = DAG.getNode(ARM64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3111 // If we need a second CSEL, emit it, using the output of the first as the
3112 // RHS. We're effectively OR'ing the two CC's together.
3113 if (CC2 != ARM64CC::AL) {
3114 SDValue CC2Val = DAG.getConstant(CC2, MVT::i32);
3115 return DAG.getNode(ARM64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3118 // Otherwise, return the output of the first CSEL.
3122 SDValue ARM64TargetLowering::LowerJumpTable(SDValue Op,
3123 SelectionDAG &DAG) const {
3124 // Jump table entries as PC relative offsets. No additional tweaking
3125 // is necessary here. Just get the address of the jump table.
3126 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
3127 EVT PtrVT = getPointerTy();
3130 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3131 !Subtarget->isTargetMachO()) {
3132 const unsigned char MO_NC = ARM64II::MO_NC;
3134 ARM64ISD::WrapperLarge, DL, PtrVT,
3135 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, ARM64II::MO_G3),
3136 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, ARM64II::MO_G2 | MO_NC),
3137 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, ARM64II::MO_G1 | MO_NC),
3138 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, ARM64II::MO_G0 | MO_NC));
3141 SDValue Hi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, ARM64II::MO_PAGE);
3142 SDValue Lo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
3143 ARM64II::MO_PAGEOFF | ARM64II::MO_NC);
3144 SDValue ADRP = DAG.getNode(ARM64ISD::ADRP, DL, PtrVT, Hi);
3145 return DAG.getNode(ARM64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3148 SDValue ARM64TargetLowering::LowerConstantPool(SDValue Op,
3149 SelectionDAG &DAG) const {
3150 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3151 EVT PtrVT = getPointerTy();
3154 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
3155 // Use the GOT for the large code model on iOS.
3156 if (Subtarget->isTargetMachO()) {
3157 SDValue GotAddr = DAG.getTargetConstantPool(
3158 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
3160 return DAG.getNode(ARM64ISD::LOADgot, DL, PtrVT, GotAddr);
3163 const unsigned char MO_NC = ARM64II::MO_NC;
3165 ARM64ISD::WrapperLarge, DL, PtrVT,
3166 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3167 CP->getOffset(), ARM64II::MO_G3),
3168 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3169 CP->getOffset(), ARM64II::MO_G2 | MO_NC),
3170 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3171 CP->getOffset(), ARM64II::MO_G1 | MO_NC),
3172 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3173 CP->getOffset(), ARM64II::MO_G0 | MO_NC));
3175 // Use ADRP/ADD or ADRP/LDR for everything else: the small memory model on
3176 // ELF, the only valid one on Darwin.
3178 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3179 CP->getOffset(), ARM64II::MO_PAGE);
3180 SDValue Lo = DAG.getTargetConstantPool(
3181 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
3182 ARM64II::MO_PAGEOFF | ARM64II::MO_NC);
3184 SDValue ADRP = DAG.getNode(ARM64ISD::ADRP, DL, PtrVT, Hi);
3185 return DAG.getNode(ARM64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3189 SDValue ARM64TargetLowering::LowerBlockAddress(SDValue Op,
3190 SelectionDAG &DAG) const {
3191 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
3192 EVT PtrVT = getPointerTy();
3194 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3195 !Subtarget->isTargetMachO()) {
3196 const unsigned char MO_NC = ARM64II::MO_NC;
3198 ARM64ISD::WrapperLarge, DL, PtrVT,
3199 DAG.getTargetBlockAddress(BA, PtrVT, 0, ARM64II::MO_G3),
3200 DAG.getTargetBlockAddress(BA, PtrVT, 0, ARM64II::MO_G2 | MO_NC),
3201 DAG.getTargetBlockAddress(BA, PtrVT, 0, ARM64II::MO_G1 | MO_NC),
3202 DAG.getTargetBlockAddress(BA, PtrVT, 0, ARM64II::MO_G0 | MO_NC));
3204 SDValue Hi = DAG.getTargetBlockAddress(BA, PtrVT, 0, ARM64II::MO_PAGE);
3205 SDValue Lo = DAG.getTargetBlockAddress(BA, PtrVT, 0, ARM64II::MO_PAGEOFF |
3207 SDValue ADRP = DAG.getNode(ARM64ISD::ADRP, DL, PtrVT, Hi);
3208 return DAG.getNode(ARM64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3212 SDValue ARM64TargetLowering::LowerDarwin_VASTART(SDValue Op,
3213 SelectionDAG &DAG) const {
3214 ARM64FunctionInfo *FuncInfo =
3215 DAG.getMachineFunction().getInfo<ARM64FunctionInfo>();
3219 DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), getPointerTy());
3220 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3221 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
3222 MachinePointerInfo(SV), false, false, 0);
3225 SDValue ARM64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
3226 SelectionDAG &DAG) const {
3227 // The layout of the va_list struct is specified in the AArch64 Procedure Call
3228 // Standard, section B.3.
3229 MachineFunction &MF = DAG.getMachineFunction();
3230 ARM64FunctionInfo *FuncInfo = MF.getInfo<ARM64FunctionInfo>();
3233 SDValue Chain = Op.getOperand(0);
3234 SDValue VAList = Op.getOperand(1);
3235 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3236 SmallVector<SDValue, 4> MemOps;
3238 // void *__stack at offset 0
3240 DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), getPointerTy());
3241 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
3242 MachinePointerInfo(SV), false, false, 8));
3244 // void *__gr_top at offset 8
3245 int GPRSize = FuncInfo->getVarArgsGPRSize();
3247 SDValue GRTop, GRTopAddr;
3249 GRTopAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3250 DAG.getConstant(8, getPointerTy()));
3252 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), getPointerTy());
3253 GRTop = DAG.getNode(ISD::ADD, DL, getPointerTy(), GRTop,
3254 DAG.getConstant(GPRSize, getPointerTy()));
3256 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
3257 MachinePointerInfo(SV, 8), false, false, 8));
3260 // void *__vr_top at offset 16
3261 int FPRSize = FuncInfo->getVarArgsFPRSize();
3263 SDValue VRTop, VRTopAddr;
3264 VRTopAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3265 DAG.getConstant(16, getPointerTy()));
3267 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), getPointerTy());
3268 VRTop = DAG.getNode(ISD::ADD, DL, getPointerTy(), VRTop,
3269 DAG.getConstant(FPRSize, getPointerTy()));
3271 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
3272 MachinePointerInfo(SV, 16), false, false, 8));
3275 // int __gr_offs at offset 24
3276 SDValue GROffsAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3277 DAG.getConstant(24, getPointerTy()));
3278 MemOps.push_back(DAG.getStore(Chain, DL, DAG.getConstant(-GPRSize, MVT::i32),
3279 GROffsAddr, MachinePointerInfo(SV, 24), false,
3282 // int __vr_offs at offset 28
3283 SDValue VROffsAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3284 DAG.getConstant(28, getPointerTy()));
3285 MemOps.push_back(DAG.getStore(Chain, DL, DAG.getConstant(-FPRSize, MVT::i32),
3286 VROffsAddr, MachinePointerInfo(SV, 28), false,
3289 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
3292 SDValue ARM64TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3293 return Subtarget->isTargetDarwin() ? LowerDarwin_VASTART(Op, DAG)
3294 : LowerAAPCS_VASTART(Op, DAG);
3297 SDValue ARM64TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
3298 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
3300 unsigned VaListSize = Subtarget->isTargetDarwin() ? 8 : 32;
3301 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
3302 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
3304 return DAG.getMemcpy(Op.getOperand(0), SDLoc(Op), Op.getOperand(1),
3305 Op.getOperand(2), DAG.getConstant(VaListSize, MVT::i32),
3306 8, false, false, MachinePointerInfo(DestSV),
3307 MachinePointerInfo(SrcSV));
3310 SDValue ARM64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
3311 assert(Subtarget->isTargetDarwin() &&
3312 "automatic va_arg instruction only works on Darwin");
3314 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3315 EVT VT = Op.getValueType();
3317 SDValue Chain = Op.getOperand(0);
3318 SDValue Addr = Op.getOperand(1);
3319 unsigned Align = Op.getConstantOperandVal(3);
3321 SDValue VAList = DAG.getLoad(getPointerTy(), DL, Chain, Addr,
3322 MachinePointerInfo(V), false, false, false, 0);
3323 Chain = VAList.getValue(1);
3326 assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
3327 VAList = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3328 DAG.getConstant(Align - 1, getPointerTy()));
3329 VAList = DAG.getNode(ISD::AND, DL, getPointerTy(), VAList,
3330 DAG.getConstant(-(int64_t)Align, getPointerTy()));
3333 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
3334 uint64_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
3336 // Scalar integer and FP values smaller than 64 bits are implicitly extended
3337 // up to 64 bits. At the very least, we have to increase the striding of the
3338 // vaargs list to match this, and for FP values we need to introduce
3339 // FP_ROUND nodes as well.
3340 if (VT.isInteger() && !VT.isVector())
3342 bool NeedFPTrunc = false;
3343 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
3348 // Increment the pointer, VAList, to the next vaarg
3349 SDValue VANext = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3350 DAG.getConstant(ArgSize, getPointerTy()));
3351 // Store the incremented VAList to the legalized pointer
3352 SDValue APStore = DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V),
3355 // Load the actual argument out of the pointer VAList
3357 // Load the value as an f64.
3358 SDValue WideFP = DAG.getLoad(MVT::f64, DL, APStore, VAList,
3359 MachinePointerInfo(), false, false, false, 0);
3360 // Round the value down to an f32.
3361 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
3362 DAG.getIntPtrConstant(1));
3363 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
3364 // Merge the rounded value with the chain output of the load.
3365 return DAG.getMergeValues(Ops, DL);
3368 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo(), false,
3372 SDValue ARM64TargetLowering::LowerFRAMEADDR(SDValue Op,
3373 SelectionDAG &DAG) const {
3374 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3375 MFI->setFrameAddressIsTaken(true);
3377 EVT VT = Op.getValueType();
3379 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3380 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, ARM64::FP, VT);
3382 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
3383 MachinePointerInfo(), false, false, false, 0);
3387 SDValue ARM64TargetLowering::LowerRETURNADDR(SDValue Op,
3388 SelectionDAG &DAG) const {
3389 MachineFunction &MF = DAG.getMachineFunction();
3390 MachineFrameInfo *MFI = MF.getFrameInfo();
3391 MFI->setReturnAddressIsTaken(true);
3393 EVT VT = Op.getValueType();
3395 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3397 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3398 SDValue Offset = DAG.getConstant(8, getPointerTy());
3399 return DAG.getLoad(VT, DL, DAG.getEntryNode(),
3400 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
3401 MachinePointerInfo(), false, false, false, 0);
3404 // Return LR, which contains the return address. Mark it an implicit live-in.
3405 unsigned Reg = MF.addLiveIn(ARM64::LR, &ARM64::GPR64RegClass);
3406 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
3409 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3410 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
3411 SDValue ARM64TargetLowering::LowerShiftRightParts(SDValue Op,
3412 SelectionDAG &DAG) const {
3413 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3414 EVT VT = Op.getValueType();
3415 unsigned VTBits = VT.getSizeInBits();
3417 SDValue ShOpLo = Op.getOperand(0);
3418 SDValue ShOpHi = Op.getOperand(1);
3419 SDValue ShAmt = Op.getOperand(2);
3421 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3423 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3425 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
3426 DAG.getConstant(VTBits, MVT::i64), ShAmt);
3427 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3428 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
3429 DAG.getConstant(VTBits, MVT::i64));
3430 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3432 SDValue Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, MVT::i64),
3433 ISD::SETGE, dl, DAG);
3434 SDValue CCVal = DAG.getConstant(ARM64CC::GE, MVT::i32);
3436 SDValue FalseValLo = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3437 SDValue TrueValLo = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3439 DAG.getNode(ARM64ISD::CSEL, dl, VT, TrueValLo, FalseValLo, CCVal, Cmp);
3441 // ARM64 shifts larger than the register width are wrapped rather than
3442 // clamped, so we can't just emit "hi >> x".
3443 SDValue FalseValHi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3444 SDValue TrueValHi = Opc == ISD::SRA
3445 ? DAG.getNode(Opc, dl, VT, ShOpHi,
3446 DAG.getConstant(VTBits - 1, MVT::i64))
3447 : DAG.getConstant(0, VT);
3449 DAG.getNode(ARM64ISD::CSEL, dl, VT, TrueValHi, FalseValHi, CCVal, Cmp);
3451 SDValue Ops[2] = { Lo, Hi };
3452 return DAG.getMergeValues(Ops, dl);
3455 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3456 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
3457 SDValue ARM64TargetLowering::LowerShiftLeftParts(SDValue Op,
3458 SelectionDAG &DAG) const {
3459 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3460 EVT VT = Op.getValueType();
3461 unsigned VTBits = VT.getSizeInBits();
3463 SDValue ShOpLo = Op.getOperand(0);
3464 SDValue ShOpHi = Op.getOperand(1);
3465 SDValue ShAmt = Op.getOperand(2);
3468 assert(Op.getOpcode() == ISD::SHL_PARTS);
3469 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
3470 DAG.getConstant(VTBits, MVT::i64), ShAmt);
3471 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3472 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
3473 DAG.getConstant(VTBits, MVT::i64));
3474 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3475 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3477 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3479 SDValue Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, MVT::i64),
3480 ISD::SETGE, dl, DAG);
3481 SDValue CCVal = DAG.getConstant(ARM64CC::GE, MVT::i32);
3482 SDValue Hi = DAG.getNode(ARM64ISD::CSEL, dl, VT, Tmp3, FalseVal, CCVal, Cmp);
3484 // ARM64 shifts of larger than register sizes are wrapped rather than clamped,
3485 // so we can't just emit "lo << a" if a is too big.
3486 SDValue TrueValLo = DAG.getConstant(0, VT);
3487 SDValue FalseValLo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3489 DAG.getNode(ARM64ISD::CSEL, dl, VT, TrueValLo, FalseValLo, CCVal, Cmp);
3491 SDValue Ops[2] = { Lo, Hi };
3492 return DAG.getMergeValues(Ops, dl);
3496 ARM64TargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3497 // The ARM64 target doesn't support folding offsets into global addresses.
3501 bool ARM64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3502 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
3503 // FIXME: We should be able to handle f128 as well with a clever lowering.
3504 if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32))
3508 return ARM64_AM::getFP64Imm(Imm) != -1;
3509 else if (VT == MVT::f32)
3510 return ARM64_AM::getFP32Imm(Imm) != -1;
3514 //===----------------------------------------------------------------------===//
3515 // ARM64 Optimization Hooks
3516 //===----------------------------------------------------------------------===//
3518 //===----------------------------------------------------------------------===//
3519 // ARM64 Inline Assembly Support
3520 //===----------------------------------------------------------------------===//
3522 // Table of Constraints
3523 // TODO: This is the current set of constraints supported by ARM for the
3524 // compiler, not all of them may make sense, e.g. S may be difficult to support.
3526 // r - A general register
3527 // w - An FP/SIMD register of some size in the range v0-v31
3528 // x - An FP/SIMD register of some size in the range v0-v15
3529 // I - Constant that can be used with an ADD instruction
3530 // J - Constant that can be used with a SUB instruction
3531 // K - Constant that can be used with a 32-bit logical instruction
3532 // L - Constant that can be used with a 64-bit logical instruction
3533 // M - Constant that can be used as a 32-bit MOV immediate
3534 // N - Constant that can be used as a 64-bit MOV immediate
3535 // Q - A memory reference with base register and no offset
3536 // S - A symbolic address
3537 // Y - Floating point constant zero
3538 // Z - Integer constant zero
3540 // Note that general register operands will be output using their 64-bit x
3541 // register name, whatever the size of the variable, unless the asm operand
3542 // is prefixed by the %w modifier. Floating-point and SIMD register operands
3543 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
3546 /// getConstraintType - Given a constraint letter, return the type of
3547 /// constraint it is for this target.
3548 ARM64TargetLowering::ConstraintType
3549 ARM64TargetLowering::getConstraintType(const std::string &Constraint) const {
3550 if (Constraint.size() == 1) {
3551 switch (Constraint[0]) {
3558 return C_RegisterClass;
3559 // An address with a single base register. Due to the way we
3560 // currently handle addresses it is the same as 'r'.
3565 return TargetLowering::getConstraintType(Constraint);
3568 /// Examine constraint type and operand type and determine a weight value.
3569 /// This object must already have been set up with the operand type
3570 /// and the current alternative constraint selected.
3571 TargetLowering::ConstraintWeight
3572 ARM64TargetLowering::getSingleConstraintMatchWeight(
3573 AsmOperandInfo &info, const char *constraint) const {
3574 ConstraintWeight weight = CW_Invalid;
3575 Value *CallOperandVal = info.CallOperandVal;
3576 // If we don't have a value, we can't do a match,
3577 // but allow it at the lowest weight.
3578 if (!CallOperandVal)
3580 Type *type = CallOperandVal->getType();
3581 // Look at the constraint type.
3582 switch (*constraint) {
3584 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
3588 if (type->isFloatingPointTy() || type->isVectorTy())
3589 weight = CW_Register;
3592 weight = CW_Constant;
3598 std::pair<unsigned, const TargetRegisterClass *>
3599 ARM64TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
3601 if (Constraint.size() == 1) {
3602 switch (Constraint[0]) {
3604 if (VT.getSizeInBits() == 64)
3605 return std::make_pair(0U, &ARM64::GPR64commonRegClass);
3606 return std::make_pair(0U, &ARM64::GPR32commonRegClass);
3609 return std::make_pair(0U, &ARM64::FPR32RegClass);
3610 if (VT.getSizeInBits() == 64)
3611 return std::make_pair(0U, &ARM64::FPR64RegClass);
3612 if (VT.getSizeInBits() == 128)
3613 return std::make_pair(0U, &ARM64::FPR128RegClass);
3615 // The instructions that this constraint is designed for can
3616 // only take 128-bit registers so just use that regclass.
3618 if (VT.getSizeInBits() == 128)
3619 return std::make_pair(0U, &ARM64::FPR128_loRegClass);
3623 if (StringRef("{cc}").equals_lower(Constraint))
3624 return std::make_pair(unsigned(ARM64::NZCV), &ARM64::CCRRegClass);
3626 // Use the default implementation in TargetLowering to convert the register
3627 // constraint into a member of a register class.
3628 std::pair<unsigned, const TargetRegisterClass *> Res;
3629 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
3631 // Not found as a standard register?
3633 unsigned Size = Constraint.size();
3634 if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
3635 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
3636 const std::string Reg =
3637 std::string(&Constraint[2], &Constraint[Size - 1]);
3638 int RegNo = atoi(Reg.c_str());
3639 if (RegNo >= 0 && RegNo <= 31) {
3640 // v0 - v31 are aliases of q0 - q31.
3641 // By default we'll emit v0-v31 for this unless there's a modifier where
3642 // we'll emit the correct register as well.
3643 Res.first = ARM64::FPR128RegClass.getRegister(RegNo);
3644 Res.second = &ARM64::FPR128RegClass;
3652 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3653 /// vector. If it is invalid, don't add anything to Ops.
3654 void ARM64TargetLowering::LowerAsmOperandForConstraint(
3655 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
3656 SelectionDAG &DAG) const {
3659 // Currently only support length 1 constraints.
3660 if (Constraint.length() != 1)
3663 char ConstraintLetter = Constraint[0];
3664 switch (ConstraintLetter) {
3668 // This set of constraints deal with valid constants for various instructions.
3669 // Validate and return a target constant for them if we can.
3671 // 'z' maps to xzr or wzr so it needs an input of 0.
3672 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3673 if (!C || C->getZExtValue() != 0)
3676 if (Op.getValueType() == MVT::i64)
3677 Result = DAG.getRegister(ARM64::XZR, MVT::i64);
3679 Result = DAG.getRegister(ARM64::WZR, MVT::i32);
3689 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3693 // Grab the value and do some validation.
3694 uint64_t CVal = C->getZExtValue();
3695 switch (ConstraintLetter) {
3696 // The I constraint applies only to simple ADD or SUB immediate operands:
3697 // i.e. 0 to 4095 with optional shift by 12
3698 // The J constraint applies only to ADD or SUB immediates that would be
3699 // valid when negated, i.e. if [an add pattern] were to be output as a SUB
3700 // instruction [or vice versa], in other words -1 to -4095 with optional
3701 // left shift by 12.
3703 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
3707 uint64_t NVal = -C->getSExtValue();
3708 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal))
3712 // The K and L constraints apply *only* to logical immediates, including
3713 // what used to be the MOVI alias for ORR (though the MOVI alias has now
3714 // been removed and MOV should be used). So these constraints have to
3715 // distinguish between bit patterns that are valid 32-bit or 64-bit
3716 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
3717 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
3720 if (ARM64_AM::isLogicalImmediate(CVal, 32))
3724 if (ARM64_AM::isLogicalImmediate(CVal, 64))
3727 // The M and N constraints are a superset of K and L respectively, for use
3728 // with the MOV (immediate) alias. As well as the logical immediates they
3729 // also match 32 or 64-bit immediates that can be loaded either using a
3730 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
3731 // (M) or 64-bit 0x1234000000000000 (N) etc.
3732 // As a note some of this code is liberally stolen from the asm parser.
3734 if (!isUInt<32>(CVal))
3736 if (ARM64_AM::isLogicalImmediate(CVal, 32))
3738 if ((CVal & 0xFFFF) == CVal)
3740 if ((CVal & 0xFFFF0000ULL) == CVal)
3742 uint64_t NCVal = ~(uint32_t)CVal;
3743 if ((NCVal & 0xFFFFULL) == NCVal)
3745 if ((NCVal & 0xFFFF0000ULL) == NCVal)
3750 if (ARM64_AM::isLogicalImmediate(CVal, 64))
3752 if ((CVal & 0xFFFFULL) == CVal)
3754 if ((CVal & 0xFFFF0000ULL) == CVal)
3756 if ((CVal & 0xFFFF00000000ULL) == CVal)
3758 if ((CVal & 0xFFFF000000000000ULL) == CVal)
3760 uint64_t NCVal = ~CVal;
3761 if ((NCVal & 0xFFFFULL) == NCVal)
3763 if ((NCVal & 0xFFFF0000ULL) == NCVal)
3765 if ((NCVal & 0xFFFF00000000ULL) == NCVal)
3767 if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
3775 // All assembler immediates are 64-bit integers.
3776 Result = DAG.getTargetConstant(CVal, MVT::i64);
3780 if (Result.getNode()) {
3781 Ops.push_back(Result);
3785 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3788 //===----------------------------------------------------------------------===//
3789 // ARM64 Advanced SIMD Support
3790 //===----------------------------------------------------------------------===//
3792 /// WidenVector - Given a value in the V64 register class, produce the
3793 /// equivalent value in the V128 register class.
3794 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
3795 EVT VT = V64Reg.getValueType();
3796 unsigned NarrowSize = VT.getVectorNumElements();
3797 MVT EltTy = VT.getVectorElementType().getSimpleVT();
3798 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
3801 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
3802 V64Reg, DAG.getConstant(0, MVT::i32));
3805 /// getExtFactor - Determine the adjustment factor for the position when
3806 /// generating an "extract from vector registers" instruction.
3807 static unsigned getExtFactor(SDValue &V) {
3808 EVT EltType = V.getValueType().getVectorElementType();
3809 return EltType.getSizeInBits() / 8;
3812 /// NarrowVector - Given a value in the V128 register class, produce the
3813 /// equivalent value in the V64 register class.
3814 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
3815 EVT VT = V128Reg.getValueType();
3816 unsigned WideSize = VT.getVectorNumElements();
3817 MVT EltTy = VT.getVectorElementType().getSimpleVT();
3818 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
3821 return DAG.getTargetExtractSubreg(ARM64::dsub, DL, NarrowTy, V128Reg);
3824 // Gather data to see if the operation can be modelled as a
3825 // shuffle in combination with VEXTs.
3826 SDValue ARM64TargetLowering::ReconstructShuffle(SDValue Op,
3827 SelectionDAG &DAG) const {
3829 EVT VT = Op.getValueType();
3830 unsigned NumElts = VT.getVectorNumElements();
3832 SmallVector<SDValue, 2> SourceVecs;
3833 SmallVector<unsigned, 2> MinElts;
3834 SmallVector<unsigned, 2> MaxElts;
3836 for (unsigned i = 0; i < NumElts; ++i) {
3837 SDValue V = Op.getOperand(i);
3838 if (V.getOpcode() == ISD::UNDEF)
3840 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
3841 // A shuffle can only come from building a vector from various
3842 // elements of other vectors.
3846 // Record this extraction against the appropriate vector if possible...
3847 SDValue SourceVec = V.getOperand(0);
3848 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
3849 bool FoundSource = false;
3850 for (unsigned j = 0; j < SourceVecs.size(); ++j) {
3851 if (SourceVecs[j] == SourceVec) {
3852 if (MinElts[j] > EltNo)
3854 if (MaxElts[j] < EltNo)
3861 // Or record a new source if not...
3863 SourceVecs.push_back(SourceVec);
3864 MinElts.push_back(EltNo);
3865 MaxElts.push_back(EltNo);
3869 // Currently only do something sane when at most two source vectors
3871 if (SourceVecs.size() > 2)
3874 SDValue ShuffleSrcs[2] = { DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
3875 int VEXTOffsets[2] = { 0, 0 };
3877 // This loop extracts the usage patterns of the source vectors
3878 // and prepares appropriate SDValues for a shuffle if possible.
3879 for (unsigned i = 0; i < SourceVecs.size(); ++i) {
3880 if (SourceVecs[i].getValueType() == VT) {
3881 // No VEXT necessary
3882 ShuffleSrcs[i] = SourceVecs[i];
3885 } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
3886 // We can pad out the smaller vector for free, so if it's part of a
3888 ShuffleSrcs[i] = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, SourceVecs[i],
3889 DAG.getUNDEF(SourceVecs[i].getValueType()));
3893 // Don't attempt to extract subvectors from BUILD_VECTOR sources
3894 // that expand or trunc the original value.
3895 // TODO: We can try to bitcast and ANY_EXTEND the result but
3896 // we need to consider the cost of vector ANY_EXTEND, and the
3897 // legality of all the types.
3898 if (SourceVecs[i].getValueType().getVectorElementType() !=
3899 VT.getVectorElementType())
3902 // Since only 64-bit and 128-bit vectors are legal on ARM and
3903 // we've eliminated the other cases...
3904 assert(SourceVecs[i].getValueType().getVectorNumElements() == 2 * NumElts &&
3905 "unexpected vector sizes in ReconstructShuffle");
3907 if (MaxElts[i] - MinElts[i] >= NumElts) {
3908 // Span too large for a VEXT to cope
3912 if (MinElts[i] >= NumElts) {
3913 // The extraction can just take the second half
3914 VEXTOffsets[i] = NumElts;
3916 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SourceVecs[i],
3917 DAG.getIntPtrConstant(NumElts));
3918 } else if (MaxElts[i] < NumElts) {
3919 // The extraction can just take the first half
3921 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
3922 SourceVecs[i], DAG.getIntPtrConstant(0));
3924 // An actual VEXT is needed
3925 VEXTOffsets[i] = MinElts[i];
3926 SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
3927 SourceVecs[i], DAG.getIntPtrConstant(0));
3929 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SourceVecs[i],
3930 DAG.getIntPtrConstant(NumElts));
3931 unsigned Imm = VEXTOffsets[i] * getExtFactor(VEXTSrc1);
3932 ShuffleSrcs[i] = DAG.getNode(ARM64ISD::EXT, dl, VT, VEXTSrc1, VEXTSrc2,
3933 DAG.getConstant(Imm, MVT::i32));
3937 SmallVector<int, 8> Mask;
3939 for (unsigned i = 0; i < NumElts; ++i) {
3940 SDValue Entry = Op.getOperand(i);
3941 if (Entry.getOpcode() == ISD::UNDEF) {
3946 SDValue ExtractVec = Entry.getOperand(0);
3948 cast<ConstantSDNode>(Op.getOperand(i).getOperand(1))->getSExtValue();
3949 if (ExtractVec == SourceVecs[0]) {
3950 Mask.push_back(ExtractElt - VEXTOffsets[0]);
3952 Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
3956 // Final check before we try to produce nonsense...
3957 if (isShuffleMaskLegal(Mask, VT))
3958 return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
3964 // check if an EXT instruction can handle the shuffle mask when the
3965 // vector sources of the shuffle are the same.
3966 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
3967 unsigned NumElts = VT.getVectorNumElements();
3969 // Assume that the first shuffle index is not UNDEF. Fail if it is.
3975 // If this is a VEXT shuffle, the immediate value is the index of the first
3976 // element. The other shuffle indices must be the successive elements after
3978 unsigned ExpectedElt = Imm;
3979 for (unsigned i = 1; i < NumElts; ++i) {
3980 // Increment the expected index. If it wraps around, just follow it
3981 // back to index zero and keep going.
3983 if (ExpectedElt == NumElts)
3987 continue; // ignore UNDEF indices
3988 if (ExpectedElt != static_cast<unsigned>(M[i]))
3995 // check if an EXT instruction can handle the shuffle mask when the
3996 // vector sources of the shuffle are different.
3997 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
3999 // Look for the first non-undef element.
4000 const int *FirstRealElt = std::find_if(M.begin(), M.end(),
4001 [](int Elt) {return Elt >= 0;});
4003 // Benefit form APInt to handle overflow when calculating expected element.
4004 unsigned NumElts = VT.getVectorNumElements();
4005 unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
4006 APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
4007 // The following shuffle indices must be the successive elements after the
4008 // first real element.
4009 const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
4010 [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
4011 if (FirstWrongElt != M.end())
4014 // The index of an EXT is the first element if it is not UNDEF.
4015 // Watch out for the beginning UNDEFs. The EXT index should be the expected
4016 // value of the first element.
4017 // E.g. <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
4018 // <-1, -1, 0, 1, ...> is treated as <IDX, IDX+1, 0, 1, ...>. IDX is
4019 // equal to the ExpectedElt.
4020 Imm = (M[0] >= 0) ? static_cast<unsigned>(M[0]) : ExpectedElt.getZExtValue();
4022 // If no beginning UNDEFs, do swap when M[0] >= NumElts.
4023 if (M[0] >= 0 && Imm >= NumElts) {
4026 } else if (M[0] < 0) {
4027 // Only do swap when beginning UNDEFs more than the first real element,
4028 if (*FirstRealElt < FirstRealElt - M.begin())
4037 /// isREVMask - Check if a vector shuffle corresponds to a REV
4038 /// instruction with the specified blocksize. (The order of the elements
4039 /// within each block of the vector is reversed.)
4040 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
4041 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
4042 "Only possible block sizes for REV are: 16, 32, 64");
4044 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
4048 unsigned NumElts = VT.getVectorNumElements();
4049 unsigned BlockElts = M[0] + 1;
4050 // If the first shuffle index is UNDEF, be optimistic.
4052 BlockElts = BlockSize / EltSz;
4054 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4057 for (unsigned i = 0; i < NumElts; ++i) {
4059 continue; // ignore UNDEF indices
4060 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
4067 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4068 unsigned NumElts = VT.getVectorNumElements();
4069 WhichResult = (M[0] == 0 ? 0 : 1);
4070 unsigned Idx = WhichResult * NumElts / 2;
4071 for (unsigned i = 0; i != NumElts; i += 2) {
4072 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
4073 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
4081 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4082 unsigned NumElts = VT.getVectorNumElements();
4083 WhichResult = (M[0] == 0 ? 0 : 1);
4084 for (unsigned i = 0; i != NumElts; ++i) {
4086 continue; // ignore UNDEF indices
4087 if ((unsigned)M[i] != 2 * i + WhichResult)
4094 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4095 unsigned NumElts = VT.getVectorNumElements();
4096 WhichResult = (M[0] == 0 ? 0 : 1);
4097 for (unsigned i = 0; i < NumElts; i += 2) {
4098 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
4099 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
4105 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
4106 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4107 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4108 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4109 unsigned NumElts = VT.getVectorNumElements();
4110 WhichResult = (M[0] == 0 ? 0 : 1);
4111 unsigned Idx = WhichResult * NumElts / 2;
4112 for (unsigned i = 0; i != NumElts; i += 2) {
4113 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
4114 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
4122 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
4123 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4124 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4125 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4126 unsigned Half = VT.getVectorNumElements() / 2;
4127 WhichResult = (M[0] == 0 ? 0 : 1);
4128 for (unsigned j = 0; j != 2; ++j) {
4129 unsigned Idx = WhichResult;
4130 for (unsigned i = 0; i != Half; ++i) {
4131 int MIdx = M[i + j * Half];
4132 if (MIdx >= 0 && (unsigned)MIdx != Idx)
4141 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
4142 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4143 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4144 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4145 unsigned NumElts = VT.getVectorNumElements();
4146 WhichResult = (M[0] == 0 ? 0 : 1);
4147 for (unsigned i = 0; i < NumElts; i += 2) {
4148 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
4149 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
4155 static bool isINSMask(ArrayRef<int> M, int NumInputElements,
4156 bool &DstIsLeft, int &Anomaly) {
4157 if (M.size() != static_cast<size_t>(NumInputElements))
4160 int NumLHSMatch = 0, NumRHSMatch = 0;
4161 int LastLHSMismatch = -1, LastRHSMismatch = -1;
4163 for (int i = 0; i < NumInputElements; ++i) {
4173 LastLHSMismatch = i;
4175 if (M[i] == i + NumInputElements)
4178 LastRHSMismatch = i;
4181 if (NumLHSMatch == NumInputElements - 1) {
4183 Anomaly = LastLHSMismatch;
4185 } else if (NumRHSMatch == NumInputElements - 1) {
4187 Anomaly = LastRHSMismatch;
4194 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
4195 if (VT.getSizeInBits() != 128)
4198 unsigned NumElts = VT.getVectorNumElements();
4200 for (int I = 0, E = NumElts / 2; I != E; I++) {
4205 int Offset = NumElts / 2;
4206 for (int I = NumElts / 2, E = NumElts; I != E; I++) {
4207 if (Mask[I] != I + SplitLHS * Offset)
4214 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
4216 EVT VT = Op.getValueType();
4217 SDValue V0 = Op.getOperand(0);
4218 SDValue V1 = Op.getOperand(1);
4219 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
4221 if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
4222 VT.getVectorElementType() != V1.getValueType().getVectorElementType())
4225 bool SplitV0 = V0.getValueType().getSizeInBits() == 128;
4227 if (!isConcatMask(Mask, VT, SplitV0))
4230 EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
4231 VT.getVectorNumElements() / 2);
4233 V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
4234 DAG.getConstant(0, MVT::i64));
4236 if (V1.getValueType().getSizeInBits() == 128) {
4237 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
4238 DAG.getConstant(0, MVT::i64));
4240 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
4243 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
4244 /// the specified operations to build the shuffle.
4245 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
4246 SDValue RHS, SelectionDAG &DAG,
4248 unsigned OpNum = (PFEntry >> 26) & 0x0F;
4249 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
4250 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
4253 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
4262 OP_VUZPL, // VUZP, left result
4263 OP_VUZPR, // VUZP, right result
4264 OP_VZIPL, // VZIP, left result
4265 OP_VZIPR, // VZIP, right result
4266 OP_VTRNL, // VTRN, left result
4267 OP_VTRNR // VTRN, right result
4270 if (OpNum == OP_COPY) {
4271 if (LHSID == (1 * 9 + 2) * 9 + 3)
4273 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
4277 SDValue OpLHS, OpRHS;
4278 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
4279 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
4280 EVT VT = OpLHS.getValueType();
4284 llvm_unreachable("Unknown shuffle opcode!");
4286 // VREV divides the vector in half and swaps within the half.
4287 if (VT.getVectorElementType() == MVT::i32 ||
4288 VT.getVectorElementType() == MVT::f32)
4289 return DAG.getNode(ARM64ISD::REV64, dl, VT, OpLHS);
4290 // vrev <4 x i16> -> REV32
4291 if (VT.getVectorElementType() == MVT::i16)
4292 return DAG.getNode(ARM64ISD::REV32, dl, VT, OpLHS);
4293 // vrev <4 x i8> -> REV16
4294 assert(VT.getVectorElementType() == MVT::i8);
4295 return DAG.getNode(ARM64ISD::REV16, dl, VT, OpLHS);
4300 EVT EltTy = VT.getVectorElementType();
4302 if (EltTy == MVT::i8)
4303 Opcode = ARM64ISD::DUPLANE8;
4304 else if (EltTy == MVT::i16)
4305 Opcode = ARM64ISD::DUPLANE16;
4306 else if (EltTy == MVT::i32 || EltTy == MVT::f32)
4307 Opcode = ARM64ISD::DUPLANE32;
4308 else if (EltTy == MVT::i64 || EltTy == MVT::f64)
4309 Opcode = ARM64ISD::DUPLANE64;
4311 llvm_unreachable("Invalid vector element type?");
4313 if (VT.getSizeInBits() == 64)
4314 OpLHS = WidenVector(OpLHS, DAG);
4315 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, MVT::i64);
4316 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
4321 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
4322 return DAG.getNode(ARM64ISD::EXT, dl, VT, OpLHS, OpRHS,
4323 DAG.getConstant(Imm, MVT::i32));
4326 return DAG.getNode(ARM64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS, OpRHS);
4328 return DAG.getNode(ARM64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS, OpRHS);
4330 return DAG.getNode(ARM64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS, OpRHS);
4332 return DAG.getNode(ARM64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS, OpRHS);
4334 return DAG.getNode(ARM64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS, OpRHS);
4336 return DAG.getNode(ARM64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS, OpRHS);
4340 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
4341 SelectionDAG &DAG) {
4342 // Check to see if we can use the TBL instruction.
4343 SDValue V1 = Op.getOperand(0);
4344 SDValue V2 = Op.getOperand(1);
4347 EVT EltVT = Op.getValueType().getVectorElementType();
4348 unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
4350 SmallVector<SDValue, 8> TBLMask;
4351 for (int Val : ShuffleMask) {
4352 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
4353 unsigned Offset = Byte + Val * BytesPerElt;
4354 TBLMask.push_back(DAG.getConstant(Offset, MVT::i32));
4358 MVT IndexVT = MVT::v8i8;
4359 unsigned IndexLen = 8;
4360 if (Op.getValueType().getSizeInBits() == 128) {
4361 IndexVT = MVT::v16i8;
4365 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
4366 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
4369 if (V2.getNode()->getOpcode() == ISD::UNDEF) {
4371 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
4372 Shuffle = DAG.getNode(
4373 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
4374 DAG.getConstant(Intrinsic::arm64_neon_tbl1, MVT::i32), V1Cst,
4375 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
4376 makeArrayRef(TBLMask.data(), IndexLen)));
4378 if (IndexLen == 8) {
4379 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
4380 Shuffle = DAG.getNode(
4381 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
4382 DAG.getConstant(Intrinsic::arm64_neon_tbl1, MVT::i32), V1Cst,
4383 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
4384 makeArrayRef(TBLMask.data(), IndexLen)));
4386 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
4387 // cannot currently represent the register constraints on the input
4389 // Shuffle = DAG.getNode(ARM64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
4390 // DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
4391 // &TBLMask[0], IndexLen));
4392 Shuffle = DAG.getNode(
4393 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
4394 DAG.getConstant(Intrinsic::arm64_neon_tbl2, MVT::i32), V1Cst, V2Cst,
4395 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
4396 makeArrayRef(TBLMask.data(), IndexLen)));
4399 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
4402 static unsigned getDUPLANEOp(EVT EltType) {
4403 if (EltType == MVT::i8)
4404 return ARM64ISD::DUPLANE8;
4405 if (EltType == MVT::i16)
4406 return ARM64ISD::DUPLANE16;
4407 if (EltType == MVT::i32 || EltType == MVT::f32)
4408 return ARM64ISD::DUPLANE32;
4409 if (EltType == MVT::i64 || EltType == MVT::f64)
4410 return ARM64ISD::DUPLANE64;
4412 llvm_unreachable("Invalid vector element type?");
4415 SDValue ARM64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
4416 SelectionDAG &DAG) const {
4418 EVT VT = Op.getValueType();
4420 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
4422 // Convert shuffles that are directly supported on NEON to target-specific
4423 // DAG nodes, instead of keeping them as shuffles and matching them again
4424 // during code selection. This is more efficient and avoids the possibility
4425 // of inconsistencies between legalization and selection.
4426 ArrayRef<int> ShuffleMask = SVN->getMask();
4428 SDValue V1 = Op.getOperand(0);
4429 SDValue V2 = Op.getOperand(1);
4431 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0],
4432 V1.getValueType().getSimpleVT())) {
4433 int Lane = SVN->getSplatIndex();
4434 // If this is undef splat, generate it via "just" vdup, if possible.
4438 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
4439 return DAG.getNode(ARM64ISD::DUP, dl, V1.getValueType(),
4441 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
4442 // constant. If so, we can just reference the lane's definition directly.
4443 if (V1.getOpcode() == ISD::BUILD_VECTOR &&
4444 !isa<ConstantSDNode>(V1.getOperand(Lane)))
4445 return DAG.getNode(ARM64ISD::DUP, dl, VT, V1.getOperand(Lane));
4447 // Otherwise, duplicate from the lane of the input vector.
4448 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
4450 // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
4451 // to make a vector of the same size as this SHUFFLE. We can ignore the
4452 // extract entirely, and canonicalise the concat using WidenVector.
4453 if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
4454 Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
4455 V1 = V1.getOperand(0);
4456 } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
4457 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
4458 Lane -= Idx * VT.getVectorNumElements() / 2;
4459 V1 = WidenVector(V1.getOperand(Idx), DAG);
4460 } else if (VT.getSizeInBits() == 64)
4461 V1 = WidenVector(V1, DAG);
4463 return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, MVT::i64));
4466 if (isREVMask(ShuffleMask, VT, 64))
4467 return DAG.getNode(ARM64ISD::REV64, dl, V1.getValueType(), V1, V2);
4468 if (isREVMask(ShuffleMask, VT, 32))
4469 return DAG.getNode(ARM64ISD::REV32, dl, V1.getValueType(), V1, V2);
4470 if (isREVMask(ShuffleMask, VT, 16))
4471 return DAG.getNode(ARM64ISD::REV16, dl, V1.getValueType(), V1, V2);
4473 bool ReverseEXT = false;
4475 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
4478 Imm *= getExtFactor(V1);
4479 return DAG.getNode(ARM64ISD::EXT, dl, V1.getValueType(), V1, V2,
4480 DAG.getConstant(Imm, MVT::i32));
4481 } else if (V2->getOpcode() == ISD::UNDEF &&
4482 isSingletonEXTMask(ShuffleMask, VT, Imm)) {
4483 Imm *= getExtFactor(V1);
4484 return DAG.getNode(ARM64ISD::EXT, dl, V1.getValueType(), V1, V1,
4485 DAG.getConstant(Imm, MVT::i32));
4488 unsigned WhichResult;
4489 if (isZIPMask(ShuffleMask, VT, WhichResult)) {
4490 unsigned Opc = (WhichResult == 0) ? ARM64ISD::ZIP1 : ARM64ISD::ZIP2;
4491 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
4493 if (isUZPMask(ShuffleMask, VT, WhichResult)) {
4494 unsigned Opc = (WhichResult == 0) ? ARM64ISD::UZP1 : ARM64ISD::UZP2;
4495 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
4497 if (isTRNMask(ShuffleMask, VT, WhichResult)) {
4498 unsigned Opc = (WhichResult == 0) ? ARM64ISD::TRN1 : ARM64ISD::TRN2;
4499 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
4502 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
4503 unsigned Opc = (WhichResult == 0) ? ARM64ISD::ZIP1 : ARM64ISD::ZIP2;
4504 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
4506 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
4507 unsigned Opc = (WhichResult == 0) ? ARM64ISD::UZP1 : ARM64ISD::UZP2;
4508 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
4510 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
4511 unsigned Opc = (WhichResult == 0) ? ARM64ISD::TRN1 : ARM64ISD::TRN2;
4512 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
4515 SDValue Concat = tryFormConcatFromShuffle(Op, DAG);
4516 if (Concat.getNode())
4521 int NumInputElements = V1.getValueType().getVectorNumElements();
4522 if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
4523 SDValue DstVec = DstIsLeft ? V1 : V2;
4524 SDValue DstLaneV = DAG.getConstant(Anomaly, MVT::i64);
4526 SDValue SrcVec = V1;
4527 int SrcLane = ShuffleMask[Anomaly];
4528 if (SrcLane >= NumInputElements) {
4530 SrcLane -= VT.getVectorNumElements();
4532 SDValue SrcLaneV = DAG.getConstant(SrcLane, MVT::i64);
4534 EVT ScalarVT = VT.getVectorElementType();
4535 if (ScalarVT.getSizeInBits() < 32)
4536 ScalarVT = MVT::i32;
4539 ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
4540 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
4544 // If the shuffle is not directly supported and it has 4 elements, use
4545 // the PerfectShuffle-generated table to synthesize it from other shuffles.
4546 unsigned NumElts = VT.getVectorNumElements();
4548 unsigned PFIndexes[4];
4549 for (unsigned i = 0; i != 4; ++i) {
4550 if (ShuffleMask[i] < 0)
4553 PFIndexes[i] = ShuffleMask[i];
4556 // Compute the index in the perfect shuffle table.
4557 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
4558 PFIndexes[2] * 9 + PFIndexes[3];
4559 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4560 unsigned Cost = (PFEntry >> 30);
4563 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
4566 return GenerateTBL(Op, ShuffleMask, DAG);
4569 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
4571 EVT VT = BVN->getValueType(0);
4572 APInt SplatBits, SplatUndef;
4573 unsigned SplatBitSize;
4575 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4576 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
4578 for (unsigned i = 0; i < NumSplats; ++i) {
4579 CnstBits <<= SplatBitSize;
4580 UndefBits <<= SplatBitSize;
4581 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
4582 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
4591 SDValue ARM64TargetLowering::LowerVectorAND(SDValue Op,
4592 SelectionDAG &DAG) const {
4593 BuildVectorSDNode *BVN =
4594 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
4595 SDValue LHS = Op.getOperand(0);
4597 EVT VT = Op.getValueType();
4602 APInt CnstBits(VT.getSizeInBits(), 0);
4603 APInt UndefBits(VT.getSizeInBits(), 0);
4604 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
4605 // We only have BIC vector immediate instruction, which is and-not.
4606 CnstBits = ~CnstBits;
4608 // We make use of a little bit of goto ickiness in order to avoid having to
4609 // duplicate the immediate matching logic for the undef toggled case.
4610 bool SecondTry = false;
4613 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
4614 CnstBits = CnstBits.zextOrTrunc(64);
4615 uint64_t CnstVal = CnstBits.getZExtValue();
4617 if (ARM64_AM::isAdvSIMDModImmType1(CnstVal)) {
4618 CnstVal = ARM64_AM::encodeAdvSIMDModImmType1(CnstVal);
4619 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4620 SDValue Mov = DAG.getNode(ARM64ISD::BICi, dl, MovTy, LHS,
4621 DAG.getConstant(CnstVal, MVT::i32),
4622 DAG.getConstant(0, MVT::i32));
4623 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4626 if (ARM64_AM::isAdvSIMDModImmType2(CnstVal)) {
4627 CnstVal = ARM64_AM::encodeAdvSIMDModImmType2(CnstVal);
4628 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4629 SDValue Mov = DAG.getNode(ARM64ISD::BICi, dl, MovTy, LHS,
4630 DAG.getConstant(CnstVal, MVT::i32),
4631 DAG.getConstant(8, MVT::i32));
4632 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4635 if (ARM64_AM::isAdvSIMDModImmType3(CnstVal)) {
4636 CnstVal = ARM64_AM::encodeAdvSIMDModImmType3(CnstVal);
4637 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4638 SDValue Mov = DAG.getNode(ARM64ISD::BICi, dl, MovTy, LHS,
4639 DAG.getConstant(CnstVal, MVT::i32),
4640 DAG.getConstant(16, MVT::i32));
4641 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4644 if (ARM64_AM::isAdvSIMDModImmType4(CnstVal)) {
4645 CnstVal = ARM64_AM::encodeAdvSIMDModImmType4(CnstVal);
4646 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4647 SDValue Mov = DAG.getNode(ARM64ISD::BICi, dl, MovTy, LHS,
4648 DAG.getConstant(CnstVal, MVT::i32),
4649 DAG.getConstant(24, MVT::i32));
4650 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4653 if (ARM64_AM::isAdvSIMDModImmType5(CnstVal)) {
4654 CnstVal = ARM64_AM::encodeAdvSIMDModImmType5(CnstVal);
4655 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
4656 SDValue Mov = DAG.getNode(ARM64ISD::BICi, dl, MovTy, LHS,
4657 DAG.getConstant(CnstVal, MVT::i32),
4658 DAG.getConstant(0, MVT::i32));
4659 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4662 if (ARM64_AM::isAdvSIMDModImmType6(CnstVal)) {
4663 CnstVal = ARM64_AM::encodeAdvSIMDModImmType6(CnstVal);
4664 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
4665 SDValue Mov = DAG.getNode(ARM64ISD::BICi, dl, MovTy, LHS,
4666 DAG.getConstant(CnstVal, MVT::i32),
4667 DAG.getConstant(8, MVT::i32));
4668 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4675 CnstBits = ~UndefBits;
4679 // We can always fall back to a non-immediate AND.
4684 // Specialized code to quickly find if PotentialBVec is a BuildVector that
4685 // consists of only the same constant int value, returned in reference arg
4687 static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
4688 uint64_t &ConstVal) {
4689 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
4692 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
4695 EVT VT = Bvec->getValueType(0);
4696 unsigned NumElts = VT.getVectorNumElements();
4697 for (unsigned i = 1; i < NumElts; ++i)
4698 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
4700 ConstVal = FirstElt->getZExtValue();
4704 static unsigned getIntrinsicID(const SDNode *N) {
4705 unsigned Opcode = N->getOpcode();
4708 return Intrinsic::not_intrinsic;
4709 case ISD::INTRINSIC_WO_CHAIN: {
4710 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
4711 if (IID < Intrinsic::num_intrinsics)
4713 return Intrinsic::not_intrinsic;
4718 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
4719 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
4720 // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
4721 // Also, logical shift right -> sri, with the same structure.
4722 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
4723 EVT VT = N->getValueType(0);
4730 // Is the first op an AND?
4731 const SDValue And = N->getOperand(0);
4732 if (And.getOpcode() != ISD::AND)
4735 // Is the second op an shl or lshr?
4736 SDValue Shift = N->getOperand(1);
4737 // This will have been turned into: ARM64ISD::VSHL vector, #shift
4738 // or ARM64ISD::VLSHR vector, #shift
4739 unsigned ShiftOpc = Shift.getOpcode();
4740 if ((ShiftOpc != ARM64ISD::VSHL && ShiftOpc != ARM64ISD::VLSHR))
4742 bool IsShiftRight = ShiftOpc == ARM64ISD::VLSHR;
4744 // Is the shift amount constant?
4745 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
4749 // Is the and mask vector all constant?
4751 if (!isAllConstantBuildVector(And.getOperand(1), C1))
4754 // Is C1 == ~C2, taking into account how much one can shift elements of a
4756 uint64_t C2 = C2node->getZExtValue();
4757 unsigned ElemSizeInBits = VT.getVectorElementType().getSizeInBits();
4758 if (C2 > ElemSizeInBits)
4760 unsigned ElemMask = (1 << ElemSizeInBits) - 1;
4761 if ((C1 & ElemMask) != (~C2 & ElemMask))
4764 SDValue X = And.getOperand(0);
4765 SDValue Y = Shift.getOperand(0);
4768 IsShiftRight ? Intrinsic::arm64_neon_vsri : Intrinsic::arm64_neon_vsli;
4770 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
4771 DAG.getConstant(Intrin, MVT::i32), X, Y, Shift.getOperand(1));
4773 DEBUG(dbgs() << "arm64-lower: transformed: \n");
4774 DEBUG(N->dump(&DAG));
4775 DEBUG(dbgs() << "into: \n");
4776 DEBUG(ResultSLI->dump(&DAG));
4782 SDValue ARM64TargetLowering::LowerVectorOR(SDValue Op,
4783 SelectionDAG &DAG) const {
4784 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
4785 if (EnableARM64SlrGeneration) {
4786 SDValue Res = tryLowerToSLI(Op.getNode(), DAG);
4791 BuildVectorSDNode *BVN =
4792 dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
4793 SDValue LHS = Op.getOperand(1);
4795 EVT VT = Op.getValueType();
4797 // OR commutes, so try swapping the operands.
4799 LHS = Op.getOperand(0);
4800 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
4805 APInt CnstBits(VT.getSizeInBits(), 0);
4806 APInt UndefBits(VT.getSizeInBits(), 0);
4807 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
4808 // We make use of a little bit of goto ickiness in order to avoid having to
4809 // duplicate the immediate matching logic for the undef toggled case.
4810 bool SecondTry = false;
4813 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
4814 CnstBits = CnstBits.zextOrTrunc(64);
4815 uint64_t CnstVal = CnstBits.getZExtValue();
4817 if (ARM64_AM::isAdvSIMDModImmType1(CnstVal)) {
4818 CnstVal = ARM64_AM::encodeAdvSIMDModImmType1(CnstVal);
4819 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4820 SDValue Mov = DAG.getNode(ARM64ISD::ORRi, dl, MovTy, LHS,
4821 DAG.getConstant(CnstVal, MVT::i32),
4822 DAG.getConstant(0, MVT::i32));
4823 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4826 if (ARM64_AM::isAdvSIMDModImmType2(CnstVal)) {
4827 CnstVal = ARM64_AM::encodeAdvSIMDModImmType2(CnstVal);
4828 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4829 SDValue Mov = DAG.getNode(ARM64ISD::ORRi, dl, MovTy, LHS,
4830 DAG.getConstant(CnstVal, MVT::i32),
4831 DAG.getConstant(8, MVT::i32));
4832 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4835 if (ARM64_AM::isAdvSIMDModImmType3(CnstVal)) {
4836 CnstVal = ARM64_AM::encodeAdvSIMDModImmType3(CnstVal);
4837 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4838 SDValue Mov = DAG.getNode(ARM64ISD::ORRi, dl, MovTy, LHS,
4839 DAG.getConstant(CnstVal, MVT::i32),
4840 DAG.getConstant(16, MVT::i32));
4841 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4844 if (ARM64_AM::isAdvSIMDModImmType4(CnstVal)) {
4845 CnstVal = ARM64_AM::encodeAdvSIMDModImmType4(CnstVal);
4846 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4847 SDValue Mov = DAG.getNode(ARM64ISD::ORRi, dl, MovTy, LHS,
4848 DAG.getConstant(CnstVal, MVT::i32),
4849 DAG.getConstant(24, MVT::i32));
4850 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4853 if (ARM64_AM::isAdvSIMDModImmType5(CnstVal)) {
4854 CnstVal = ARM64_AM::encodeAdvSIMDModImmType5(CnstVal);
4855 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
4856 SDValue Mov = DAG.getNode(ARM64ISD::ORRi, dl, MovTy, LHS,
4857 DAG.getConstant(CnstVal, MVT::i32),
4858 DAG.getConstant(0, MVT::i32));
4859 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4862 if (ARM64_AM::isAdvSIMDModImmType6(CnstVal)) {
4863 CnstVal = ARM64_AM::encodeAdvSIMDModImmType6(CnstVal);
4864 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
4865 SDValue Mov = DAG.getNode(ARM64ISD::ORRi, dl, MovTy, LHS,
4866 DAG.getConstant(CnstVal, MVT::i32),
4867 DAG.getConstant(8, MVT::i32));
4868 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4875 CnstBits = UndefBits;
4879 // We can always fall back to a non-immediate OR.
4884 SDValue ARM64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
4885 SelectionDAG &DAG) const {
4886 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4888 EVT VT = Op.getValueType();
4890 APInt CnstBits(VT.getSizeInBits(), 0);
4891 APInt UndefBits(VT.getSizeInBits(), 0);
4892 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
4893 // We make use of a little bit of goto ickiness in order to avoid having to
4894 // duplicate the immediate matching logic for the undef toggled case.
4895 bool SecondTry = false;
4898 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
4899 CnstBits = CnstBits.zextOrTrunc(64);
4900 uint64_t CnstVal = CnstBits.getZExtValue();
4902 // Certain magic vector constants (used to express things like NOT
4903 // and NEG) are passed through unmodified. This allows codegen patterns
4904 // for these operations to match. Special-purpose patterns will lower
4905 // these immediates to MOVIs if it proves necessary.
4906 if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL))
4909 // The many faces of MOVI...
4910 if (ARM64_AM::isAdvSIMDModImmType10(CnstVal)) {
4911 CnstVal = ARM64_AM::encodeAdvSIMDModImmType10(CnstVal);
4912 if (VT.getSizeInBits() == 128) {
4913 SDValue Mov = DAG.getNode(ARM64ISD::MOVIedit, dl, MVT::v2i64,
4914 DAG.getConstant(CnstVal, MVT::i32));
4915 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4918 // Support the V64 version via subregister insertion.
4919 SDValue Mov = DAG.getNode(ARM64ISD::MOVIedit, dl, MVT::f64,
4920 DAG.getConstant(CnstVal, MVT::i32));
4921 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4924 if (ARM64_AM::isAdvSIMDModImmType1(CnstVal)) {
4925 CnstVal = ARM64_AM::encodeAdvSIMDModImmType1(CnstVal);
4926 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4927 SDValue Mov = DAG.getNode(ARM64ISD::MOVIshift, dl, MovTy,
4928 DAG.getConstant(CnstVal, MVT::i32),
4929 DAG.getConstant(0, MVT::i32));
4930 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4933 if (ARM64_AM::isAdvSIMDModImmType2(CnstVal)) {
4934 CnstVal = ARM64_AM::encodeAdvSIMDModImmType2(CnstVal);
4935 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4936 SDValue Mov = DAG.getNode(ARM64ISD::MOVIshift, dl, MovTy,
4937 DAG.getConstant(CnstVal, MVT::i32),
4938 DAG.getConstant(8, MVT::i32));
4939 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4942 if (ARM64_AM::isAdvSIMDModImmType3(CnstVal)) {
4943 CnstVal = ARM64_AM::encodeAdvSIMDModImmType3(CnstVal);
4944 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4945 SDValue Mov = DAG.getNode(ARM64ISD::MOVIshift, dl, MovTy,
4946 DAG.getConstant(CnstVal, MVT::i32),
4947 DAG.getConstant(16, MVT::i32));
4948 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4951 if (ARM64_AM::isAdvSIMDModImmType4(CnstVal)) {
4952 CnstVal = ARM64_AM::encodeAdvSIMDModImmType4(CnstVal);
4953 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4954 SDValue Mov = DAG.getNode(ARM64ISD::MOVIshift, dl, MovTy,
4955 DAG.getConstant(CnstVal, MVT::i32),
4956 DAG.getConstant(24, MVT::i32));
4957 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4960 if (ARM64_AM::isAdvSIMDModImmType5(CnstVal)) {
4961 CnstVal = ARM64_AM::encodeAdvSIMDModImmType5(CnstVal);
4962 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
4963 SDValue Mov = DAG.getNode(ARM64ISD::MOVIshift, dl, MovTy,
4964 DAG.getConstant(CnstVal, MVT::i32),
4965 DAG.getConstant(0, MVT::i32));
4966 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4969 if (ARM64_AM::isAdvSIMDModImmType6(CnstVal)) {
4970 CnstVal = ARM64_AM::encodeAdvSIMDModImmType6(CnstVal);
4971 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
4972 SDValue Mov = DAG.getNode(ARM64ISD::MOVIshift, dl, MovTy,
4973 DAG.getConstant(CnstVal, MVT::i32),
4974 DAG.getConstant(8, MVT::i32));
4975 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4978 if (ARM64_AM::isAdvSIMDModImmType7(CnstVal)) {
4979 CnstVal = ARM64_AM::encodeAdvSIMDModImmType7(CnstVal);
4980 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4981 SDValue Mov = DAG.getNode(ARM64ISD::MOVImsl, dl, MovTy,
4982 DAG.getConstant(CnstVal, MVT::i32),
4983 DAG.getConstant(264, MVT::i32));
4984 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4987 if (ARM64_AM::isAdvSIMDModImmType8(CnstVal)) {
4988 CnstVal = ARM64_AM::encodeAdvSIMDModImmType8(CnstVal);
4989 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4990 SDValue Mov = DAG.getNode(ARM64ISD::MOVImsl, dl, MovTy,
4991 DAG.getConstant(CnstVal, MVT::i32),
4992 DAG.getConstant(272, MVT::i32));
4993 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4996 if (ARM64_AM::isAdvSIMDModImmType9(CnstVal)) {
4997 CnstVal = ARM64_AM::encodeAdvSIMDModImmType9(CnstVal);
4998 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
4999 SDValue Mov = DAG.getNode(ARM64ISD::MOVI, dl, MovTy,
5000 DAG.getConstant(CnstVal, MVT::i32));
5001 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5004 // The few faces of FMOV...
5005 if (ARM64_AM::isAdvSIMDModImmType11(CnstVal)) {
5006 CnstVal = ARM64_AM::encodeAdvSIMDModImmType11(CnstVal);
5007 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32;
5008 SDValue Mov = DAG.getNode(ARM64ISD::FMOV, dl, MovTy,
5009 DAG.getConstant(CnstVal, MVT::i32));
5010 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5013 if (ARM64_AM::isAdvSIMDModImmType12(CnstVal) &&
5014 VT.getSizeInBits() == 128) {
5015 CnstVal = ARM64_AM::encodeAdvSIMDModImmType12(CnstVal);
5016 SDValue Mov = DAG.getNode(ARM64ISD::FMOV, dl, MVT::v2f64,
5017 DAG.getConstant(CnstVal, MVT::i32));
5018 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5021 // The many faces of MVNI...
5023 if (ARM64_AM::isAdvSIMDModImmType1(CnstVal)) {
5024 CnstVal = ARM64_AM::encodeAdvSIMDModImmType1(CnstVal);
5025 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5026 SDValue Mov = DAG.getNode(ARM64ISD::MVNIshift, dl, MovTy,
5027 DAG.getConstant(CnstVal, MVT::i32),
5028 DAG.getConstant(0, MVT::i32));
5029 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5032 if (ARM64_AM::isAdvSIMDModImmType2(CnstVal)) {
5033 CnstVal = ARM64_AM::encodeAdvSIMDModImmType2(CnstVal);
5034 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5035 SDValue Mov = DAG.getNode(ARM64ISD::MVNIshift, dl, MovTy,
5036 DAG.getConstant(CnstVal, MVT::i32),
5037 DAG.getConstant(8, MVT::i32));
5038 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5041 if (ARM64_AM::isAdvSIMDModImmType3(CnstVal)) {
5042 CnstVal = ARM64_AM::encodeAdvSIMDModImmType3(CnstVal);
5043 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5044 SDValue Mov = DAG.getNode(ARM64ISD::MVNIshift, dl, MovTy,
5045 DAG.getConstant(CnstVal, MVT::i32),
5046 DAG.getConstant(16, MVT::i32));
5047 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5050 if (ARM64_AM::isAdvSIMDModImmType4(CnstVal)) {
5051 CnstVal = ARM64_AM::encodeAdvSIMDModImmType4(CnstVal);
5052 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5053 SDValue Mov = DAG.getNode(ARM64ISD::MVNIshift, dl, MovTy,
5054 DAG.getConstant(CnstVal, MVT::i32),
5055 DAG.getConstant(24, MVT::i32));
5056 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5059 if (ARM64_AM::isAdvSIMDModImmType5(CnstVal)) {
5060 CnstVal = ARM64_AM::encodeAdvSIMDModImmType5(CnstVal);
5061 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5062 SDValue Mov = DAG.getNode(ARM64ISD::MVNIshift, dl, MovTy,
5063 DAG.getConstant(CnstVal, MVT::i32),
5064 DAG.getConstant(0, MVT::i32));
5065 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5068 if (ARM64_AM::isAdvSIMDModImmType6(CnstVal)) {
5069 CnstVal = ARM64_AM::encodeAdvSIMDModImmType6(CnstVal);
5070 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5071 SDValue Mov = DAG.getNode(ARM64ISD::MVNIshift, dl, MovTy,
5072 DAG.getConstant(CnstVal, MVT::i32),
5073 DAG.getConstant(8, MVT::i32));
5074 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5077 if (ARM64_AM::isAdvSIMDModImmType7(CnstVal)) {
5078 CnstVal = ARM64_AM::encodeAdvSIMDModImmType7(CnstVal);
5079 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5080 SDValue Mov = DAG.getNode(ARM64ISD::MVNImsl, dl, MovTy,
5081 DAG.getConstant(CnstVal, MVT::i32),
5082 DAG.getConstant(264, MVT::i32));
5083 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5086 if (ARM64_AM::isAdvSIMDModImmType8(CnstVal)) {
5087 CnstVal = ARM64_AM::encodeAdvSIMDModImmType8(CnstVal);
5088 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5089 SDValue Mov = DAG.getNode(ARM64ISD::MVNImsl, dl, MovTy,
5090 DAG.getConstant(CnstVal, MVT::i32),
5091 DAG.getConstant(272, MVT::i32));
5092 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5099 CnstBits = UndefBits;
5104 // Scan through the operands to find some interesting properties we can
5106 // 1) If only one value is used, we can use a DUP, or
5107 // 2) if only the low element is not undef, we can just insert that, or
5108 // 3) if only one constant value is used (w/ some non-constant lanes),
5109 // we can splat the constant value into the whole vector then fill
5110 // in the non-constant lanes.
5111 // 4) FIXME: If different constant values are used, but we can intelligently
5112 // select the values we'll be overwriting for the non-constant
5113 // lanes such that we can directly materialize the vector
5114 // some other way (MOVI, e.g.), we can be sneaky.
5115 unsigned NumElts = VT.getVectorNumElements();
5116 bool isOnlyLowElement = true;
5117 bool usesOnlyOneValue = true;
5118 bool usesOnlyOneConstantValue = true;
5119 bool isConstant = true;
5120 unsigned NumConstantLanes = 0;
5122 SDValue ConstantValue;
5123 for (unsigned i = 0; i < NumElts; ++i) {
5124 SDValue V = Op.getOperand(i);
5125 if (V.getOpcode() == ISD::UNDEF)
5128 isOnlyLowElement = false;
5129 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5132 if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
5134 if (!ConstantValue.getNode())
5136 else if (ConstantValue != V)
5137 usesOnlyOneConstantValue = false;
5140 if (!Value.getNode())
5142 else if (V != Value)
5143 usesOnlyOneValue = false;
5146 if (!Value.getNode())
5147 return DAG.getUNDEF(VT);
5149 if (isOnlyLowElement)
5150 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5152 // Use DUP for non-constant splats. For f32 constant splats, reduce to
5153 // i32 and try again.
5154 if (usesOnlyOneValue) {
5156 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5157 Value.getValueType() != VT)
5158 return DAG.getNode(ARM64ISD::DUP, dl, VT, Value);
5160 // This is actually a DUPLANExx operation, which keeps everything vectory.
5162 // DUPLANE works on 128-bit vectors, widen it if necessary.
5163 SDValue Lane = Value.getOperand(1);
5164 Value = Value.getOperand(0);
5165 if (Value.getValueType().getSizeInBits() == 64)
5166 Value = WidenVector(Value, DAG);
5168 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
5169 return DAG.getNode(Opcode, dl, VT, Value, Lane);
5172 if (VT.getVectorElementType().isFloatingPoint()) {
5173 SmallVector<SDValue, 8> Ops;
5175 (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
5176 for (unsigned i = 0; i < NumElts; ++i)
5177 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
5178 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
5179 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
5180 Val = LowerBUILD_VECTOR(Val, DAG);
5182 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5186 // If there was only one constant value used and for more than one lane,
5187 // start by splatting that value, then replace the non-constant lanes. This
5188 // is better than the default, which will perform a separate initialization
5190 if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
5191 SDValue Val = DAG.getNode(ARM64ISD::DUP, dl, VT, ConstantValue);
5192 // Now insert the non-constant lanes.
5193 for (unsigned i = 0; i < NumElts; ++i) {
5194 SDValue V = Op.getOperand(i);
5195 SDValue LaneIdx = DAG.getConstant(i, MVT::i64);
5196 if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) {
5197 // Note that type legalization likely mucked about with the VT of the
5198 // source operand, so we may have to convert it here before inserting.
5199 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
5205 // If all elements are constants and the case above didn't get hit, fall back
5206 // to the default expansion, which will generate a load from the constant
5211 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5213 SDValue shuffle = ReconstructShuffle(Op, DAG);
5214 if (shuffle != SDValue())
5218 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5219 // know the default expansion would otherwise fall back on something even
5220 // worse. For a vector with one or two non-undef values, that's
5221 // scalar_to_vector for the elements followed by a shuffle (provided the
5222 // shuffle is valid for the target) and materialization element by element
5223 // on the stack followed by a load for everything else.
5224 if (!isConstant && !usesOnlyOneValue) {
5225 SDValue Vec = DAG.getUNDEF(VT);
5226 SDValue Op0 = Op.getOperand(0);
5227 unsigned ElemSize = VT.getVectorElementType().getSizeInBits();
5229 // For 32 and 64 bit types, use INSERT_SUBREG for lane zero to
5230 // a) Avoid a RMW dependency on the full vector register, and
5231 // b) Allow the register coalescer to fold away the copy if the
5232 // value is already in an S or D register.
5233 if (Op0.getOpcode() != ISD::UNDEF && (ElemSize == 32 || ElemSize == 64)) {
5234 unsigned SubIdx = ElemSize == 32 ? ARM64::ssub : ARM64::dsub;
5236 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl, VT, Vec, Op0,
5237 DAG.getTargetConstant(SubIdx, MVT::i32));
5238 Vec = SDValue(N, 0);
5241 for (; i < NumElts; ++i) {
5242 SDValue V = Op.getOperand(i);
5243 if (V.getOpcode() == ISD::UNDEF)
5245 SDValue LaneIdx = DAG.getConstant(i, MVT::i64);
5246 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5251 // Just use the default expansion. We failed to find a better alternative.
5255 SDValue ARM64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
5256 SelectionDAG &DAG) const {
5257 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
5259 // Check for non-constant lane.
5260 if (!isa<ConstantSDNode>(Op.getOperand(2)))
5263 EVT VT = Op.getOperand(0).getValueType();
5265 // Insertion/extraction are legal for V128 types.
5266 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
5267 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64)
5270 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
5271 VT != MVT::v1i64 && VT != MVT::v2f32)
5274 // For V64 types, we perform insertion by expanding the value
5275 // to a V128 type and perform the insertion on that.
5277 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
5278 EVT WideTy = WideVec.getValueType();
5280 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
5281 Op.getOperand(1), Op.getOperand(2));
5282 // Re-narrow the resultant vector.
5283 return NarrowVector(Node, DAG);
5286 SDValue ARM64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
5287 SelectionDAG &DAG) const {
5288 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
5290 // Check for non-constant lane.
5291 if (!isa<ConstantSDNode>(Op.getOperand(1)))
5294 EVT VT = Op.getOperand(0).getValueType();
5296 // Insertion/extraction are legal for V128 types.
5297 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
5298 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64)
5301 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
5302 VT != MVT::v1i64 && VT != MVT::v2f32)
5305 // For V64 types, we perform extraction by expanding the value
5306 // to a V128 type and perform the extraction on that.
5308 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
5309 EVT WideTy = WideVec.getValueType();
5311 EVT ExtrTy = WideTy.getVectorElementType();
5312 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
5315 // For extractions, we just return the result directly.
5316 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
5320 SDValue ARM64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
5321 SelectionDAG &DAG) const {
5322 EVT VT = Op.getOperand(0).getValueType();
5328 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5331 unsigned Val = Cst->getZExtValue();
5333 unsigned Size = Op.getValueType().getSizeInBits();
5337 return DAG.getTargetExtractSubreg(ARM64::bsub, dl, Op.getValueType(),
5340 return DAG.getTargetExtractSubreg(ARM64::hsub, dl, Op.getValueType(),
5343 return DAG.getTargetExtractSubreg(ARM64::ssub, dl, Op.getValueType(),
5346 return DAG.getTargetExtractSubreg(ARM64::dsub, dl, Op.getValueType(),
5349 llvm_unreachable("Unexpected vector type in extract_subvector!");
5352 // If this is extracting the upper 64-bits of a 128-bit vector, we match
5354 if (Size == 64 && Val * VT.getVectorElementType().getSizeInBits() == 64)
5360 bool ARM64TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5362 if (VT.getVectorNumElements() == 4 &&
5363 (VT.is128BitVector() || VT.is64BitVector())) {
5364 unsigned PFIndexes[4];
5365 for (unsigned i = 0; i != 4; ++i) {
5369 PFIndexes[i] = M[i];
5372 // Compute the index in the perfect shuffle table.
5373 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
5374 PFIndexes[2] * 9 + PFIndexes[3];
5375 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5376 unsigned Cost = (PFEntry >> 30);
5384 unsigned DummyUnsigned;
5386 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
5387 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
5388 isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
5389 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
5390 isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
5391 isZIPMask(M, VT, DummyUnsigned) ||
5392 isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
5393 isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
5394 isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
5395 isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
5396 isConcatMask(M, VT, VT.getSizeInBits() == 128));
5399 /// getVShiftImm - Check if this is a valid build_vector for the immediate
5400 /// operand of a vector shift operation, where all the elements of the
5401 /// build_vector must have the same constant integer value.
5402 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
5403 // Ignore bit_converts.
5404 while (Op.getOpcode() == ISD::BITCAST)
5405 Op = Op.getOperand(0);
5406 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
5407 APInt SplatBits, SplatUndef;
5408 unsigned SplatBitSize;
5410 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
5411 HasAnyUndefs, ElementBits) ||
5412 SplatBitSize > ElementBits)
5414 Cnt = SplatBits.getSExtValue();
5418 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
5419 /// operand of a vector shift left operation. That value must be in the range:
5420 /// 0 <= Value < ElementBits for a left shift; or
5421 /// 0 <= Value <= ElementBits for a long left shift.
5422 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
5423 assert(VT.isVector() && "vector shift count is not a vector type");
5424 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
5425 if (!getVShiftImm(Op, ElementBits, Cnt))
5427 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
5430 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
5431 /// operand of a vector shift right operation. For a shift opcode, the value
5432 /// is positive, but for an intrinsic the value count must be negative. The
5433 /// absolute value must be in the range:
5434 /// 1 <= |Value| <= ElementBits for a right shift; or
5435 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
5436 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
5438 assert(VT.isVector() && "vector shift count is not a vector type");
5439 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
5440 if (!getVShiftImm(Op, ElementBits, Cnt))
5444 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
5447 SDValue ARM64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
5448 SelectionDAG &DAG) const {
5449 EVT VT = Op.getValueType();
5453 if (!Op.getOperand(1).getValueType().isVector())
5455 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5457 switch (Op.getOpcode()) {
5459 llvm_unreachable("unexpected shift opcode");
5462 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
5463 return DAG.getNode(ARM64ISD::VSHL, SDLoc(Op), VT, Op.getOperand(0),
5464 DAG.getConstant(Cnt, MVT::i32));
5465 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
5466 DAG.getConstant(Intrinsic::arm64_neon_ushl, MVT::i32),
5467 Op.getOperand(0), Op.getOperand(1));
5470 // Right shift immediate
5471 if (isVShiftRImm(Op.getOperand(1), VT, false, false, Cnt) &&
5474 (Op.getOpcode() == ISD::SRA) ? ARM64ISD::VASHR : ARM64ISD::VLSHR;
5475 return DAG.getNode(Opc, SDLoc(Op), VT, Op.getOperand(0),
5476 DAG.getConstant(Cnt, MVT::i32));
5479 // Right shift register. Note, there is not a shift right register
5480 // instruction, but the shift left register instruction takes a signed
5481 // value, where negative numbers specify a right shift.
5482 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::arm64_neon_sshl
5483 : Intrinsic::arm64_neon_ushl;
5484 // negate the shift amount
5485 SDValue NegShift = DAG.getNode(ARM64ISD::NEG, DL, VT, Op.getOperand(1));
5486 SDValue NegShiftLeft =
5487 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
5488 DAG.getConstant(Opc, MVT::i32), Op.getOperand(0), NegShift);
5489 return NegShiftLeft;
5495 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
5496 ARM64CC::CondCode CC, bool NoNans, EVT VT,
5497 SDLoc dl, SelectionDAG &DAG) {
5498 EVT SrcVT = LHS.getValueType();
5500 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
5501 APInt CnstBits(VT.getSizeInBits(), 0);
5502 APInt UndefBits(VT.getSizeInBits(), 0);
5503 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
5504 bool IsZero = IsCnst && (CnstBits == 0);
5506 if (SrcVT.getVectorElementType().isFloatingPoint()) {
5513 Fcmeq = DAG.getNode(ARM64ISD::FCMEQz, dl, VT, LHS);
5515 Fcmeq = DAG.getNode(ARM64ISD::FCMEQ, dl, VT, LHS, RHS);
5516 return DAG.getNode(ARM64ISD::NOT, dl, VT, Fcmeq);
5520 return DAG.getNode(ARM64ISD::FCMEQz, dl, VT, LHS);
5521 return DAG.getNode(ARM64ISD::FCMEQ, dl, VT, LHS, RHS);
5524 return DAG.getNode(ARM64ISD::FCMGEz, dl, VT, LHS);
5525 return DAG.getNode(ARM64ISD::FCMGE, dl, VT, LHS, RHS);
5528 return DAG.getNode(ARM64ISD::FCMGTz, dl, VT, LHS);
5529 return DAG.getNode(ARM64ISD::FCMGT, dl, VT, LHS, RHS);
5532 return DAG.getNode(ARM64ISD::FCMLEz, dl, VT, LHS);
5533 return DAG.getNode(ARM64ISD::FCMGE, dl, VT, RHS, LHS);
5537 // If we ignore NaNs then we can use to the MI implementation.
5541 return DAG.getNode(ARM64ISD::FCMLTz, dl, VT, LHS);
5542 return DAG.getNode(ARM64ISD::FCMGT, dl, VT, RHS, LHS);
5552 Cmeq = DAG.getNode(ARM64ISD::CMEQz, dl, VT, LHS);
5554 Cmeq = DAG.getNode(ARM64ISD::CMEQ, dl, VT, LHS, RHS);
5555 return DAG.getNode(ARM64ISD::NOT, dl, VT, Cmeq);
5559 return DAG.getNode(ARM64ISD::CMEQz, dl, VT, LHS);
5560 return DAG.getNode(ARM64ISD::CMEQ, dl, VT, LHS, RHS);
5563 return DAG.getNode(ARM64ISD::CMGEz, dl, VT, LHS);
5564 return DAG.getNode(ARM64ISD::CMGE, dl, VT, LHS, RHS);
5567 return DAG.getNode(ARM64ISD::CMGTz, dl, VT, LHS);
5568 return DAG.getNode(ARM64ISD::CMGT, dl, VT, LHS, RHS);
5571 return DAG.getNode(ARM64ISD::CMLEz, dl, VT, LHS);
5572 return DAG.getNode(ARM64ISD::CMGE, dl, VT, RHS, LHS);
5574 return DAG.getNode(ARM64ISD::CMHS, dl, VT, RHS, LHS);
5576 return DAG.getNode(ARM64ISD::CMHI, dl, VT, RHS, LHS);
5579 return DAG.getNode(ARM64ISD::CMLTz, dl, VT, LHS);
5580 return DAG.getNode(ARM64ISD::CMGT, dl, VT, RHS, LHS);
5582 return DAG.getNode(ARM64ISD::CMHI, dl, VT, LHS, RHS);
5584 return DAG.getNode(ARM64ISD::CMHS, dl, VT, LHS, RHS);
5588 SDValue ARM64TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
5589 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
5590 SDValue LHS = Op.getOperand(0);
5591 SDValue RHS = Op.getOperand(1);
5594 if (LHS.getValueType().getVectorElementType().isInteger()) {
5595 assert(LHS.getValueType() == RHS.getValueType());
5596 ARM64CC::CondCode ARM64CC = changeIntCCToARM64CC(CC);
5597 return EmitVectorComparison(LHS, RHS, ARM64CC, false, Op.getValueType(), dl,
5601 assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
5602 LHS.getValueType().getVectorElementType() == MVT::f64);
5604 // Unfortunately, the mapping of LLVM FP CC's onto ARM64 CC's isn't totally
5605 // clean. Some of them require two branches to implement.
5606 ARM64CC::CondCode CC1, CC2;
5608 changeVectorFPCCToARM64CC(CC, CC1, CC2, ShouldInvert);
5610 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
5612 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, Op.getValueType(), dl, DAG);
5616 if (CC2 != ARM64CC::AL) {
5618 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, Op.getValueType(), dl, DAG);
5619 if (!Cmp2.getNode())
5622 Cmp = DAG.getNode(ISD::OR, dl, Cmp.getValueType(), Cmp, Cmp2);
5626 return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
5631 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
5632 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
5633 /// specified in the intrinsic calls.
5634 bool ARM64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
5636 unsigned Intrinsic) const {
5637 switch (Intrinsic) {
5638 case Intrinsic::arm64_neon_ld2:
5639 case Intrinsic::arm64_neon_ld3:
5640 case Intrinsic::arm64_neon_ld4:
5641 case Intrinsic::arm64_neon_ld2lane:
5642 case Intrinsic::arm64_neon_ld3lane:
5643 case Intrinsic::arm64_neon_ld4lane:
5644 case Intrinsic::arm64_neon_ld2r:
5645 case Intrinsic::arm64_neon_ld3r:
5646 case Intrinsic::arm64_neon_ld4r: {
5647 Info.opc = ISD::INTRINSIC_W_CHAIN;
5648 // Conservatively set memVT to the entire set of vectors loaded.
5649 uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
5650 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
5651 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
5654 Info.vol = false; // volatile loads with NEON intrinsics not supported
5655 Info.readMem = true;
5656 Info.writeMem = false;
5659 case Intrinsic::arm64_neon_st2:
5660 case Intrinsic::arm64_neon_st3:
5661 case Intrinsic::arm64_neon_st4:
5662 case Intrinsic::arm64_neon_st2lane:
5663 case Intrinsic::arm64_neon_st3lane:
5664 case Intrinsic::arm64_neon_st4lane: {
5665 Info.opc = ISD::INTRINSIC_VOID;
5666 // Conservatively set memVT to the entire set of vectors stored.
5667 unsigned NumElts = 0;
5668 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
5669 Type *ArgTy = I.getArgOperand(ArgI)->getType();
5670 if (!ArgTy->isVectorTy())
5672 NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
5674 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
5675 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
5678 Info.vol = false; // volatile stores with NEON intrinsics not supported
5679 Info.readMem = false;
5680 Info.writeMem = true;
5683 case Intrinsic::arm64_ldaxr:
5684 case Intrinsic::arm64_ldxr: {
5685 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
5686 Info.opc = ISD::INTRINSIC_W_CHAIN;
5687 Info.memVT = MVT::getVT(PtrTy->getElementType());
5688 Info.ptrVal = I.getArgOperand(0);
5690 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
5692 Info.readMem = true;
5693 Info.writeMem = false;
5696 case Intrinsic::arm64_stlxr:
5697 case Intrinsic::arm64_stxr: {
5698 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
5699 Info.opc = ISD::INTRINSIC_W_CHAIN;
5700 Info.memVT = MVT::getVT(PtrTy->getElementType());
5701 Info.ptrVal = I.getArgOperand(1);
5703 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
5705 Info.readMem = false;
5706 Info.writeMem = true;
5709 case Intrinsic::arm64_ldaxp:
5710 case Intrinsic::arm64_ldxp: {
5711 Info.opc = ISD::INTRINSIC_W_CHAIN;
5712 Info.memVT = MVT::i128;
5713 Info.ptrVal = I.getArgOperand(0);
5717 Info.readMem = true;
5718 Info.writeMem = false;
5721 case Intrinsic::arm64_stlxp:
5722 case Intrinsic::arm64_stxp: {
5723 Info.opc = ISD::INTRINSIC_W_CHAIN;
5724 Info.memVT = MVT::i128;
5725 Info.ptrVal = I.getArgOperand(2);
5729 Info.readMem = false;
5730 Info.writeMem = true;
5740 // Truncations from 64-bit GPR to 32-bit GPR is free.
5741 bool ARM64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
5742 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
5744 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
5745 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
5746 if (NumBits1 <= NumBits2)
5750 bool ARM64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
5751 if (!VT1.isInteger() || !VT2.isInteger())
5753 unsigned NumBits1 = VT1.getSizeInBits();
5754 unsigned NumBits2 = VT2.getSizeInBits();
5755 if (NumBits1 <= NumBits2)
5760 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
5762 bool ARM64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
5763 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
5765 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
5766 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
5767 if (NumBits1 == 32 && NumBits2 == 64)
5771 bool ARM64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
5772 if (!VT1.isInteger() || !VT2.isInteger())
5774 unsigned NumBits1 = VT1.getSizeInBits();
5775 unsigned NumBits2 = VT2.getSizeInBits();
5776 if (NumBits1 == 32 && NumBits2 == 64)
5781 bool ARM64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
5782 EVT VT1 = Val.getValueType();
5783 if (isZExtFree(VT1, VT2)) {
5787 if (Val.getOpcode() != ISD::LOAD)
5790 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
5791 return (VT1.isSimple() && VT1.isInteger() && VT2.isSimple() &&
5792 VT2.isInteger() && VT1.getSizeInBits() <= 32);
5795 bool ARM64TargetLowering::hasPairedLoad(Type *LoadedType,
5796 unsigned &RequiredAligment) const {
5797 if (!LoadedType->isIntegerTy() && !LoadedType->isFloatTy())
5799 // Cyclone supports unaligned accesses.
5800 RequiredAligment = 0;
5801 unsigned NumBits = LoadedType->getPrimitiveSizeInBits();
5802 return NumBits == 32 || NumBits == 64;
5805 bool ARM64TargetLowering::hasPairedLoad(EVT LoadedType,
5806 unsigned &RequiredAligment) const {
5807 if (!LoadedType.isSimple() ||
5808 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
5810 // Cyclone supports unaligned accesses.
5811 RequiredAligment = 0;
5812 unsigned NumBits = LoadedType.getSizeInBits();
5813 return NumBits == 32 || NumBits == 64;
5816 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
5817 unsigned AlignCheck) {
5818 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
5819 (DstAlign == 0 || DstAlign % AlignCheck == 0));
5822 EVT ARM64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
5823 unsigned SrcAlign, bool IsMemset,
5824 bool ZeroMemset, bool MemcpyStrSrc,
5825 MachineFunction &MF) const {
5826 // Don't use AdvSIMD to implement 16-byte memset. It would have taken one
5827 // instruction to materialize the v2i64 zero and one store (with restrictive
5828 // addressing mode). Just do two i64 store of zero-registers.
5830 const Function *F = MF.getFunction();
5831 if (Subtarget->hasFPARMv8() && !IsMemset && Size >= 16 &&
5832 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
5833 Attribute::NoImplicitFloat) &&
5834 (memOpAlign(SrcAlign, DstAlign, 16) ||
5835 (allowsUnalignedMemoryAccesses(MVT::f128, 0, &Fast) && Fast)))
5838 return Size >= 8 ? MVT::i64 : MVT::i32;
5841 // 12-bit optionally shifted immediates are legal for adds.
5842 bool ARM64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
5843 if ((Immed >> 12) == 0 || ((Immed & 0xfff) == 0 && Immed >> 24 == 0))
5848 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
5849 // immediates is the same as for an add or a sub.
5850 bool ARM64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
5853 return isLegalAddImmediate(Immed);
5856 /// isLegalAddressingMode - Return true if the addressing mode represented
5857 /// by AM is legal for this target, for a load/store of the specified type.
5858 bool ARM64TargetLowering::isLegalAddressingMode(const AddrMode &AM,
5860 // ARM64 has five basic addressing modes:
5862 // reg + 9-bit signed offset
5863 // reg + SIZE_IN_BYTES * 12-bit unsigned offset
5865 // reg + SIZE_IN_BYTES * reg
5867 // No global is ever allowed as a base.
5871 // No reg+reg+imm addressing.
5872 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
5875 // check reg + imm case:
5876 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
5877 uint64_t NumBytes = 0;
5878 if (Ty->isSized()) {
5879 uint64_t NumBits = getDataLayout()->getTypeSizeInBits(Ty);
5880 NumBytes = NumBits / 8;
5881 if (!isPowerOf2_64(NumBits))
5886 int64_t Offset = AM.BaseOffs;
5888 // 9-bit signed offset
5889 if (Offset >= -(1LL << 9) && Offset <= (1LL << 9) - 1)
5892 // 12-bit unsigned offset
5893 unsigned shift = Log2_64(NumBytes);
5894 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
5895 // Must be a multiple of NumBytes (NumBytes is a power of 2)
5896 (Offset >> shift) << shift == Offset)
5901 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
5903 if (!AM.Scale || AM.Scale == 1 ||
5904 (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes))
5909 int ARM64TargetLowering::getScalingFactorCost(const AddrMode &AM,
5911 // Scaling factors are not free at all.
5912 // Operands | Rt Latency
5913 // -------------------------------------------
5915 // -------------------------------------------
5916 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5
5917 // Rt, [Xn, Wm, <extend> #imm] |
5918 if (isLegalAddressingMode(AM, Ty))
5919 // Scale represents reg2 * scale, thus account for 1 if
5920 // it is not equal to 0 or 1.
5921 return AM.Scale != 0 && AM.Scale != 1;
5925 bool ARM64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
5926 VT = VT.getScalarType();
5931 switch (VT.getSimpleVT().SimpleTy) {
5943 ARM64TargetLowering::getScratchRegisters(CallingConv::ID) const {
5944 // LR is a callee-save register, but we must treat it as clobbered by any call
5945 // site. Hence we include LR in the scratch registers, which are in turn added
5946 // as implicit-defs for stackmaps and patchpoints.
5947 static const MCPhysReg ScratchRegs[] = {
5948 ARM64::X16, ARM64::X17, ARM64::LR, 0
5953 bool ARM64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N) const {
5954 EVT VT = N->getValueType(0);
5955 // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
5956 // it with shift to let it be lowered to UBFX.
5957 if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
5958 isa<ConstantSDNode>(N->getOperand(1))) {
5959 uint64_t TruncMask = N->getConstantOperandVal(1);
5960 if (isMask_64(TruncMask) &&
5961 N->getOperand(0).getOpcode() == ISD::SRL &&
5962 isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
5968 bool ARM64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
5970 assert(Ty->isIntegerTy());
5972 unsigned BitSize = Ty->getPrimitiveSizeInBits();
5976 int64_t Val = Imm.getSExtValue();
5977 if (Val == 0 || ARM64_AM::isLogicalImmediate(Val, BitSize))
5980 if ((int64_t)Val < 0)
5983 Val &= (1LL << 32) - 1;
5985 unsigned LZ = countLeadingZeros((uint64_t)Val);
5986 unsigned Shift = (63 - LZ) / 16;
5987 // MOVZ is free so return true for one or fewer MOVK.
5988 return (Shift < 3) ? true : false;
5991 // Generate SUBS and CSEL for integer abs.
5992 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
5993 EVT VT = N->getValueType(0);
5995 SDValue N0 = N->getOperand(0);
5996 SDValue N1 = N->getOperand(1);
5999 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
6000 // and change it to SUB and CSEL.
6001 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
6002 N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
6003 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
6004 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
6005 if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
6006 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, VT),
6008 // Generate SUBS & CSEL.
6010 DAG.getNode(ARM64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
6011 N0.getOperand(0), DAG.getConstant(0, VT));
6012 return DAG.getNode(ARM64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
6013 DAG.getConstant(ARM64CC::PL, MVT::i32),
6014 SDValue(Cmp.getNode(), 1));
6019 // performXorCombine - Attempts to handle integer ABS.
6020 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
6021 TargetLowering::DAGCombinerInfo &DCI,
6022 const ARM64Subtarget *Subtarget) {
6023 if (DCI.isBeforeLegalizeOps())
6026 return performIntegerAbsCombine(N, DAG);
6029 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
6030 TargetLowering::DAGCombinerInfo &DCI,
6031 const ARM64Subtarget *Subtarget) {
6032 if (DCI.isBeforeLegalizeOps())
6035 // Multiplication of a power of two plus/minus one can be done more
6036 // cheaply as as shift+add/sub. For now, this is true unilaterally. If
6037 // future CPUs have a cheaper MADD instruction, this may need to be
6038 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
6039 // 64-bit is 5 cycles, so this is always a win.
6040 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
6041 APInt Value = C->getAPIntValue();
6042 EVT VT = N->getValueType(0);
6043 APInt VP1 = Value + 1;
6044 if (VP1.isPowerOf2()) {
6045 // Multiplying by one less than a power of two, replace with a shift
6047 SDValue ShiftedVal =
6048 DAG.getNode(ISD::SHL, SDLoc(N), VT, N->getOperand(0),
6049 DAG.getConstant(VP1.logBase2(), MVT::i64));
6050 return DAG.getNode(ISD::SUB, SDLoc(N), VT, ShiftedVal, N->getOperand(0));
6052 APInt VM1 = Value - 1;
6053 if (VM1.isPowerOf2()) {
6054 // Multiplying by one more than a power of two, replace with a shift
6056 SDValue ShiftedVal =
6057 DAG.getNode(ISD::SHL, SDLoc(N), VT, N->getOperand(0),
6058 DAG.getConstant(VM1.logBase2(), MVT::i64));
6059 return DAG.getNode(ISD::ADD, SDLoc(N), VT, ShiftedVal, N->getOperand(0));
6065 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG) {
6066 EVT VT = N->getValueType(0);
6067 if (VT != MVT::f32 && VT != MVT::f64)
6069 // Only optimize when the source and destination types have the same width.
6070 if (VT.getSizeInBits() != N->getOperand(0).getValueType().getSizeInBits())
6073 // If the result of an integer load is only used by an integer-to-float
6074 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
6075 // This eliminates an "integer-to-vector-move UOP and improve throughput.
6076 SDValue N0 = N->getOperand(0);
6077 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6078 // Do not change the width of a volatile load.
6079 !cast<LoadSDNode>(N0)->isVolatile()) {
6080 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6081 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
6082 LN0->getPointerInfo(), LN0->isVolatile(),
6083 LN0->isNonTemporal(), LN0->isInvariant(),
6084 LN0->getAlignment());
6086 // Make sure successors of the original load stay after it by updating them
6087 // to use the new Chain.
6088 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
6091 (N->getOpcode() == ISD::SINT_TO_FP) ? ARM64ISD::SITOF : ARM64ISD::UITOF;
6092 return DAG.getNode(Opcode, SDLoc(N), VT, Load);
6098 /// An EXTR instruction is made up of two shifts, ORed together. This helper
6099 /// searches for and classifies those shifts.
6100 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
6102 if (N.getOpcode() == ISD::SHL)
6104 else if (N.getOpcode() == ISD::SRL)
6109 if (!isa<ConstantSDNode>(N.getOperand(1)))
6112 ShiftAmount = N->getConstantOperandVal(1);
6113 Src = N->getOperand(0);
6117 /// EXTR instruction extracts a contiguous chunk of bits from two existing
6118 /// registers viewed as a high/low pair. This function looks for the pattern:
6119 /// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an
6120 /// EXTR. Can't quite be done in TableGen because the two immediates aren't
6122 static SDValue tryCombineToEXTR(SDNode *N,
6123 TargetLowering::DAGCombinerInfo &DCI) {
6124 SelectionDAG &DAG = DCI.DAG;
6126 EVT VT = N->getValueType(0);
6128 assert(N->getOpcode() == ISD::OR && "Unexpected root");
6130 if (VT != MVT::i32 && VT != MVT::i64)
6134 uint32_t ShiftLHS = 0;
6136 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
6140 uint32_t ShiftRHS = 0;
6142 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
6145 // If they're both trying to come from the high part of the register, they're
6146 // not really an EXTR.
6147 if (LHSFromHi == RHSFromHi)
6150 if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
6154 std::swap(LHS, RHS);
6155 std::swap(ShiftLHS, ShiftRHS);
6158 return DAG.getNode(ARM64ISD::EXTR, DL, VT, LHS, RHS,
6159 DAG.getConstant(ShiftRHS, MVT::i64));
6162 static SDValue tryCombineToBSL(SDNode *N,
6163 TargetLowering::DAGCombinerInfo &DCI) {
6164 EVT VT = N->getValueType(0);
6165 SelectionDAG &DAG = DCI.DAG;
6171 SDValue N0 = N->getOperand(0);
6172 if (N0.getOpcode() != ISD::AND)
6175 SDValue N1 = N->getOperand(1);
6176 if (N1.getOpcode() != ISD::AND)
6179 // We only have to look for constant vectors here since the general, variable
6180 // case can be handled in TableGen.
6181 unsigned Bits = VT.getVectorElementType().getSizeInBits();
6182 uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
6183 for (int i = 1; i >= 0; --i)
6184 for (int j = 1; j >= 0; --j) {
6185 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
6186 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
6190 bool FoundMatch = true;
6191 for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
6192 ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
6193 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
6195 CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
6202 return DAG.getNode(ARM64ISD::BSL, DL, VT, SDValue(BVN0, 0),
6203 N0->getOperand(1 - i), N1->getOperand(1 - j));
6209 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
6210 const ARM64Subtarget *Subtarget) {
6211 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
6212 if (!EnableARM64ExtrGeneration)
6214 SelectionDAG &DAG = DCI.DAG;
6215 EVT VT = N->getValueType(0);
6217 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
6220 SDValue Res = tryCombineToEXTR(N, DCI);
6224 Res = tryCombineToBSL(N, DCI);
6231 static SDValue performBitcastCombine(SDNode *N,
6232 TargetLowering::DAGCombinerInfo &DCI,
6233 SelectionDAG &DAG) {
6234 // Wait 'til after everything is legalized to try this. That way we have
6235 // legal vector types and such.
6236 if (DCI.isBeforeLegalizeOps())
6239 // Remove extraneous bitcasts around an extract_subvector.
6241 // (v4i16 (bitconvert
6242 // (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
6244 // (extract_subvector ((v8i16 ...), (i64 4)))
6246 // Only interested in 64-bit vectors as the ultimate result.
6247 EVT VT = N->getValueType(0);
6250 if (VT.getSimpleVT().getSizeInBits() != 64)
6252 // Is the operand an extract_subvector starting at the beginning or halfway
6253 // point of the vector? A low half may also come through as an
6254 // EXTRACT_SUBREG, so look for that, too.
6255 SDValue Op0 = N->getOperand(0);
6256 if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
6257 !(Op0->isMachineOpcode() &&
6258 Op0->getMachineOpcode() == ARM64::EXTRACT_SUBREG))
6260 uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
6261 if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
6262 if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
6264 } else if (Op0->getMachineOpcode() == ARM64::EXTRACT_SUBREG) {
6265 if (idx != ARM64::dsub)
6267 // The dsub reference is equivalent to a lane zero subvector reference.
6270 // Look through the bitcast of the input to the extract.
6271 if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
6273 SDValue Source = Op0->getOperand(0)->getOperand(0);
6274 // If the source type has twice the number of elements as our destination
6275 // type, we know this is an extract of the high or low half of the vector.
6276 EVT SVT = Source->getValueType(0);
6277 if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
6280 DEBUG(dbgs() << "arm64-lower: bitcast extract_subvector simplification\n");
6282 // Create the simplified form to just extract the low or high half of the
6283 // vector directly rather than bothering with the bitcasts.
6285 unsigned NumElements = VT.getVectorNumElements();
6287 SDValue HalfIdx = DAG.getConstant(NumElements, MVT::i64);
6288 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
6290 SDValue SubReg = DAG.getTargetConstant(ARM64::dsub, MVT::i32);
6291 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
6297 static SDValue performConcatVectorsCombine(SDNode *N,
6298 TargetLowering::DAGCombinerInfo &DCI,
6299 SelectionDAG &DAG) {
6300 // Wait 'til after everything is legalized to try this. That way we have
6301 // legal vector types and such.
6302 if (DCI.isBeforeLegalizeOps())
6306 EVT VT = N->getValueType(0);
6308 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
6309 // splat. The indexed instructions are going to be expecting a DUPLANE64, so
6310 // canonicalise to that.
6311 if (N->getOperand(0) == N->getOperand(1) && VT.getVectorNumElements() == 2) {
6312 assert(VT.getVectorElementType().getSizeInBits() == 64);
6313 return DAG.getNode(ARM64ISD::DUPLANE64, dl, VT,
6314 WidenVector(N->getOperand(0), DAG),
6315 DAG.getConstant(0, MVT::i64));
6318 // Canonicalise concat_vectors so that the right-hand vector has as few
6319 // bit-casts as possible before its real operation. The primary matching
6320 // destination for these operations will be the narrowing "2" instructions,
6321 // which depend on the operation being performed on this right-hand vector.
6323 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS))))
6325 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
6327 SDValue Op1 = N->getOperand(1);
6328 if (Op1->getOpcode() != ISD::BITCAST)
6330 SDValue RHS = Op1->getOperand(0);
6331 MVT RHSTy = RHS.getValueType().getSimpleVT();
6332 // If the RHS is not a vector, this is not the pattern we're looking for.
6333 if (!RHSTy.isVector())
6336 DEBUG(dbgs() << "arm64-lower: concat_vectors bitcast simplification\n");
6338 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
6339 RHSTy.getVectorNumElements() * 2);
6341 ISD::BITCAST, dl, VT,
6342 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
6343 DAG.getNode(ISD::BITCAST, dl, RHSTy, N->getOperand(0)), RHS));
6346 static SDValue tryCombineFixedPointConvert(SDNode *N,
6347 TargetLowering::DAGCombinerInfo &DCI,
6348 SelectionDAG &DAG) {
6349 // Wait 'til after everything is legalized to try this. That way we have
6350 // legal vector types and such.
6351 if (DCI.isBeforeLegalizeOps())
6353 // Transform a scalar conversion of a value from a lane extract into a
6354 // lane extract of a vector conversion. E.g., from foo1 to foo2:
6355 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
6356 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
6358 // The second form interacts better with instruction selection and the
6359 // register allocator to avoid cross-class register copies that aren't
6360 // coalescable due to a lane reference.
6362 // Check the operand and see if it originates from a lane extract.
6363 SDValue Op1 = N->getOperand(1);
6364 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
6365 // Yep, no additional predication needed. Perform the transform.
6366 SDValue IID = N->getOperand(0);
6367 SDValue Shift = N->getOperand(2);
6368 SDValue Vec = Op1.getOperand(0);
6369 SDValue Lane = Op1.getOperand(1);
6370 EVT ResTy = N->getValueType(0);
6374 // The vector width should be 128 bits by the time we get here, even
6375 // if it started as 64 bits (the extract_vector handling will have
6377 assert(Vec.getValueType().getSizeInBits() == 128 &&
6378 "unexpected vector size on extract_vector_elt!");
6379 if (Vec.getValueType() == MVT::v4i32)
6380 VecResTy = MVT::v4f32;
6381 else if (Vec.getValueType() == MVT::v2i64)
6382 VecResTy = MVT::v2f64;
6384 assert(0 && "unexpected vector type!");
6387 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
6388 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
6393 // AArch64 high-vector "long" operations are formed by performing the non-high
6394 // version on an extract_subvector of each operand which gets the high half:
6396 // (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
6398 // However, there are cases which don't have an extract_high explicitly, but
6399 // have another operation that can be made compatible with one for free. For
6402 // (dupv64 scalar) --> (extract_high (dup128 scalar))
6404 // This routine does the actual conversion of such DUPs, once outer routines
6405 // have determined that everything else is in order.
6406 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
6407 // We can handle most types of duplicate, but the lane ones have an extra
6408 // operand saying *which* lane, so we need to know.
6410 switch (N.getOpcode()) {
6414 case ARM64ISD::DUPLANE8:
6415 case ARM64ISD::DUPLANE16:
6416 case ARM64ISD::DUPLANE32:
6417 case ARM64ISD::DUPLANE64:
6424 MVT NarrowTy = N.getSimpleValueType();
6425 if (!NarrowTy.is64BitVector())
6428 MVT ElementTy = NarrowTy.getVectorElementType();
6429 unsigned NumElems = NarrowTy.getVectorNumElements();
6430 MVT NewDUPVT = MVT::getVectorVT(ElementTy, NumElems * 2);
6434 NewDUP = DAG.getNode(N.getOpcode(), SDLoc(N), NewDUPVT, N.getOperand(0),
6437 NewDUP = DAG.getNode(ARM64ISD::DUP, SDLoc(N), NewDUPVT, N.getOperand(0));
6439 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N.getNode()), NarrowTy,
6440 NewDUP, DAG.getConstant(NumElems, MVT::i64));
6443 static bool isEssentiallyExtractSubvector(SDValue N) {
6444 if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
6447 return N.getOpcode() == ISD::BITCAST &&
6448 N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
6451 /// \brief Helper structure to keep track of ISD::SET_CC operands.
6452 struct GenericSetCCInfo {
6453 const SDValue *Opnd0;
6454 const SDValue *Opnd1;
6458 /// \brief Helper structure to keep track of a SET_CC lowered into ARM64 code.
6459 struct ARM64SetCCInfo {
6461 ARM64CC::CondCode CC;
6464 /// \brief Helper structure to keep track of SetCC information.
6466 GenericSetCCInfo Generic;
6467 ARM64SetCCInfo ARM64;
6470 /// \brief Helper structure to be able to read SetCC information.
6471 /// If set to true, IsARM64 field, Info is a ARM64SetCCInfo, otherwise Info is
6472 /// a GenericSetCCInfo.
6473 struct SetCCInfoAndKind {
6478 /// \brief Check whether or not \p Op is a SET_CC operation, either a generic or
6480 /// ARM64 lowered one.
6481 /// \p SetCCInfo is filled accordingly.
6482 /// \post SetCCInfo is meanginfull only when this function returns true.
6483 /// \return True when Op is a kind of SET_CC operation.
6484 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
6485 // If this is a setcc, this is straight forward.
6486 if (Op.getOpcode() == ISD::SETCC) {
6487 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
6488 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
6489 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6490 SetCCInfo.IsARM64 = false;
6493 // Otherwise, check if this is a matching csel instruction.
6497 if (Op.getOpcode() != ARM64ISD::CSEL)
6499 // Set the information about the operands.
6500 // TODO: we want the operands of the Cmp not the csel
6501 SetCCInfo.Info.ARM64.Cmp = &Op.getOperand(3);
6502 SetCCInfo.IsARM64 = true;
6503 SetCCInfo.Info.ARM64.CC = static_cast<ARM64CC::CondCode>(
6504 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
6506 // Check that the operands matches the constraints:
6507 // (1) Both operands must be constants.
6508 // (2) One must be 1 and the other must be 0.
6509 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
6510 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6513 if (!TValue || !FValue)
6517 if (!TValue->isOne()) {
6518 // Update the comparison when we are interested in !cc.
6519 std::swap(TValue, FValue);
6520 SetCCInfo.Info.ARM64.CC =
6521 ARM64CC::getInvertedCondCode(SetCCInfo.Info.ARM64.CC);
6523 return TValue->isOne() && FValue->isNullValue();
6526 // The folding we want to perform is:
6527 // (add x, (setcc cc ...) )
6529 // (csel x, (add x, 1), !cc ...)
6531 // The latter will get matched to a CSINC instruction.
6532 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
6533 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
6534 SDValue LHS = Op->getOperand(0);
6535 SDValue RHS = Op->getOperand(1);
6536 SetCCInfoAndKind InfoAndKind;
6538 // If neither operand is a SET_CC, give up.
6539 if (!isSetCC(LHS, InfoAndKind)) {
6540 std::swap(LHS, RHS);
6541 if (!isSetCC(LHS, InfoAndKind))
6545 // FIXME: This could be generatized to work for FP comparisons.
6546 EVT CmpVT = InfoAndKind.IsARM64
6547 ? InfoAndKind.Info.ARM64.Cmp->getOperand(0).getValueType()
6548 : InfoAndKind.Info.Generic.Opnd0->getValueType();
6549 if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
6555 if (InfoAndKind.IsARM64) {
6556 CCVal = DAG.getConstant(
6557 ARM64CC::getInvertedCondCode(InfoAndKind.Info.ARM64.CC), MVT::i32);
6558 Cmp = *InfoAndKind.Info.ARM64.Cmp;
6560 Cmp = getARM64Cmp(*InfoAndKind.Info.Generic.Opnd0,
6561 *InfoAndKind.Info.Generic.Opnd1,
6562 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
6565 EVT VT = Op->getValueType(0);
6566 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, VT));
6567 return DAG.getNode(ARM64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
6570 // The basic add/sub long vector instructions have variants with "2" on the end
6571 // which act on the high-half of their inputs. They are normally matched by
6574 // (add (zeroext (extract_high LHS)),
6575 // (zeroext (extract_high RHS)))
6576 // -> uaddl2 vD, vN, vM
6578 // However, if one of the extracts is something like a duplicate, this
6579 // instruction can still be used profitably. This function puts the DAG into a
6580 // more appropriate form for those patterns to trigger.
6581 static SDValue performAddSubLongCombine(SDNode *N,
6582 TargetLowering::DAGCombinerInfo &DCI,
6583 SelectionDAG &DAG) {
6584 if (DCI.isBeforeLegalizeOps())
6587 MVT VT = N->getSimpleValueType(0);
6588 if (!VT.is128BitVector()) {
6589 if (N->getOpcode() == ISD::ADD)
6590 return performSetccAddFolding(N, DAG);
6594 // Make sure both branches are extended in the same way.
6595 SDValue LHS = N->getOperand(0);
6596 SDValue RHS = N->getOperand(1);
6597 if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
6598 LHS.getOpcode() != ISD::SIGN_EXTEND) ||
6599 LHS.getOpcode() != RHS.getOpcode())
6602 unsigned ExtType = LHS.getOpcode();
6604 // It's not worth doing if at least one of the inputs isn't already an
6605 // extract, but we don't know which it'll be so we have to try both.
6606 if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
6607 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
6611 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
6612 } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
6613 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
6617 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
6620 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
6623 // Massage DAGs which we can use the high-half "long" operations on into
6624 // something isel will recognize better. E.g.
6626 // (arm64_neon_umull (extract_high vec) (dupv64 scalar)) -->
6627 // (arm64_neon_umull (extract_high (v2i64 vec)))
6628 // (extract_high (v2i64 (dup128 scalar)))))
6630 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
6631 TargetLowering::DAGCombinerInfo &DCI,
6632 SelectionDAG &DAG) {
6633 if (DCI.isBeforeLegalizeOps())
6636 SDValue LHS = N->getOperand(1);
6637 SDValue RHS = N->getOperand(2);
6638 assert(LHS.getValueType().is64BitVector() &&
6639 RHS.getValueType().is64BitVector() &&
6640 "unexpected shape for long operation");
6642 // Either node could be a DUP, but it's not worth doing both of them (you'd
6643 // just as well use the non-high version) so look for a corresponding extract
6644 // operation on the other "wing".
6645 if (isEssentiallyExtractSubvector(LHS)) {
6646 RHS = tryExtendDUPToExtractHigh(RHS, DAG);
6649 } else if (isEssentiallyExtractSubvector(RHS)) {
6650 LHS = tryExtendDUPToExtractHigh(LHS, DAG);
6655 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
6656 N->getOperand(0), LHS, RHS);
6659 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
6660 MVT ElemTy = N->getSimpleValueType(0).getScalarType();
6661 unsigned ElemBits = ElemTy.getSizeInBits();
6663 int64_t ShiftAmount;
6664 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
6665 APInt SplatValue, SplatUndef;
6666 unsigned SplatBitSize;
6668 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
6669 HasAnyUndefs, ElemBits) ||
6670 SplatBitSize != ElemBits)
6673 ShiftAmount = SplatValue.getSExtValue();
6674 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
6675 ShiftAmount = CVN->getSExtValue();
6683 llvm_unreachable("Unknown shift intrinsic");
6684 case Intrinsic::arm64_neon_sqshl:
6685 Opcode = ARM64ISD::SQSHL_I;
6686 IsRightShift = false;
6688 case Intrinsic::arm64_neon_uqshl:
6689 Opcode = ARM64ISD::UQSHL_I;
6690 IsRightShift = false;
6692 case Intrinsic::arm64_neon_srshl:
6693 Opcode = ARM64ISD::SRSHR_I;
6694 IsRightShift = true;
6696 case Intrinsic::arm64_neon_urshl:
6697 Opcode = ARM64ISD::URSHR_I;
6698 IsRightShift = true;
6700 case Intrinsic::arm64_neon_sqshlu:
6701 Opcode = ARM64ISD::SQSHLU_I;
6702 IsRightShift = false;
6706 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits)
6707 return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), N->getOperand(1),
6708 DAG.getConstant(-ShiftAmount, MVT::i32));
6709 else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount <= ElemBits)
6710 return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), N->getOperand(1),
6711 DAG.getConstant(ShiftAmount, MVT::i32));
6716 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
6717 // the intrinsics must be legal and take an i32, this means there's almost
6718 // certainly going to be a zext in the DAG which we can eliminate.
6719 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
6720 SDValue AndN = N->getOperand(2);
6721 if (AndN.getOpcode() != ISD::AND)
6724 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
6725 if (!CMask || CMask->getZExtValue() != Mask)
6728 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
6729 N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
6732 static SDValue performIntrinsicCombine(SDNode *N,
6733 TargetLowering::DAGCombinerInfo &DCI,
6734 const ARM64Subtarget *Subtarget) {
6735 SelectionDAG &DAG = DCI.DAG;
6736 unsigned IID = getIntrinsicID(N);
6740 case Intrinsic::arm64_neon_vcvtfxs2fp:
6741 case Intrinsic::arm64_neon_vcvtfxu2fp:
6742 return tryCombineFixedPointConvert(N, DCI, DAG);
6744 case Intrinsic::arm64_neon_fmax:
6745 return DAG.getNode(ARM64ISD::FMAX, SDLoc(N), N->getValueType(0),
6746 N->getOperand(1), N->getOperand(2));
6747 case Intrinsic::arm64_neon_fmin:
6748 return DAG.getNode(ARM64ISD::FMIN, SDLoc(N), N->getValueType(0),
6749 N->getOperand(1), N->getOperand(2));
6750 case Intrinsic::arm64_neon_smull:
6751 case Intrinsic::arm64_neon_umull:
6752 case Intrinsic::arm64_neon_pmull:
6753 case Intrinsic::arm64_neon_sqdmull:
6754 return tryCombineLongOpWithDup(IID, N, DCI, DAG);
6755 case Intrinsic::arm64_neon_sqshl:
6756 case Intrinsic::arm64_neon_uqshl:
6757 case Intrinsic::arm64_neon_sqshlu:
6758 case Intrinsic::arm64_neon_srshl:
6759 case Intrinsic::arm64_neon_urshl:
6760 return tryCombineShiftImm(IID, N, DAG);
6761 case Intrinsic::arm64_crc32b:
6762 case Intrinsic::arm64_crc32cb:
6763 return tryCombineCRC32(0xff, N, DAG);
6764 case Intrinsic::arm64_crc32h:
6765 case Intrinsic::arm64_crc32ch:
6766 return tryCombineCRC32(0xffff, N, DAG);
6771 static SDValue performExtendCombine(SDNode *N,
6772 TargetLowering::DAGCombinerInfo &DCI,
6773 SelectionDAG &DAG) {
6774 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
6775 // we can convert that DUP into another extract_high (of a bigger DUP), which
6776 // helps the backend to decide that an sabdl2 would be useful, saving a real
6777 // extract_high operation.
6778 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
6779 N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
6780 SDNode *ABDNode = N->getOperand(0).getNode();
6781 unsigned IID = getIntrinsicID(ABDNode);
6782 if (IID == Intrinsic::arm64_neon_sabd ||
6783 IID == Intrinsic::arm64_neon_uabd) {
6784 SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
6785 if (!NewABD.getNode())
6788 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
6793 // This is effectively a custom type legalization for ARM64.
6795 // Type legalization will split an extend of a small, legal, type to a larger
6796 // illegal type by first splitting the destination type, often creating
6797 // illegal source types, which then get legalized in isel-confusing ways,
6798 // leading to really terrible codegen. E.g.,
6799 // %result = v8i32 sext v8i8 %value
6801 // %losrc = extract_subreg %value, ...
6802 // %hisrc = extract_subreg %value, ...
6803 // %lo = v4i32 sext v4i8 %losrc
6804 // %hi = v4i32 sext v4i8 %hisrc
6805 // Things go rapidly downhill from there.
6807 // For ARM64, the [sz]ext vector instructions can only go up one element
6808 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
6809 // take two instructions.
6811 // This implies that the most efficient way to do the extend from v8i8
6812 // to two v4i32 values is to first extend the v8i8 to v8i16, then do
6813 // the normal splitting to happen for the v8i16->v8i32.
6815 // This is pre-legalization to catch some cases where the default
6816 // type legalization will create ill-tempered code.
6817 if (!DCI.isBeforeLegalizeOps())
6820 // We're only interested in cleaning things up for non-legal vector types
6821 // here. If both the source and destination are legal, things will just
6822 // work naturally without any fiddling.
6823 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6824 EVT ResVT = N->getValueType(0);
6825 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
6827 // If the vector type isn't a simple VT, it's beyond the scope of what
6828 // we're worried about here. Let legalization do its thing and hope for
6830 if (!ResVT.isSimple())
6833 SDValue Src = N->getOperand(0);
6834 MVT SrcVT = Src->getValueType(0).getSimpleVT();
6835 // If the source VT is a 64-bit vector, we can play games and get the
6836 // better results we want.
6837 if (SrcVT.getSizeInBits() != 64)
6840 unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits();
6841 unsigned ElementCount = SrcVT.getVectorNumElements();
6842 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
6844 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
6846 // Now split the rest of the operation into two halves, each with a 64
6850 unsigned NumElements = ResVT.getVectorNumElements();
6851 assert(!(NumElements & 1) && "Splitting vector, but not in half!");
6852 LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
6853 ResVT.getVectorElementType(), NumElements / 2);
6855 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
6856 LoVT.getVectorNumElements());
6857 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
6858 DAG.getIntPtrConstant(0));
6859 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
6860 DAG.getIntPtrConstant(InNVT.getVectorNumElements()));
6861 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
6862 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
6864 // Now combine the parts back together so we still have a single result
6865 // like the combiner expects.
6866 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
6869 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
6870 /// value. The load store optimizer pass will merge them to store pair stores.
6871 /// This has better performance than a splat of the scalar followed by a split
6872 /// vector store. Even if the stores are not merged it is four stores vs a dup,
6873 /// followed by an ext.b and two stores.
6874 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode *St) {
6875 SDValue StVal = St->getValue();
6876 EVT VT = StVal.getValueType();
6878 // Don't replace floating point stores, they possibly won't be transformed to
6879 // stp because of the store pair suppress pass.
6880 if (VT.isFloatingPoint())
6883 // Check for insert vector elements.
6884 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
6887 // We can express a splat as store pair(s) for 2 or 4 elements.
6888 unsigned NumVecElts = VT.getVectorNumElements();
6889 if (NumVecElts != 4 && NumVecElts != 2)
6891 SDValue SplatVal = StVal.getOperand(1);
6892 unsigned RemainInsertElts = NumVecElts - 1;
6894 // Check that this is a splat.
6895 while (--RemainInsertElts) {
6896 SDValue NextInsertElt = StVal.getOperand(0);
6897 if (NextInsertElt.getOpcode() != ISD::INSERT_VECTOR_ELT)
6899 if (NextInsertElt.getOperand(1) != SplatVal)
6901 StVal = NextInsertElt;
6903 unsigned OrigAlignment = St->getAlignment();
6904 unsigned EltOffset = NumVecElts == 4 ? 4 : 8;
6905 unsigned Alignment = std::min(OrigAlignment, EltOffset);
6907 // Create scalar stores. This is at least as good as the code sequence for a
6908 // split unaligned store wich is a dup.s, ext.b, and two stores.
6909 // Most of the time the three stores should be replaced by store pair
6910 // instructions (stp).
6912 SDValue BasePtr = St->getBasePtr();
6914 DAG.getStore(St->getChain(), DL, SplatVal, BasePtr, St->getPointerInfo(),
6915 St->isVolatile(), St->isNonTemporal(), St->getAlignment());
6917 unsigned Offset = EltOffset;
6918 while (--NumVecElts) {
6919 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
6920 DAG.getConstant(Offset, MVT::i64));
6921 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
6922 St->getPointerInfo(), St->isVolatile(),
6923 St->isNonTemporal(), Alignment);
6924 Offset += EltOffset;
6929 static SDValue performSTORECombine(SDNode *N,
6930 TargetLowering::DAGCombinerInfo &DCI,
6932 const ARM64Subtarget *Subtarget) {
6933 if (!DCI.isBeforeLegalize())
6936 StoreSDNode *S = cast<StoreSDNode>(N);
6937 if (S->isVolatile())
6940 // Cyclone has bad performance on unaligned 16B stores when crossing line and
6941 // page boundries. We want to split such stores.
6942 if (!Subtarget->isCyclone())
6945 // Don't split at Oz.
6946 MachineFunction &MF = DAG.getMachineFunction();
6947 bool IsMinSize = MF.getFunction()->getAttributes().hasAttribute(
6948 AttributeSet::FunctionIndex, Attribute::MinSize);
6952 SDValue StVal = S->getValue();
6953 EVT VT = StVal.getValueType();
6955 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
6956 // those up regresses performance on micro-benchmarks and olden/bh.
6957 if (!VT.isVector() || VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
6960 // Split unaligned 16B stores. They are terrible for performance.
6961 // Don't split stores with alignment of 1 or 2. Code that uses clang vector
6962 // extensions can use this to mark that it does not want splitting to happen
6963 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
6964 // eliminating alignment hazards is only 1 in 8 for alignment of 2.
6965 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
6966 S->getAlignment() <= 2)
6969 // If we get a splat of a scalar convert this vector store to a store of
6970 // scalars. They will be merged into store pairs thereby removing two
6972 SDValue ReplacedSplat = replaceSplatVectorStore(DAG, S);
6973 if (ReplacedSplat != SDValue())
6974 return ReplacedSplat;
6977 unsigned NumElts = VT.getVectorNumElements() / 2;
6978 // Split VT into two.
6980 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
6981 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
6982 DAG.getIntPtrConstant(0));
6983 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
6984 DAG.getIntPtrConstant(NumElts));
6985 SDValue BasePtr = S->getBasePtr();
6987 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
6988 S->isVolatile(), S->isNonTemporal(), S->getAlignment());
6989 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
6990 DAG.getConstant(8, MVT::i64));
6991 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
6992 S->getPointerInfo(), S->isVolatile(), S->isNonTemporal(),
6996 // Optimize compare with zero and branch.
6997 static SDValue performBRCONDCombine(SDNode *N,
6998 TargetLowering::DAGCombinerInfo &DCI,
6999 SelectionDAG &DAG) {
7000 SDValue Chain = N->getOperand(0);
7001 SDValue Dest = N->getOperand(1);
7002 SDValue CCVal = N->getOperand(2);
7003 SDValue Cmp = N->getOperand(3);
7005 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
7006 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
7007 if (CC != ARM64CC::EQ && CC != ARM64CC::NE)
7010 unsigned CmpOpc = Cmp.getOpcode();
7011 if (CmpOpc != ARM64ISD::ADDS && CmpOpc != ARM64ISD::SUBS)
7014 // Only attempt folding if there is only one use of the flag and no use of the
7016 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
7019 SDValue LHS = Cmp.getOperand(0);
7020 SDValue RHS = Cmp.getOperand(1);
7022 assert(LHS.getValueType() == RHS.getValueType() &&
7023 "Expected the value type to be the same for both operands!");
7024 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
7027 if (isa<ConstantSDNode>(LHS) && cast<ConstantSDNode>(LHS)->isNullValue())
7028 std::swap(LHS, RHS);
7030 if (!isa<ConstantSDNode>(RHS) || !cast<ConstantSDNode>(RHS)->isNullValue())
7033 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
7034 LHS.getOpcode() == ISD::SRL)
7037 // Fold the compare into the branch instruction.
7039 if (CC == ARM64CC::EQ)
7040 BR = DAG.getNode(ARM64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
7042 BR = DAG.getNode(ARM64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
7044 // Do not add new nodes to DAG combiner worklist.
7045 DCI.CombineTo(N, BR, false);
7050 // vselect (v1i1 setcc) ->
7051 // vselect (v1iXX setcc) (XX is the size of the compared operand type)
7052 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
7053 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
7055 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
7056 SDValue N0 = N->getOperand(0);
7057 EVT CCVT = N0.getValueType();
7059 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
7060 CCVT.getVectorElementType() != MVT::i1)
7063 EVT ResVT = N->getValueType(0);
7064 EVT CmpVT = N0.getOperand(0).getValueType();
7065 // Only combine when the result type is of the same size as the compared
7067 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
7070 SDValue IfTrue = N->getOperand(1);
7071 SDValue IfFalse = N->getOperand(2);
7073 DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
7074 N0.getOperand(0), N0.getOperand(1),
7075 cast<CondCodeSDNode>(N0.getOperand(2))->get());
7076 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
7080 SDValue ARM64TargetLowering::PerformDAGCombine(SDNode *N,
7081 DAGCombinerInfo &DCI) const {
7082 SelectionDAG &DAG = DCI.DAG;
7083 switch (N->getOpcode()) {
7088 return performAddSubLongCombine(N, DCI, DAG);
7090 return performXorCombine(N, DAG, DCI, Subtarget);
7092 return performMulCombine(N, DAG, DCI, Subtarget);
7093 case ISD::SINT_TO_FP:
7094 case ISD::UINT_TO_FP:
7095 return performIntToFpCombine(N, DAG);
7097 return performORCombine(N, DCI, Subtarget);
7098 case ISD::INTRINSIC_WO_CHAIN:
7099 return performIntrinsicCombine(N, DCI, Subtarget);
7100 case ISD::ANY_EXTEND:
7101 case ISD::ZERO_EXTEND:
7102 case ISD::SIGN_EXTEND:
7103 return performExtendCombine(N, DCI, DAG);
7105 return performBitcastCombine(N, DCI, DAG);
7106 case ISD::CONCAT_VECTORS:
7107 return performConcatVectorsCombine(N, DCI, DAG);
7109 return performVSelectCombine(N, DCI.DAG);
7111 return performSTORECombine(N, DCI, DAG, Subtarget);
7112 case ARM64ISD::BRCOND:
7113 return performBRCONDCombine(N, DCI, DAG);
7118 // Check if the return value is used as only a return value, as otherwise
7119 // we can't perform a tail-call. In particular, we need to check for
7120 // target ISD nodes that are returns and any other "odd" constructs
7121 // that the generic analysis code won't necessarily catch.
7122 bool ARM64TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
7123 if (N->getNumValues() != 1)
7125 if (!N->hasNUsesOfValue(1, 0))
7128 SDValue TCChain = Chain;
7129 SDNode *Copy = *N->use_begin();
7130 if (Copy->getOpcode() == ISD::CopyToReg) {
7131 // If the copy has a glue operand, we conservatively assume it isn't safe to
7132 // perform a tail call.
7133 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
7136 TCChain = Copy->getOperand(0);
7137 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
7140 bool HasRet = false;
7141 for (SDNode *Node : Copy->uses()) {
7142 if (Node->getOpcode() != ARM64ISD::RET_FLAG)
7154 // Return whether the an instruction can potentially be optimized to a tail
7155 // call. This will cause the optimizers to attempt to move, or duplicate,
7156 // return instructions to help enable tail call optimizations for this
7158 bool ARM64TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
7159 if (!EnableARM64TailCalls)
7162 if (!CI->isTailCall())
7168 bool ARM64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
7170 ISD::MemIndexedMode &AM,
7172 SelectionDAG &DAG) const {
7173 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
7176 Base = Op->getOperand(0);
7177 // All of the indexed addressing mode instructions take a signed
7178 // 9 bit immediate offset.
7179 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
7180 int64_t RHSC = (int64_t)RHS->getZExtValue();
7181 if (RHSC >= 256 || RHSC <= -256)
7183 IsInc = (Op->getOpcode() == ISD::ADD);
7184 Offset = Op->getOperand(1);
7190 bool ARM64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
7192 ISD::MemIndexedMode &AM,
7193 SelectionDAG &DAG) const {
7196 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7197 VT = LD->getMemoryVT();
7198 Ptr = LD->getBasePtr();
7199 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7200 VT = ST->getMemoryVT();
7201 Ptr = ST->getBasePtr();
7206 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
7208 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
7212 bool ARM64TargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
7215 ISD::MemIndexedMode &AM,
7216 SelectionDAG &DAG) const {
7219 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7220 VT = LD->getMemoryVT();
7221 Ptr = LD->getBasePtr();
7222 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7223 VT = ST->getMemoryVT();
7224 Ptr = ST->getBasePtr();
7229 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
7231 // Post-indexing updates the base, so it's not a valid transform
7232 // if that's not the same as the load's pointer.
7235 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
7239 void ARM64TargetLowering::ReplaceNodeResults(SDNode *N,
7240 SmallVectorImpl<SDValue> &Results,
7241 SelectionDAG &DAG) const {
7242 switch (N->getOpcode()) {
7244 llvm_unreachable("Don't know how to custom expand this");
7245 case ISD::FP_TO_UINT:
7246 case ISD::FP_TO_SINT:
7247 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
7248 // Let normal code take care of it by not adding anything to Results.
7253 bool ARM64TargetLowering::shouldExpandAtomicInIR(Instruction *Inst) const {
7254 // Loads and stores less than 128-bits are already atomic; ones above that
7255 // are doomed anyway, so defer to the default libcall and blame the OS when
7257 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
7258 return SI->getValueOperand()->getType()->getPrimitiveSizeInBits() == 128;
7259 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
7260 return LI->getType()->getPrimitiveSizeInBits() == 128;
7262 // For the real atomic operations, we have ldxr/stxr up to 128 bits.
7263 return Inst->getType()->getPrimitiveSizeInBits() <= 128;
7266 Value *ARM64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
7267 AtomicOrdering Ord) const {
7268 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
7269 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
7271 Ord == Acquire || Ord == AcquireRelease || Ord == SequentiallyConsistent;
7273 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
7274 // intrinsic must return {i64, i64} and we have to recombine them into a
7275 // single i128 here.
7276 if (ValTy->getPrimitiveSizeInBits() == 128) {
7278 IsAcquire ? Intrinsic::arm64_ldaxp : Intrinsic::arm64_ldxp;
7279 Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int);
7281 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
7282 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
7284 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
7285 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
7286 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
7287 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
7288 return Builder.CreateOr(
7289 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
7292 Type *Tys[] = { Addr->getType() };
7294 IsAcquire ? Intrinsic::arm64_ldaxr : Intrinsic::arm64_ldxr;
7295 Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int, Tys);
7297 return Builder.CreateTruncOrBitCast(
7298 Builder.CreateCall(Ldxr, Addr),
7299 cast<PointerType>(Addr->getType())->getElementType());
7302 Value *ARM64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
7303 Value *Val, Value *Addr,
7304 AtomicOrdering Ord) const {
7305 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
7307 Ord == Release || Ord == AcquireRelease || Ord == SequentiallyConsistent;
7309 // Since the intrinsics must have legal type, the i128 intrinsics take two
7310 // parameters: "i64, i64". We must marshal Val into the appropriate form
7312 if (Val->getType()->getPrimitiveSizeInBits() == 128) {
7314 IsRelease ? Intrinsic::arm64_stlxp : Intrinsic::arm64_stxp;
7315 Function *Stxr = Intrinsic::getDeclaration(M, Int);
7316 Type *Int64Ty = Type::getInt64Ty(M->getContext());
7318 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
7319 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
7320 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
7321 return Builder.CreateCall3(Stxr, Lo, Hi, Addr);
7325 IsRelease ? Intrinsic::arm64_stlxr : Intrinsic::arm64_stxr;
7326 Type *Tys[] = { Addr->getType() };
7327 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
7329 return Builder.CreateCall2(
7330 Stxr, Builder.CreateZExtOrBitCast(
7331 Val, Stxr->getFunctionType()->getParamType(0)),