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 #define DEBUG_TYPE "arm64-lower"
16 #include "ARM64ISelLowering.h"
17 #include "ARM64PerfectShuffle.h"
18 #include "ARM64Subtarget.h"
19 #include "ARM64CallingConv.h"
20 #include "ARM64MachineFunctionInfo.h"
21 #include "ARM64TargetMachine.h"
22 #include "ARM64TargetObjectFile.h"
23 #include "MCTargetDesc/ARM64AddressingModes.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/CodeGen/CallingConvLower.h"
26 #include "llvm/CodeGen/MachineFrameInfo.h"
27 #include "llvm/CodeGen/MachineInstrBuilder.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/Intrinsics.h"
31 #include "llvm/IR/Type.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetOptions.h"
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)."),
49 StrictAlign("arm64-strict-align", cl::Hidden,
50 cl::desc("Disallow all unaligned memory accesses"));
52 // Place holder until extr generation is tested fully.
54 EnableARM64ExtrGeneration("arm64-extr-generation", cl::Hidden,
55 cl::desc("Allow ARM64 (or (shift)(shift))->extract"),
59 EnableARM64SlrGeneration("arm64-shift-insert-generation", cl::Hidden,
60 cl::desc("Allow ARM64 SLI/SRI formation"),
63 //===----------------------------------------------------------------------===//
64 // ARM64 Lowering public interface.
65 //===----------------------------------------------------------------------===//
66 static TargetLoweringObjectFile *createTLOF(TargetMachine &TM) {
67 if (TM.getSubtarget<ARM64Subtarget>().isTargetDarwin())
68 return new ARM64_MachoTargetObjectFile();
70 return new ARM64_ELFTargetObjectFile();
73 ARM64TargetLowering::ARM64TargetLowering(ARM64TargetMachine &TM)
74 : TargetLowering(TM, createTLOF(TM)) {
75 Subtarget = &TM.getSubtarget<ARM64Subtarget>();
77 // ARM64 doesn't have comparisons which set GPRs or setcc instructions, so
78 // we have to make something up. Arbitrarily, choose ZeroOrOne.
79 setBooleanContents(ZeroOrOneBooleanContent);
80 // When comparing vectors the result sets the different elements in the
81 // vector to all-one or all-zero.
82 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
84 // Set up the register classes.
85 addRegisterClass(MVT::i32, &ARM64::GPR32allRegClass);
86 addRegisterClass(MVT::i64, &ARM64::GPR64allRegClass);
87 addRegisterClass(MVT::f16, &ARM64::FPR16RegClass);
88 addRegisterClass(MVT::f32, &ARM64::FPR32RegClass);
89 addRegisterClass(MVT::f64, &ARM64::FPR64RegClass);
90 addRegisterClass(MVT::f128, &ARM64::FPR128RegClass);
91 addRegisterClass(MVT::v16i8, &ARM64::FPR8RegClass);
92 addRegisterClass(MVT::v8i16, &ARM64::FPR16RegClass);
94 // Someone set us up the NEON.
95 addDRTypeForNEON(MVT::v2f32);
96 addDRTypeForNEON(MVT::v8i8);
97 addDRTypeForNEON(MVT::v4i16);
98 addDRTypeForNEON(MVT::v2i32);
99 addDRTypeForNEON(MVT::v1i64);
100 addDRTypeForNEON(MVT::v1f64);
102 addQRTypeForNEON(MVT::v4f32);
103 addQRTypeForNEON(MVT::v2f64);
104 addQRTypeForNEON(MVT::v16i8);
105 addQRTypeForNEON(MVT::v8i16);
106 addQRTypeForNEON(MVT::v4i32);
107 addQRTypeForNEON(MVT::v2i64);
109 // Compute derived properties from the register classes
110 computeRegisterProperties();
112 // Provide all sorts of operation actions
113 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
114 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
115 setOperationAction(ISD::SETCC, MVT::i32, Custom);
116 setOperationAction(ISD::SETCC, MVT::i64, Custom);
117 setOperationAction(ISD::SETCC, MVT::f32, Custom);
118 setOperationAction(ISD::SETCC, MVT::f64, Custom);
119 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
120 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
121 setOperationAction(ISD::BR_CC, MVT::i64, Custom);
122 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
123 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
124 setOperationAction(ISD::SELECT, MVT::i32, Custom);
125 setOperationAction(ISD::SELECT, MVT::i64, Custom);
126 setOperationAction(ISD::SELECT, MVT::f32, Custom);
127 setOperationAction(ISD::SELECT, MVT::f64, Custom);
128 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
129 setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
130 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
131 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
132 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
133 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
135 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
136 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
137 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
139 setOperationAction(ISD::FREM, MVT::f32, Expand);
140 setOperationAction(ISD::FREM, MVT::f64, Expand);
141 setOperationAction(ISD::FREM, MVT::f80, Expand);
143 // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
144 // silliness like this:
145 setOperationAction(ISD::FABS, MVT::v1f64, Expand);
146 setOperationAction(ISD::FADD, MVT::v1f64, Expand);
147 setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
148 setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
149 setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
150 setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
151 setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
152 setOperationAction(ISD::FMA, MVT::v1f64, Expand);
153 setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
154 setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
155 setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
156 setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
157 setOperationAction(ISD::FREM, MVT::v1f64, Expand);
158 setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
159 setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
160 setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
161 setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
162 setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
163 setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
164 setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
165 setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
166 setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
167 setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
168 setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
169 setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
171 setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
172 setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
173 setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
174 setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
175 setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
177 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
179 // Custom lowering hooks are needed for XOR
180 // to fold it into CSINC/CSINV.
181 setOperationAction(ISD::XOR, MVT::i32, Custom);
182 setOperationAction(ISD::XOR, MVT::i64, Custom);
184 // Virtually no operation on f128 is legal, but LLVM can't expand them when
185 // there's a valid register class, so we need custom operations in most cases.
186 setOperationAction(ISD::FABS, MVT::f128, Expand);
187 setOperationAction(ISD::FADD, MVT::f128, Custom);
188 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
189 setOperationAction(ISD::FCOS, MVT::f128, Expand);
190 setOperationAction(ISD::FDIV, MVT::f128, Custom);
191 setOperationAction(ISD::FMA, MVT::f128, Expand);
192 setOperationAction(ISD::FMUL, MVT::f128, Custom);
193 setOperationAction(ISD::FNEG, MVT::f128, Expand);
194 setOperationAction(ISD::FPOW, MVT::f128, Expand);
195 setOperationAction(ISD::FREM, MVT::f128, Expand);
196 setOperationAction(ISD::FRINT, MVT::f128, Expand);
197 setOperationAction(ISD::FSIN, MVT::f128, Expand);
198 setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
199 setOperationAction(ISD::FSQRT, MVT::f128, Expand);
200 setOperationAction(ISD::FSUB, MVT::f128, Custom);
201 setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
202 setOperationAction(ISD::SETCC, MVT::f128, Custom);
203 setOperationAction(ISD::BR_CC, MVT::f128, Custom);
204 setOperationAction(ISD::SELECT, MVT::f128, Custom);
205 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
206 setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
208 // Lowering for many of the conversions is actually specified by the non-f128
209 // type. The LowerXXX function will be trivial when f128 isn't involved.
210 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
211 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
212 setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
213 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
214 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
215 setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
216 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
217 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
218 setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
219 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
220 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
221 setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
222 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
223 setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
225 // Variable arguments.
226 setOperationAction(ISD::VASTART, MVT::Other, Custom);
227 setOperationAction(ISD::VAARG, MVT::Other, Custom);
228 setOperationAction(ISD::VACOPY, MVT::Other, Custom);
229 setOperationAction(ISD::VAEND, MVT::Other, Expand);
231 // Variable-sized objects.
232 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
233 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
234 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
236 // Exception handling.
237 // FIXME: These are guesses. Has this been defined yet?
238 setExceptionPointerRegister(ARM64::X0);
239 setExceptionSelectorRegister(ARM64::X1);
241 // Constant pool entries
242 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
245 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
247 // Add/Sub overflow ops with MVT::Glues are lowered to CPSR dependences.
248 setOperationAction(ISD::ADDC, MVT::i32, Custom);
249 setOperationAction(ISD::ADDE, MVT::i32, Custom);
250 setOperationAction(ISD::SUBC, MVT::i32, Custom);
251 setOperationAction(ISD::SUBE, MVT::i32, Custom);
252 setOperationAction(ISD::ADDC, MVT::i64, Custom);
253 setOperationAction(ISD::ADDE, MVT::i64, Custom);
254 setOperationAction(ISD::SUBC, MVT::i64, Custom);
255 setOperationAction(ISD::SUBE, MVT::i64, Custom);
257 // ARM64 lacks both left-rotate and popcount instructions.
258 setOperationAction(ISD::ROTL, MVT::i32, Expand);
259 setOperationAction(ISD::ROTL, MVT::i64, Expand);
261 // ARM64 doesn't have a direct vector ->f32 conversion instructions for
262 // elements smaller than i32, so promote the input to i32 first.
263 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Promote);
264 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Promote);
265 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Promote);
266 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Promote);
267 // Similarly, there is no direct i32 -> f64 vector conversion instruction.
268 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
269 setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
270 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
271 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
273 // ARM64 doesn't have {U|S}MUL_LOHI.
274 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
275 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
277 // ARM64 doesn't have MUL.2d:
278 setOperationAction(ISD::MUL, MVT::v2i64, Expand);
280 // Expand the undefined-at-zero variants to cttz/ctlz to their defined-at-zero
281 // counterparts, which ARM64 supports directly.
282 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
283 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
284 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
285 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
287 setOperationAction(ISD::CTPOP, MVT::i32, Custom);
288 setOperationAction(ISD::CTPOP, MVT::i64, Custom);
290 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
291 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
292 setOperationAction(ISD::SREM, MVT::i32, Expand);
293 setOperationAction(ISD::SREM, MVT::i64, Expand);
294 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
295 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
296 setOperationAction(ISD::UREM, MVT::i32, Expand);
297 setOperationAction(ISD::UREM, MVT::i64, Expand);
299 // Custom lower Add/Sub/Mul with overflow.
300 setOperationAction(ISD::SADDO, MVT::i32, Custom);
301 setOperationAction(ISD::SADDO, MVT::i64, Custom);
302 setOperationAction(ISD::UADDO, MVT::i32, Custom);
303 setOperationAction(ISD::UADDO, MVT::i64, Custom);
304 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
305 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
306 setOperationAction(ISD::USUBO, MVT::i32, Custom);
307 setOperationAction(ISD::USUBO, MVT::i64, Custom);
308 setOperationAction(ISD::SMULO, MVT::i32, Custom);
309 setOperationAction(ISD::SMULO, MVT::i64, Custom);
310 setOperationAction(ISD::UMULO, MVT::i32, Custom);
311 setOperationAction(ISD::UMULO, MVT::i64, Custom);
313 setOperationAction(ISD::FSIN, MVT::f32, Expand);
314 setOperationAction(ISD::FSIN, MVT::f64, Expand);
315 setOperationAction(ISD::FCOS, MVT::f32, Expand);
316 setOperationAction(ISD::FCOS, MVT::f64, Expand);
317 setOperationAction(ISD::FPOW, MVT::f32, Expand);
318 setOperationAction(ISD::FPOW, MVT::f64, Expand);
319 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
320 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
322 // ARM64 has implementations of a lot of rounding-like FP operations.
323 static MVT RoundingTypes[] = { MVT::f32, MVT::f64, MVT::v2f32,
324 MVT::v4f32, MVT::v2f64 };
325 for (unsigned I = 0; I < array_lengthof(RoundingTypes); ++I) {
326 MVT Ty = RoundingTypes[I];
327 setOperationAction(ISD::FFLOOR, Ty, Legal);
328 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
329 setOperationAction(ISD::FCEIL, Ty, Legal);
330 setOperationAction(ISD::FRINT, Ty, Legal);
331 setOperationAction(ISD::FTRUNC, Ty, Legal);
332 setOperationAction(ISD::FROUND, Ty, Legal);
335 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
337 if (Subtarget->isTargetMachO()) {
338 // For iOS, we don't want to the normal expansion of a libcall to
339 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
341 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
342 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
344 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
345 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
348 // ARM64 does not have floating-point extending loads, i1 sign-extending load,
349 // floating-point truncating stores, or v2i32->v2i16 truncating store.
350 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
351 setLoadExtAction(ISD::EXTLOAD, MVT::f64, Expand);
352 setLoadExtAction(ISD::EXTLOAD, MVT::f80, Expand);
353 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Expand);
354 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
355 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
356 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
357 setTruncStoreAction(MVT::f128, MVT::f80, Expand);
358 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
359 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
360 setTruncStoreAction(MVT::f128, MVT::f16, Expand);
361 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
362 // Indexed loads and stores are supported.
363 for (unsigned im = (unsigned)ISD::PRE_INC;
364 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
365 setIndexedLoadAction(im, MVT::i8, Legal);
366 setIndexedLoadAction(im, MVT::i16, Legal);
367 setIndexedLoadAction(im, MVT::i32, Legal);
368 setIndexedLoadAction(im, MVT::i64, Legal);
369 setIndexedLoadAction(im, MVT::f64, Legal);
370 setIndexedLoadAction(im, MVT::f32, Legal);
371 setIndexedStoreAction(im, MVT::i8, Legal);
372 setIndexedStoreAction(im, MVT::i16, Legal);
373 setIndexedStoreAction(im, MVT::i32, Legal);
374 setIndexedStoreAction(im, MVT::i64, Legal);
375 setIndexedStoreAction(im, MVT::f64, Legal);
376 setIndexedStoreAction(im, MVT::f32, Legal);
379 // Likewise, narrowing and extending vector loads/stores aren't handled
381 for (unsigned VT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
382 VT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++VT) {
384 setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
387 for (unsigned InnerVT = (unsigned)MVT::FIRST_VECTOR_VALUETYPE;
388 InnerVT <= (unsigned)MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
389 setTruncStoreAction((MVT::SimpleValueType)VT,
390 (MVT::SimpleValueType)InnerVT, Expand);
391 setLoadExtAction(ISD::SEXTLOAD, (MVT::SimpleValueType)VT, Expand);
392 setLoadExtAction(ISD::ZEXTLOAD, (MVT::SimpleValueType)VT, Expand);
393 setLoadExtAction(ISD::EXTLOAD, (MVT::SimpleValueType)VT, Expand);
397 setOperationAction(ISD::TRAP, MVT::Other, Legal);
398 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
400 // We combine OR nodes for bitfield operations.
401 setTargetDAGCombine(ISD::OR);
403 // Vector add and sub nodes may conceal a high-half opportunity.
404 // Also, try to fold ADD into CSINC/CSINV..
405 setTargetDAGCombine(ISD::ADD);
406 setTargetDAGCombine(ISD::SUB);
408 setTargetDAGCombine(ISD::XOR);
409 setTargetDAGCombine(ISD::SINT_TO_FP);
410 setTargetDAGCombine(ISD::UINT_TO_FP);
412 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
414 setTargetDAGCombine(ISD::ANY_EXTEND);
415 setTargetDAGCombine(ISD::ZERO_EXTEND);
416 setTargetDAGCombine(ISD::SIGN_EXTEND);
417 setTargetDAGCombine(ISD::BITCAST);
418 setTargetDAGCombine(ISD::CONCAT_VECTORS);
419 setTargetDAGCombine(ISD::STORE);
421 setTargetDAGCombine(ISD::MUL);
423 setTargetDAGCombine(ISD::VSELECT);
425 MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 8;
426 MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 4;
427 MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = 4;
429 setStackPointerRegisterToSaveRestore(ARM64::SP);
431 setSchedulingPreference(Sched::Hybrid);
434 MaskAndBranchFoldingIsLegal = true;
436 setMinFunctionAlignment(2);
438 RequireStrictAlign = StrictAlign;
441 void ARM64TargetLowering::addTypeForNEON(EVT VT, EVT PromotedBitwiseVT) {
442 if (VT == MVT::v2f32) {
443 setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
444 AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i32);
446 setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
447 AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i32);
448 } else if (VT == MVT::v2f64 || VT == MVT::v4f32) {
449 setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
450 AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i64);
452 setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
453 AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i64);
456 // Mark vector float intrinsics as expand.
457 if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
458 setOperationAction(ISD::FSIN, VT.getSimpleVT(), Expand);
459 setOperationAction(ISD::FCOS, VT.getSimpleVT(), Expand);
460 setOperationAction(ISD::FPOWI, VT.getSimpleVT(), Expand);
461 setOperationAction(ISD::FPOW, VT.getSimpleVT(), Expand);
462 setOperationAction(ISD::FLOG, VT.getSimpleVT(), Expand);
463 setOperationAction(ISD::FLOG2, VT.getSimpleVT(), Expand);
464 setOperationAction(ISD::FLOG10, VT.getSimpleVT(), Expand);
465 setOperationAction(ISD::FEXP, VT.getSimpleVT(), Expand);
466 setOperationAction(ISD::FEXP2, VT.getSimpleVT(), Expand);
469 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT.getSimpleVT(), Custom);
470 setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getSimpleVT(), Custom);
471 setOperationAction(ISD::BUILD_VECTOR, VT.getSimpleVT(), Custom);
472 setOperationAction(ISD::VECTOR_SHUFFLE, VT.getSimpleVT(), Custom);
473 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT.getSimpleVT(), Custom);
474 setOperationAction(ISD::SRA, VT.getSimpleVT(), Custom);
475 setOperationAction(ISD::SRL, VT.getSimpleVT(), Custom);
476 setOperationAction(ISD::SHL, VT.getSimpleVT(), Custom);
477 setOperationAction(ISD::AND, VT.getSimpleVT(), Custom);
478 setOperationAction(ISD::OR, VT.getSimpleVT(), Custom);
479 setOperationAction(ISD::SETCC, VT.getSimpleVT(), Custom);
480 setOperationAction(ISD::CONCAT_VECTORS, VT.getSimpleVT(), Legal);
482 setOperationAction(ISD::SELECT, VT.getSimpleVT(), Expand);
483 setOperationAction(ISD::SELECT_CC, VT.getSimpleVT(), Expand);
484 setOperationAction(ISD::VSELECT, VT.getSimpleVT(), Expand);
485 setLoadExtAction(ISD::EXTLOAD, VT.getSimpleVT(), Expand);
487 // CNT supports only B element sizes.
488 if (VT != MVT::v8i8 && VT != MVT::v16i8)
489 setOperationAction(ISD::CTPOP, VT.getSimpleVT(), Expand);
491 setOperationAction(ISD::UDIV, VT.getSimpleVT(), Expand);
492 setOperationAction(ISD::SDIV, VT.getSimpleVT(), Expand);
493 setOperationAction(ISD::UREM, VT.getSimpleVT(), Expand);
494 setOperationAction(ISD::SREM, VT.getSimpleVT(), Expand);
495 setOperationAction(ISD::FREM, VT.getSimpleVT(), Expand);
497 setOperationAction(ISD::FP_TO_SINT, VT.getSimpleVT(), Custom);
498 setOperationAction(ISD::FP_TO_UINT, VT.getSimpleVT(), Custom);
501 void ARM64TargetLowering::addDRTypeForNEON(MVT VT) {
502 addRegisterClass(VT, &ARM64::FPR64RegClass);
503 addTypeForNEON(VT, MVT::v2i32);
506 void ARM64TargetLowering::addQRTypeForNEON(MVT VT) {
507 addRegisterClass(VT, &ARM64::FPR128RegClass);
508 addTypeForNEON(VT, MVT::v4i32);
511 EVT ARM64TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
514 return VT.changeVectorElementTypeToInteger();
517 /// computeMaskedBitsForTargetNode - Determine which of the bits specified in
518 /// Mask are known to be either zero or one and return them in the
519 /// KnownZero/KnownOne bitsets.
520 void ARM64TargetLowering::computeMaskedBitsForTargetNode(
521 const SDValue Op, APInt &KnownZero, APInt &KnownOne,
522 const SelectionDAG &DAG, unsigned Depth) const {
523 switch (Op.getOpcode()) {
526 case ARM64ISD::CSEL: {
527 APInt KnownZero2, KnownOne2;
528 DAG.ComputeMaskedBits(Op->getOperand(0), KnownZero, KnownOne, Depth + 1);
529 DAG.ComputeMaskedBits(Op->getOperand(1), KnownZero2, KnownOne2, Depth + 1);
530 KnownZero &= KnownZero2;
531 KnownOne &= KnownOne2;
534 case ISD::INTRINSIC_W_CHAIN: {
535 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
536 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
539 case Intrinsic::arm64_ldaxr:
540 case Intrinsic::arm64_ldxr: {
541 unsigned BitWidth = KnownOne.getBitWidth();
542 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
543 unsigned MemBits = VT.getScalarType().getSizeInBits();
544 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
550 case ISD::INTRINSIC_WO_CHAIN:
551 case ISD::INTRINSIC_VOID: {
552 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
556 case Intrinsic::arm64_neon_umaxv:
557 case Intrinsic::arm64_neon_uminv: {
558 // Figure out the datatype of the vector operand. The UMINV instruction
559 // will zero extend the result, so we can mark as known zero all the
560 // bits larger than the element datatype. 32-bit or larget doesn't need
561 // this as those are legal types and will be handled by isel directly.
562 MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
563 unsigned BitWidth = KnownZero.getBitWidth();
564 if (VT == MVT::v8i8 || VT == MVT::v16i8) {
565 assert(BitWidth >= 8 && "Unexpected width!");
566 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
568 } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
569 assert(BitWidth >= 16 && "Unexpected width!");
570 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
580 MVT ARM64TargetLowering::getScalarShiftAmountTy(EVT LHSTy) const {
584 unsigned ARM64TargetLowering::getMaximalGlobalOffset() const {
585 // FIXME: On ARM64, this depends on the type.
586 // Basically, the addressable offsets are o to 4095 * Ty.getSizeInBytes().
587 // and the offset has to be a multiple of the related size in bytes.
592 ARM64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
593 const TargetLibraryInfo *libInfo) const {
594 return ARM64::createFastISel(funcInfo, libInfo);
597 const char *ARM64TargetLowering::getTargetNodeName(unsigned Opcode) const {
601 case ARM64ISD::CALL: return "ARM64ISD::CALL";
602 case ARM64ISD::ADRP: return "ARM64ISD::ADRP";
603 case ARM64ISD::ADDlow: return "ARM64ISD::ADDlow";
604 case ARM64ISD::LOADgot: return "ARM64ISD::LOADgot";
605 case ARM64ISD::RET_FLAG: return "ARM64ISD::RET_FLAG";
606 case ARM64ISD::BRCOND: return "ARM64ISD::BRCOND";
607 case ARM64ISD::CSEL: return "ARM64ISD::CSEL";
608 case ARM64ISD::FCSEL: return "ARM64ISD::FCSEL";
609 case ARM64ISD::CSINV: return "ARM64ISD::CSINV";
610 case ARM64ISD::CSNEG: return "ARM64ISD::CSNEG";
611 case ARM64ISD::CSINC: return "ARM64ISD::CSINC";
612 case ARM64ISD::THREAD_POINTER: return "ARM64ISD::THREAD_POINTER";
613 case ARM64ISD::TLSDESC_CALL: return "ARM64ISD::TLSDESC_CALL";
614 case ARM64ISD::ADC: return "ARM64ISD::ADC";
615 case ARM64ISD::SBC: return "ARM64ISD::SBC";
616 case ARM64ISD::ADDS: return "ARM64ISD::ADDS";
617 case ARM64ISD::SUBS: return "ARM64ISD::SUBS";
618 case ARM64ISD::ADCS: return "ARM64ISD::ADCS";
619 case ARM64ISD::SBCS: return "ARM64ISD::SBCS";
620 case ARM64ISD::ANDS: return "ARM64ISD::ANDS";
621 case ARM64ISD::FCMP: return "ARM64ISD::FCMP";
622 case ARM64ISD::FMIN: return "ARM64ISD::FMIN";
623 case ARM64ISD::FMAX: return "ARM64ISD::FMAX";
624 case ARM64ISD::DUP: return "ARM64ISD::DUP";
625 case ARM64ISD::DUPLANE8: return "ARM64ISD::DUPLANE8";
626 case ARM64ISD::DUPLANE16: return "ARM64ISD::DUPLANE16";
627 case ARM64ISD::DUPLANE32: return "ARM64ISD::DUPLANE32";
628 case ARM64ISD::DUPLANE64: return "ARM64ISD::DUPLANE64";
629 case ARM64ISD::MOVI: return "ARM64ISD::MOVI";
630 case ARM64ISD::MOVIshift: return "ARM64ISD::MOVIshift";
631 case ARM64ISD::MOVIedit: return "ARM64ISD::MOVIedit";
632 case ARM64ISD::MOVImsl: return "ARM64ISD::MOVImsl";
633 case ARM64ISD::FMOV: return "ARM64ISD::FMOV";
634 case ARM64ISD::MVNIshift: return "ARM64ISD::MVNIshift";
635 case ARM64ISD::MVNImsl: return "ARM64ISD::MVNImsl";
636 case ARM64ISD::BICi: return "ARM64ISD::BICi";
637 case ARM64ISD::ORRi: return "ARM64ISD::ORRi";
638 case ARM64ISD::BSL: return "ARM64ISD::BSL";
639 case ARM64ISD::NEG: return "ARM64ISD::NEG";
640 case ARM64ISD::EXTR: return "ARM64ISD::EXTR";
641 case ARM64ISD::ZIP1: return "ARM64ISD::ZIP1";
642 case ARM64ISD::ZIP2: return "ARM64ISD::ZIP2";
643 case ARM64ISD::UZP1: return "ARM64ISD::UZP1";
644 case ARM64ISD::UZP2: return "ARM64ISD::UZP2";
645 case ARM64ISD::TRN1: return "ARM64ISD::TRN1";
646 case ARM64ISD::TRN2: return "ARM64ISD::TRN2";
647 case ARM64ISD::REV16: return "ARM64ISD::REV16";
648 case ARM64ISD::REV32: return "ARM64ISD::REV32";
649 case ARM64ISD::REV64: return "ARM64ISD::REV64";
650 case ARM64ISD::EXT: return "ARM64ISD::EXT";
651 case ARM64ISD::VSHL: return "ARM64ISD::VSHL";
652 case ARM64ISD::VLSHR: return "ARM64ISD::VLSHR";
653 case ARM64ISD::VASHR: return "ARM64ISD::VASHR";
654 case ARM64ISD::CMEQ: return "ARM64ISD::CMEQ";
655 case ARM64ISD::CMGE: return "ARM64ISD::CMGE";
656 case ARM64ISD::CMGT: return "ARM64ISD::CMGT";
657 case ARM64ISD::CMHI: return "ARM64ISD::CMHI";
658 case ARM64ISD::CMHS: return "ARM64ISD::CMHS";
659 case ARM64ISD::FCMEQ: return "ARM64ISD::FCMEQ";
660 case ARM64ISD::FCMGE: return "ARM64ISD::FCMGE";
661 case ARM64ISD::FCMGT: return "ARM64ISD::FCMGT";
662 case ARM64ISD::CMEQz: return "ARM64ISD::CMEQz";
663 case ARM64ISD::CMGEz: return "ARM64ISD::CMGEz";
664 case ARM64ISD::CMGTz: return "ARM64ISD::CMGTz";
665 case ARM64ISD::CMLEz: return "ARM64ISD::CMLEz";
666 case ARM64ISD::CMLTz: return "ARM64ISD::CMLTz";
667 case ARM64ISD::FCMEQz: return "ARM64ISD::FCMEQz";
668 case ARM64ISD::FCMGEz: return "ARM64ISD::FCMGEz";
669 case ARM64ISD::FCMGTz: return "ARM64ISD::FCMGTz";
670 case ARM64ISD::FCMLEz: return "ARM64ISD::FCMLEz";
671 case ARM64ISD::FCMLTz: return "ARM64ISD::FCMLTz";
672 case ARM64ISD::NOT: return "ARM64ISD::NOT";
673 case ARM64ISD::BIT: return "ARM64ISD::BIT";
674 case ARM64ISD::CBZ: return "ARM64ISD::CBZ";
675 case ARM64ISD::CBNZ: return "ARM64ISD::CBNZ";
676 case ARM64ISD::TBZ: return "ARM64ISD::TBZ";
677 case ARM64ISD::TBNZ: return "ARM64ISD::TBNZ";
678 case ARM64ISD::TC_RETURN: return "ARM64ISD::TC_RETURN";
679 case ARM64ISD::SITOF: return "ARM64ISD::SITOF";
680 case ARM64ISD::UITOF: return "ARM64ISD::UITOF";
681 case ARM64ISD::SQSHL_I: return "ARM64ISD::SQSHL_I";
682 case ARM64ISD::UQSHL_I: return "ARM64ISD::UQSHL_I";
683 case ARM64ISD::SRSHR_I: return "ARM64ISD::SRSHR_I";
684 case ARM64ISD::URSHR_I: return "ARM64ISD::URSHR_I";
685 case ARM64ISD::SQSHLU_I: return "ARM64ISD::SQSHLU_I";
686 case ARM64ISD::WrapperLarge: return "ARM64ISD::WrapperLarge";
691 ARM64TargetLowering::EmitF128CSEL(MachineInstr *MI,
692 MachineBasicBlock *MBB) const {
693 // We materialise the F128CSEL pseudo-instruction as some control flow and a
697 // [... previous instrs leading to comparison ...]
703 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
705 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
706 MachineFunction *MF = MBB->getParent();
707 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
708 DebugLoc DL = MI->getDebugLoc();
709 MachineFunction::iterator It = MBB;
712 unsigned DestReg = MI->getOperand(0).getReg();
713 unsigned IfTrueReg = MI->getOperand(1).getReg();
714 unsigned IfFalseReg = MI->getOperand(2).getReg();
715 unsigned CondCode = MI->getOperand(3).getImm();
716 bool CPSRKilled = MI->getOperand(4).isKill();
718 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
719 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
720 MF->insert(It, TrueBB);
721 MF->insert(It, EndBB);
723 // Transfer rest of current basic-block to EndBB
724 EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
726 EndBB->transferSuccessorsAndUpdatePHIs(MBB);
728 BuildMI(MBB, DL, TII->get(ARM64::Bcc)).addImm(CondCode).addMBB(TrueBB);
729 BuildMI(MBB, DL, TII->get(ARM64::B)).addMBB(EndBB);
730 MBB->addSuccessor(TrueBB);
731 MBB->addSuccessor(EndBB);
733 // TrueBB falls through to the end.
734 TrueBB->addSuccessor(EndBB);
737 TrueBB->addLiveIn(ARM64::CPSR);
738 EndBB->addLiveIn(ARM64::CPSR);
741 BuildMI(*EndBB, EndBB->begin(), DL, TII->get(ARM64::PHI), DestReg)
747 MI->eraseFromParent();
752 ARM64TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
753 MachineBasicBlock *BB) const {
754 switch (MI->getOpcode()) {
759 assert(0 && "Unexpected instruction for custom inserter!");
762 case ARM64::F128CSEL:
763 return EmitF128CSEL(MI, BB);
765 case TargetOpcode::STACKMAP:
766 case TargetOpcode::PATCHPOINT:
767 return emitPatchPoint(MI, BB);
769 llvm_unreachable("Unexpected instruction for custom inserter!");
772 //===----------------------------------------------------------------------===//
773 // ARM64 Lowering private implementation.
774 //===----------------------------------------------------------------------===//
776 //===----------------------------------------------------------------------===//
778 //===----------------------------------------------------------------------===//
780 /// changeIntCCToARM64CC - Convert a DAG integer condition code to an ARM64 CC
781 static ARM64CC::CondCode changeIntCCToARM64CC(ISD::CondCode CC) {
784 llvm_unreachable("Unknown condition code!");
808 /// changeFPCCToARM64CC - Convert a DAG fp condition code to an ARM64 CC.
809 static void changeFPCCToARM64CC(ISD::CondCode CC, ARM64CC::CondCode &CondCode,
810 ARM64CC::CondCode &CondCode2) {
811 CondCode2 = ARM64CC::AL;
814 llvm_unreachable("Unknown FP condition!");
817 CondCode = ARM64CC::EQ;
821 CondCode = ARM64CC::GT;
825 CondCode = ARM64CC::GE;
828 CondCode = ARM64CC::MI;
831 CondCode = ARM64CC::LS;
834 CondCode = ARM64CC::MI;
835 CondCode2 = ARM64CC::GT;
838 CondCode = ARM64CC::VC;
841 CondCode = ARM64CC::VS;
844 CondCode = ARM64CC::EQ;
845 CondCode2 = ARM64CC::VS;
848 CondCode = ARM64CC::HI;
851 CondCode = ARM64CC::PL;
855 CondCode = ARM64CC::LT;
859 CondCode = ARM64CC::LE;
863 CondCode = ARM64CC::NE;
868 /// changeVectorFPCCToARM64CC - Convert a DAG fp condition code to an ARM64 CC
869 /// usable with the vector instructions. Fewer operations are available without
870 /// a real NZCV register, so we have to use less efficient combinations to get
872 static void changeVectorFPCCToARM64CC(ISD::CondCode CC,
873 ARM64CC::CondCode &CondCode,
874 ARM64CC::CondCode &CondCode2,
879 // Mostly the scalar mappings work fine.
880 changeFPCCToARM64CC(CC, CondCode, CondCode2);
883 Invert = true; // Fallthrough
885 CondCode = ARM64CC::MI;
886 CondCode2 = ARM64CC::GE;
893 // All of the compare-mask comparisons are ordered, but we can switch
894 // between the two by a double inversion. E.g. ULE == !OGT.
896 changeFPCCToARM64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
901 static bool isLegalArithImmed(uint64_t C) {
902 // Matches ARM64DAGToDAGISel::SelectArithImmed().
903 return (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
906 static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
907 SDLoc dl, SelectionDAG &DAG) {
908 EVT VT = LHS.getValueType();
910 if (VT.isFloatingPoint())
911 return DAG.getNode(ARM64ISD::FCMP, dl, VT, LHS, RHS);
913 // The CMP instruction is just an alias for SUBS, and representing it as
914 // SUBS means that it's possible to get CSE with subtract operations.
915 // A later phase can perform the optimization of setting the destination
916 // register to WZR/XZR if it ends up being unused.
918 // We'd like to combine a (CMP op1, (sub 0, op2) into a CMN instruction on the
919 // grounds that "op1 - (-op2) == op1 + op2". However, the C and V flags can be
920 // set differently by this operation. It comes down to whether "SInt(~op2)+1
921 // == SInt(~op2+1)" (and the same for UInt). If they are then everything is
922 // fine. If not then the optimization is wrong. Thus general comparisons are
923 // only valid if op2 != 0.
925 // So, finally, the only LLVM-native comparisons that don't mention C and V
926 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in the
927 // absence of information about op2.
928 unsigned Opcode = ARM64ISD::SUBS;
929 if (RHS.getOpcode() == ISD::SUB && isa<ConstantSDNode>(RHS.getOperand(0)) &&
930 cast<ConstantSDNode>(RHS.getOperand(0))->getZExtValue() == 0 &&
931 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
932 Opcode = ARM64ISD::ADDS;
933 RHS = RHS.getOperand(1);
936 return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS)
940 static SDValue getARM64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
941 SDValue &ARM64cc, SelectionDAG &DAG, SDLoc dl) {
942 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
943 EVT VT = RHS.getValueType();
944 uint64_t C = RHSC->getZExtValue();
945 if (!isLegalArithImmed(C)) {
946 // Constant does not fit, try adjusting it by one?
952 if ((VT == MVT::i32 && C != 0x80000000 &&
953 isLegalArithImmed((uint32_t)(C - 1))) ||
954 (VT == MVT::i64 && C != 0x80000000ULL &&
955 isLegalArithImmed(C - 1ULL))) {
956 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
957 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
958 RHS = DAG.getConstant(C, VT);
963 if ((VT == MVT::i32 && C != 0 &&
964 isLegalArithImmed((uint32_t)(C - 1))) ||
965 (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
966 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
967 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
968 RHS = DAG.getConstant(C, VT);
973 if ((VT == MVT::i32 && C != 0x7fffffff &&
974 isLegalArithImmed((uint32_t)(C + 1))) ||
975 (VT == MVT::i64 && C != 0x7ffffffffffffffULL &&
976 isLegalArithImmed(C + 1ULL))) {
977 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
978 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
979 RHS = DAG.getConstant(C, VT);
984 if ((VT == MVT::i32 && C != 0xffffffff &&
985 isLegalArithImmed((uint32_t)(C + 1))) ||
986 (VT == MVT::i64 && C != 0xfffffffffffffffULL &&
987 isLegalArithImmed(C + 1ULL))) {
988 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
989 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
990 RHS = DAG.getConstant(C, VT);
997 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
998 ARM64CC::CondCode ARM64CC = changeIntCCToARM64CC(CC);
999 ARM64cc = DAG.getConstant(ARM64CC, MVT::i32);
1003 static std::pair<SDValue, SDValue>
1004 getARM64XALUOOp(ARM64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
1005 assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
1006 "Unsupported value type");
1007 SDValue Value, Overflow;
1009 SDValue LHS = Op.getOperand(0);
1010 SDValue RHS = Op.getOperand(1);
1012 switch (Op.getOpcode()) {
1014 llvm_unreachable("Unknown overflow instruction!");
1016 Opc = ARM64ISD::ADDS;
1020 Opc = ARM64ISD::ADDS;
1024 Opc = ARM64ISD::SUBS;
1028 Opc = ARM64ISD::SUBS;
1031 // Multiply needs a little bit extra work.
1035 bool IsSigned = (Op.getOpcode() == ISD::SMULO) ? true : false;
1036 if (Op.getValueType() == MVT::i32) {
1037 unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1038 // For a 32 bit multiply with overflow check we want the instruction
1039 // selector to generate a widening multiply (SMADDL/UMADDL). For that we
1040 // need to generate the following pattern:
1041 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
1042 LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
1043 RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
1044 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1045 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
1046 DAG.getConstant(0, MVT::i64));
1047 // On ARM64 the upper 32 bits are always zero extended for a 32 bit
1048 // operation. We need to clear out the upper 32 bits, because we used a
1049 // widening multiply that wrote all 64 bits. In the end this should be a
1051 Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
1053 // The signed overflow check requires more than just a simple check for
1054 // any bit set in the upper 32 bits of the result. These bits could be
1055 // just the sign bits of a negative number. To perform the overflow
1056 // check we have to arithmetic shift right the 32nd bit of the result by
1057 // 31 bits. Then we compare the result to the upper 32 bits.
1058 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
1059 DAG.getConstant(32, MVT::i64));
1060 UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
1061 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
1062 DAG.getConstant(31, MVT::i64));
1063 // It is important that LowerBits is last, otherwise the arithmetic
1064 // shift will not be folded into the compare (SUBS).
1065 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
1066 Overflow = DAG.getNode(ARM64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1069 // The overflow check for unsigned multiply is easy. We only need to
1070 // check if any of the upper 32 bits are set. This can be done with a
1071 // CMP (shifted register). For that we need to generate the following
1073 // (i64 ARM64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
1074 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
1075 DAG.getConstant(32, MVT::i64));
1076 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1078 DAG.getNode(ARM64ISD::SUBS, DL, VTs, DAG.getConstant(0, MVT::i64),
1079 UpperBits).getValue(1);
1083 assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
1084 // For the 64 bit multiply
1085 Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1087 SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
1088 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
1089 DAG.getConstant(63, MVT::i64));
1090 // It is important that LowerBits is last, otherwise the arithmetic
1091 // shift will not be folded into the compare (SUBS).
1092 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1093 Overflow = DAG.getNode(ARM64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1096 SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
1097 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1099 DAG.getNode(ARM64ISD::SUBS, DL, VTs, DAG.getConstant(0, MVT::i64),
1100 UpperBits).getValue(1);
1107 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
1109 // Emit the ARM64 operation with overflow check.
1110 Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
1111 Overflow = Value.getValue(1);
1113 return std::make_pair(Value, Overflow);
1116 SDValue ARM64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
1117 RTLIB::Libcall Call) const {
1118 SmallVector<SDValue, 2> Ops;
1119 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i)
1120 Ops.push_back(Op.getOperand(i));
1122 return makeLibCall(DAG, Call, MVT::f128, &Ops[0], Ops.size(), false,
1126 static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
1127 SDValue Sel = Op.getOperand(0);
1128 SDValue Other = Op.getOperand(1);
1130 // If neither operand is a SELECT_CC, give up.
1131 if (Sel.getOpcode() != ISD::SELECT_CC)
1132 std::swap(Sel, Other);
1133 if (Sel.getOpcode() != ISD::SELECT_CC)
1136 // The folding we want to perform is:
1137 // (xor x, (select_cc a, b, cc, 0, -1) )
1139 // (csel x, (xor x, -1), cc ...)
1141 // The latter will get matched to a CSINV instruction.
1143 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
1144 SDValue LHS = Sel.getOperand(0);
1145 SDValue RHS = Sel.getOperand(1);
1146 SDValue TVal = Sel.getOperand(2);
1147 SDValue FVal = Sel.getOperand(3);
1150 // FIXME: This could be generalized to non-integer comparisons.
1151 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
1154 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
1155 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
1157 // The the values aren't constants, this isn't the pattern we're looking for.
1158 if (!CFVal || !CTVal)
1161 // We can commute the SELECT_CC by inverting the condition. This
1162 // might be needed to make this fit into a CSINV pattern.
1163 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
1164 std::swap(TVal, FVal);
1165 std::swap(CTVal, CFVal);
1166 CC = ISD::getSetCCInverse(CC, true);
1169 // If the constants line up, perform the transform!
1170 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
1172 SDValue Cmp = getARM64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
1175 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
1176 DAG.getConstant(-1ULL, Other.getValueType()));
1178 return DAG.getNode(ARM64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
1185 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
1186 EVT VT = Op.getValueType();
1188 // Let legalize expand this if it isn't a legal type yet.
1189 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
1192 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
1195 bool ExtraOp = false;
1196 switch (Op.getOpcode()) {
1198 assert(0 && "Invalid code");
1200 Opc = ARM64ISD::ADDS;
1203 Opc = ARM64ISD::SUBS;
1206 Opc = ARM64ISD::ADCS;
1210 Opc = ARM64ISD::SBCS;
1216 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
1217 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
1221 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
1222 // Let legalize expand this if it isn't a legal type yet.
1223 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
1226 ARM64CC::CondCode CC;
1227 // The actual operation that sets the overflow or carry flag.
1228 SDValue Value, Overflow;
1229 std::tie(Value, Overflow) = getARM64XALUOOp(CC, Op, DAG);
1231 // We use 0 and 1 as false and true values.
1232 SDValue TVal = DAG.getConstant(1, MVT::i32);
1233 SDValue FVal = DAG.getConstant(0, MVT::i32);
1235 // We use an inverted condition, because the conditional select is inverted
1236 // too. This will allow it to be selected to a single instruction:
1237 // CSINC Wd, WZR, WZR, invert(cond).
1238 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), MVT::i32);
1239 Overflow = DAG.getNode(ARM64ISD::CSEL, SDLoc(Op), MVT::i32, FVal, TVal, CCVal,
1242 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
1243 return DAG.getNode(ISD::MERGE_VALUES, SDLoc(Op), VTs, Value, Overflow);
1246 // Prefetch operands are:
1247 // 1: Address to prefetch
1249 // 3: int locality (0 = no locality ... 3 = extreme locality)
1250 // 4: bool isDataCache
1251 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
1253 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
1254 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
1255 // The data thing is not used.
1256 // unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
1258 bool IsStream = !Locality;
1259 // When the locality number is set
1261 // The front-end should have filtered out the out-of-range values
1262 assert(Locality <= 3 && "Prefetch locality out-of-range");
1263 // The locality degree is the opposite of the cache speed.
1264 // Put the number the other way around.
1265 // The encoding starts at 0 for level 1
1266 Locality = 3 - Locality;
1269 // built the mask value encoding the expected behavior.
1270 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit
1271 (Locality << 1) | // Cache level bits
1272 (unsigned)IsStream; // Stream bit
1273 return DAG.getNode(ARM64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
1274 DAG.getConstant(PrfOp, MVT::i32), Op.getOperand(1));
1277 SDValue ARM64TargetLowering::LowerFP_EXTEND(SDValue Op,
1278 SelectionDAG &DAG) const {
1279 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
1282 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
1284 return LowerF128Call(Op, DAG, LC);
1287 SDValue ARM64TargetLowering::LowerFP_ROUND(SDValue Op,
1288 SelectionDAG &DAG) const {
1289 if (Op.getOperand(0).getValueType() != MVT::f128) {
1290 // It's legal except when f128 is involved
1295 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
1297 // FP_ROUND node has a second operand indicating whether it is known to be
1298 // precise. That doesn't take part in the LibCall so we can't directly use
1300 SDValue SrcVal = Op.getOperand(0);
1301 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
1302 /*isSigned*/ false, SDLoc(Op)).first;
1305 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
1306 // Warning: We maintain cost tables in ARM64TargetTransformInfo.cpp.
1307 // Any additional optimization in this function should be recorded
1308 // in the cost tables.
1309 EVT InVT = Op.getOperand(0).getValueType();
1310 EVT VT = Op.getValueType();
1312 // FP_TO_XINT conversion from the same type are legal.
1313 if (VT.getSizeInBits() == InVT.getSizeInBits())
1316 if (InVT == MVT::v2f64) {
1318 SDValue Cv = DAG.getNode(Op.getOpcode(), dl, MVT::v2i64, Op.getOperand(0));
1319 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
1322 // Type changing conversions are illegal.
1326 SDValue ARM64TargetLowering::LowerFP_TO_INT(SDValue Op,
1327 SelectionDAG &DAG) const {
1328 if (Op.getOperand(0).getValueType().isVector())
1329 return LowerVectorFP_TO_INT(Op, DAG);
1331 if (Op.getOperand(0).getValueType() != MVT::f128) {
1332 // It's legal except when f128 is involved
1337 if (Op.getOpcode() == ISD::FP_TO_SINT)
1338 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
1340 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
1342 SmallVector<SDValue, 2> Ops;
1343 for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i)
1344 Ops.push_back(Op.getOperand(i));
1346 return makeLibCall(DAG, LC, Op.getValueType(), &Ops[0], Ops.size(), false,
1350 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
1351 // Warning: We maintain cost tables in ARM64TargetTransformInfo.cpp.
1352 // Any additional optimization in this function should be recorded
1353 // in the cost tables.
1354 EVT VT = Op.getValueType();
1356 SDValue In = Op.getOperand(0);
1357 EVT InVT = In.getValueType();
1359 // v2i32 to v2f32 is legal.
1360 if (VT == MVT::v2f32 && InVT == MVT::v2i32)
1363 // This function only handles v2f64 outputs.
1364 if (VT == MVT::v2f64) {
1365 // Extend the input argument to a v2i64 that we can feed into the
1366 // floating point conversion. Zero or sign extend based on whether
1367 // we're doing a signed or unsigned float conversion.
1369 Op.getOpcode() == ISD::UINT_TO_FP ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
1370 assert(Op.getNumOperands() == 1 && "FP conversions take one argument");
1371 SDValue Promoted = DAG.getNode(Opc, dl, MVT::v2i64, Op.getOperand(0));
1372 return DAG.getNode(Op.getOpcode(), dl, Op.getValueType(), Promoted);
1375 // Scalarize v2i64 to v2f32 conversions.
1376 std::vector<SDValue> BuildVectorOps;
1377 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
1378 SDValue Sclr = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, In,
1379 DAG.getConstant(i, MVT::i64));
1380 Sclr = DAG.getNode(Op->getOpcode(), dl, MVT::f32, Sclr);
1381 BuildVectorOps.push_back(Sclr);
1384 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &BuildVectorOps[0],
1385 BuildVectorOps.size());
1388 SDValue ARM64TargetLowering::LowerINT_TO_FP(SDValue Op,
1389 SelectionDAG &DAG) const {
1390 if (Op.getValueType().isVector())
1391 return LowerVectorINT_TO_FP(Op, DAG);
1393 // i128 conversions are libcalls.
1394 if (Op.getOperand(0).getValueType() == MVT::i128)
1397 // Other conversions are legal, unless it's to the completely software-based
1399 if (Op.getValueType() != MVT::f128)
1403 if (Op.getOpcode() == ISD::SINT_TO_FP)
1404 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
1406 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
1408 return LowerF128Call(Op, DAG, LC);
1411 SDValue ARM64TargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
1412 // For iOS, we want to call an alternative entry point: __sincos_stret,
1413 // which returns the values in two S / D registers.
1415 SDValue Arg = Op.getOperand(0);
1416 EVT ArgVT = Arg.getValueType();
1417 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
1424 Entry.isSExt = false;
1425 Entry.isZExt = false;
1426 Args.push_back(Entry);
1428 const char *LibcallName =
1429 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
1430 SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy());
1432 StructType *RetTy = StructType::get(ArgTy, ArgTy, NULL);
1433 TargetLowering::CallLoweringInfo CLI(
1434 DAG.getEntryNode(), RetTy, false, false, false, false, 0,
1435 CallingConv::Fast, /*isTaillCall=*/false,
1436 /*doesNotRet=*/false, /*isReturnValueUsed*/ true, Callee, Args, DAG, dl);
1437 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1438 return CallResult.first;
1441 SDValue ARM64TargetLowering::LowerOperation(SDValue Op,
1442 SelectionDAG &DAG) const {
1443 switch (Op.getOpcode()) {
1445 llvm_unreachable("unimplemented operand");
1447 case ISD::GlobalAddress:
1448 return LowerGlobalAddress(Op, DAG);
1449 case ISD::GlobalTLSAddress:
1450 return LowerGlobalTLSAddress(Op, DAG);
1452 return LowerSETCC(Op, DAG);
1454 return LowerBR_CC(Op, DAG);
1456 return LowerSELECT(Op, DAG);
1457 case ISD::SELECT_CC:
1458 return LowerSELECT_CC(Op, DAG);
1459 case ISD::JumpTable:
1460 return LowerJumpTable(Op, DAG);
1461 case ISD::ConstantPool:
1462 return LowerConstantPool(Op, DAG);
1463 case ISD::BlockAddress:
1464 return LowerBlockAddress(Op, DAG);
1466 return LowerVASTART(Op, DAG);
1468 return LowerVACOPY(Op, DAG);
1470 return LowerVAARG(Op, DAG);
1475 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
1482 return LowerXALUO(Op, DAG);
1484 return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
1486 return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
1488 return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
1490 return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
1492 return LowerFP_ROUND(Op, DAG);
1493 case ISD::FP_EXTEND:
1494 return LowerFP_EXTEND(Op, DAG);
1495 case ISD::FRAMEADDR:
1496 return LowerFRAMEADDR(Op, DAG);
1497 case ISD::RETURNADDR:
1498 return LowerRETURNADDR(Op, DAG);
1499 case ISD::INSERT_VECTOR_ELT:
1500 return LowerINSERT_VECTOR_ELT(Op, DAG);
1501 case ISD::EXTRACT_VECTOR_ELT:
1502 return LowerEXTRACT_VECTOR_ELT(Op, DAG);
1503 case ISD::BUILD_VECTOR:
1504 return LowerBUILD_VECTOR(Op, DAG);
1505 case ISD::VECTOR_SHUFFLE:
1506 return LowerVECTOR_SHUFFLE(Op, DAG);
1507 case ISD::EXTRACT_SUBVECTOR:
1508 return LowerEXTRACT_SUBVECTOR(Op, DAG);
1512 return LowerVectorSRA_SRL_SHL(Op, DAG);
1513 case ISD::SHL_PARTS:
1514 return LowerShiftLeftParts(Op, DAG);
1515 case ISD::SRL_PARTS:
1516 case ISD::SRA_PARTS:
1517 return LowerShiftRightParts(Op, DAG);
1519 return LowerCTPOP(Op, DAG);
1520 case ISD::FCOPYSIGN:
1521 return LowerFCOPYSIGN(Op, DAG);
1523 return LowerVectorAND(Op, DAG);
1525 return LowerVectorOR(Op, DAG);
1527 return LowerXOR(Op, DAG);
1529 return LowerPREFETCH(Op, DAG);
1530 case ISD::SINT_TO_FP:
1531 case ISD::UINT_TO_FP:
1532 return LowerINT_TO_FP(Op, DAG);
1533 case ISD::FP_TO_SINT:
1534 case ISD::FP_TO_UINT:
1535 return LowerFP_TO_INT(Op, DAG);
1537 return LowerFSINCOS(Op, DAG);
1541 /// getFunctionAlignment - Return the Log2 alignment of this function.
1542 unsigned ARM64TargetLowering::getFunctionAlignment(const Function *F) const {
1546 //===----------------------------------------------------------------------===//
1547 // Calling Convention Implementation
1548 //===----------------------------------------------------------------------===//
1550 #include "ARM64GenCallingConv.inc"
1552 /// Selects the correct CCAssignFn for a the given CallingConvention
1554 CCAssignFn *ARM64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
1555 bool IsVarArg) const {
1558 llvm_unreachable("Unsupported calling convention.");
1559 case CallingConv::WebKit_JS:
1560 return CC_ARM64_WebKit_JS;
1561 case CallingConv::C:
1562 case CallingConv::Fast:
1563 if (!Subtarget->isTargetDarwin())
1564 return CC_ARM64_AAPCS;
1565 return IsVarArg ? CC_ARM64_DarwinPCS_VarArg : CC_ARM64_DarwinPCS;
1569 SDValue ARM64TargetLowering::LowerFormalArguments(
1570 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
1571 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
1572 SmallVectorImpl<SDValue> &InVals) const {
1573 MachineFunction &MF = DAG.getMachineFunction();
1574 MachineFrameInfo *MFI = MF.getFrameInfo();
1576 // Assign locations to all of the incoming arguments.
1577 SmallVector<CCValAssign, 16> ArgLocs;
1578 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1579 getTargetMachine(), ArgLocs, *DAG.getContext());
1581 // At this point, Ins[].VT may already be promoted to i32. To correctly
1582 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
1583 // i8 to CC_ARM64_AAPCS with i32 being ValVT and i8 being LocVT.
1584 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
1585 // we use a special version of AnalyzeFormalArguments to pass in ValVT and
1587 unsigned NumArgs = Ins.size();
1588 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
1589 unsigned CurArgIdx = 0;
1590 for (unsigned i = 0; i != NumArgs; ++i) {
1591 MVT ValVT = Ins[i].VT;
1592 std::advance(CurOrigArg, Ins[i].OrigArgIndex - CurArgIdx);
1593 CurArgIdx = Ins[i].OrigArgIndex;
1595 // Get type of the original argument.
1596 EVT ActualVT = getValueType(CurOrigArg->getType(), /*AllowUnknown*/ true);
1597 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
1598 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
1600 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
1602 else if (ActualMVT == MVT::i16)
1605 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
1607 AssignFn(i, ValVT, LocVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
1608 assert(!Res && "Call operand has unhandled type");
1611 assert(ArgLocs.size() == Ins.size());
1612 SmallVector<SDValue, 16> ArgValues;
1613 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1614 CCValAssign &VA = ArgLocs[i];
1616 if (Ins[i].Flags.isByVal()) {
1617 // Byval is used for HFAs in the PCS, but the system should work in a
1618 // non-compliant manner for larger structs.
1619 EVT PtrTy = getPointerTy();
1620 int Size = Ins[i].Flags.getByValSize();
1621 unsigned NumRegs = (Size + 7) / 8;
1624 MFI->CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
1625 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrTy);
1626 InVals.push_back(FrameIdxN);
1629 } if (VA.isRegLoc()) {
1630 // Arguments stored in registers.
1631 EVT RegVT = VA.getLocVT();
1634 const TargetRegisterClass *RC;
1636 if (RegVT == MVT::i32)
1637 RC = &ARM64::GPR32RegClass;
1638 else if (RegVT == MVT::i64)
1639 RC = &ARM64::GPR64RegClass;
1640 else if (RegVT == MVT::f32)
1641 RC = &ARM64::FPR32RegClass;
1642 else if (RegVT == MVT::f64 || RegVT == MVT::v1i64 ||
1643 RegVT == MVT::v1f64 || RegVT == MVT::v2i32 ||
1644 RegVT == MVT::v4i16 || RegVT == MVT::v8i8)
1645 RC = &ARM64::FPR64RegClass;
1646 else if (RegVT == MVT::v2i64 || RegVT == MVT::v4i32 ||
1647 RegVT == MVT::v8i16 || RegVT == MVT::v16i8)
1648 RC = &ARM64::FPR128RegClass;
1650 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
1652 // Transform the arguments in physical registers into virtual ones.
1653 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
1654 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
1656 // If this is an 8, 16 or 32-bit value, it is really passed promoted
1657 // to 64 bits. Insert an assert[sz]ext to capture this, then
1658 // truncate to the right size.
1659 switch (VA.getLocInfo()) {
1661 llvm_unreachable("Unknown loc info!");
1662 case CCValAssign::Full:
1664 case CCValAssign::BCvt:
1665 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
1667 case CCValAssign::SExt:
1668 ArgValue = DAG.getNode(ISD::AssertSext, DL, RegVT, ArgValue,
1669 DAG.getValueType(VA.getValVT()));
1670 ArgValue = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), ArgValue);
1672 case CCValAssign::ZExt:
1673 ArgValue = DAG.getNode(ISD::AssertZext, DL, RegVT, ArgValue,
1674 DAG.getValueType(VA.getValVT()));
1675 ArgValue = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), ArgValue);
1679 InVals.push_back(ArgValue);
1681 } else { // VA.isRegLoc()
1682 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
1683 unsigned ArgOffset = VA.getLocMemOffset();
1684 unsigned ArgSize = VA.getLocVT().getSizeInBits() / 8;
1685 int FI = MFI->CreateFixedObject(ArgSize, ArgOffset, true);
1687 // Create load nodes to retrieve arguments from the stack.
1688 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
1689 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, FIN,
1690 MachinePointerInfo::getFixedStack(FI), false,
1697 if (!Subtarget->isTargetDarwin()) {
1698 // The AAPCS variadic function ABI is identical to the non-variadic
1699 // one. As a result there may be more arguments in registers and we should
1700 // save them for future reference.
1701 saveVarArgRegisters(CCInfo, DAG, DL, Chain);
1704 ARM64FunctionInfo *AFI = MF.getInfo<ARM64FunctionInfo>();
1705 // This will point to the next argument passed via stack.
1706 unsigned StackOffset = CCInfo.getNextStackOffset();
1707 // We currently pass all varargs at 8-byte alignment.
1708 StackOffset = ((StackOffset + 7) & ~7);
1709 AFI->setVarArgsStackIndex(MFI->CreateFixedObject(4, StackOffset, true));
1715 void ARM64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
1716 SelectionDAG &DAG, SDLoc DL,
1717 SDValue &Chain) const {
1718 MachineFunction &MF = DAG.getMachineFunction();
1719 MachineFrameInfo *MFI = MF.getFrameInfo();
1720 ARM64FunctionInfo *FuncInfo = MF.getInfo<ARM64FunctionInfo>();
1722 SmallVector<SDValue, 8> MemOps;
1724 static const MCPhysReg GPRArgRegs[] = { ARM64::X0, ARM64::X1, ARM64::X2,
1725 ARM64::X3, ARM64::X4, ARM64::X5,
1726 ARM64::X6, ARM64::X7 };
1727 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
1728 unsigned FirstVariadicGPR =
1729 CCInfo.getFirstUnallocated(GPRArgRegs, NumGPRArgRegs);
1731 static const MCPhysReg FPRArgRegs[] = { ARM64::Q0, ARM64::Q1, ARM64::Q2,
1732 ARM64::Q3, ARM64::Q4, ARM64::Q5,
1733 ARM64::Q6, ARM64::Q7 };
1734 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
1735 unsigned FirstVariadicFPR =
1736 CCInfo.getFirstUnallocated(FPRArgRegs, NumFPRArgRegs);
1738 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
1740 if (GPRSaveSize != 0) {
1741 GPRIdx = MFI->CreateStackObject(GPRSaveSize, 8, false);
1743 SDValue FIN = DAG.getFrameIndex(GPRIdx, getPointerTy());
1745 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
1746 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &ARM64::GPR64RegClass);
1747 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
1749 DAG.getStore(Val.getValue(1), DL, Val, FIN,
1750 MachinePointerInfo::getStack(i * 8), false, false, 0);
1751 MemOps.push_back(Store);
1752 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), FIN,
1753 DAG.getConstant(8, getPointerTy()));
1757 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
1759 if (FPRSaveSize != 0) {
1760 FPRIdx = MFI->CreateStackObject(FPRSaveSize, 16, false);
1762 SDValue FIN = DAG.getFrameIndex(FPRIdx, getPointerTy());
1764 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
1765 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &ARM64::FPR128RegClass);
1766 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::v2i64);
1768 DAG.getStore(Val.getValue(1), DL, Val, FIN,
1769 MachinePointerInfo::getStack(i * 16), false, false, 0);
1770 MemOps.push_back(Store);
1771 FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(), FIN,
1772 DAG.getConstant(16, getPointerTy()));
1776 FuncInfo->setVarArgsGPRIndex(GPRIdx);
1777 FuncInfo->setVarArgsGPRSize(GPRSaveSize);
1778 FuncInfo->setVarArgsFPRIndex(FPRIdx);
1779 FuncInfo->setVarArgsFPRSize(FPRSaveSize);
1781 if (!MemOps.empty()) {
1782 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &MemOps[0],
1787 /// LowerCallResult - Lower the result values of a call into the
1788 /// appropriate copies out of appropriate physical registers.
1789 SDValue ARM64TargetLowering::LowerCallResult(
1790 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
1791 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
1792 SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
1793 SDValue ThisVal) const {
1794 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS ? RetCC_ARM64_WebKit_JS
1795 : RetCC_ARM64_AAPCS;
1796 // Assign locations to each value returned by this call.
1797 SmallVector<CCValAssign, 16> RVLocs;
1798 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1799 getTargetMachine(), RVLocs, *DAG.getContext());
1800 CCInfo.AnalyzeCallResult(Ins, RetCC);
1802 // Copy all of the result registers out of their specified physreg.
1803 for (unsigned i = 0; i != RVLocs.size(); ++i) {
1804 CCValAssign VA = RVLocs[i];
1806 // Pass 'this' value directly from the argument to return value, to avoid
1807 // reg unit interference
1808 if (i == 0 && isThisReturn) {
1809 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
1810 "unexpected return calling convention register assignment");
1811 InVals.push_back(ThisVal);
1816 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
1817 Chain = Val.getValue(1);
1818 InFlag = Val.getValue(2);
1820 switch (VA.getLocInfo()) {
1822 llvm_unreachable("Unknown loc info!");
1823 case CCValAssign::Full:
1825 case CCValAssign::BCvt:
1826 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
1830 InVals.push_back(Val);
1836 bool ARM64TargetLowering::isEligibleForTailCallOptimization(
1837 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
1838 bool isCalleeStructRet, bool isCallerStructRet,
1839 const SmallVectorImpl<ISD::OutputArg> &Outs,
1840 const SmallVectorImpl<SDValue> &OutVals,
1841 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
1842 // Look for obvious safe cases to perform tail call optimization that do not
1843 // require ABI changes. This is what gcc calls sibcall.
1845 // Do not sibcall optimize vararg calls unless the call site is not passing
1847 if (isVarArg && !Outs.empty())
1850 // Also avoid sibcall optimization if either caller or callee uses struct
1851 // return semantics.
1852 if (isCalleeStructRet || isCallerStructRet)
1855 // Note that currently ARM64 "C" calling convention and "Fast" calling
1856 // convention are compatible. If/when that ever changes, we'll need to
1857 // add checks here to make sure any interactions are OK.
1859 // If the callee takes no arguments then go on to check the results of the
1861 if (!Outs.empty()) {
1862 // Check if stack adjustment is needed. For now, do not do this if any
1863 // argument is passed on the stack.
1864 SmallVector<CCValAssign, 16> ArgLocs;
1865 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
1866 getTargetMachine(), ArgLocs, *DAG.getContext());
1867 CCAssignFn *AssignFn = CCAssignFnForCall(CalleeCC, /*IsVarArg=*/false);
1868 CCInfo.AnalyzeCallOperands(Outs, AssignFn);
1869 if (CCInfo.getNextStackOffset()) {
1870 // Check if the arguments are already laid out in the right way as
1871 // the caller's fixed stack objects.
1872 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
1873 ++i, ++realArgIdx) {
1874 CCValAssign &VA = ArgLocs[i];
1875 if (VA.getLocInfo() == CCValAssign::Indirect)
1877 if (VA.needsCustom()) {
1878 // Just don't handle anything that needs custom adjustments for now.
1879 // If need be, we can revisit later, but we shouldn't ever end up
1882 } else if (!VA.isRegLoc()) {
1883 // Likewise, don't try to handle stack based arguments for the
1893 /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
1894 /// and add input and output parameter nodes.
1895 SDValue ARM64TargetLowering::LowerCall(CallLoweringInfo &CLI,
1896 SmallVectorImpl<SDValue> &InVals) const {
1897 SelectionDAG &DAG = CLI.DAG;
1899 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
1900 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
1901 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
1902 SDValue Chain = CLI.Chain;
1903 SDValue Callee = CLI.Callee;
1904 bool &IsTailCall = CLI.IsTailCall;
1905 CallingConv::ID CallConv = CLI.CallConv;
1906 bool IsVarArg = CLI.IsVarArg;
1908 MachineFunction &MF = DAG.getMachineFunction();
1909 bool IsStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1910 bool IsThisReturn = false;
1912 // If tail calls are explicitly disabled, make sure not to use them.
1913 if (!EnableARM64TailCalls)
1917 // Check if it's really possible to do a tail call.
1918 IsTailCall = isEligibleForTailCallOptimization(
1919 Callee, CallConv, IsVarArg, IsStructRet,
1920 MF.getFunction()->hasStructRetAttr(), Outs, OutVals, Ins, DAG);
1921 // We don't support GuaranteedTailCallOpt, only automatically
1922 // detected sibcalls.
1923 // FIXME: Re-evaluate. Is this true? Should it be true?
1928 // Analyze operands of the call, assigning locations to each operand.
1929 SmallVector<CCValAssign, 16> ArgLocs;
1930 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
1931 getTargetMachine(), ArgLocs, *DAG.getContext());
1934 // Handle fixed and variable vector arguments differently.
1935 // Variable vector arguments always go into memory.
1936 unsigned NumArgs = Outs.size();
1938 for (unsigned i = 0; i != NumArgs; ++i) {
1939 MVT ArgVT = Outs[i].VT;
1940 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
1941 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
1942 /*IsVarArg=*/ !Outs[i].IsFixed);
1943 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
1944 assert(!Res && "Call operand has unhandled type");
1948 // At this point, Outs[].VT may already be promoted to i32. To correctly
1949 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
1950 // i8 to CC_ARM64_AAPCS with i32 being ValVT and i8 being LocVT.
1951 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
1952 // we use a special version of AnalyzeCallOperands to pass in ValVT and
1954 unsigned NumArgs = Outs.size();
1955 for (unsigned i = 0; i != NumArgs; ++i) {
1956 MVT ValVT = Outs[i].VT;
1957 // Get type of the original argument.
1958 EVT ActualVT = getValueType(CLI.Args[Outs[i].OrigArgIndex].Ty,
1959 /*AllowUnknown*/ true);
1960 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
1961 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
1962 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
1964 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
1966 else if (ActualMVT == MVT::i16)
1969 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
1970 bool Res = AssignFn(i, ValVT, LocVT, CCValAssign::Full, ArgFlags, CCInfo);
1971 assert(!Res && "Call operand has unhandled type");
1976 // Get a count of how many bytes are to be pushed on the stack.
1977 unsigned NumBytes = CCInfo.getNextStackOffset();
1979 // Adjust the stack pointer for the new arguments...
1980 // These operations are automatically eliminated by the prolog/epilog pass
1983 DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, true), DL);
1985 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, ARM64::SP, getPointerTy());
1987 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
1988 SmallVector<SDValue, 8> MemOpChains;
1990 // Walk the register/memloc assignments, inserting copies/loads.
1991 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
1992 ++i, ++realArgIdx) {
1993 CCValAssign &VA = ArgLocs[i];
1994 SDValue Arg = OutVals[realArgIdx];
1995 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1997 // Promote the value if needed.
1998 switch (VA.getLocInfo()) {
2000 llvm_unreachable("Unknown loc info!");
2001 case CCValAssign::Full:
2003 case CCValAssign::SExt:
2004 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2006 case CCValAssign::ZExt:
2007 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2009 case CCValAssign::AExt:
2010 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2012 case CCValAssign::BCvt:
2013 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2015 case CCValAssign::FPExt:
2016 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
2020 if (VA.isRegLoc()) {
2021 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i64) {
2022 assert(VA.getLocVT() == MVT::i64 &&
2023 "unexpected calling convention register assignment");
2024 assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
2025 "unexpected use of 'returned'");
2026 IsThisReturn = true;
2028 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2030 assert(VA.isMemLoc());
2031 // There's no reason we can't support stack args w/ tailcall, but
2032 // we currently don't, so assert if we see one.
2033 assert(!IsTailCall && "stack argument with tail call!?");
2034 unsigned LocMemOffset = VA.getLocMemOffset();
2035 SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2036 PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr, PtrOff);
2038 if (Outs[i].Flags.isByVal()) {
2040 DAG.getConstant(Outs[i].Flags.getByValSize(), MVT::i64);
2041 SDValue Cpy = DAG.getMemcpy(
2042 Chain, DL, PtrOff, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
2043 /*isVolatile = */ false,
2044 /*alwaysInline = */ false,
2045 MachinePointerInfo::getStack(LocMemOffset), MachinePointerInfo());
2047 MemOpChains.push_back(Cpy);
2049 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
2050 // promoted to a legal register type i32, we should truncate Arg back to
2052 if (Arg.getValueType().isSimple() &&
2053 Arg.getValueType().getSimpleVT() == MVT::i32 &&
2054 (VA.getLocVT() == MVT::i1 || VA.getLocVT() == MVT::i8 ||
2055 VA.getLocVT() == MVT::i16))
2056 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getLocVT(), Arg);
2058 SDValue Store = DAG.getStore(Chain, DL, Arg, PtrOff,
2059 MachinePointerInfo::getStack(LocMemOffset),
2061 MemOpChains.push_back(Store);
2066 if (!MemOpChains.empty())
2067 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &MemOpChains[0],
2068 MemOpChains.size());
2070 // Build a sequence of copy-to-reg nodes chained together with token chain
2071 // and flag operands which copy the outgoing args into the appropriate regs.
2073 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2074 Chain = DAG.getCopyToReg(Chain, DL, RegsToPass[i].first,
2075 RegsToPass[i].second, InFlag);
2076 InFlag = Chain.getValue(1);
2079 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2080 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2081 // node so that legalize doesn't hack it.
2082 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
2083 Subtarget->isTargetMachO()) {
2084 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2085 const GlobalValue *GV = G->getGlobal();
2086 bool InternalLinkage = GV->hasInternalLinkage();
2087 if (InternalLinkage)
2088 Callee = DAG.getTargetGlobalAddress(GV, DL, getPointerTy(), 0, 0);
2090 Callee = DAG.getTargetGlobalAddress(GV, DL, getPointerTy(), 0,
2092 Callee = DAG.getNode(ARM64ISD::LOADgot, DL, getPointerTy(), Callee);
2094 } else if (ExternalSymbolSDNode *S =
2095 dyn_cast<ExternalSymbolSDNode>(Callee)) {
2096 const char *Sym = S->getSymbol();
2098 DAG.getTargetExternalSymbol(Sym, getPointerTy(), ARM64II::MO_GOT);
2099 Callee = DAG.getNode(ARM64ISD::LOADgot, DL, getPointerTy(), Callee);
2101 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2102 const GlobalValue *GV = G->getGlobal();
2103 Callee = DAG.getTargetGlobalAddress(GV, DL, getPointerTy(), 0, 0);
2104 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2105 const char *Sym = S->getSymbol();
2106 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(), 0);
2109 std::vector<SDValue> Ops;
2110 Ops.push_back(Chain);
2111 Ops.push_back(Callee);
2113 // Add argument registers to the end of the list so that they are known live
2115 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2116 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2117 RegsToPass[i].second.getValueType()));
2119 // Add a register mask operand representing the call-preserved registers.
2120 const uint32_t *Mask;
2121 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2122 const ARM64RegisterInfo *ARI = static_cast<const ARM64RegisterInfo *>(TRI);
2124 // For 'this' returns, use the X0-preserving mask if applicable
2125 Mask = ARI->getThisReturnPreservedMask(CallConv);
2127 IsThisReturn = false;
2128 Mask = ARI->getCallPreservedMask(CallConv);
2131 Mask = ARI->getCallPreservedMask(CallConv);
2133 assert(Mask && "Missing call preserved mask for calling convention");
2134 Ops.push_back(DAG.getRegisterMask(Mask));
2136 if (InFlag.getNode())
2137 Ops.push_back(InFlag);
2139 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2141 // If we're doing a tall call, use a TC_RETURN here rather than an
2142 // actual call instruction.
2144 return DAG.getNode(ARM64ISD::TC_RETURN, DL, NodeTys, &Ops[0], Ops.size());
2146 // Returns a chain and a flag for retval copy to use.
2147 Chain = DAG.getNode(ARM64ISD::CALL, DL, NodeTys, &Ops[0], Ops.size());
2148 InFlag = Chain.getValue(1);
2150 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, true),
2151 DAG.getIntPtrConstant(0, true), InFlag, DL);
2153 InFlag = Chain.getValue(1);
2155 // Handle result values, copying them out of physregs into vregs that we
2157 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
2158 InVals, IsThisReturn,
2159 IsThisReturn ? OutVals[0] : SDValue());
2162 bool ARM64TargetLowering::CanLowerReturn(
2163 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
2164 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
2165 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS ? RetCC_ARM64_WebKit_JS
2166 : RetCC_ARM64_AAPCS;
2167 SmallVector<CCValAssign, 16> RVLocs;
2168 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(), RVLocs, Context);
2169 return CCInfo.CheckReturn(Outs, RetCC);
2173 ARM64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2175 const SmallVectorImpl<ISD::OutputArg> &Outs,
2176 const SmallVectorImpl<SDValue> &OutVals,
2177 SDLoc DL, SelectionDAG &DAG) const {
2178 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS ? RetCC_ARM64_WebKit_JS
2179 : RetCC_ARM64_AAPCS;
2180 SmallVector<CCValAssign, 16> RVLocs;
2181 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2182 getTargetMachine(), RVLocs, *DAG.getContext());
2183 CCInfo.AnalyzeReturn(Outs, RetCC);
2185 // Copy the result values into the output registers.
2187 SmallVector<SDValue, 4> RetOps(1, Chain);
2188 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
2189 ++i, ++realRVLocIdx) {
2190 CCValAssign &VA = RVLocs[i];
2191 assert(VA.isRegLoc() && "Can only return in registers!");
2192 SDValue Arg = OutVals[realRVLocIdx];
2194 switch (VA.getLocInfo()) {
2196 llvm_unreachable("Unknown loc info!");
2197 case CCValAssign::Full:
2199 case CCValAssign::BCvt:
2200 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2204 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2205 Flag = Chain.getValue(1);
2206 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2209 RetOps[0] = Chain; // Update chain.
2211 // Add the flag if we have it.
2213 RetOps.push_back(Flag);
2215 return DAG.getNode(ARM64ISD::RET_FLAG, DL, MVT::Other, &RetOps[0],
2219 //===----------------------------------------------------------------------===//
2220 // Other Lowering Code
2221 //===----------------------------------------------------------------------===//
2223 SDValue ARM64TargetLowering::LowerGlobalAddress(SDValue Op,
2224 SelectionDAG &DAG) const {
2225 EVT PtrVT = getPointerTy();
2227 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2228 unsigned char OpFlags =
2229 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
2231 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
2232 "unexpected offset in global node");
2234 // This also catched the large code model case for Darwin.
2235 if ((OpFlags & ARM64II::MO_GOT) != 0) {
2236 SDValue GotAddr = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
2237 // FIXME: Once remat is capable of dealing with instructions with register
2238 // operands, expand this into two nodes instead of using a wrapper node.
2239 return DAG.getNode(ARM64ISD::LOADgot, DL, PtrVT, GotAddr);
2242 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2243 const unsigned char MO_NC = ARM64II::MO_NC;
2245 ARM64ISD::WrapperLarge, DL, PtrVT,
2246 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ARM64II::MO_G3),
2247 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ARM64II::MO_G2 | MO_NC),
2248 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ARM64II::MO_G1 | MO_NC),
2249 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ARM64II::MO_G0 | MO_NC));
2251 // Use ADRP/ADD or ADRP/LDR for everything else: the small model on ELF and
2252 // the only correct model on Darwin.
2253 SDValue Hi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2254 OpFlags | ARM64II::MO_PAGE);
2255 unsigned char LoFlags = OpFlags | ARM64II::MO_PAGEOFF | ARM64II::MO_NC;
2256 SDValue Lo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, LoFlags);
2258 SDValue ADRP = DAG.getNode(ARM64ISD::ADRP, DL, PtrVT, Hi);
2259 return DAG.getNode(ARM64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
2263 /// \brief Convert a TLS address reference into the correct sequence of loads
2264 /// and calls to compute the variable's address (for Darwin, currently) and
2265 /// return an SDValue containing the final node.
2267 /// Darwin only has one TLS scheme which must be capable of dealing with the
2268 /// fully general situation, in the worst case. This means:
2269 /// + "extern __thread" declaration.
2270 /// + Defined in a possibly unknown dynamic library.
2272 /// The general system is that each __thread variable has a [3 x i64] descriptor
2273 /// which contains information used by the runtime to calculate the address. The
2274 /// only part of this the compiler needs to know about is the first xword, which
2275 /// contains a function pointer that must be called with the address of the
2276 /// entire descriptor in "x0".
2278 /// Since this descriptor may be in a different unit, in general even the
2279 /// descriptor must be accessed via an indirect load. The "ideal" code sequence
2281 /// adrp x0, _var@TLVPPAGE
2282 /// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor
2283 /// ldr x1, [x0] ; x1 contains 1st entry of descriptor,
2284 /// ; the function pointer
2285 /// blr x1 ; Uses descriptor address in x0
2286 /// ; Address of _var is now in x0.
2288 /// If the address of _var's descriptor *is* known to the linker, then it can
2289 /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
2290 /// a slight efficiency gain.
2292 ARM64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
2293 SelectionDAG &DAG) const {
2294 assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
2297 MVT PtrVT = getPointerTy();
2298 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2301 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ARM64II::MO_TLS);
2302 SDValue DescAddr = DAG.getNode(ARM64ISD::LOADgot, DL, PtrVT, TLVPAddr);
2304 // The first entry in the descriptor is a function pointer that we must call
2305 // to obtain the address of the variable.
2306 SDValue Chain = DAG.getEntryNode();
2307 SDValue FuncTLVGet =
2308 DAG.getLoad(MVT::i64, DL, Chain, DescAddr, MachinePointerInfo::getGOT(),
2309 false, true, true, 8);
2310 Chain = FuncTLVGet.getValue(1);
2312 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2313 MFI->setAdjustsStack(true);
2315 // TLS calls preserve all registers except those that absolutely must be
2316 // trashed: X0 (it takes an argument), LR (it's a call) and CPSR (let's not be
2318 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2319 const ARM64RegisterInfo *ARI = static_cast<const ARM64RegisterInfo *>(TRI);
2320 const uint32_t *Mask = ARI->getTLSCallPreservedMask();
2322 // Finally, we can make the call. This is just a degenerate version of a
2323 // normal ARM64 call node: x0 takes the address of the descriptor, and returns
2324 // the address of the variable in this thread.
2325 Chain = DAG.getCopyToReg(Chain, DL, ARM64::X0, DescAddr, SDValue());
2326 Chain = DAG.getNode(ARM64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
2327 Chain, FuncTLVGet, DAG.getRegister(ARM64::X0, MVT::i64),
2328 DAG.getRegisterMask(Mask), Chain.getValue(1));
2329 return DAG.getCopyFromReg(Chain, DL, ARM64::X0, PtrVT, Chain.getValue(1));
2332 /// When accessing thread-local variables under either the general-dynamic or
2333 /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
2334 /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
2335 /// is a function pointer to carry out the resolution. This function takes the
2336 /// address of the descriptor in X0 and returns the TPIDR_EL0 offset in X0. All
2337 /// other registers (except LR, CPSR) are preserved.
2339 /// Thus, the ideal call sequence on AArch64 is:
2341 /// adrp x0, :tlsdesc:thread_var
2342 /// ldr x8, [x0, :tlsdesc_lo12:thread_var]
2343 /// add x0, x0, :tlsdesc_lo12:thread_var
2344 /// .tlsdesccall thread_var
2346 /// (TPIDR_EL0 offset now in x0).
2348 /// The ".tlsdesccall" directive instructs the assembler to insert a particular
2349 /// relocation to help the linker relax this sequence if it turns out to be too
2352 /// FIXME: we currently produce an extra, duplicated, ADRP instruction, but this
2354 SDValue ARM64TargetLowering::LowerELFTLSDescCall(SDValue SymAddr,
2355 SDValue DescAddr, SDLoc DL,
2356 SelectionDAG &DAG) const {
2357 EVT PtrVT = getPointerTy();
2359 // The function we need to call is simply the first entry in the GOT for this
2360 // descriptor, load it in preparation.
2361 SDValue Func = DAG.getNode(ARM64ISD::LOADgot, DL, PtrVT, SymAddr);
2363 // TLS calls preserve all registers except those that absolutely must be
2364 // trashed: X0 (it takes an argument), LR (it's a call) and CPSR (let's not be
2366 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2367 const ARM64RegisterInfo *ARI = static_cast<const ARM64RegisterInfo *>(TRI);
2368 const uint32_t *Mask = ARI->getTLSCallPreservedMask();
2370 // The function takes only one argument: the address of the descriptor itself
2372 SDValue Glue, Chain;
2373 Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM64::X0, DescAddr, Glue);
2374 Glue = Chain.getValue(1);
2376 // We're now ready to populate the argument list, as with a normal call:
2377 SmallVector<SDValue, 6> Ops;
2378 Ops.push_back(Chain);
2379 Ops.push_back(Func);
2380 Ops.push_back(SymAddr);
2381 Ops.push_back(DAG.getRegister(ARM64::X0, PtrVT));
2382 Ops.push_back(DAG.getRegisterMask(Mask));
2383 Ops.push_back(Glue);
2385 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2386 Chain = DAG.getNode(ARM64ISD::TLSDESC_CALL, DL, NodeTys, &Ops[0], Ops.size());
2387 Glue = Chain.getValue(1);
2389 return DAG.getCopyFromReg(Chain, DL, ARM64::X0, PtrVT, Glue);
2392 SDValue ARM64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
2393 SelectionDAG &DAG) const {
2394 assert(Subtarget->isTargetELF() && "This function expects an ELF target");
2395 assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
2396 "ELF TLS only supported in small memory model");
2397 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2399 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
2402 EVT PtrVT = getPointerTy();
2404 const GlobalValue *GV = GA->getGlobal();
2406 SDValue ThreadBase = DAG.getNode(ARM64ISD::THREAD_POINTER, DL, PtrVT);
2408 if (Model == TLSModel::LocalExec) {
2409 SDValue HiVar = DAG.getTargetGlobalAddress(
2410 GV, DL, PtrVT, 0, ARM64II::MO_TLS | ARM64II::MO_G1);
2411 SDValue LoVar = DAG.getTargetGlobalAddress(
2412 GV, DL, PtrVT, 0, ARM64II::MO_TLS | ARM64II::MO_G0 | ARM64II::MO_NC);
2414 TPOff = SDValue(DAG.getMachineNode(ARM64::MOVZXi, DL, PtrVT, HiVar,
2415 DAG.getTargetConstant(16, MVT::i32)),
2417 TPOff = SDValue(DAG.getMachineNode(ARM64::MOVKXi, DL, PtrVT, TPOff, LoVar,
2418 DAG.getTargetConstant(0, MVT::i32)),
2420 } else if (Model == TLSModel::InitialExec) {
2421 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ARM64II::MO_TLS);
2422 TPOff = DAG.getNode(ARM64ISD::LOADgot, DL, PtrVT, TPOff);
2423 } else if (Model == TLSModel::LocalDynamic) {
2424 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
2425 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
2426 // the beginning of the module's TLS region, followed by a DTPREL offset
2429 // These accesses will need deduplicating if there's more than one.
2430 ARM64FunctionInfo *MFI =
2431 DAG.getMachineFunction().getInfo<ARM64FunctionInfo>();
2432 MFI->incNumLocalDynamicTLSAccesses();
2434 // Accesses used in this sequence go via the TLS descriptor which lives in
2435 // the GOT. Prepare an address we can use to handle this.
2436 SDValue HiDesc = DAG.getTargetExternalSymbol(
2437 "_TLS_MODULE_BASE_", PtrVT, ARM64II::MO_TLS | ARM64II::MO_PAGE);
2438 SDValue LoDesc = DAG.getTargetExternalSymbol(
2439 "_TLS_MODULE_BASE_", PtrVT,
2440 ARM64II::MO_TLS | ARM64II::MO_PAGEOFF | ARM64II::MO_NC);
2442 // First argument to the descriptor call is the address of the descriptor
2444 SDValue DescAddr = DAG.getNode(ARM64ISD::ADRP, DL, PtrVT, HiDesc);
2445 DescAddr = DAG.getNode(ARM64ISD::ADDlow, DL, PtrVT, DescAddr, LoDesc);
2447 // The call needs a relocation too for linker relaxation. It doesn't make
2448 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
2450 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
2453 // Now we can calculate the offset from TPIDR_EL0 to this module's
2454 // thread-local area.
2455 TPOff = LowerELFTLSDescCall(SymAddr, DescAddr, DL, DAG);
2457 // Now use :dtprel_whatever: operations to calculate this variable's offset
2458 // in its thread-storage area.
2459 SDValue HiVar = DAG.getTargetGlobalAddress(
2460 GV, DL, MVT::i64, 0, ARM64II::MO_TLS | ARM64II::MO_G1);
2461 SDValue LoVar = DAG.getTargetGlobalAddress(
2462 GV, DL, MVT::i64, 0, ARM64II::MO_TLS | ARM64II::MO_G0 | ARM64II::MO_NC);
2465 SDValue(DAG.getMachineNode(ARM64::MOVZXi, DL, PtrVT, HiVar,
2466 DAG.getTargetConstant(16, MVT::i32)),
2468 DTPOff = SDValue(DAG.getMachineNode(ARM64::MOVKXi, DL, PtrVT, DTPOff, LoVar,
2469 DAG.getTargetConstant(0, MVT::i32)),
2472 TPOff = DAG.getNode(ISD::ADD, DL, PtrVT, TPOff, DTPOff);
2473 } else if (Model == TLSModel::GeneralDynamic) {
2474 // Accesses used in this sequence go via the TLS descriptor which lives in
2475 // the GOT. Prepare an address we can use to handle this.
2476 SDValue HiDesc = DAG.getTargetGlobalAddress(
2477 GV, DL, PtrVT, 0, ARM64II::MO_TLS | ARM64II::MO_PAGE);
2478 SDValue LoDesc = DAG.getTargetGlobalAddress(
2480 ARM64II::MO_TLS | ARM64II::MO_PAGEOFF | ARM64II::MO_NC);
2482 // First argument to the descriptor call is the address of the descriptor
2484 SDValue DescAddr = DAG.getNode(ARM64ISD::ADRP, DL, PtrVT, HiDesc);
2485 DescAddr = DAG.getNode(ARM64ISD::ADDlow, DL, PtrVT, DescAddr, LoDesc);
2487 // The call needs a relocation too for linker relaxation. It doesn't make
2488 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
2491 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, ARM64II::MO_TLS);
2493 // Finally we can make a call to calculate the offset from tpidr_el0.
2494 TPOff = LowerELFTLSDescCall(SymAddr, DescAddr, DL, DAG);
2496 llvm_unreachable("Unsupported ELF TLS access model");
2498 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
2501 SDValue ARM64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
2502 SelectionDAG &DAG) const {
2503 if (Subtarget->isTargetDarwin())
2504 return LowerDarwinGlobalTLSAddress(Op, DAG);
2505 else if (Subtarget->isTargetELF())
2506 return LowerELFGlobalTLSAddress(Op, DAG);
2508 llvm_unreachable("Unexpected platform trying to use TLS");
2510 SDValue ARM64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
2511 SDValue Chain = Op.getOperand(0);
2512 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
2513 SDValue LHS = Op.getOperand(2);
2514 SDValue RHS = Op.getOperand(3);
2515 SDValue Dest = Op.getOperand(4);
2518 // Handle f128 first, since lowering it will result in comparing the return
2519 // value of a libcall against zero, which is just what the rest of LowerBR_CC
2520 // is expecting to deal with.
2521 if (LHS.getValueType() == MVT::f128) {
2522 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
2524 // If softenSetCCOperands returned a scalar, we need to compare the result
2525 // against zero to select between true and false values.
2526 if (RHS.getNode() == 0) {
2527 RHS = DAG.getConstant(0, LHS.getValueType());
2532 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
2534 unsigned Opc = LHS.getOpcode();
2535 if (LHS.getResNo() == 1 && isa<ConstantSDNode>(RHS) &&
2536 cast<ConstantSDNode>(RHS)->isOne() &&
2537 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
2538 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
2539 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
2540 "Unexpected condition code.");
2541 // Only lower legal XALUO ops.
2542 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
2545 // The actual operation with overflow check.
2546 ARM64CC::CondCode OFCC;
2547 SDValue Value, Overflow;
2548 std::tie(Value, Overflow) = getARM64XALUOOp(OFCC, LHS.getValue(0), DAG);
2550 if (CC == ISD::SETNE)
2551 OFCC = getInvertedCondCode(OFCC);
2552 SDValue CCVal = DAG.getConstant(OFCC, MVT::i32);
2554 return DAG.getNode(ARM64ISD::BRCOND, SDLoc(LHS), MVT::Other, Chain, Dest,
2558 if (LHS.getValueType().isInteger()) {
2559 assert((LHS.getValueType() == RHS.getValueType()) &&
2560 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
2562 // If the RHS of the comparison is zero, we can potentially fold this
2563 // to a specialized branch.
2564 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
2565 if (RHSC && RHSC->getZExtValue() == 0) {
2566 if (CC == ISD::SETEQ) {
2567 // See if we can use a TBZ to fold in an AND as well.
2568 // TBZ has a smaller branch displacement than CBZ. If the offset is
2569 // out of bounds, a late MI-layer pass rewrites branches.
2570 // 403.gcc is an example that hits this case.
2571 if (LHS.getOpcode() == ISD::AND &&
2572 isa<ConstantSDNode>(LHS.getOperand(1)) &&
2573 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
2574 SDValue Test = LHS.getOperand(0);
2575 uint64_t Mask = LHS.getConstantOperandVal(1);
2577 // TBZ only operates on i64's, but the ext should be free.
2578 if (Test.getValueType() == MVT::i32)
2579 Test = DAG.getAnyExtOrTrunc(Test, dl, MVT::i64);
2581 return DAG.getNode(ARM64ISD::TBZ, dl, MVT::Other, Chain, Test,
2582 DAG.getConstant(Log2_64(Mask), MVT::i64), Dest);
2585 return DAG.getNode(ARM64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
2586 } else if (CC == ISD::SETNE) {
2587 // See if we can use a TBZ to fold in an AND as well.
2588 // TBZ has a smaller branch displacement than CBZ. If the offset is
2589 // out of bounds, a late MI-layer pass rewrites branches.
2590 // 403.gcc is an example that hits this case.
2591 if (LHS.getOpcode() == ISD::AND &&
2592 isa<ConstantSDNode>(LHS.getOperand(1)) &&
2593 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
2594 SDValue Test = LHS.getOperand(0);
2595 uint64_t Mask = LHS.getConstantOperandVal(1);
2597 // TBNZ only operates on i64's, but the ext should be free.
2598 if (Test.getValueType() == MVT::i32)
2599 Test = DAG.getAnyExtOrTrunc(Test, dl, MVT::i64);
2601 return DAG.getNode(ARM64ISD::TBNZ, dl, MVT::Other, Chain, Test,
2602 DAG.getConstant(Log2_64(Mask), MVT::i64), Dest);
2605 return DAG.getNode(ARM64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
2610 SDValue Cmp = getARM64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
2611 return DAG.getNode(ARM64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
2615 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
2617 // Unfortunately, the mapping of LLVM FP CC's onto ARM64 CC's isn't totally
2618 // clean. Some of them require two branches to implement.
2619 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
2620 ARM64CC::CondCode CC1, CC2;
2621 changeFPCCToARM64CC(CC, CC1, CC2);
2622 SDValue CC1Val = DAG.getConstant(CC1, MVT::i32);
2624 DAG.getNode(ARM64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
2625 if (CC2 != ARM64CC::AL) {
2626 SDValue CC2Val = DAG.getConstant(CC2, MVT::i32);
2627 return DAG.getNode(ARM64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
2634 SDValue ARM64TargetLowering::LowerFCOPYSIGN(SDValue Op,
2635 SelectionDAG &DAG) const {
2636 EVT VT = Op.getValueType();
2639 SDValue In1 = Op.getOperand(0);
2640 SDValue In2 = Op.getOperand(1);
2641 EVT SrcVT = In2.getValueType();
2643 if (SrcVT == MVT::f32 && VT == MVT::f64)
2644 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
2645 else if (SrcVT == MVT::f64 && VT == MVT::f32)
2646 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0));
2648 // FIXME: Src type is different, bail out for now. Can VT really be a
2655 SDValue EltMask, VecVal1, VecVal2;
2656 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
2659 EltMask = DAG.getConstant(0x80000000ULL, EltVT);
2661 if (!VT.isVector()) {
2662 VecVal1 = DAG.getTargetInsertSubreg(ARM64::ssub, DL, VecVT,
2663 DAG.getUNDEF(VecVT), In1);
2664 VecVal2 = DAG.getTargetInsertSubreg(ARM64::ssub, DL, VecVT,
2665 DAG.getUNDEF(VecVT), In2);
2667 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
2668 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
2670 } else if (VT == MVT::f64 || VT == MVT::v2f64) {
2674 // We want to materialize a mask with the the high bit set, but the AdvSIMD
2675 // immediate moves cannot materialize that in a single instruction for
2676 // 64-bit elements. Instead, materialize zero and then negate it.
2677 EltMask = DAG.getConstant(0, EltVT);
2679 if (!VT.isVector()) {
2680 VecVal1 = DAG.getTargetInsertSubreg(ARM64::dsub, DL, VecVT,
2681 DAG.getUNDEF(VecVT), In1);
2682 VecVal2 = DAG.getTargetInsertSubreg(ARM64::dsub, DL, VecVT,
2683 DAG.getUNDEF(VecVT), In2);
2685 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
2686 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
2689 llvm_unreachable("Invalid type for copysign!");
2692 std::vector<SDValue> BuildVectorOps;
2693 for (unsigned i = 0; i < VecVT.getVectorNumElements(); ++i)
2694 BuildVectorOps.push_back(EltMask);
2696 SDValue BuildVec = DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT,
2697 &BuildVectorOps[0], BuildVectorOps.size());
2699 // If we couldn't materialize the mask above, then the mask vector will be
2700 // the zero vector, and we need to negate it here.
2701 if (VT == MVT::f64 || VT == MVT::v2f64) {
2702 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
2703 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
2704 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
2708 DAG.getNode(ARM64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
2711 return DAG.getTargetExtractSubreg(ARM64::ssub, DL, VT, Sel);
2712 else if (VT == MVT::f64)
2713 return DAG.getTargetExtractSubreg(ARM64::dsub, DL, VT, Sel);
2715 return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
2718 SDValue ARM64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
2719 if (DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
2720 AttributeSet::FunctionIndex, Attribute::NoImplicitFloat))
2723 // While there is no integer popcount instruction, it can
2724 // be more efficiently lowered to the following sequence that uses
2725 // AdvSIMD registers/instructions as long as the copies to/from
2726 // the AdvSIMD registers are cheap.
2727 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd
2728 // CNT V0.8B, V0.8B // 8xbyte pop-counts
2729 // ADDV B0, V0.8B // sum 8xbyte pop-counts
2730 // UMOV X0, V0.B[0] // copy byte result back to integer reg
2731 SDValue Val = Op.getOperand(0);
2733 EVT VT = Op.getValueType();
2734 SDValue ZeroVec = DAG.getUNDEF(MVT::v8i8);
2737 if (VT == MVT::i32) {
2738 VecVal = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val);
2740 DAG.getTargetInsertSubreg(ARM64::ssub, DL, MVT::v8i8, ZeroVec, VecVal);
2742 VecVal = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
2745 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, VecVal);
2746 SDValue UaddLV = DAG.getNode(
2747 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
2748 DAG.getConstant(Intrinsic::arm64_neon_uaddlv, MVT::i32), CtPop);
2751 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
2755 SDValue ARM64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2757 if (Op.getValueType().isVector())
2758 return LowerVSETCC(Op, DAG);
2760 SDValue LHS = Op.getOperand(0);
2761 SDValue RHS = Op.getOperand(1);
2762 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
2765 // We chose ZeroOrOneBooleanContents, so use zero and one.
2766 EVT VT = Op.getValueType();
2767 SDValue TVal = DAG.getConstant(1, VT);
2768 SDValue FVal = DAG.getConstant(0, VT);
2770 // Handle f128 first, since one possible outcome is a normal integer
2771 // comparison which gets picked up by the next if statement.
2772 if (LHS.getValueType() == MVT::f128) {
2773 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
2775 // If softenSetCCOperands returned a scalar, use it.
2776 if (RHS.getNode() == 0) {
2777 assert(LHS.getValueType() == Op.getValueType() &&
2778 "Unexpected setcc expansion!");
2783 if (LHS.getValueType().isInteger()) {
2786 getARM64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
2788 // Note that we inverted the condition above, so we reverse the order of
2789 // the true and false operands here. This will allow the setcc to be
2790 // matched to a single CSINC instruction.
2791 return DAG.getNode(ARM64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
2794 // Now we know we're dealing with FP values.
2795 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
2797 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
2798 // and do the comparison.
2799 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
2801 ARM64CC::CondCode CC1, CC2;
2802 changeFPCCToARM64CC(CC, CC1, CC2);
2803 if (CC2 == ARM64CC::AL) {
2804 changeFPCCToARM64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
2805 SDValue CC1Val = DAG.getConstant(CC1, MVT::i32);
2807 // Note that we inverted the condition above, so we reverse the order of
2808 // the true and false operands here. This will allow the setcc to be
2809 // matched to a single CSINC instruction.
2810 return DAG.getNode(ARM64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
2812 // Unfortunately, the mapping of LLVM FP CC's onto ARM64 CC's isn't totally
2813 // clean. Some of them require two CSELs to implement. As is in this case,
2814 // we emit the first CSEL and then emit a second using the output of the
2815 // first as the RHS. We're effectively OR'ing the two CC's together.
2817 // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
2818 SDValue CC1Val = DAG.getConstant(CC1, MVT::i32);
2819 SDValue CS1 = DAG.getNode(ARM64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
2821 SDValue CC2Val = DAG.getConstant(CC2, MVT::i32);
2822 return DAG.getNode(ARM64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
2826 /// A SELECT_CC operation is really some kind of max or min if both values being
2827 /// compared are, in some sense, equal to the results in either case. However,
2828 /// it is permissible to compare f32 values and produce directly extended f64
2831 /// Extending the comparison operands would also be allowed, but is less likely
2832 /// to happen in practice since their use is right here. Note that truncate
2833 /// operations would *not* be semantically equivalent.
2834 static bool selectCCOpsAreFMaxCompatible(SDValue Cmp, SDValue Result) {
2838 ConstantFPSDNode *CCmp = dyn_cast<ConstantFPSDNode>(Cmp);
2839 ConstantFPSDNode *CResult = dyn_cast<ConstantFPSDNode>(Result);
2840 if (CCmp && CResult && Cmp.getValueType() == MVT::f32 &&
2841 Result.getValueType() == MVT::f64) {
2843 APFloat CmpVal = CCmp->getValueAPF();
2844 CmpVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &Lossy);
2845 return CResult->getValueAPF().bitwiseIsEqual(CmpVal);
2848 return Result->getOpcode() == ISD::FP_EXTEND && Result->getOperand(0) == Cmp;
2851 SDValue ARM64TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
2852 SDValue CC = Op->getOperand(0);
2853 SDValue TVal = Op->getOperand(1);
2854 SDValue FVal = Op->getOperand(2);
2857 unsigned Opc = CC.getOpcode();
2858 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
2860 if (CC.getResNo() == 1 &&
2861 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
2862 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
2863 // Only lower legal XALUO ops.
2864 if (!DAG.getTargetLoweringInfo().isTypeLegal(CC->getValueType(0)))
2867 ARM64CC::CondCode OFCC;
2868 SDValue Value, Overflow;
2869 std::tie(Value, Overflow) = getARM64XALUOOp(OFCC, CC.getValue(0), DAG);
2870 SDValue CCVal = DAG.getConstant(OFCC, MVT::i32);
2872 return DAG.getNode(ARM64ISD::CSEL, DL, Op.getValueType(), TVal, FVal, CCVal,
2876 if (CC.getOpcode() == ISD::SETCC)
2877 return DAG.getSelectCC(DL, CC.getOperand(0), CC.getOperand(1), TVal, FVal,
2878 cast<CondCodeSDNode>(CC.getOperand(2))->get());
2880 return DAG.getSelectCC(DL, CC, DAG.getConstant(0, CC.getValueType()), TVal,
2884 SDValue ARM64TargetLowering::LowerSELECT_CC(SDValue Op,
2885 SelectionDAG &DAG) const {
2886 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
2887 SDValue LHS = Op.getOperand(0);
2888 SDValue RHS = Op.getOperand(1);
2889 SDValue TVal = Op.getOperand(2);
2890 SDValue FVal = Op.getOperand(3);
2893 // Handle f128 first, because it will result in a comparison of some RTLIB
2894 // call result against zero.
2895 if (LHS.getValueType() == MVT::f128) {
2896 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
2898 // If softenSetCCOperands returned a scalar, we need to compare the result
2899 // against zero to select between true and false values.
2900 if (RHS.getNode() == 0) {
2901 RHS = DAG.getConstant(0, LHS.getValueType());
2906 // Handle integers first.
2907 if (LHS.getValueType().isInteger()) {
2908 assert((LHS.getValueType() == RHS.getValueType()) &&
2909 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
2911 unsigned Opcode = ARM64ISD::CSEL;
2913 // If both the TVal and the FVal are constants, see if we can swap them in
2914 // order to for a CSINV or CSINC out of them.
2915 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
2916 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
2918 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
2919 std::swap(TVal, FVal);
2920 std::swap(CTVal, CFVal);
2921 CC = ISD::getSetCCInverse(CC, true);
2922 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
2923 std::swap(TVal, FVal);
2924 std::swap(CTVal, CFVal);
2925 CC = ISD::getSetCCInverse(CC, true);
2926 } else if (TVal.getOpcode() == ISD::XOR) {
2927 // If TVal is a NOT we want to swap TVal and FVal so that we can match
2928 // with a CSINV rather than a CSEL.
2929 ConstantSDNode *CVal = dyn_cast<ConstantSDNode>(TVal.getOperand(1));
2931 if (CVal && CVal->isAllOnesValue()) {
2932 std::swap(TVal, FVal);
2933 std::swap(CTVal, CFVal);
2934 CC = ISD::getSetCCInverse(CC, true);
2936 } else if (TVal.getOpcode() == ISD::SUB) {
2937 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
2938 // that we can match with a CSNEG rather than a CSEL.
2939 ConstantSDNode *CVal = dyn_cast<ConstantSDNode>(TVal.getOperand(0));
2941 if (CVal && CVal->isNullValue()) {
2942 std::swap(TVal, FVal);
2943 std::swap(CTVal, CFVal);
2944 CC = ISD::getSetCCInverse(CC, true);
2946 } else if (CTVal && CFVal) {
2947 const int64_t TrueVal = CTVal->getSExtValue();
2948 const int64_t FalseVal = CFVal->getSExtValue();
2951 // If both TVal and FVal are constants, see if FVal is the
2952 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
2953 // instead of a CSEL in that case.
2954 if (TrueVal == ~FalseVal) {
2955 Opcode = ARM64ISD::CSINV;
2956 } else if (TrueVal == -FalseVal) {
2957 Opcode = ARM64ISD::CSNEG;
2958 } else if (TVal.getValueType() == MVT::i32) {
2959 // If our operands are only 32-bit wide, make sure we use 32-bit
2960 // arithmetic for the check whether we can use CSINC. This ensures that
2961 // the addition in the check will wrap around properly in case there is
2962 // an overflow (which would not be the case if we do the check with
2963 // 64-bit arithmetic).
2964 const uint32_t TrueVal32 = CTVal->getZExtValue();
2965 const uint32_t FalseVal32 = CFVal->getZExtValue();
2967 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
2968 Opcode = ARM64ISD::CSINC;
2970 if (TrueVal32 > FalseVal32) {
2974 // 64-bit check whether we can use CSINC.
2975 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
2976 Opcode = ARM64ISD::CSINC;
2978 if (TrueVal > FalseVal) {
2983 // Swap TVal and FVal if necessary.
2985 std::swap(TVal, FVal);
2986 std::swap(CTVal, CFVal);
2987 CC = ISD::getSetCCInverse(CC, true);
2990 if (Opcode != ARM64ISD::CSEL) {
2991 // Drop FVal since we can get its value by simply inverting/negating
2998 SDValue Cmp = getARM64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3000 EVT VT = Op.getValueType();
3001 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
3004 // Now we know we're dealing with FP values.
3005 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3006 assert(LHS.getValueType() == RHS.getValueType());
3007 EVT VT = Op.getValueType();
3009 // Try to match this select into a max/min operation, which have dedicated
3010 // opcode in the instruction set.
3011 // NOTE: This is not correct in the presence of NaNs, so we only enable this
3013 if (getTargetMachine().Options.NoNaNsFPMath) {
3014 if (selectCCOpsAreFMaxCompatible(LHS, FVal) &&
3015 selectCCOpsAreFMaxCompatible(RHS, TVal)) {
3016 CC = ISD::getSetCCSwappedOperands(CC);
3017 std::swap(TVal, FVal);
3020 if (selectCCOpsAreFMaxCompatible(LHS, TVal) &&
3021 selectCCOpsAreFMaxCompatible(RHS, FVal)) {
3031 return DAG.getNode(ARM64ISD::FMAX, dl, VT, TVal, FVal);
3039 return DAG.getNode(ARM64ISD::FMIN, dl, VT, TVal, FVal);
3045 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
3046 // and do the comparison.
3047 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3049 // Unfortunately, the mapping of LLVM FP CC's onto ARM64 CC's isn't totally
3050 // clean. Some of them require two CSELs to implement.
3051 ARM64CC::CondCode CC1, CC2;
3052 changeFPCCToARM64CC(CC, CC1, CC2);
3053 SDValue CC1Val = DAG.getConstant(CC1, MVT::i32);
3054 SDValue CS1 = DAG.getNode(ARM64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3056 // If we need a second CSEL, emit it, using the output of the first as the
3057 // RHS. We're effectively OR'ing the two CC's together.
3058 if (CC2 != ARM64CC::AL) {
3059 SDValue CC2Val = DAG.getConstant(CC2, MVT::i32);
3060 return DAG.getNode(ARM64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3063 // Otherwise, return the output of the first CSEL.
3067 SDValue ARM64TargetLowering::LowerJumpTable(SDValue Op,
3068 SelectionDAG &DAG) const {
3069 // Jump table entries as PC relative offsets. No additional tweaking
3070 // is necessary here. Just get the address of the jump table.
3071 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
3072 EVT PtrVT = getPointerTy();
3075 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3076 !Subtarget->isTargetMachO()) {
3077 const unsigned char MO_NC = ARM64II::MO_NC;
3079 ARM64ISD::WrapperLarge, DL, PtrVT,
3080 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, ARM64II::MO_G3),
3081 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, ARM64II::MO_G2 | MO_NC),
3082 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, ARM64II::MO_G1 | MO_NC),
3083 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, ARM64II::MO_G0 | MO_NC));
3086 SDValue Hi = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, ARM64II::MO_PAGE);
3087 SDValue Lo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
3088 ARM64II::MO_PAGEOFF | ARM64II::MO_NC);
3089 SDValue ADRP = DAG.getNode(ARM64ISD::ADRP, DL, PtrVT, Hi);
3090 return DAG.getNode(ARM64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3093 SDValue ARM64TargetLowering::LowerConstantPool(SDValue Op,
3094 SelectionDAG &DAG) const {
3095 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
3096 EVT PtrVT = getPointerTy();
3099 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
3100 // Use the GOT for the large code model on iOS.
3101 if (Subtarget->isTargetMachO()) {
3102 SDValue GotAddr = DAG.getTargetConstantPool(
3103 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
3105 return DAG.getNode(ARM64ISD::LOADgot, DL, PtrVT, GotAddr);
3108 const unsigned char MO_NC = ARM64II::MO_NC;
3110 ARM64ISD::WrapperLarge, DL, PtrVT,
3111 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3112 CP->getOffset(), ARM64II::MO_G3),
3113 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3114 CP->getOffset(), ARM64II::MO_G2 | MO_NC),
3115 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3116 CP->getOffset(), ARM64II::MO_G1 | MO_NC),
3117 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3118 CP->getOffset(), ARM64II::MO_G0 | MO_NC));
3120 // Use ADRP/ADD or ADRP/LDR for everything else: the small memory model on
3121 // ELF, the only valid one on Darwin.
3123 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
3124 CP->getOffset(), ARM64II::MO_PAGE);
3125 SDValue Lo = DAG.getTargetConstantPool(
3126 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
3127 ARM64II::MO_PAGEOFF | ARM64II::MO_NC);
3129 SDValue ADRP = DAG.getNode(ARM64ISD::ADRP, DL, PtrVT, Hi);
3130 return DAG.getNode(ARM64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3134 SDValue ARM64TargetLowering::LowerBlockAddress(SDValue Op,
3135 SelectionDAG &DAG) const {
3136 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
3137 EVT PtrVT = getPointerTy();
3139 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3140 !Subtarget->isTargetMachO()) {
3141 const unsigned char MO_NC = ARM64II::MO_NC;
3143 ARM64ISD::WrapperLarge, DL, PtrVT,
3144 DAG.getTargetBlockAddress(BA, PtrVT, 0, ARM64II::MO_G3),
3145 DAG.getTargetBlockAddress(BA, PtrVT, 0, ARM64II::MO_G2 | MO_NC),
3146 DAG.getTargetBlockAddress(BA, PtrVT, 0, ARM64II::MO_G1 | MO_NC),
3147 DAG.getTargetBlockAddress(BA, PtrVT, 0, ARM64II::MO_G0 | MO_NC));
3149 SDValue Hi = DAG.getTargetBlockAddress(BA, PtrVT, 0, ARM64II::MO_PAGE);
3150 SDValue Lo = DAG.getTargetBlockAddress(BA, PtrVT, 0, ARM64II::MO_PAGEOFF |
3152 SDValue ADRP = DAG.getNode(ARM64ISD::ADRP, DL, PtrVT, Hi);
3153 return DAG.getNode(ARM64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3157 SDValue ARM64TargetLowering::LowerDarwin_VASTART(SDValue Op,
3158 SelectionDAG &DAG) const {
3159 ARM64FunctionInfo *FuncInfo =
3160 DAG.getMachineFunction().getInfo<ARM64FunctionInfo>();
3164 DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), getPointerTy());
3165 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3166 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
3167 MachinePointerInfo(SV), false, false, 0);
3170 SDValue ARM64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
3171 SelectionDAG &DAG) const {
3172 // The layout of the va_list struct is specified in the AArch64 Procedure Call
3173 // Standard, section B.3.
3174 MachineFunction &MF = DAG.getMachineFunction();
3175 ARM64FunctionInfo *FuncInfo = MF.getInfo<ARM64FunctionInfo>();
3178 SDValue Chain = Op.getOperand(0);
3179 SDValue VAList = Op.getOperand(1);
3180 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3181 SmallVector<SDValue, 4> MemOps;
3183 // void *__stack at offset 0
3185 DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), getPointerTy());
3186 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
3187 MachinePointerInfo(SV), false, false, 8));
3189 // void *__gr_top at offset 8
3190 int GPRSize = FuncInfo->getVarArgsGPRSize();
3192 SDValue GRTop, GRTopAddr;
3194 GRTopAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3195 DAG.getConstant(8, getPointerTy()));
3197 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), getPointerTy());
3198 GRTop = DAG.getNode(ISD::ADD, DL, getPointerTy(), GRTop,
3199 DAG.getConstant(GPRSize, getPointerTy()));
3201 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
3202 MachinePointerInfo(SV, 8), false, false, 8));
3205 // void *__vr_top at offset 16
3206 int FPRSize = FuncInfo->getVarArgsFPRSize();
3208 SDValue VRTop, VRTopAddr;
3209 VRTopAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3210 DAG.getConstant(16, getPointerTy()));
3212 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), getPointerTy());
3213 VRTop = DAG.getNode(ISD::ADD, DL, getPointerTy(), VRTop,
3214 DAG.getConstant(FPRSize, getPointerTy()));
3216 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
3217 MachinePointerInfo(SV, 16), false, false, 8));
3220 // int __gr_offs at offset 24
3221 SDValue GROffsAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3222 DAG.getConstant(24, getPointerTy()));
3223 MemOps.push_back(DAG.getStore(Chain, DL, DAG.getConstant(-GPRSize, MVT::i32),
3224 GROffsAddr, MachinePointerInfo(SV, 24), false,
3227 // int __vr_offs at offset 28
3228 SDValue VROffsAddr = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3229 DAG.getConstant(28, getPointerTy()));
3230 MemOps.push_back(DAG.getStore(Chain, DL, DAG.getConstant(-FPRSize, MVT::i32),
3231 VROffsAddr, MachinePointerInfo(SV, 28), false,
3234 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, &MemOps[0],
3238 SDValue ARM64TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
3239 return Subtarget->isTargetDarwin() ? LowerDarwin_VASTART(Op, DAG)
3240 : LowerAAPCS_VASTART(Op, DAG);
3243 SDValue ARM64TargetLowering::LowerVACOPY(SDValue Op, SelectionDAG &DAG) const {
3244 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
3246 unsigned VaListSize = Subtarget->isTargetDarwin() ? 8 : 32;
3247 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
3248 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
3250 return DAG.getMemcpy(Op.getOperand(0), SDLoc(Op), Op.getOperand(1),
3251 Op.getOperand(2), DAG.getConstant(VaListSize, MVT::i32),
3252 8, false, false, MachinePointerInfo(DestSV),
3253 MachinePointerInfo(SrcSV));
3256 SDValue ARM64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
3257 assert(Subtarget->isTargetDarwin() &&
3258 "automatic va_arg instruction only works on Darwin");
3260 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3261 EVT VT = Op.getValueType();
3263 SDValue Chain = Op.getOperand(0);
3264 SDValue Addr = Op.getOperand(1);
3265 unsigned Align = Op.getConstantOperandVal(3);
3267 SDValue VAList = DAG.getLoad(getPointerTy(), DL, Chain, Addr,
3268 MachinePointerInfo(V), false, false, false, 0);
3269 Chain = VAList.getValue(1);
3272 assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
3273 VAList = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3274 DAG.getConstant(Align - 1, getPointerTy()));
3275 VAList = DAG.getNode(ISD::AND, DL, getPointerTy(), VAList,
3276 DAG.getConstant(-(int64_t)Align, getPointerTy()));
3279 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
3280 uint64_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
3282 // Scalar integer and FP values smaller than 64 bits are implicitly extended
3283 // up to 64 bits. At the very least, we have to increase the striding of the
3284 // vaargs list to match this, and for FP values we need to introduce
3285 // FP_ROUND nodes as well.
3286 if (VT.isInteger() && !VT.isVector())
3288 bool NeedFPTrunc = false;
3289 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
3294 // Increment the pointer, VAList, to the next vaarg
3295 SDValue VANext = DAG.getNode(ISD::ADD, DL, getPointerTy(), VAList,
3296 DAG.getConstant(ArgSize, getPointerTy()));
3297 // Store the incremented VAList to the legalized pointer
3298 SDValue APStore = DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V),
3301 // Load the actual argument out of the pointer VAList
3303 // Load the value as an f64.
3304 SDValue WideFP = DAG.getLoad(MVT::f64, DL, APStore, VAList,
3305 MachinePointerInfo(), false, false, false, 0);
3306 // Round the value down to an f32.
3307 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
3308 DAG.getIntPtrConstant(1));
3309 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
3310 // Merge the rounded value with the chain output of the load.
3311 return DAG.getMergeValues(Ops, 2, DL);
3314 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo(), false,
3318 SDValue ARM64TargetLowering::LowerFRAMEADDR(SDValue Op,
3319 SelectionDAG &DAG) const {
3320 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3321 MFI->setFrameAddressIsTaken(true);
3323 EVT VT = Op.getValueType();
3325 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3326 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, ARM64::FP, VT);
3328 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
3329 MachinePointerInfo(), false, false, false, 0);
3333 SDValue ARM64TargetLowering::LowerRETURNADDR(SDValue Op,
3334 SelectionDAG &DAG) const {
3335 MachineFunction &MF = DAG.getMachineFunction();
3336 MachineFrameInfo *MFI = MF.getFrameInfo();
3337 MFI->setReturnAddressIsTaken(true);
3339 EVT VT = Op.getValueType();
3341 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3343 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
3344 SDValue Offset = DAG.getConstant(8, getPointerTy());
3345 return DAG.getLoad(VT, DL, DAG.getEntryNode(),
3346 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
3347 MachinePointerInfo(), false, false, false, 0);
3350 // Return LR, which contains the return address. Mark it an implicit live-in.
3351 unsigned Reg = MF.addLiveIn(ARM64::LR, &ARM64::GPR64RegClass);
3352 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
3355 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
3356 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
3357 SDValue ARM64TargetLowering::LowerShiftRightParts(SDValue Op,
3358 SelectionDAG &DAG) const {
3359 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3360 EVT VT = Op.getValueType();
3361 unsigned VTBits = VT.getSizeInBits();
3363 SDValue ShOpLo = Op.getOperand(0);
3364 SDValue ShOpHi = Op.getOperand(1);
3365 SDValue ShAmt = Op.getOperand(2);
3367 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
3369 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
3371 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
3372 DAG.getConstant(VTBits, MVT::i64), ShAmt);
3373 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
3374 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
3375 DAG.getConstant(VTBits, MVT::i64));
3376 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
3378 SDValue Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, MVT::i64),
3379 ISD::SETGE, dl, DAG);
3380 SDValue CCVal = DAG.getConstant(ARM64CC::GE, MVT::i32);
3382 SDValue FalseValLo = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3383 SDValue TrueValLo = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
3385 DAG.getNode(ARM64ISD::CSEL, dl, VT, TrueValLo, FalseValLo, CCVal, Cmp);
3387 // ARM64 shifts larger than the register width are wrapped rather than
3388 // clamped, so we can't just emit "hi >> x".
3389 SDValue FalseValHi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
3390 SDValue TrueValHi = Opc == ISD::SRA
3391 ? DAG.getNode(Opc, dl, VT, ShOpHi,
3392 DAG.getConstant(VTBits - 1, MVT::i64))
3393 : DAG.getConstant(0, VT);
3395 DAG.getNode(ARM64ISD::CSEL, dl, VT, TrueValHi, FalseValHi, CCVal, Cmp);
3397 SDValue Ops[2] = { Lo, Hi };
3398 return DAG.getMergeValues(Ops, 2, dl);
3401 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
3402 /// i64 values and take a 2 x i64 value to shift plus a shift amount.
3403 SDValue ARM64TargetLowering::LowerShiftLeftParts(SDValue Op,
3404 SelectionDAG &DAG) const {
3405 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
3406 EVT VT = Op.getValueType();
3407 unsigned VTBits = VT.getSizeInBits();
3409 SDValue ShOpLo = Op.getOperand(0);
3410 SDValue ShOpHi = Op.getOperand(1);
3411 SDValue ShAmt = Op.getOperand(2);
3414 assert(Op.getOpcode() == ISD::SHL_PARTS);
3415 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
3416 DAG.getConstant(VTBits, MVT::i64), ShAmt);
3417 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
3418 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
3419 DAG.getConstant(VTBits, MVT::i64));
3420 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
3421 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
3423 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
3425 SDValue Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, MVT::i64),
3426 ISD::SETGE, dl, DAG);
3427 SDValue CCVal = DAG.getConstant(ARM64CC::GE, MVT::i32);
3428 SDValue Hi = DAG.getNode(ARM64ISD::CSEL, dl, VT, Tmp3, FalseVal, CCVal, Cmp);
3430 // ARM64 shifts of larger than register sizes are wrapped rather than clamped,
3431 // so we can't just emit "lo << a" if a is too big.
3432 SDValue TrueValLo = DAG.getConstant(0, VT);
3433 SDValue FalseValLo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
3435 DAG.getNode(ARM64ISD::CSEL, dl, VT, TrueValLo, FalseValLo, CCVal, Cmp);
3437 SDValue Ops[2] = { Lo, Hi };
3438 return DAG.getMergeValues(Ops, 2, dl);
3442 ARM64TargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3443 // The ARM64 target doesn't support folding offsets into global addresses.
3447 bool ARM64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3448 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
3449 // FIXME: We should be able to handle f128 as well with a clever lowering.
3450 if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32))
3454 return ARM64_AM::getFP64Imm(Imm) != -1;
3455 else if (VT == MVT::f32)
3456 return ARM64_AM::getFP32Imm(Imm) != -1;
3460 //===----------------------------------------------------------------------===//
3461 // ARM64 Optimization Hooks
3462 //===----------------------------------------------------------------------===//
3464 //===----------------------------------------------------------------------===//
3465 // ARM64 Inline Assembly Support
3466 //===----------------------------------------------------------------------===//
3468 // Table of Constraints
3469 // TODO: This is the current set of constraints supported by ARM for the
3470 // compiler, not all of them may make sense, e.g. S may be difficult to support.
3472 // r - A general register
3473 // w - An FP/SIMD register of some size in the range v0-v31
3474 // x - An FP/SIMD register of some size in the range v0-v15
3475 // I - Constant that can be used with an ADD instruction
3476 // J - Constant that can be used with a SUB instruction
3477 // K - Constant that can be used with a 32-bit logical instruction
3478 // L - Constant that can be used with a 64-bit logical instruction
3479 // M - Constant that can be used as a 32-bit MOV immediate
3480 // N - Constant that can be used as a 64-bit MOV immediate
3481 // Q - A memory reference with base register and no offset
3482 // S - A symbolic address
3483 // Y - Floating point constant zero
3484 // Z - Integer constant zero
3486 // Note that general register operands will be output using their 64-bit x
3487 // register name, whatever the size of the variable, unless the asm operand
3488 // is prefixed by the %w modifier. Floating-point and SIMD register operands
3489 // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
3492 /// getConstraintType - Given a constraint letter, return the type of
3493 /// constraint it is for this target.
3494 ARM64TargetLowering::ConstraintType
3495 ARM64TargetLowering::getConstraintType(const std::string &Constraint) const {
3496 if (Constraint.size() == 1) {
3497 switch (Constraint[0]) {
3504 return C_RegisterClass;
3505 // An address with a single base register. Due to the way we
3506 // currently handle addresses it is the same as 'r'.
3511 return TargetLowering::getConstraintType(Constraint);
3514 /// Examine constraint type and operand type and determine a weight value.
3515 /// This object must already have been set up with the operand type
3516 /// and the current alternative constraint selected.
3517 TargetLowering::ConstraintWeight
3518 ARM64TargetLowering::getSingleConstraintMatchWeight(
3519 AsmOperandInfo &info, const char *constraint) const {
3520 ConstraintWeight weight = CW_Invalid;
3521 Value *CallOperandVal = info.CallOperandVal;
3522 // If we don't have a value, we can't do a match,
3523 // but allow it at the lowest weight.
3524 if (CallOperandVal == NULL)
3526 Type *type = CallOperandVal->getType();
3527 // Look at the constraint type.
3528 switch (*constraint) {
3530 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
3534 if (type->isFloatingPointTy() || type->isVectorTy())
3535 weight = CW_Register;
3538 weight = CW_Constant;
3544 std::pair<unsigned, const TargetRegisterClass *>
3545 ARM64TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
3547 if (Constraint.size() == 1) {
3548 switch (Constraint[0]) {
3550 if (VT.getSizeInBits() == 64)
3551 return std::make_pair(0U, &ARM64::GPR64commonRegClass);
3552 return std::make_pair(0U, &ARM64::GPR32commonRegClass);
3555 return std::make_pair(0U, &ARM64::FPR32RegClass);
3556 if (VT.getSizeInBits() == 64)
3557 return std::make_pair(0U, &ARM64::FPR64RegClass);
3558 if (VT.getSizeInBits() == 128)
3559 return std::make_pair(0U, &ARM64::FPR128RegClass);
3561 // The instructions that this constraint is designed for can
3562 // only take 128-bit registers so just use that regclass.
3564 if (VT.getSizeInBits() == 128)
3565 return std::make_pair(0U, &ARM64::FPR128_loRegClass);
3569 if (StringRef("{cc}").equals_lower(Constraint))
3570 return std::make_pair(unsigned(ARM64::CPSR), &ARM64::CCRRegClass);
3572 // Use the default implementation in TargetLowering to convert the register
3573 // constraint into a member of a register class.
3574 std::pair<unsigned, const TargetRegisterClass *> Res;
3575 Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
3577 // Not found as a standard register?
3578 if (Res.second == 0) {
3579 unsigned Size = Constraint.size();
3580 if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
3581 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
3582 const std::string Reg =
3583 std::string(&Constraint[2], &Constraint[Size - 1]);
3584 int RegNo = atoi(Reg.c_str());
3585 if (RegNo >= 0 && RegNo <= 31) {
3586 // v0 - v31 are aliases of q0 - q31.
3587 // By default we'll emit v0-v31 for this unless there's a modifier where
3588 // we'll emit the correct register as well.
3589 Res.first = ARM64::FPR128RegClass.getRegister(RegNo);
3590 Res.second = &ARM64::FPR128RegClass;
3598 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3599 /// vector. If it is invalid, don't add anything to Ops.
3600 void ARM64TargetLowering::LowerAsmOperandForConstraint(
3601 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
3602 SelectionDAG &DAG) const {
3603 SDValue Result(0, 0);
3605 // Currently only support length 1 constraints.
3606 if (Constraint.length() != 1)
3609 char ConstraintLetter = Constraint[0];
3610 switch (ConstraintLetter) {
3614 // This set of constraints deal with valid constants for various instructions.
3615 // Validate and return a target constant for them if we can.
3617 // 'z' maps to xzr or wzr so it needs an input of 0.
3618 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3619 if (!C || C->getZExtValue() != 0)
3622 if (Op.getValueType() == MVT::i64)
3623 Result = DAG.getRegister(ARM64::XZR, MVT::i64);
3625 Result = DAG.getRegister(ARM64::WZR, MVT::i32);
3635 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
3639 // Grab the value and do some validation.
3640 uint64_t CVal = C->getZExtValue();
3641 switch (ConstraintLetter) {
3642 // The I constraint applies only to simple ADD or SUB immediate operands:
3643 // i.e. 0 to 4095 with optional shift by 12
3644 // The J constraint applies only to ADD or SUB immediates that would be
3645 // valid when negated, i.e. if [an add pattern] were to be output as a SUB
3646 // instruction [or vice versa], in other words -1 to -4095 with optional
3647 // left shift by 12.
3649 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
3653 uint64_t NVal = -C->getSExtValue();
3654 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal))
3658 // The K and L constraints apply *only* to logical immediates, including
3659 // what used to be the MOVI alias for ORR (though the MOVI alias has now
3660 // been removed and MOV should be used). So these constraints have to
3661 // distinguish between bit patterns that are valid 32-bit or 64-bit
3662 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
3663 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
3666 if (ARM64_AM::isLogicalImmediate(CVal, 32))
3670 if (ARM64_AM::isLogicalImmediate(CVal, 64))
3673 // The M and N constraints are a superset of K and L respectively, for use
3674 // with the MOV (immediate) alias. As well as the logical immediates they
3675 // also match 32 or 64-bit immediates that can be loaded either using a
3676 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
3677 // (M) or 64-bit 0x1234000000000000 (N) etc.
3678 // As a note some of this code is liberally stolen from the asm parser.
3680 if (!isUInt<32>(CVal))
3682 if (ARM64_AM::isLogicalImmediate(CVal, 32))
3684 if ((CVal & 0xFFFF) == CVal)
3686 if ((CVal & 0xFFFF0000ULL) == CVal)
3688 uint64_t NCVal = ~(uint32_t)CVal;
3689 if ((NCVal & 0xFFFFULL) == NCVal)
3691 if ((NCVal & 0xFFFF0000ULL) == NCVal)
3696 if (ARM64_AM::isLogicalImmediate(CVal, 64))
3698 if ((CVal & 0xFFFFULL) == CVal)
3700 if ((CVal & 0xFFFF0000ULL) == CVal)
3702 if ((CVal & 0xFFFF00000000ULL) == CVal)
3704 if ((CVal & 0xFFFF000000000000ULL) == CVal)
3706 uint64_t NCVal = ~CVal;
3707 if ((NCVal & 0xFFFFULL) == NCVal)
3709 if ((NCVal & 0xFFFF0000ULL) == NCVal)
3711 if ((NCVal & 0xFFFF00000000ULL) == NCVal)
3713 if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
3721 // All assembler immediates are 64-bit integers.
3722 Result = DAG.getTargetConstant(CVal, MVT::i64);
3726 if (Result.getNode()) {
3727 Ops.push_back(Result);
3731 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3734 //===----------------------------------------------------------------------===//
3735 // ARM64 Advanced SIMD Support
3736 //===----------------------------------------------------------------------===//
3738 /// WidenVector - Given a value in the V64 register class, produce the
3739 /// equivalent value in the V128 register class.
3740 static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
3741 EVT VT = V64Reg.getValueType();
3742 unsigned NarrowSize = VT.getVectorNumElements();
3743 MVT EltTy = VT.getVectorElementType().getSimpleVT();
3744 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
3747 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
3748 V64Reg, DAG.getConstant(0, MVT::i32));
3751 /// getExtFactor - Determine the adjustment factor for the position when
3752 /// generating an "extract from vector registers" instruction.
3753 static unsigned getExtFactor(SDValue &V) {
3754 EVT EltType = V.getValueType().getVectorElementType();
3755 return EltType.getSizeInBits() / 8;
3758 /// NarrowVector - Given a value in the V128 register class, produce the
3759 /// equivalent value in the V64 register class.
3760 static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
3761 EVT VT = V128Reg.getValueType();
3762 unsigned WideSize = VT.getVectorNumElements();
3763 MVT EltTy = VT.getVectorElementType().getSimpleVT();
3764 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
3767 return DAG.getTargetExtractSubreg(ARM64::dsub, DL, NarrowTy, V128Reg);
3770 // Gather data to see if the operation can be modelled as a
3771 // shuffle in combination with VEXTs.
3772 SDValue ARM64TargetLowering::ReconstructShuffle(SDValue Op,
3773 SelectionDAG &DAG) const {
3775 EVT VT = Op.getValueType();
3776 unsigned NumElts = VT.getVectorNumElements();
3778 SmallVector<SDValue, 2> SourceVecs;
3779 SmallVector<unsigned, 2> MinElts;
3780 SmallVector<unsigned, 2> MaxElts;
3782 for (unsigned i = 0; i < NumElts; ++i) {
3783 SDValue V = Op.getOperand(i);
3784 if (V.getOpcode() == ISD::UNDEF)
3786 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
3787 // A shuffle can only come from building a vector from various
3788 // elements of other vectors.
3792 // Record this extraction against the appropriate vector if possible...
3793 SDValue SourceVec = V.getOperand(0);
3794 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
3795 bool FoundSource = false;
3796 for (unsigned j = 0; j < SourceVecs.size(); ++j) {
3797 if (SourceVecs[j] == SourceVec) {
3798 if (MinElts[j] > EltNo)
3800 if (MaxElts[j] < EltNo)
3807 // Or record a new source if not...
3809 SourceVecs.push_back(SourceVec);
3810 MinElts.push_back(EltNo);
3811 MaxElts.push_back(EltNo);
3815 // Currently only do something sane when at most two source vectors
3817 if (SourceVecs.size() > 2)
3820 SDValue ShuffleSrcs[2] = { DAG.getUNDEF(VT), DAG.getUNDEF(VT) };
3821 int VEXTOffsets[2] = { 0, 0 };
3823 // This loop extracts the usage patterns of the source vectors
3824 // and prepares appropriate SDValues for a shuffle if possible.
3825 for (unsigned i = 0; i < SourceVecs.size(); ++i) {
3826 if (SourceVecs[i].getValueType() == VT) {
3827 // No VEXT necessary
3828 ShuffleSrcs[i] = SourceVecs[i];
3831 } else if (SourceVecs[i].getValueType().getVectorNumElements() < NumElts) {
3832 // It probably isn't worth padding out a smaller vector just to
3833 // break it down again in a shuffle.
3837 // Don't attempt to extract subvectors from BUILD_VECTOR sources
3838 // that expand or trunc the original value.
3839 // TODO: We can try to bitcast and ANY_EXTEND the result but
3840 // we need to consider the cost of vector ANY_EXTEND, and the
3841 // legality of all the types.
3842 if (SourceVecs[i].getValueType().getVectorElementType() !=
3843 VT.getVectorElementType())
3846 // Since only 64-bit and 128-bit vectors are legal on ARM and
3847 // we've eliminated the other cases...
3848 assert(SourceVecs[i].getValueType().getVectorNumElements() == 2 * NumElts &&
3849 "unexpected vector sizes in ReconstructShuffle");
3851 if (MaxElts[i] - MinElts[i] >= NumElts) {
3852 // Span too large for a VEXT to cope
3856 if (MinElts[i] >= NumElts) {
3857 // The extraction can just take the second half
3858 VEXTOffsets[i] = NumElts;
3860 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SourceVecs[i],
3861 DAG.getIntPtrConstant(NumElts));
3862 } else if (MaxElts[i] < NumElts) {
3863 // The extraction can just take the first half
3865 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
3866 SourceVecs[i], DAG.getIntPtrConstant(0));
3868 // An actual VEXT is needed
3869 VEXTOffsets[i] = MinElts[i];
3870 SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
3871 SourceVecs[i], DAG.getIntPtrConstant(0));
3873 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SourceVecs[i],
3874 DAG.getIntPtrConstant(NumElts));
3875 unsigned Imm = VEXTOffsets[i] * getExtFactor(VEXTSrc1);
3876 ShuffleSrcs[i] = DAG.getNode(ARM64ISD::EXT, dl, VT, VEXTSrc1, VEXTSrc2,
3877 DAG.getConstant(Imm, MVT::i32));
3881 SmallVector<int, 8> Mask;
3883 for (unsigned i = 0; i < NumElts; ++i) {
3884 SDValue Entry = Op.getOperand(i);
3885 if (Entry.getOpcode() == ISD::UNDEF) {
3890 SDValue ExtractVec = Entry.getOperand(0);
3892 cast<ConstantSDNode>(Op.getOperand(i).getOperand(1))->getSExtValue();
3893 if (ExtractVec == SourceVecs[0]) {
3894 Mask.push_back(ExtractElt - VEXTOffsets[0]);
3896 Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
3900 // Final check before we try to produce nonsense...
3901 if (isShuffleMaskLegal(Mask, VT))
3902 return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
3908 // check if an EXT instruction can handle the shuffle mask when the
3909 // vector sources of the shuffle are the same.
3910 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
3911 unsigned NumElts = VT.getVectorNumElements();
3913 // Assume that the first shuffle index is not UNDEF. Fail if it is.
3919 // If this is a VEXT shuffle, the immediate value is the index of the first
3920 // element. The other shuffle indices must be the successive elements after
3922 unsigned ExpectedElt = Imm;
3923 for (unsigned i = 1; i < NumElts; ++i) {
3924 // Increment the expected index. If it wraps around, just follow it
3925 // back to index zero and keep going.
3927 if (ExpectedElt == NumElts)
3931 continue; // ignore UNDEF indices
3932 if (ExpectedElt != static_cast<unsigned>(M[i]))
3939 // check if an EXT instruction can handle the shuffle mask when the
3940 // vector sources of the shuffle are different.
3941 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
3943 unsigned NumElts = VT.getVectorNumElements();
3946 // Assume that the first shuffle index is not UNDEF. Fail if it is.
3952 // If this is a VEXT shuffle, the immediate value is the index of the first
3953 // element. The other shuffle indices must be the successive elements after
3955 unsigned ExpectedElt = Imm;
3956 for (unsigned i = 1; i < NumElts; ++i) {
3957 // Increment the expected index. If it wraps around, it may still be
3958 // a VEXT but the source vectors must be swapped.
3960 if (ExpectedElt == NumElts * 2) {
3966 continue; // ignore UNDEF indices
3967 if (ExpectedElt != static_cast<unsigned>(M[i]))
3971 // Adjust the index value if the source operands will be swapped.
3978 /// isREVMask - Check if a vector shuffle corresponds to a REV
3979 /// instruction with the specified blocksize. (The order of the elements
3980 /// within each block of the vector is reversed.)
3981 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
3982 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
3983 "Only possible block sizes for REV are: 16, 32, 64");
3985 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3989 unsigned NumElts = VT.getVectorNumElements();
3990 unsigned BlockElts = M[0] + 1;
3991 // If the first shuffle index is UNDEF, be optimistic.
3993 BlockElts = BlockSize / EltSz;
3995 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
3998 for (unsigned i = 0; i < NumElts; ++i) {
4000 continue; // ignore UNDEF indices
4001 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
4008 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4009 unsigned NumElts = VT.getVectorNumElements();
4010 WhichResult = (M[0] == 0 ? 0 : 1);
4011 unsigned Idx = WhichResult * NumElts / 2;
4012 for (unsigned i = 0; i != NumElts; i += 2) {
4013 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
4014 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
4022 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4023 unsigned NumElts = VT.getVectorNumElements();
4024 WhichResult = (M[0] == 0 ? 0 : 1);
4025 for (unsigned i = 0; i != NumElts; ++i) {
4027 continue; // ignore UNDEF indices
4028 if ((unsigned)M[i] != 2 * i + WhichResult)
4035 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4036 unsigned NumElts = VT.getVectorNumElements();
4037 WhichResult = (M[0] == 0 ? 0 : 1);
4038 for (unsigned i = 0; i < NumElts; i += 2) {
4039 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
4040 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
4046 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
4047 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4048 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4049 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4050 unsigned NumElts = VT.getVectorNumElements();
4051 WhichResult = (M[0] == 0 ? 0 : 1);
4052 unsigned Idx = WhichResult * NumElts / 2;
4053 for (unsigned i = 0; i != NumElts; i += 2) {
4054 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
4055 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
4063 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
4064 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4065 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4066 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4067 unsigned Half = VT.getVectorNumElements() / 2;
4068 WhichResult = (M[0] == 0 ? 0 : 1);
4069 for (unsigned j = 0; j != 2; ++j) {
4070 unsigned Idx = WhichResult;
4071 for (unsigned i = 0; i != Half; ++i) {
4072 int MIdx = M[i + j * Half];
4073 if (MIdx >= 0 && (unsigned)MIdx != Idx)
4082 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
4083 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4084 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4085 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4086 unsigned NumElts = VT.getVectorNumElements();
4087 WhichResult = (M[0] == 0 ? 0 : 1);
4088 for (unsigned i = 0; i < NumElts; i += 2) {
4089 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
4090 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
4096 static bool isINSMask(ArrayRef<int> M, int NumInputElements,
4097 bool &BulkIsLeft, int &Anomaly) {
4098 if (M.size() != static_cast<size_t>(NumInputElements))
4101 int NumLHSMatch = 0, NumRHSMatch = 0;
4102 int LastLHSMismatch = -1, LastRHSMismatch = -1;
4104 for (int i = 0; i < NumInputElements; ++i) {
4114 LastLHSMismatch = i;
4116 if (M[i] == i + NumInputElements)
4119 LastRHSMismatch = i;
4122 if (NumLHSMatch == NumInputElements - 1) {
4124 Anomaly = LastLHSMismatch;
4126 } else if (NumRHSMatch == NumInputElements - 1) {
4128 Anomaly = LastRHSMismatch;
4135 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
4136 /// the specified operations to build the shuffle.
4137 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
4138 SDValue RHS, SelectionDAG &DAG,
4140 unsigned OpNum = (PFEntry >> 26) & 0x0F;
4141 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
4142 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
4145 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
4154 OP_VUZPL, // VUZP, left result
4155 OP_VUZPR, // VUZP, right result
4156 OP_VZIPL, // VZIP, left result
4157 OP_VZIPR, // VZIP, right result
4158 OP_VTRNL, // VTRN, left result
4159 OP_VTRNR // VTRN, right result
4162 if (OpNum == OP_COPY) {
4163 if (LHSID == (1 * 9 + 2) * 9 + 3)
4165 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
4169 SDValue OpLHS, OpRHS;
4170 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
4171 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
4172 EVT VT = OpLHS.getValueType();
4176 llvm_unreachable("Unknown shuffle opcode!");
4178 // VREV divides the vector in half and swaps within the half.
4179 if (VT.getVectorElementType() == MVT::i32 ||
4180 VT.getVectorElementType() == MVT::f32)
4181 return DAG.getNode(ARM64ISD::REV64, dl, VT, OpLHS);
4182 // vrev <4 x i16> -> REV32
4183 if (VT.getVectorElementType() == MVT::i16)
4184 return DAG.getNode(ARM64ISD::REV32, dl, VT, OpLHS);
4185 // vrev <4 x i8> -> REV16
4186 assert(VT.getVectorElementType() == MVT::i8);
4187 return DAG.getNode(ARM64ISD::REV16, dl, VT, OpLHS);
4192 EVT EltTy = VT.getVectorElementType();
4194 if (EltTy == MVT::i8)
4195 Opcode = ARM64ISD::DUPLANE8;
4196 else if (EltTy == MVT::i16)
4197 Opcode = ARM64ISD::DUPLANE16;
4198 else if (EltTy == MVT::i32 || EltTy == MVT::f32)
4199 Opcode = ARM64ISD::DUPLANE32;
4200 else if (EltTy == MVT::i64 || EltTy == MVT::f64)
4201 Opcode = ARM64ISD::DUPLANE64;
4203 llvm_unreachable("Invalid vector element type?");
4205 if (VT.getSizeInBits() == 64)
4206 OpLHS = WidenVector(OpLHS, DAG);
4207 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, MVT::i64);
4208 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
4213 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
4214 return DAG.getNode(ARM64ISD::EXT, dl, VT, OpLHS, OpRHS,
4215 DAG.getConstant(Imm, MVT::i32));
4218 return DAG.getNode(ARM64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS, OpRHS);
4220 return DAG.getNode(ARM64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS, OpRHS);
4222 return DAG.getNode(ARM64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS, OpRHS);
4224 return DAG.getNode(ARM64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS, OpRHS);
4226 return DAG.getNode(ARM64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS, OpRHS);
4228 return DAG.getNode(ARM64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS, OpRHS);
4232 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
4233 SelectionDAG &DAG) {
4234 // Check to see if we can use the TBL instruction.
4235 SDValue V1 = Op.getOperand(0);
4236 SDValue V2 = Op.getOperand(1);
4239 EVT EltVT = Op.getValueType().getVectorElementType();
4240 unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
4242 SmallVector<SDValue, 8> TBLMask;
4243 for (int Val : ShuffleMask) {
4244 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
4245 unsigned Offset = Byte + Val * BytesPerElt;
4246 TBLMask.push_back(DAG.getConstant(Offset, MVT::i32));
4250 MVT IndexVT = MVT::v8i8;
4251 unsigned IndexLen = 8;
4252 if (Op.getValueType().getSizeInBits() == 128) {
4253 IndexVT = MVT::v16i8;
4257 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
4258 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
4261 if (V2.getNode()->getOpcode() == ISD::UNDEF) {
4263 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
4264 Shuffle = DAG.getNode(
4265 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
4266 DAG.getConstant(Intrinsic::arm64_neon_tbl1, MVT::i32), V1Cst,
4267 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT, &TBLMask[0], IndexLen));
4269 if (IndexLen == 8) {
4270 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
4271 Shuffle = DAG.getNode(
4272 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
4273 DAG.getConstant(Intrinsic::arm64_neon_tbl1, MVT::i32), V1Cst,
4274 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT, &TBLMask[0], IndexLen));
4276 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
4277 // cannot currently represent the register constraints on the input
4279 // Shuffle = DAG.getNode(ARM64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
4280 // DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
4281 // &TBLMask[0], IndexLen));
4282 Shuffle = DAG.getNode(
4283 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
4284 DAG.getConstant(Intrinsic::arm64_neon_tbl2, MVT::i32), V1Cst, V2Cst,
4285 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT, &TBLMask[0], IndexLen));
4288 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
4291 static unsigned getDUPLANEOp(EVT EltType) {
4292 if (EltType == MVT::i8)
4293 return ARM64ISD::DUPLANE8;
4294 if (EltType == MVT::i16)
4295 return ARM64ISD::DUPLANE16;
4296 if (EltType == MVT::i32 || EltType == MVT::f32)
4297 return ARM64ISD::DUPLANE32;
4298 if (EltType == MVT::i64 || EltType == MVT::f64)
4299 return ARM64ISD::DUPLANE64;
4301 llvm_unreachable("Invalid vector element type?");
4304 SDValue ARM64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
4305 SelectionDAG &DAG) const {
4307 EVT VT = Op.getValueType();
4309 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
4311 // Convert shuffles that are directly supported on NEON to target-specific
4312 // DAG nodes, instead of keeping them as shuffles and matching them again
4313 // during code selection. This is more efficient and avoids the possibility
4314 // of inconsistencies between legalization and selection.
4315 ArrayRef<int> ShuffleMask = SVN->getMask();
4317 SDValue V1 = Op.getOperand(0);
4318 SDValue V2 = Op.getOperand(1);
4320 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0],
4321 V1.getValueType().getSimpleVT())) {
4322 int Lane = SVN->getSplatIndex();
4323 // If this is undef splat, generate it via "just" vdup, if possible.
4327 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
4328 return DAG.getNode(ARM64ISD::DUP, dl, V1.getValueType(),
4330 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
4331 // constant. If so, we can just reference the lane's definition directly.
4332 if (V1.getOpcode() == ISD::BUILD_VECTOR &&
4333 !isa<ConstantSDNode>(V1.getOperand(Lane)))
4334 return DAG.getNode(ARM64ISD::DUP, dl, VT, V1.getOperand(Lane));
4336 // Otherwise, duplicate from the lane of the input vector.
4337 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
4339 // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
4340 // to make a vector of the same size as this SHUFFLE. We can ignore the
4341 // extract entirely, and canonicalise the concat using WidenVector.
4342 if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
4343 Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
4344 V1 = V1.getOperand(0);
4345 } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
4346 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
4347 Lane -= Idx * VT.getVectorNumElements() / 2;
4348 V1 = WidenVector(V1.getOperand(Idx), DAG);
4349 } else if (VT.getSizeInBits() == 64)
4350 V1 = WidenVector(V1, DAG);
4352 return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, MVT::i64));
4355 if (isREVMask(ShuffleMask, VT, 64))
4356 return DAG.getNode(ARM64ISD::REV64, dl, V1.getValueType(), V1, V2);
4357 if (isREVMask(ShuffleMask, VT, 32))
4358 return DAG.getNode(ARM64ISD::REV32, dl, V1.getValueType(), V1, V2);
4359 if (isREVMask(ShuffleMask, VT, 16))
4360 return DAG.getNode(ARM64ISD::REV16, dl, V1.getValueType(), V1, V2);
4362 bool ReverseEXT = false;
4364 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
4367 Imm *= getExtFactor(V1);
4368 return DAG.getNode(ARM64ISD::EXT, dl, V1.getValueType(), V1, V2,
4369 DAG.getConstant(Imm, MVT::i32));
4370 } else if (V2->getOpcode() == ISD::UNDEF &&
4371 isSingletonEXTMask(ShuffleMask, VT, Imm)) {
4372 Imm *= getExtFactor(V1);
4373 return DAG.getNode(ARM64ISD::EXT, dl, V1.getValueType(), V1, V1,
4374 DAG.getConstant(Imm, MVT::i32));
4377 unsigned WhichResult;
4378 if (isZIPMask(ShuffleMask, VT, WhichResult)) {
4379 unsigned Opc = (WhichResult == 0) ? ARM64ISD::ZIP1 : ARM64ISD::ZIP2;
4380 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
4382 if (isUZPMask(ShuffleMask, VT, WhichResult)) {
4383 unsigned Opc = (WhichResult == 0) ? ARM64ISD::UZP1 : ARM64ISD::UZP2;
4384 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
4386 if (isTRNMask(ShuffleMask, VT, WhichResult)) {
4387 unsigned Opc = (WhichResult == 0) ? ARM64ISD::TRN1 : ARM64ISD::TRN2;
4388 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
4391 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
4392 unsigned Opc = (WhichResult == 0) ? ARM64ISD::ZIP1 : ARM64ISD::ZIP2;
4393 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
4395 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
4396 unsigned Opc = (WhichResult == 0) ? ARM64ISD::UZP1 : ARM64ISD::UZP2;
4397 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
4399 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
4400 unsigned Opc = (WhichResult == 0) ? ARM64ISD::TRN1 : ARM64ISD::TRN2;
4401 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
4406 int NumInputElements = V1.getValueType().getVectorNumElements();
4407 if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
4408 SDValue DstVec = DstIsLeft ? V1 : V2;
4409 SDValue DstLaneV = DAG.getConstant(Anomaly, MVT::i64);
4411 SDValue SrcVec = V1;
4412 int SrcLane = ShuffleMask[Anomaly];
4413 if (SrcLane >= NumInputElements) {
4415 SrcLane -= VT.getVectorNumElements();
4417 SDValue SrcLaneV = DAG.getConstant(SrcLane, MVT::i64);
4419 EVT ScalarVT = VT.getVectorElementType();
4420 if (ScalarVT.getSizeInBits() < 32)
4421 ScalarVT = MVT::i32;
4424 ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
4425 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
4429 // If the shuffle is not directly supported and it has 4 elements, use
4430 // the PerfectShuffle-generated table to synthesize it from other shuffles.
4431 unsigned NumElts = VT.getVectorNumElements();
4433 unsigned PFIndexes[4];
4434 for (unsigned i = 0; i != 4; ++i) {
4435 if (ShuffleMask[i] < 0)
4438 PFIndexes[i] = ShuffleMask[i];
4441 // Compute the index in the perfect shuffle table.
4442 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
4443 PFIndexes[2] * 9 + PFIndexes[3];
4444 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4445 unsigned Cost = (PFEntry >> 30);
4448 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
4451 return GenerateTBL(Op, ShuffleMask, DAG);
4454 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
4456 EVT VT = BVN->getValueType(0);
4457 APInt SplatBits, SplatUndef;
4458 unsigned SplatBitSize;
4460 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4461 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
4463 for (unsigned i = 0; i < NumSplats; ++i) {
4464 CnstBits <<= SplatBitSize;
4465 UndefBits <<= SplatBitSize;
4466 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
4467 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
4476 SDValue ARM64TargetLowering::LowerVectorAND(SDValue Op,
4477 SelectionDAG &DAG) const {
4478 BuildVectorSDNode *BVN =
4479 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
4480 SDValue LHS = Op.getOperand(0);
4482 EVT VT = Op.getValueType();
4487 APInt CnstBits(VT.getSizeInBits(), 0);
4488 APInt UndefBits(VT.getSizeInBits(), 0);
4489 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
4490 // We only have BIC vector immediate instruction, which is and-not.
4491 CnstBits = ~CnstBits;
4493 // We make use of a little bit of goto ickiness in order to avoid having to
4494 // duplicate the immediate matching logic for the undef toggled case.
4495 bool SecondTry = false;
4498 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
4499 CnstBits = CnstBits.zextOrTrunc(64);
4500 uint64_t CnstVal = CnstBits.getZExtValue();
4502 if (ARM64_AM::isAdvSIMDModImmType1(CnstVal)) {
4503 CnstVal = ARM64_AM::encodeAdvSIMDModImmType1(CnstVal);
4504 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4505 SDValue Mov = DAG.getNode(ARM64ISD::BICi, dl, MovTy, LHS,
4506 DAG.getConstant(CnstVal, MVT::i32),
4507 DAG.getConstant(0, MVT::i32));
4508 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4511 if (ARM64_AM::isAdvSIMDModImmType2(CnstVal)) {
4512 CnstVal = ARM64_AM::encodeAdvSIMDModImmType2(CnstVal);
4513 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4514 SDValue Mov = DAG.getNode(ARM64ISD::BICi, dl, MovTy, LHS,
4515 DAG.getConstant(CnstVal, MVT::i32),
4516 DAG.getConstant(8, MVT::i32));
4517 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4520 if (ARM64_AM::isAdvSIMDModImmType3(CnstVal)) {
4521 CnstVal = ARM64_AM::encodeAdvSIMDModImmType3(CnstVal);
4522 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4523 SDValue Mov = DAG.getNode(ARM64ISD::BICi, dl, MovTy, LHS,
4524 DAG.getConstant(CnstVal, MVT::i32),
4525 DAG.getConstant(16, MVT::i32));
4526 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4529 if (ARM64_AM::isAdvSIMDModImmType4(CnstVal)) {
4530 CnstVal = ARM64_AM::encodeAdvSIMDModImmType4(CnstVal);
4531 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4532 SDValue Mov = DAG.getNode(ARM64ISD::BICi, dl, MovTy, LHS,
4533 DAG.getConstant(CnstVal, MVT::i32),
4534 DAG.getConstant(24, MVT::i32));
4535 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4538 if (ARM64_AM::isAdvSIMDModImmType5(CnstVal)) {
4539 CnstVal = ARM64_AM::encodeAdvSIMDModImmType5(CnstVal);
4540 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
4541 SDValue Mov = DAG.getNode(ARM64ISD::BICi, dl, MovTy, LHS,
4542 DAG.getConstant(CnstVal, MVT::i32),
4543 DAG.getConstant(0, MVT::i32));
4544 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4547 if (ARM64_AM::isAdvSIMDModImmType6(CnstVal)) {
4548 CnstVal = ARM64_AM::encodeAdvSIMDModImmType6(CnstVal);
4549 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
4550 SDValue Mov = DAG.getNode(ARM64ISD::BICi, dl, MovTy, LHS,
4551 DAG.getConstant(CnstVal, MVT::i32),
4552 DAG.getConstant(8, MVT::i32));
4553 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4560 CnstBits = ~UndefBits;
4564 // We can always fall back to a non-immediate AND.
4569 // Specialized code to quickly find if PotentialBVec is a BuildVector that
4570 // consists of only the same constant int value, returned in reference arg
4572 static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
4573 uint64_t &ConstVal) {
4574 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
4577 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
4580 EVT VT = Bvec->getValueType(0);
4581 unsigned NumElts = VT.getVectorNumElements();
4582 for (unsigned i = 1; i < NumElts; ++i)
4583 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
4585 ConstVal = FirstElt->getZExtValue();
4589 static unsigned getIntrinsicID(const SDNode *N) {
4590 unsigned Opcode = N->getOpcode();
4593 return Intrinsic::not_intrinsic;
4594 case ISD::INTRINSIC_WO_CHAIN: {
4595 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
4596 if (IID < Intrinsic::num_intrinsics)
4598 return Intrinsic::not_intrinsic;
4603 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
4604 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
4605 // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
4606 // Also, logical shift right -> sri, with the same structure.
4607 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
4608 EVT VT = N->getValueType(0);
4615 // Is the first op an AND?
4616 const SDValue And = N->getOperand(0);
4617 if (And.getOpcode() != ISD::AND)
4620 // Is the second op an shl or lshr?
4621 SDValue Shift = N->getOperand(1);
4622 // This will have been turned into: ARM64ISD::VSHL vector, #shift
4623 // or ARM64ISD::VLSHR vector, #shift
4624 unsigned ShiftOpc = Shift.getOpcode();
4625 if ((ShiftOpc != ARM64ISD::VSHL && ShiftOpc != ARM64ISD::VLSHR))
4627 bool IsShiftRight = ShiftOpc == ARM64ISD::VLSHR;
4629 // Is the shift amount constant?
4630 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
4634 // Is the and mask vector all constant?
4636 if (!isAllConstantBuildVector(And.getOperand(1), C1))
4639 // Is C1 == ~C2, taking into account how much one can shift elements of a
4641 uint64_t C2 = C2node->getZExtValue();
4642 unsigned ElemSizeInBits = VT.getVectorElementType().getSizeInBits();
4643 if (C2 > ElemSizeInBits)
4645 unsigned ElemMask = (1 << ElemSizeInBits) - 1;
4646 if ((C1 & ElemMask) != (~C2 & ElemMask))
4649 SDValue X = And.getOperand(0);
4650 SDValue Y = Shift.getOperand(0);
4653 IsShiftRight ? Intrinsic::arm64_neon_vsri : Intrinsic::arm64_neon_vsli;
4655 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
4656 DAG.getConstant(Intrin, MVT::i32), X, Y, Shift.getOperand(1));
4658 DEBUG(dbgs() << "arm64-lower: transformed: \n");
4659 DEBUG(N->dump(&DAG));
4660 DEBUG(dbgs() << "into: \n");
4661 DEBUG(ResultSLI->dump(&DAG));
4667 SDValue ARM64TargetLowering::LowerVectorOR(SDValue Op,
4668 SelectionDAG &DAG) const {
4669 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
4670 if (EnableARM64SlrGeneration) {
4671 SDValue Res = tryLowerToSLI(Op.getNode(), DAG);
4676 BuildVectorSDNode *BVN =
4677 dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
4678 SDValue LHS = Op.getOperand(1);
4680 EVT VT = Op.getValueType();
4682 // OR commutes, so try swapping the operands.
4684 LHS = Op.getOperand(0);
4685 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
4690 APInt CnstBits(VT.getSizeInBits(), 0);
4691 APInt UndefBits(VT.getSizeInBits(), 0);
4692 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
4693 // We make use of a little bit of goto ickiness in order to avoid having to
4694 // duplicate the immediate matching logic for the undef toggled case.
4695 bool SecondTry = false;
4698 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
4699 CnstBits = CnstBits.zextOrTrunc(64);
4700 uint64_t CnstVal = CnstBits.getZExtValue();
4702 if (ARM64_AM::isAdvSIMDModImmType1(CnstVal)) {
4703 CnstVal = ARM64_AM::encodeAdvSIMDModImmType1(CnstVal);
4704 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4705 SDValue Mov = DAG.getNode(ARM64ISD::ORRi, dl, MovTy, LHS,
4706 DAG.getConstant(CnstVal, MVT::i32),
4707 DAG.getConstant(0, MVT::i32));
4708 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4711 if (ARM64_AM::isAdvSIMDModImmType2(CnstVal)) {
4712 CnstVal = ARM64_AM::encodeAdvSIMDModImmType2(CnstVal);
4713 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4714 SDValue Mov = DAG.getNode(ARM64ISD::ORRi, dl, MovTy, LHS,
4715 DAG.getConstant(CnstVal, MVT::i32),
4716 DAG.getConstant(8, MVT::i32));
4717 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4720 if (ARM64_AM::isAdvSIMDModImmType3(CnstVal)) {
4721 CnstVal = ARM64_AM::encodeAdvSIMDModImmType3(CnstVal);
4722 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4723 SDValue Mov = DAG.getNode(ARM64ISD::ORRi, dl, MovTy, LHS,
4724 DAG.getConstant(CnstVal, MVT::i32),
4725 DAG.getConstant(16, MVT::i32));
4726 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4729 if (ARM64_AM::isAdvSIMDModImmType4(CnstVal)) {
4730 CnstVal = ARM64_AM::encodeAdvSIMDModImmType4(CnstVal);
4731 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4732 SDValue Mov = DAG.getNode(ARM64ISD::ORRi, dl, MovTy, LHS,
4733 DAG.getConstant(CnstVal, MVT::i32),
4734 DAG.getConstant(24, MVT::i32));
4735 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4738 if (ARM64_AM::isAdvSIMDModImmType5(CnstVal)) {
4739 CnstVal = ARM64_AM::encodeAdvSIMDModImmType5(CnstVal);
4740 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
4741 SDValue Mov = DAG.getNode(ARM64ISD::ORRi, dl, MovTy, LHS,
4742 DAG.getConstant(CnstVal, MVT::i32),
4743 DAG.getConstant(0, MVT::i32));
4744 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4747 if (ARM64_AM::isAdvSIMDModImmType6(CnstVal)) {
4748 CnstVal = ARM64_AM::encodeAdvSIMDModImmType6(CnstVal);
4749 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
4750 SDValue Mov = DAG.getNode(ARM64ISD::ORRi, dl, MovTy, LHS,
4751 DAG.getConstant(CnstVal, MVT::i32),
4752 DAG.getConstant(8, MVT::i32));
4753 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4760 CnstBits = UndefBits;
4764 // We can always fall back to a non-immediate OR.
4769 SDValue ARM64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
4770 SelectionDAG &DAG) const {
4771 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4773 EVT VT = Op.getValueType();
4775 APInt CnstBits(VT.getSizeInBits(), 0);
4776 APInt UndefBits(VT.getSizeInBits(), 0);
4777 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
4778 // We make use of a little bit of goto ickiness in order to avoid having to
4779 // duplicate the immediate matching logic for the undef toggled case.
4780 bool SecondTry = false;
4783 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
4784 CnstBits = CnstBits.zextOrTrunc(64);
4785 uint64_t CnstVal = CnstBits.getZExtValue();
4787 // Certain magic vector constants (used to express things like NOT
4788 // and NEG) are passed through unmodified. This allows codegen patterns
4789 // for these operations to match. Special-purpose patterns will lower
4790 // these immediates to MOVIs if it proves necessary.
4791 if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL))
4794 // The many faces of MOVI...
4795 if (ARM64_AM::isAdvSIMDModImmType10(CnstVal)) {
4796 CnstVal = ARM64_AM::encodeAdvSIMDModImmType10(CnstVal);
4797 if (VT.getSizeInBits() == 128) {
4798 SDValue Mov = DAG.getNode(ARM64ISD::MOVIedit, dl, MVT::v2i64,
4799 DAG.getConstant(CnstVal, MVT::i32));
4800 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4803 // Support the V64 version via subregister insertion.
4804 SDValue Mov = DAG.getNode(ARM64ISD::MOVIedit, dl, MVT::f64,
4805 DAG.getConstant(CnstVal, MVT::i32));
4806 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4809 if (ARM64_AM::isAdvSIMDModImmType1(CnstVal)) {
4810 CnstVal = ARM64_AM::encodeAdvSIMDModImmType1(CnstVal);
4811 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4812 SDValue Mov = DAG.getNode(ARM64ISD::MOVIshift, dl, MovTy,
4813 DAG.getConstant(CnstVal, MVT::i32),
4814 DAG.getConstant(0, MVT::i32));
4815 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4818 if (ARM64_AM::isAdvSIMDModImmType2(CnstVal)) {
4819 CnstVal = ARM64_AM::encodeAdvSIMDModImmType2(CnstVal);
4820 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4821 SDValue Mov = DAG.getNode(ARM64ISD::MOVIshift, dl, MovTy,
4822 DAG.getConstant(CnstVal, MVT::i32),
4823 DAG.getConstant(8, MVT::i32));
4824 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4827 if (ARM64_AM::isAdvSIMDModImmType3(CnstVal)) {
4828 CnstVal = ARM64_AM::encodeAdvSIMDModImmType3(CnstVal);
4829 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4830 SDValue Mov = DAG.getNode(ARM64ISD::MOVIshift, dl, MovTy,
4831 DAG.getConstant(CnstVal, MVT::i32),
4832 DAG.getConstant(16, MVT::i32));
4833 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4836 if (ARM64_AM::isAdvSIMDModImmType4(CnstVal)) {
4837 CnstVal = ARM64_AM::encodeAdvSIMDModImmType4(CnstVal);
4838 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4839 SDValue Mov = DAG.getNode(ARM64ISD::MOVIshift, dl, MovTy,
4840 DAG.getConstant(CnstVal, MVT::i32),
4841 DAG.getConstant(24, MVT::i32));
4842 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4845 if (ARM64_AM::isAdvSIMDModImmType5(CnstVal)) {
4846 CnstVal = ARM64_AM::encodeAdvSIMDModImmType5(CnstVal);
4847 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
4848 SDValue Mov = DAG.getNode(ARM64ISD::MOVIshift, dl, MovTy,
4849 DAG.getConstant(CnstVal, MVT::i32),
4850 DAG.getConstant(0, MVT::i32));
4851 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4854 if (ARM64_AM::isAdvSIMDModImmType6(CnstVal)) {
4855 CnstVal = ARM64_AM::encodeAdvSIMDModImmType6(CnstVal);
4856 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
4857 SDValue Mov = DAG.getNode(ARM64ISD::MOVIshift, dl, MovTy,
4858 DAG.getConstant(CnstVal, MVT::i32),
4859 DAG.getConstant(8, MVT::i32));
4860 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4863 if (ARM64_AM::isAdvSIMDModImmType7(CnstVal)) {
4864 CnstVal = ARM64_AM::encodeAdvSIMDModImmType7(CnstVal);
4865 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4866 SDValue Mov = DAG.getNode(ARM64ISD::MOVImsl, dl, MovTy,
4867 DAG.getConstant(CnstVal, MVT::i32),
4868 DAG.getConstant(264, MVT::i32));
4869 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4872 if (ARM64_AM::isAdvSIMDModImmType8(CnstVal)) {
4873 CnstVal = ARM64_AM::encodeAdvSIMDModImmType8(CnstVal);
4874 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4875 SDValue Mov = DAG.getNode(ARM64ISD::MOVImsl, dl, MovTy,
4876 DAG.getConstant(CnstVal, MVT::i32),
4877 DAG.getConstant(272, MVT::i32));
4878 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4881 if (ARM64_AM::isAdvSIMDModImmType9(CnstVal)) {
4882 CnstVal = ARM64_AM::encodeAdvSIMDModImmType9(CnstVal);
4883 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
4884 SDValue Mov = DAG.getNode(ARM64ISD::MOVI, dl, MovTy,
4885 DAG.getConstant(CnstVal, MVT::i32));
4886 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4889 // The few faces of FMOV...
4890 if (ARM64_AM::isAdvSIMDModImmType11(CnstVal)) {
4891 CnstVal = ARM64_AM::encodeAdvSIMDModImmType11(CnstVal);
4892 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32;
4893 SDValue Mov = DAG.getNode(ARM64ISD::FMOV, dl, MovTy,
4894 DAG.getConstant(CnstVal, MVT::i32));
4895 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4898 if (ARM64_AM::isAdvSIMDModImmType12(CnstVal) &&
4899 VT.getSizeInBits() == 128) {
4900 CnstVal = ARM64_AM::encodeAdvSIMDModImmType12(CnstVal);
4901 SDValue Mov = DAG.getNode(ARM64ISD::FMOV, dl, MVT::v2f64,
4902 DAG.getConstant(CnstVal, MVT::i32));
4903 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4906 // The many faces of MVNI...
4908 if (ARM64_AM::isAdvSIMDModImmType1(CnstVal)) {
4909 CnstVal = ARM64_AM::encodeAdvSIMDModImmType1(CnstVal);
4910 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4911 SDValue Mov = DAG.getNode(ARM64ISD::MVNIshift, dl, MovTy,
4912 DAG.getConstant(CnstVal, MVT::i32),
4913 DAG.getConstant(0, MVT::i32));
4914 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4917 if (ARM64_AM::isAdvSIMDModImmType2(CnstVal)) {
4918 CnstVal = ARM64_AM::encodeAdvSIMDModImmType2(CnstVal);
4919 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4920 SDValue Mov = DAG.getNode(ARM64ISD::MVNIshift, dl, MovTy,
4921 DAG.getConstant(CnstVal, MVT::i32),
4922 DAG.getConstant(8, MVT::i32));
4923 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4926 if (ARM64_AM::isAdvSIMDModImmType3(CnstVal)) {
4927 CnstVal = ARM64_AM::encodeAdvSIMDModImmType3(CnstVal);
4928 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4929 SDValue Mov = DAG.getNode(ARM64ISD::MVNIshift, dl, MovTy,
4930 DAG.getConstant(CnstVal, MVT::i32),
4931 DAG.getConstant(16, MVT::i32));
4932 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4935 if (ARM64_AM::isAdvSIMDModImmType4(CnstVal)) {
4936 CnstVal = ARM64_AM::encodeAdvSIMDModImmType4(CnstVal);
4937 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4938 SDValue Mov = DAG.getNode(ARM64ISD::MVNIshift, dl, MovTy,
4939 DAG.getConstant(CnstVal, MVT::i32),
4940 DAG.getConstant(24, MVT::i32));
4941 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4944 if (ARM64_AM::isAdvSIMDModImmType5(CnstVal)) {
4945 CnstVal = ARM64_AM::encodeAdvSIMDModImmType5(CnstVal);
4946 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
4947 SDValue Mov = DAG.getNode(ARM64ISD::MVNIshift, dl, MovTy,
4948 DAG.getConstant(CnstVal, MVT::i32),
4949 DAG.getConstant(0, MVT::i32));
4950 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4953 if (ARM64_AM::isAdvSIMDModImmType6(CnstVal)) {
4954 CnstVal = ARM64_AM::encodeAdvSIMDModImmType6(CnstVal);
4955 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
4956 SDValue Mov = DAG.getNode(ARM64ISD::MVNIshift, dl, MovTy,
4957 DAG.getConstant(CnstVal, MVT::i32),
4958 DAG.getConstant(8, MVT::i32));
4959 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4962 if (ARM64_AM::isAdvSIMDModImmType7(CnstVal)) {
4963 CnstVal = ARM64_AM::encodeAdvSIMDModImmType7(CnstVal);
4964 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4965 SDValue Mov = DAG.getNode(ARM64ISD::MVNImsl, dl, MovTy,
4966 DAG.getConstant(CnstVal, MVT::i32),
4967 DAG.getConstant(264, MVT::i32));
4968 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4971 if (ARM64_AM::isAdvSIMDModImmType8(CnstVal)) {
4972 CnstVal = ARM64_AM::encodeAdvSIMDModImmType8(CnstVal);
4973 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4974 SDValue Mov = DAG.getNode(ARM64ISD::MVNImsl, dl, MovTy,
4975 DAG.getConstant(CnstVal, MVT::i32),
4976 DAG.getConstant(272, MVT::i32));
4977 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4984 CnstBits = UndefBits;
4989 // Scan through the operands to find some interesting properties we can
4991 // 1) If only one value is used, we can use a DUP, or
4992 // 2) if only the low element is not undef, we can just insert that, or
4993 // 3) if only one constant value is used (w/ some non-constant lanes),
4994 // we can splat the constant value into the whole vector then fill
4995 // in the non-constant lanes.
4996 // 4) FIXME: If different constant values are used, but we can intelligently
4997 // select the values we'll be overwriting for the non-constant
4998 // lanes such that we can directly materialize the vector
4999 // some other way (MOVI, e.g.), we can be sneaky.
5000 unsigned NumElts = VT.getVectorNumElements();
5001 bool isOnlyLowElement = true;
5002 bool usesOnlyOneValue = true;
5003 bool usesOnlyOneConstantValue = true;
5004 bool isConstant = true;
5005 unsigned NumConstantLanes = 0;
5007 SDValue ConstantValue;
5008 for (unsigned i = 0; i < NumElts; ++i) {
5009 SDValue V = Op.getOperand(i);
5010 if (V.getOpcode() == ISD::UNDEF)
5013 isOnlyLowElement = false;
5014 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5017 if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
5019 if (!ConstantValue.getNode())
5021 else if (ConstantValue != V)
5022 usesOnlyOneConstantValue = false;
5025 if (!Value.getNode())
5027 else if (V != Value)
5028 usesOnlyOneValue = false;
5031 if (!Value.getNode())
5032 return DAG.getUNDEF(VT);
5034 if (isOnlyLowElement)
5035 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5037 // Use DUP for non-constant splats. For f32 constant splats, reduce to
5038 // i32 and try again.
5039 if (usesOnlyOneValue) {
5041 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5042 Value.getValueType() != VT)
5043 return DAG.getNode(ARM64ISD::DUP, dl, VT, Value);
5045 // This is actually a DUPLANExx operation, which keeps everything vectory.
5047 // DUPLANE works on 128-bit vectors, widen it if necessary.
5048 SDValue Lane = Value.getOperand(1);
5049 Value = Value.getOperand(0);
5050 if (Value.getValueType().getSizeInBits() == 64)
5051 Value = WidenVector(Value, DAG);
5053 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
5054 return DAG.getNode(Opcode, dl, VT, Value, Lane);
5057 if (VT.getVectorElementType().isFloatingPoint()) {
5058 SmallVector<SDValue, 8> Ops;
5060 (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
5061 for (unsigned i = 0; i < NumElts; ++i)
5062 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
5063 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
5064 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
5065 Val = LowerBUILD_VECTOR(Val, DAG);
5067 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5071 // If there was only one constant value used and for more than one lane,
5072 // start by splatting that value, then replace the non-constant lanes. This
5073 // is better than the default, which will perform a separate initialization
5075 if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
5076 SDValue Val = DAG.getNode(ARM64ISD::DUP, dl, VT, ConstantValue);
5077 // Now insert the non-constant lanes.
5078 for (unsigned i = 0; i < NumElts; ++i) {
5079 SDValue V = Op.getOperand(i);
5080 SDValue LaneIdx = DAG.getConstant(i, MVT::i64);
5081 if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) {
5082 // Note that type legalization likely mucked about with the VT of the
5083 // source operand, so we may have to convert it here before inserting.
5084 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
5090 // If all elements are constants and the case above didn't get hit, fall back
5091 // to the default expansion, which will generate a load from the constant
5096 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5098 SDValue shuffle = ReconstructShuffle(Op, DAG);
5099 if (shuffle != SDValue())
5103 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5104 // know the default expansion would otherwise fall back on something even
5105 // worse. For a vector with one or two non-undef values, that's
5106 // scalar_to_vector for the elements followed by a shuffle (provided the
5107 // shuffle is valid for the target) and materialization element by element
5108 // on the stack followed by a load for everything else.
5109 if (!isConstant && !usesOnlyOneValue) {
5110 SDValue Vec = DAG.getUNDEF(VT);
5111 SDValue Op0 = Op.getOperand(0);
5112 unsigned ElemSize = VT.getVectorElementType().getSizeInBits();
5114 // For 32 and 64 bit types, use INSERT_SUBREG for lane zero to
5115 // a) Avoid a RMW dependency on the full vector register, and
5116 // b) Allow the register coalescer to fold away the copy if the
5117 // value is already in an S or D register.
5118 if (Op0.getOpcode() != ISD::UNDEF && (ElemSize == 32 || ElemSize == 64)) {
5119 unsigned SubIdx = ElemSize == 32 ? ARM64::ssub : ARM64::dsub;
5121 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl, VT, Vec, Op0,
5122 DAG.getTargetConstant(SubIdx, MVT::i32));
5123 Vec = SDValue(N, 0);
5126 for (; i < NumElts; ++i) {
5127 SDValue V = Op.getOperand(i);
5128 if (V.getOpcode() == ISD::UNDEF)
5130 SDValue LaneIdx = DAG.getConstant(i, MVT::i64);
5131 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5136 // Just use the default expansion. We failed to find a better alternative.
5140 SDValue ARM64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
5141 SelectionDAG &DAG) const {
5142 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
5144 // Check for non-constant lane.
5145 if (!isa<ConstantSDNode>(Op.getOperand(2)))
5148 EVT VT = Op.getOperand(0).getValueType();
5150 // Insertion/extraction are legal for V128 types.
5151 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
5152 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64)
5155 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
5156 VT != MVT::v1i64 && VT != MVT::v2f32)
5159 // For V64 types, we perform insertion by expanding the value
5160 // to a V128 type and perform the insertion on that.
5162 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
5163 EVT WideTy = WideVec.getValueType();
5165 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
5166 Op.getOperand(1), Op.getOperand(2));
5167 // Re-narrow the resultant vector.
5168 return NarrowVector(Node, DAG);
5171 SDValue ARM64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
5172 SelectionDAG &DAG) const {
5173 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
5175 // Check for non-constant lane.
5176 if (!isa<ConstantSDNode>(Op.getOperand(1)))
5179 EVT VT = Op.getOperand(0).getValueType();
5181 // Insertion/extraction are legal for V128 types.
5182 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
5183 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64)
5186 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
5187 VT != MVT::v1i64 && VT != MVT::v2f32)
5190 // For V64 types, we perform extraction by expanding the value
5191 // to a V128 type and perform the extraction on that.
5193 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
5194 EVT WideTy = WideVec.getValueType();
5196 EVT ExtrTy = WideTy.getVectorElementType();
5197 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
5200 // For extractions, we just return the result directly.
5201 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
5205 SDValue ARM64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
5206 SelectionDAG &DAG) const {
5207 EVT VT = Op.getOperand(0).getValueType();
5213 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5216 unsigned Val = Cst->getZExtValue();
5218 unsigned Size = Op.getValueType().getSizeInBits();
5222 return DAG.getTargetExtractSubreg(ARM64::bsub, dl, Op.getValueType(),
5225 return DAG.getTargetExtractSubreg(ARM64::hsub, dl, Op.getValueType(),
5228 return DAG.getTargetExtractSubreg(ARM64::ssub, dl, Op.getValueType(),
5231 return DAG.getTargetExtractSubreg(ARM64::dsub, dl, Op.getValueType(),
5234 llvm_unreachable("Unexpected vector type in extract_subvector!");
5237 // If this is extracting the upper 64-bits of a 128-bit vector, we match
5239 if (Size == 64 && Val * VT.getVectorElementType().getSizeInBits() == 64)
5245 bool ARM64TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5247 if (VT.getVectorNumElements() == 4 &&
5248 (VT.is128BitVector() || VT.is64BitVector())) {
5249 unsigned PFIndexes[4];
5250 for (unsigned i = 0; i != 4; ++i) {
5254 PFIndexes[i] = M[i];
5257 // Compute the index in the perfect shuffle table.
5258 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
5259 PFIndexes[2] * 9 + PFIndexes[3];
5260 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5261 unsigned Cost = (PFEntry >> 30);
5268 unsigned Imm, WhichResult;
5270 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
5271 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
5272 isEXTMask(M, VT, ReverseVEXT, Imm) ||
5273 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
5274 isTRNMask(M, VT, WhichResult) || isUZPMask(M, VT, WhichResult) ||
5275 isZIPMask(M, VT, WhichResult) ||
5276 isTRN_v_undef_Mask(M, VT, WhichResult) ||
5277 isUZP_v_undef_Mask(M, VT, WhichResult) ||
5278 isZIP_v_undef_Mask(M, VT, WhichResult));
5281 /// getVShiftImm - Check if this is a valid build_vector for the immediate
5282 /// operand of a vector shift operation, where all the elements of the
5283 /// build_vector must have the same constant integer value.
5284 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
5285 // Ignore bit_converts.
5286 while (Op.getOpcode() == ISD::BITCAST)
5287 Op = Op.getOperand(0);
5288 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
5289 APInt SplatBits, SplatUndef;
5290 unsigned SplatBitSize;
5292 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
5293 HasAnyUndefs, ElementBits) ||
5294 SplatBitSize > ElementBits)
5296 Cnt = SplatBits.getSExtValue();
5300 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
5301 /// operand of a vector shift left operation. That value must be in the range:
5302 /// 0 <= Value < ElementBits for a left shift; or
5303 /// 0 <= Value <= ElementBits for a long left shift.
5304 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
5305 assert(VT.isVector() && "vector shift count is not a vector type");
5306 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
5307 if (!getVShiftImm(Op, ElementBits, Cnt))
5309 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
5312 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
5313 /// operand of a vector shift right operation. For a shift opcode, the value
5314 /// is positive, but for an intrinsic the value count must be negative. The
5315 /// absolute value must be in the range:
5316 /// 1 <= |Value| <= ElementBits for a right shift; or
5317 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
5318 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
5320 assert(VT.isVector() && "vector shift count is not a vector type");
5321 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
5322 if (!getVShiftImm(Op, ElementBits, Cnt))
5326 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
5329 SDValue ARM64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
5330 SelectionDAG &DAG) const {
5331 EVT VT = Op.getValueType();
5335 if (!Op.getOperand(1).getValueType().isVector())
5337 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5339 switch (Op.getOpcode()) {
5341 llvm_unreachable("unexpected shift opcode");
5344 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
5345 return DAG.getNode(ARM64ISD::VSHL, SDLoc(Op), VT, Op.getOperand(0),
5346 DAG.getConstant(Cnt, MVT::i32));
5347 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
5348 DAG.getConstant(Intrinsic::arm64_neon_ushl, MVT::i32),
5349 Op.getOperand(0), Op.getOperand(1));
5352 // Right shift immediate
5353 if (isVShiftRImm(Op.getOperand(1), VT, false, false, Cnt) &&
5356 (Op.getOpcode() == ISD::SRA) ? ARM64ISD::VASHR : ARM64ISD::VLSHR;
5357 return DAG.getNode(Opc, SDLoc(Op), VT, Op.getOperand(0),
5358 DAG.getConstant(Cnt, MVT::i32));
5361 // Right shift register. Note, there is not a shift right register
5362 // instruction, but the shift left register instruction takes a signed
5363 // value, where negative numbers specify a right shift.
5364 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::arm64_neon_sshl
5365 : Intrinsic::arm64_neon_ushl;
5366 // negate the shift amount
5367 SDValue NegShift = DAG.getNode(ARM64ISD::NEG, DL, VT, Op.getOperand(1));
5368 SDValue NegShiftLeft =
5369 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
5370 DAG.getConstant(Opc, MVT::i32), Op.getOperand(0), NegShift);
5371 return NegShiftLeft;
5377 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
5378 ARM64CC::CondCode CC, bool NoNans, EVT VT,
5379 SDLoc dl, SelectionDAG &DAG) {
5380 EVT SrcVT = LHS.getValueType();
5382 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
5383 APInt CnstBits(VT.getSizeInBits(), 0);
5384 APInt UndefBits(VT.getSizeInBits(), 0);
5385 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
5386 bool IsZero = IsCnst && (CnstBits == 0);
5388 if (SrcVT.getVectorElementType().isFloatingPoint()) {
5395 Fcmeq = DAG.getNode(ARM64ISD::FCMEQz, dl, VT, LHS);
5397 Fcmeq = DAG.getNode(ARM64ISD::FCMEQ, dl, VT, LHS, RHS);
5398 return DAG.getNode(ARM64ISD::NOT, dl, VT, Fcmeq);
5402 return DAG.getNode(ARM64ISD::FCMEQz, dl, VT, LHS);
5403 return DAG.getNode(ARM64ISD::FCMEQ, dl, VT, LHS, RHS);
5406 return DAG.getNode(ARM64ISD::FCMGEz, dl, VT, LHS);
5407 return DAG.getNode(ARM64ISD::FCMGE, dl, VT, LHS, RHS);
5410 return DAG.getNode(ARM64ISD::FCMGTz, dl, VT, LHS);
5411 return DAG.getNode(ARM64ISD::FCMGT, dl, VT, LHS, RHS);
5414 return DAG.getNode(ARM64ISD::FCMLEz, dl, VT, LHS);
5415 return DAG.getNode(ARM64ISD::FCMGE, dl, VT, RHS, LHS);
5419 // If we ignore NaNs then we can use to the MI implementation.
5423 return DAG.getNode(ARM64ISD::FCMLTz, dl, VT, LHS);
5424 return DAG.getNode(ARM64ISD::FCMGT, dl, VT, RHS, LHS);
5434 Cmeq = DAG.getNode(ARM64ISD::CMEQz, dl, VT, LHS);
5436 Cmeq = DAG.getNode(ARM64ISD::CMEQ, dl, VT, LHS, RHS);
5437 return DAG.getNode(ARM64ISD::NOT, dl, VT, Cmeq);
5441 return DAG.getNode(ARM64ISD::CMEQz, dl, VT, LHS);
5442 return DAG.getNode(ARM64ISD::CMEQ, dl, VT, LHS, RHS);
5445 return DAG.getNode(ARM64ISD::CMGEz, dl, VT, LHS);
5446 return DAG.getNode(ARM64ISD::CMGE, dl, VT, LHS, RHS);
5449 return DAG.getNode(ARM64ISD::CMGTz, dl, VT, LHS);
5450 return DAG.getNode(ARM64ISD::CMGT, dl, VT, LHS, RHS);
5453 return DAG.getNode(ARM64ISD::CMLEz, dl, VT, LHS);
5454 return DAG.getNode(ARM64ISD::CMGE, dl, VT, RHS, LHS);
5456 return DAG.getNode(ARM64ISD::CMHS, dl, VT, RHS, LHS);
5458 return DAG.getNode(ARM64ISD::CMHI, dl, VT, RHS, LHS);
5461 return DAG.getNode(ARM64ISD::CMLTz, dl, VT, LHS);
5462 return DAG.getNode(ARM64ISD::CMGT, dl, VT, RHS, LHS);
5464 return DAG.getNode(ARM64ISD::CMHI, dl, VT, LHS, RHS);
5466 return DAG.getNode(ARM64ISD::CMHS, dl, VT, LHS, RHS);
5470 SDValue ARM64TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
5471 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
5472 SDValue LHS = Op.getOperand(0);
5473 SDValue RHS = Op.getOperand(1);
5476 if (LHS.getValueType().getVectorElementType().isInteger()) {
5477 assert(LHS.getValueType() == RHS.getValueType());
5478 ARM64CC::CondCode ARM64CC = changeIntCCToARM64CC(CC);
5479 return EmitVectorComparison(LHS, RHS, ARM64CC, false, Op.getValueType(), dl,
5483 assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
5484 LHS.getValueType().getVectorElementType() == MVT::f64);
5486 // Unfortunately, the mapping of LLVM FP CC's onto ARM64 CC's isn't totally
5487 // clean. Some of them require two branches to implement.
5488 ARM64CC::CondCode CC1, CC2;
5490 changeVectorFPCCToARM64CC(CC, CC1, CC2, ShouldInvert);
5492 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
5494 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, Op.getValueType(), dl, DAG);
5498 if (CC2 != ARM64CC::AL) {
5500 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, Op.getValueType(), dl, DAG);
5501 if (!Cmp2.getNode())
5504 Cmp = DAG.getNode(ISD::OR, dl, Cmp.getValueType(), Cmp, Cmp2);
5508 return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
5513 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
5514 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
5515 /// specified in the intrinsic calls.
5516 bool ARM64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
5518 unsigned Intrinsic) const {
5519 switch (Intrinsic) {
5520 case Intrinsic::arm64_neon_ld2:
5521 case Intrinsic::arm64_neon_ld3:
5522 case Intrinsic::arm64_neon_ld4:
5523 case Intrinsic::arm64_neon_ld2lane:
5524 case Intrinsic::arm64_neon_ld3lane:
5525 case Intrinsic::arm64_neon_ld4lane:
5526 case Intrinsic::arm64_neon_ld2r:
5527 case Intrinsic::arm64_neon_ld3r:
5528 case Intrinsic::arm64_neon_ld4r: {
5529 Info.opc = ISD::INTRINSIC_W_CHAIN;
5530 // Conservatively set memVT to the entire set of vectors loaded.
5531 uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
5532 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
5533 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
5536 Info.vol = false; // volatile loads with NEON intrinsics not supported
5537 Info.readMem = true;
5538 Info.writeMem = false;
5541 case Intrinsic::arm64_neon_st2:
5542 case Intrinsic::arm64_neon_st3:
5543 case Intrinsic::arm64_neon_st4:
5544 case Intrinsic::arm64_neon_st2lane:
5545 case Intrinsic::arm64_neon_st3lane:
5546 case Intrinsic::arm64_neon_st4lane: {
5547 Info.opc = ISD::INTRINSIC_VOID;
5548 // Conservatively set memVT to the entire set of vectors stored.
5549 unsigned NumElts = 0;
5550 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
5551 Type *ArgTy = I.getArgOperand(ArgI)->getType();
5552 if (!ArgTy->isVectorTy())
5554 NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
5556 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
5557 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
5560 Info.vol = false; // volatile stores with NEON intrinsics not supported
5561 Info.readMem = false;
5562 Info.writeMem = true;
5565 case Intrinsic::arm64_ldaxr:
5566 case Intrinsic::arm64_ldxr: {
5567 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
5568 Info.opc = ISD::INTRINSIC_W_CHAIN;
5569 Info.memVT = MVT::getVT(PtrTy->getElementType());
5570 Info.ptrVal = I.getArgOperand(0);
5572 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
5574 Info.readMem = true;
5575 Info.writeMem = false;
5578 case Intrinsic::arm64_stlxr:
5579 case Intrinsic::arm64_stxr: {
5580 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
5581 Info.opc = ISD::INTRINSIC_W_CHAIN;
5582 Info.memVT = MVT::getVT(PtrTy->getElementType());
5583 Info.ptrVal = I.getArgOperand(1);
5585 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
5587 Info.readMem = false;
5588 Info.writeMem = true;
5591 case Intrinsic::arm64_ldaxp:
5592 case Intrinsic::arm64_ldxp: {
5593 Info.opc = ISD::INTRINSIC_W_CHAIN;
5594 Info.memVT = MVT::i128;
5595 Info.ptrVal = I.getArgOperand(0);
5599 Info.readMem = true;
5600 Info.writeMem = false;
5603 case Intrinsic::arm64_stlxp:
5604 case Intrinsic::arm64_stxp: {
5605 Info.opc = ISD::INTRINSIC_W_CHAIN;
5606 Info.memVT = MVT::i128;
5607 Info.ptrVal = I.getArgOperand(2);
5611 Info.readMem = false;
5612 Info.writeMem = true;
5622 // Truncations from 64-bit GPR to 32-bit GPR is free.
5623 bool ARM64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
5624 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
5626 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
5627 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
5628 if (NumBits1 <= NumBits2)
5632 bool ARM64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
5633 if (!VT1.isInteger() || !VT2.isInteger())
5635 unsigned NumBits1 = VT1.getSizeInBits();
5636 unsigned NumBits2 = VT2.getSizeInBits();
5637 if (NumBits1 <= NumBits2)
5642 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
5644 bool ARM64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
5645 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
5647 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
5648 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
5649 if (NumBits1 == 32 && NumBits2 == 64)
5653 bool ARM64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
5654 if (!VT1.isInteger() || !VT2.isInteger())
5656 unsigned NumBits1 = VT1.getSizeInBits();
5657 unsigned NumBits2 = VT2.getSizeInBits();
5658 if (NumBits1 == 32 && NumBits2 == 64)
5663 bool ARM64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
5664 EVT VT1 = Val.getValueType();
5665 if (isZExtFree(VT1, VT2)) {
5669 if (Val.getOpcode() != ISD::LOAD)
5672 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
5673 return (VT1.isSimple() && VT1.isInteger() && VT2.isSimple() &&
5674 VT2.isInteger() && VT1.getSizeInBits() <= 32);
5677 bool ARM64TargetLowering::hasPairedLoad(Type *LoadedType,
5678 unsigned &RequiredAligment) const {
5679 if (!LoadedType->isIntegerTy() && !LoadedType->isFloatTy())
5681 // Cyclone supports unaligned accesses.
5682 RequiredAligment = 0;
5683 unsigned NumBits = LoadedType->getPrimitiveSizeInBits();
5684 return NumBits == 32 || NumBits == 64;
5687 bool ARM64TargetLowering::hasPairedLoad(EVT LoadedType,
5688 unsigned &RequiredAligment) const {
5689 if (!LoadedType.isSimple() ||
5690 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
5692 // Cyclone supports unaligned accesses.
5693 RequiredAligment = 0;
5694 unsigned NumBits = LoadedType.getSizeInBits();
5695 return NumBits == 32 || NumBits == 64;
5698 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
5699 unsigned AlignCheck) {
5700 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
5701 (DstAlign == 0 || DstAlign % AlignCheck == 0));
5704 EVT ARM64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
5705 unsigned SrcAlign, bool IsMemset,
5706 bool ZeroMemset, bool MemcpyStrSrc,
5707 MachineFunction &MF) const {
5708 // Don't use AdvSIMD to implement 16-byte memset. It would have taken one
5709 // instruction to materialize the v2i64 zero and one store (with restrictive
5710 // addressing mode). Just do two i64 store of zero-registers.
5712 const Function *F = MF.getFunction();
5713 if (!IsMemset && Size >= 16 &&
5714 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
5715 Attribute::NoImplicitFloat) &&
5716 (memOpAlign(SrcAlign, DstAlign, 16) ||
5717 (allowsUnalignedMemoryAccesses(MVT::v2i64, 0, &Fast) && Fast)))
5720 return Size >= 8 ? MVT::i64 : MVT::i32;
5723 // 12-bit optionally shifted immediates are legal for adds.
5724 bool ARM64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
5725 if ((Immed >> 12) == 0 || ((Immed & 0xfff) == 0 && Immed >> 24 == 0))
5730 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
5731 // immediates is the same as for an add or a sub.
5732 bool ARM64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
5735 return isLegalAddImmediate(Immed);
5738 /// isLegalAddressingMode - Return true if the addressing mode represented
5739 /// by AM is legal for this target, for a load/store of the specified type.
5740 bool ARM64TargetLowering::isLegalAddressingMode(const AddrMode &AM,
5742 // ARM64 has five basic addressing modes:
5744 // reg + 9-bit signed offset
5745 // reg + SIZE_IN_BYTES * 12-bit unsigned offset
5747 // reg + SIZE_IN_BYTES * reg
5749 // No global is ever allowed as a base.
5753 // No reg+reg+imm addressing.
5754 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
5757 // check reg + imm case:
5758 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
5759 uint64_t NumBytes = 0;
5760 if (Ty->isSized()) {
5761 uint64_t NumBits = getDataLayout()->getTypeSizeInBits(Ty);
5762 NumBytes = NumBits / 8;
5763 if (!isPowerOf2_64(NumBits))
5768 int64_t Offset = AM.BaseOffs;
5770 // 9-bit signed offset
5771 if (Offset >= -(1LL << 9) && Offset <= (1LL << 9) - 1)
5774 // 12-bit unsigned offset
5775 unsigned shift = Log2_64(NumBytes);
5776 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
5777 // Must be a multiple of NumBytes (NumBytes is a power of 2)
5778 (Offset >> shift) << shift == Offset)
5783 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
5785 if (!AM.Scale || AM.Scale == 1 ||
5786 (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes))
5791 int ARM64TargetLowering::getScalingFactorCost(const AddrMode &AM,
5793 // Scaling factors are not free at all.
5794 // Operands | Rt Latency
5795 // -------------------------------------------
5797 // -------------------------------------------
5798 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5
5799 // Rt, [Xn, Wm, <extend> #imm] |
5800 if (isLegalAddressingMode(AM, Ty))
5801 // Scale represents reg2 * scale, thus account for 1 if
5802 // it is not equal to 0 or 1.
5803 return AM.Scale != 0 && AM.Scale != 1;
5807 bool ARM64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
5808 VT = VT.getScalarType();
5813 switch (VT.getSimpleVT().SimpleTy) {
5825 ARM64TargetLowering::getScratchRegisters(CallingConv::ID) const {
5826 // LR is a callee-save register, but we must treat it as clobbered by any call
5827 // site. Hence we include LR in the scratch registers, which are in turn added
5828 // as implicit-defs for stackmaps and patchpoints.
5829 static const MCPhysReg ScratchRegs[] = {
5830 ARM64::X16, ARM64::X17, ARM64::LR, 0
5835 bool ARM64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
5837 assert(Ty->isIntegerTy());
5839 unsigned BitSize = Ty->getPrimitiveSizeInBits();
5843 int64_t Val = Imm.getSExtValue();
5844 if (Val == 0 || ARM64_AM::isLogicalImmediate(Val, BitSize))
5847 if ((int64_t)Val < 0)
5850 Val &= (1LL << 32) - 1;
5852 unsigned LZ = countLeadingZeros((uint64_t)Val);
5853 unsigned Shift = (63 - LZ) / 16;
5854 // MOVZ is free so return true for one or fewer MOVK.
5855 return (Shift < 3) ? true : false;
5858 // Generate SUBS and CSEL for integer abs.
5859 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
5860 EVT VT = N->getValueType(0);
5862 SDValue N0 = N->getOperand(0);
5863 SDValue N1 = N->getOperand(1);
5866 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
5867 // and change it to SUB and CSEL.
5868 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
5869 N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
5870 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
5871 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
5872 if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
5873 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, VT),
5875 // Generate SUBS & CSEL.
5877 DAG.getNode(ARM64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
5878 N0.getOperand(0), DAG.getConstant(0, VT));
5879 return DAG.getNode(ARM64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
5880 DAG.getConstant(ARM64CC::PL, MVT::i32),
5881 SDValue(Cmp.getNode(), 1));
5886 // performXorCombine - Attempts to handle integer ABS.
5887 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
5888 TargetLowering::DAGCombinerInfo &DCI,
5889 const ARM64Subtarget *Subtarget) {
5890 if (DCI.isBeforeLegalizeOps())
5893 return performIntegerAbsCombine(N, DAG);
5896 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
5897 TargetLowering::DAGCombinerInfo &DCI,
5898 const ARM64Subtarget *Subtarget) {
5899 if (DCI.isBeforeLegalizeOps())
5902 // Multiplication of a power of two plus/minus one can be done more
5903 // cheaply as as shift+add/sub. For now, this is true unilaterally. If
5904 // future CPUs have a cheaper MADD instruction, this may need to be
5905 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
5906 // 64-bit is 5 cycles, so this is always a win.
5907 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
5908 APInt Value = C->getAPIntValue();
5909 EVT VT = N->getValueType(0);
5910 APInt VP1 = Value + 1;
5911 if (VP1.isPowerOf2()) {
5912 // Multiplying by one less than a power of two, replace with a shift
5914 SDValue ShiftedVal =
5915 DAG.getNode(ISD::SHL, SDLoc(N), VT, N->getOperand(0),
5916 DAG.getConstant(VP1.logBase2(), MVT::i64));
5917 return DAG.getNode(ISD::SUB, SDLoc(N), VT, ShiftedVal, N->getOperand(0));
5919 APInt VM1 = Value - 1;
5920 if (VM1.isPowerOf2()) {
5921 // Multiplying by one more than a power of two, replace with a shift
5923 SDValue ShiftedVal =
5924 DAG.getNode(ISD::SHL, SDLoc(N), VT, N->getOperand(0),
5925 DAG.getConstant(VM1.logBase2(), MVT::i64));
5926 return DAG.getNode(ISD::ADD, SDLoc(N), VT, ShiftedVal, N->getOperand(0));
5932 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG) {
5933 EVT VT = N->getValueType(0);
5934 if (VT != MVT::f32 && VT != MVT::f64)
5936 // Only optimize when the source and destination types have the same width.
5937 if (VT.getSizeInBits() != N->getOperand(0).getValueType().getSizeInBits())
5940 // If the result of an integer load is only used by an integer-to-float
5941 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
5942 // This eliminates an "integer-to-vector-move UOP and improve throughput.
5943 SDValue N0 = N->getOperand(0);
5944 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
5945 // Do not change the width of a volatile load.
5946 !cast<LoadSDNode>(N0)->isVolatile()) {
5947 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5948 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
5949 LN0->getPointerInfo(), LN0->isVolatile(),
5950 LN0->isNonTemporal(), LN0->isInvariant(),
5951 LN0->getAlignment());
5953 // Make sure successors of the original load stay after it by updating them
5954 // to use the new Chain.
5955 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
5958 (N->getOpcode() == ISD::SINT_TO_FP) ? ARM64ISD::SITOF : ARM64ISD::UITOF;
5959 return DAG.getNode(Opcode, SDLoc(N), VT, Load);
5965 /// An EXTR instruction is made up of two shifts, ORed together. This helper
5966 /// searches for and classifies those shifts.
5967 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
5969 if (N.getOpcode() == ISD::SHL)
5971 else if (N.getOpcode() == ISD::SRL)
5976 if (!isa<ConstantSDNode>(N.getOperand(1)))
5979 ShiftAmount = N->getConstantOperandVal(1);
5980 Src = N->getOperand(0);
5984 /// EXTR instruction extracts a contiguous chunk of bits from two existing
5985 /// registers viewed as a high/low pair. This function looks for the pattern:
5986 /// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an
5987 /// EXTR. Can't quite be done in TableGen because the two immediates aren't
5989 static SDValue tryCombineToEXTR(SDNode *N,
5990 TargetLowering::DAGCombinerInfo &DCI) {
5991 SelectionDAG &DAG = DCI.DAG;
5993 EVT VT = N->getValueType(0);
5995 assert(N->getOpcode() == ISD::OR && "Unexpected root");
5997 if (VT != MVT::i32 && VT != MVT::i64)
6001 uint32_t ShiftLHS = 0;
6003 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
6007 uint32_t ShiftRHS = 0;
6009 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
6012 // If they're both trying to come from the high part of the register, they're
6013 // not really an EXTR.
6014 if (LHSFromHi == RHSFromHi)
6017 if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
6021 std::swap(LHS, RHS);
6022 std::swap(ShiftLHS, ShiftRHS);
6025 return DAG.getNode(ARM64ISD::EXTR, DL, VT, LHS, RHS,
6026 DAG.getConstant(ShiftRHS, MVT::i64));
6029 static SDValue tryCombineToBSL(SDNode *N,
6030 TargetLowering::DAGCombinerInfo &DCI) {
6031 EVT VT = N->getValueType(0);
6032 SelectionDAG &DAG = DCI.DAG;
6038 SDValue N0 = N->getOperand(0);
6039 if (N0.getOpcode() != ISD::AND)
6042 SDValue N1 = N->getOperand(1);
6043 if (N1.getOpcode() != ISD::AND)
6046 // We only have to look for constant vectors here since the general, variable
6047 // case can be handled in TableGen.
6048 unsigned Bits = VT.getVectorElementType().getSizeInBits();
6049 uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
6050 for (int i = 1; i >= 0; --i)
6051 for (int j = 1; j >= 0; --j) {
6052 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
6053 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
6057 bool FoundMatch = true;
6058 for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
6059 ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
6060 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
6062 CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
6069 return DAG.getNode(ARM64ISD::BSL, DL, VT, SDValue(BVN0, 0),
6070 N0->getOperand(1 - i), N1->getOperand(1 - j));
6076 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
6077 const ARM64Subtarget *Subtarget) {
6078 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
6079 if (!EnableARM64ExtrGeneration)
6081 SelectionDAG &DAG = DCI.DAG;
6082 EVT VT = N->getValueType(0);
6084 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
6087 SDValue Res = tryCombineToEXTR(N, DCI);
6091 Res = tryCombineToBSL(N, DCI);
6098 static SDValue performBitcastCombine(SDNode *N,
6099 TargetLowering::DAGCombinerInfo &DCI,
6100 SelectionDAG &DAG) {
6101 // Wait 'til after everything is legalized to try this. That way we have
6102 // legal vector types and such.
6103 if (DCI.isBeforeLegalizeOps())
6106 // Remove extraneous bitcasts around an extract_subvector.
6108 // (v4i16 (bitconvert
6109 // (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
6111 // (extract_subvector ((v8i16 ...), (i64 4)))
6113 // Only interested in 64-bit vectors as the ultimate result.
6114 EVT VT = N->getValueType(0);
6117 if (VT.getSimpleVT().getSizeInBits() != 64)
6119 // Is the operand an extract_subvector starting at the beginning or halfway
6120 // point of the vector? A low half may also come through as an
6121 // EXTRACT_SUBREG, so look for that, too.
6122 SDValue Op0 = N->getOperand(0);
6123 if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
6124 !(Op0->isMachineOpcode() &&
6125 Op0->getMachineOpcode() == ARM64::EXTRACT_SUBREG))
6127 uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
6128 if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
6129 if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
6131 } else if (Op0->getMachineOpcode() == ARM64::EXTRACT_SUBREG) {
6132 if (idx != ARM64::dsub)
6134 // The dsub reference is equivalent to a lane zero subvector reference.
6137 // Look through the bitcast of the input to the extract.
6138 if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
6140 SDValue Source = Op0->getOperand(0)->getOperand(0);
6141 // If the source type has twice the number of elements as our destination
6142 // type, we know this is an extract of the high or low half of the vector.
6143 EVT SVT = Source->getValueType(0);
6144 if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
6147 DEBUG(dbgs() << "arm64-lower: bitcast extract_subvector simplification\n");
6149 // Create the simplified form to just extract the low or high half of the
6150 // vector directly rather than bothering with the bitcasts.
6152 unsigned NumElements = VT.getVectorNumElements();
6154 SDValue HalfIdx = DAG.getConstant(NumElements, MVT::i64);
6155 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
6157 SDValue SubReg = DAG.getTargetConstant(ARM64::dsub, MVT::i32);
6158 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
6164 static SDValue performConcatVectorsCombine(SDNode *N,
6165 TargetLowering::DAGCombinerInfo &DCI,
6166 SelectionDAG &DAG) {
6167 // Wait 'til after everything is legalized to try this. That way we have
6168 // legal vector types and such.
6169 if (DCI.isBeforeLegalizeOps())
6173 EVT VT = N->getValueType(0);
6175 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
6176 // splat. The indexed instructions are going to be expecting a DUPLANE64, so
6177 // canonicalise to that.
6178 if (N->getOperand(0) == N->getOperand(1) && VT.getVectorNumElements() == 2) {
6179 assert(VT.getVectorElementType().getSizeInBits() == 64);
6180 return DAG.getNode(ARM64ISD::DUPLANE64, dl, VT,
6181 WidenVector(N->getOperand(0), DAG),
6182 DAG.getConstant(0, MVT::i64));
6185 // Canonicalise concat_vectors so that the right-hand vector has as few
6186 // bit-casts as possible before its real operation. The primary matching
6187 // destination for these operations will be the narrowing "2" instructions,
6188 // which depend on the operation being performed on this right-hand vector.
6190 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS))))
6192 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
6194 SDValue Op1 = N->getOperand(1);
6195 if (Op1->getOpcode() != ISD::BITCAST)
6197 SDValue RHS = Op1->getOperand(0);
6198 MVT RHSTy = RHS.getValueType().getSimpleVT();
6199 // If the RHS is not a vector, this is not the pattern we're looking for.
6200 if (!RHSTy.isVector())
6203 DEBUG(dbgs() << "arm64-lower: concat_vectors bitcast simplification\n");
6205 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
6206 RHSTy.getVectorNumElements() * 2);
6208 ISD::BITCAST, dl, VT,
6209 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
6210 DAG.getNode(ISD::BITCAST, dl, RHSTy, N->getOperand(0)), RHS));
6213 static SDValue tryCombineFixedPointConvert(SDNode *N,
6214 TargetLowering::DAGCombinerInfo &DCI,
6215 SelectionDAG &DAG) {
6216 // Wait 'til after everything is legalized to try this. That way we have
6217 // legal vector types and such.
6218 if (DCI.isBeforeLegalizeOps())
6220 // Transform a scalar conversion of a value from a lane extract into a
6221 // lane extract of a vector conversion. E.g., from foo1 to foo2:
6222 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
6223 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
6225 // The second form interacts better with instruction selection and the
6226 // register allocator to avoid cross-class register copies that aren't
6227 // coalescable due to a lane reference.
6229 // Check the operand and see if it originates from a lane extract.
6230 SDValue Op1 = N->getOperand(1);
6231 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
6232 // Yep, no additional predication needed. Perform the transform.
6233 SDValue IID = N->getOperand(0);
6234 SDValue Shift = N->getOperand(2);
6235 SDValue Vec = Op1.getOperand(0);
6236 SDValue Lane = Op1.getOperand(1);
6237 EVT ResTy = N->getValueType(0);
6241 // The vector width should be 128 bits by the time we get here, even
6242 // if it started as 64 bits (the extract_vector handling will have
6244 assert(Vec.getValueType().getSizeInBits() == 128 &&
6245 "unexpected vector size on extract_vector_elt!");
6246 if (Vec.getValueType() == MVT::v4i32)
6247 VecResTy = MVT::v4f32;
6248 else if (Vec.getValueType() == MVT::v2i64)
6249 VecResTy = MVT::v2f64;
6251 assert(0 && "unexpected vector type!");
6254 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
6255 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
6260 // AArch64 high-vector "long" operations are formed by performing the non-high
6261 // version on an extract_subvector of each operand which gets the high half:
6263 // (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
6265 // However, there are cases which don't have an extract_high explicitly, but
6266 // have another operation that can be made compatible with one for free. For
6269 // (dupv64 scalar) --> (extract_high (dup128 scalar))
6271 // This routine does the actual conversion of such DUPs, once outer routines
6272 // have determined that everything else is in order.
6273 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
6274 // We can handle most types of duplicate, but the lane ones have an extra
6275 // operand saying *which* lane, so we need to know.
6277 switch (N.getOpcode()) {
6281 case ARM64ISD::DUPLANE8:
6282 case ARM64ISD::DUPLANE16:
6283 case ARM64ISD::DUPLANE32:
6284 case ARM64ISD::DUPLANE64:
6291 MVT NarrowTy = N.getSimpleValueType();
6292 if (!NarrowTy.is64BitVector())
6295 MVT ElementTy = NarrowTy.getVectorElementType();
6296 unsigned NumElems = NarrowTy.getVectorNumElements();
6297 MVT NewDUPVT = MVT::getVectorVT(ElementTy, NumElems * 2);
6301 NewDUP = DAG.getNode(N.getOpcode(), SDLoc(N), NewDUPVT, N.getOperand(0),
6304 NewDUP = DAG.getNode(ARM64ISD::DUP, SDLoc(N), NewDUPVT, N.getOperand(0));
6306 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N.getNode()), NarrowTy,
6307 NewDUP, DAG.getConstant(NumElems, MVT::i64));
6310 static bool isEssentiallyExtractSubvector(SDValue N) {
6311 if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
6314 return N.getOpcode() == ISD::BITCAST &&
6315 N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
6318 /// \brief Helper structure to keep track of ISD::SET_CC operands.
6319 struct GenericSetCCInfo {
6320 const SDValue *Opnd0;
6321 const SDValue *Opnd1;
6325 /// \brief Helper structure to keep track of a SET_CC lowered into ARM64 code.
6326 struct ARM64SetCCInfo {
6328 ARM64CC::CondCode CC;
6331 /// \brief Helper structure to keep track of SetCC information.
6333 GenericSetCCInfo Generic;
6334 ARM64SetCCInfo ARM64;
6337 /// \brief Helper structure to be able to read SetCC information.
6338 /// If set to true, IsARM64 field, Info is a ARM64SetCCInfo, otherwise Info is
6339 /// a GenericSetCCInfo.
6340 struct SetCCInfoAndKind {
6345 /// \brief Check whether or not \p Op is a SET_CC operation, either a generic or
6347 /// ARM64 lowered one.
6348 /// \p SetCCInfo is filled accordingly.
6349 /// \post SetCCInfo is meanginfull only when this function returns true.
6350 /// \return True when Op is a kind of SET_CC operation.
6351 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
6352 // If this is a setcc, this is straight forward.
6353 if (Op.getOpcode() == ISD::SETCC) {
6354 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
6355 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
6356 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6357 SetCCInfo.IsARM64 = false;
6360 // Otherwise, check if this is a matching csel instruction.
6364 if (Op.getOpcode() != ARM64ISD::CSEL)
6366 // Set the information about the operands.
6367 // TODO: we want the operands of the Cmp not the csel
6368 SetCCInfo.Info.ARM64.Cmp = &Op.getOperand(3);
6369 SetCCInfo.IsARM64 = true;
6370 SetCCInfo.Info.ARM64.CC = static_cast<ARM64CC::CondCode>(
6371 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
6373 // Check that the operands matches the constraints:
6374 // (1) Both operands must be constants.
6375 // (2) One must be 1 and the other must be 0.
6376 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
6377 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6380 if (!TValue || !FValue)
6384 if (!TValue->isOne()) {
6385 // Update the comparison when we are interested in !cc.
6386 std::swap(TValue, FValue);
6387 SetCCInfo.Info.ARM64.CC =
6388 ARM64CC::getInvertedCondCode(SetCCInfo.Info.ARM64.CC);
6390 return TValue->isOne() && FValue->isNullValue();
6393 // The folding we want to perform is:
6394 // (add x, (setcc cc ...) )
6396 // (csel x, (add x, 1), !cc ...)
6398 // The latter will get matched to a CSINC instruction.
6399 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
6400 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
6401 SDValue LHS = Op->getOperand(0);
6402 SDValue RHS = Op->getOperand(1);
6403 SetCCInfoAndKind InfoAndKind;
6405 // If neither operand is a SET_CC, give up.
6406 if (!isSetCC(LHS, InfoAndKind)) {
6407 std::swap(LHS, RHS);
6408 if (!isSetCC(LHS, InfoAndKind))
6412 // FIXME: This could be generatized to work for FP comparisons.
6413 EVT CmpVT = InfoAndKind.IsARM64
6414 ? InfoAndKind.Info.ARM64.Cmp->getOperand(0).getValueType()
6415 : InfoAndKind.Info.Generic.Opnd0->getValueType();
6416 if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
6422 if (InfoAndKind.IsARM64) {
6423 CCVal = DAG.getConstant(
6424 ARM64CC::getInvertedCondCode(InfoAndKind.Info.ARM64.CC), MVT::i32);
6425 Cmp = *InfoAndKind.Info.ARM64.Cmp;
6427 Cmp = getARM64Cmp(*InfoAndKind.Info.Generic.Opnd0,
6428 *InfoAndKind.Info.Generic.Opnd1,
6429 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
6432 EVT VT = Op->getValueType(0);
6433 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, VT));
6434 return DAG.getNode(ARM64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
6437 // The basic add/sub long vector instructions have variants with "2" on the end
6438 // which act on the high-half of their inputs. They are normally matched by
6441 // (add (zeroext (extract_high LHS)),
6442 // (zeroext (extract_high RHS)))
6443 // -> uaddl2 vD, vN, vM
6445 // However, if one of the extracts is something like a duplicate, this
6446 // instruction can still be used profitably. This function puts the DAG into a
6447 // more appropriate form for those patterns to trigger.
6448 static SDValue performAddSubLongCombine(SDNode *N,
6449 TargetLowering::DAGCombinerInfo &DCI,
6450 SelectionDAG &DAG) {
6451 if (DCI.isBeforeLegalizeOps())
6454 MVT VT = N->getSimpleValueType(0);
6455 if (!VT.is128BitVector()) {
6456 if (N->getOpcode() == ISD::ADD)
6457 return performSetccAddFolding(N, DAG);
6461 // Make sure both branches are extended in the same way.
6462 SDValue LHS = N->getOperand(0);
6463 SDValue RHS = N->getOperand(1);
6464 if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
6465 LHS.getOpcode() != ISD::SIGN_EXTEND) ||
6466 LHS.getOpcode() != RHS.getOpcode())
6469 unsigned ExtType = LHS.getOpcode();
6471 // It's not worth doing if at least one of the inputs isn't already an
6472 // extract, but we don't know which it'll be so we have to try both.
6473 if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
6474 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
6478 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
6479 } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
6480 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
6484 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
6487 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
6490 // Massage DAGs which we can use the high-half "long" operations on into
6491 // something isel will recognize better. E.g.
6493 // (arm64_neon_umull (extract_high vec) (dupv64 scalar)) -->
6494 // (arm64_neon_umull (extract_high (v2i64 vec)))
6495 // (extract_high (v2i64 (dup128 scalar)))))
6497 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
6498 TargetLowering::DAGCombinerInfo &DCI,
6499 SelectionDAG &DAG) {
6500 if (DCI.isBeforeLegalizeOps())
6503 SDValue LHS = N->getOperand(1);
6504 SDValue RHS = N->getOperand(2);
6505 assert(LHS.getValueType().is64BitVector() &&
6506 RHS.getValueType().is64BitVector() &&
6507 "unexpected shape for long operation");
6509 // Either node could be a DUP, but it's not worth doing both of them (you'd
6510 // just as well use the non-high version) so look for a corresponding extract
6511 // operation on the other "wing".
6512 if (isEssentiallyExtractSubvector(LHS)) {
6513 RHS = tryExtendDUPToExtractHigh(RHS, DAG);
6516 } else if (isEssentiallyExtractSubvector(RHS)) {
6517 LHS = tryExtendDUPToExtractHigh(LHS, DAG);
6522 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
6523 N->getOperand(0), LHS, RHS);
6526 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
6527 MVT ElemTy = N->getSimpleValueType(0).getScalarType();
6528 unsigned ElemBits = ElemTy.getSizeInBits();
6530 int64_t ShiftAmount;
6531 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
6532 APInt SplatValue, SplatUndef;
6533 unsigned SplatBitSize;
6535 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
6536 HasAnyUndefs, ElemBits) ||
6537 SplatBitSize != ElemBits)
6540 ShiftAmount = SplatValue.getSExtValue();
6541 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
6542 ShiftAmount = CVN->getSExtValue();
6550 llvm_unreachable("Unknown shift intrinsic");
6551 case Intrinsic::arm64_neon_sqshl:
6552 Opcode = ARM64ISD::SQSHL_I;
6553 IsRightShift = false;
6555 case Intrinsic::arm64_neon_uqshl:
6556 Opcode = ARM64ISD::UQSHL_I;
6557 IsRightShift = false;
6559 case Intrinsic::arm64_neon_srshl:
6560 Opcode = ARM64ISD::SRSHR_I;
6561 IsRightShift = true;
6563 case Intrinsic::arm64_neon_urshl:
6564 Opcode = ARM64ISD::URSHR_I;
6565 IsRightShift = true;
6567 case Intrinsic::arm64_neon_sqshlu:
6568 Opcode = ARM64ISD::SQSHLU_I;
6569 IsRightShift = false;
6573 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits)
6574 return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), N->getOperand(1),
6575 DAG.getConstant(-ShiftAmount, MVT::i32));
6576 else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount <= ElemBits)
6577 return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), N->getOperand(1),
6578 DAG.getConstant(ShiftAmount, MVT::i32));
6583 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
6584 // the intrinsics must be legal and take an i32, this means there's almost
6585 // certainly going to be a zext in the DAG which we can eliminate.
6586 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
6587 SDValue AndN = N->getOperand(2);
6588 if (AndN.getOpcode() != ISD::AND)
6591 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
6592 if (!CMask || CMask->getZExtValue() != Mask)
6595 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
6596 N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
6599 static SDValue performIntrinsicCombine(SDNode *N,
6600 TargetLowering::DAGCombinerInfo &DCI,
6601 const ARM64Subtarget *Subtarget) {
6602 SelectionDAG &DAG = DCI.DAG;
6603 unsigned IID = getIntrinsicID(N);
6607 case Intrinsic::arm64_neon_vcvtfxs2fp:
6608 case Intrinsic::arm64_neon_vcvtfxu2fp:
6609 return tryCombineFixedPointConvert(N, DCI, DAG);
6611 case Intrinsic::arm64_neon_fmax:
6612 return DAG.getNode(ARM64ISD::FMAX, SDLoc(N), N->getValueType(0),
6613 N->getOperand(1), N->getOperand(2));
6614 case Intrinsic::arm64_neon_fmin:
6615 return DAG.getNode(ARM64ISD::FMIN, SDLoc(N), N->getValueType(0),
6616 N->getOperand(1), N->getOperand(2));
6617 case Intrinsic::arm64_neon_smull:
6618 case Intrinsic::arm64_neon_umull:
6619 case Intrinsic::arm64_neon_pmull:
6620 case Intrinsic::arm64_neon_sqdmull:
6621 return tryCombineLongOpWithDup(IID, N, DCI, DAG);
6622 case Intrinsic::arm64_neon_sqshl:
6623 case Intrinsic::arm64_neon_uqshl:
6624 case Intrinsic::arm64_neon_sqshlu:
6625 case Intrinsic::arm64_neon_srshl:
6626 case Intrinsic::arm64_neon_urshl:
6627 return tryCombineShiftImm(IID, N, DAG);
6628 case Intrinsic::arm64_crc32b:
6629 case Intrinsic::arm64_crc32cb:
6630 return tryCombineCRC32(0xff, N, DAG);
6631 case Intrinsic::arm64_crc32h:
6632 case Intrinsic::arm64_crc32ch:
6633 return tryCombineCRC32(0xffff, N, DAG);
6638 static SDValue performExtendCombine(SDNode *N,
6639 TargetLowering::DAGCombinerInfo &DCI,
6640 SelectionDAG &DAG) {
6641 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
6642 // we can convert that DUP into another extract_high (of a bigger DUP), which
6643 // helps the backend to decide that an sabdl2 would be useful, saving a real
6644 // extract_high operation.
6645 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
6646 N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
6647 SDNode *ABDNode = N->getOperand(0).getNode();
6648 unsigned IID = getIntrinsicID(ABDNode);
6649 if (IID == Intrinsic::arm64_neon_sabd ||
6650 IID == Intrinsic::arm64_neon_uabd) {
6651 SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
6652 if (!NewABD.getNode())
6655 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
6660 // This is effectively a custom type legalization for ARM64.
6662 // Type legalization will split an extend of a small, legal, type to a larger
6663 // illegal type by first splitting the destination type, often creating
6664 // illegal source types, which then get legalized in isel-confusing ways,
6665 // leading to really terrible codegen. E.g.,
6666 // %result = v8i32 sext v8i8 %value
6668 // %losrc = extract_subreg %value, ...
6669 // %hisrc = extract_subreg %value, ...
6670 // %lo = v4i32 sext v4i8 %losrc
6671 // %hi = v4i32 sext v4i8 %hisrc
6672 // Things go rapidly downhill from there.
6674 // For ARM64, the [sz]ext vector instructions can only go up one element
6675 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
6676 // take two instructions.
6678 // This implies that the most efficient way to do the extend from v8i8
6679 // to two v4i32 values is to first extend the v8i8 to v8i16, then do
6680 // the normal splitting to happen for the v8i16->v8i32.
6682 // This is pre-legalization to catch some cases where the default
6683 // type legalization will create ill-tempered code.
6684 if (!DCI.isBeforeLegalizeOps())
6687 // We're only interested in cleaning things up for non-legal vector types
6688 // here. If both the source and destination are legal, things will just
6689 // work naturally without any fiddling.
6690 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6691 EVT ResVT = N->getValueType(0);
6692 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
6694 // If the vector type isn't a simple VT, it's beyond the scope of what
6695 // we're worried about here. Let legalization do its thing and hope for
6697 if (!ResVT.isSimple())
6700 SDValue Src = N->getOperand(0);
6701 MVT SrcVT = Src->getValueType(0).getSimpleVT();
6702 // If the source VT is a 64-bit vector, we can play games and get the
6703 // better results we want.
6704 if (SrcVT.getSizeInBits() != 64)
6707 unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits();
6708 unsigned ElementCount = SrcVT.getVectorNumElements();
6709 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
6711 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
6713 // Now split the rest of the operation into two halves, each with a 64
6717 unsigned NumElements = ResVT.getVectorNumElements();
6718 assert(!(NumElements & 1) && "Splitting vector, but not in half!");
6719 LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
6720 ResVT.getVectorElementType(), NumElements / 2);
6722 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
6723 LoVT.getVectorNumElements());
6724 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
6725 DAG.getIntPtrConstant(0));
6726 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
6727 DAG.getIntPtrConstant(InNVT.getVectorNumElements()));
6728 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
6729 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
6731 // Now combine the parts back together so we still have a single result
6732 // like the combiner expects.
6733 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
6736 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
6737 /// value. The load store optimizer pass will merge them to store pair stores.
6738 /// This has better performance than a splat of the scalar followed by a split
6739 /// vector store. Even if the stores are not merged it is four stores vs a dup,
6740 /// followed by an ext.b and two stores.
6741 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode *St) {
6742 SDValue StVal = St->getValue();
6743 EVT VT = StVal.getValueType();
6745 // Don't replace floating point stores, they possibly won't be transformed to
6746 // stp because of the store pair suppress pass.
6747 if (VT.isFloatingPoint())
6750 // Check for insert vector elements.
6751 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
6754 // We can express a splat as store pair(s) for 2 or 4 elements.
6755 unsigned NumVecElts = VT.getVectorNumElements();
6756 if (NumVecElts != 4 && NumVecElts != 2)
6758 SDValue SplatVal = StVal.getOperand(1);
6759 unsigned RemainInsertElts = NumVecElts - 1;
6761 // Check that this is a splat.
6762 while (--RemainInsertElts) {
6763 SDValue NextInsertElt = StVal.getOperand(0);
6764 if (NextInsertElt.getOpcode() != ISD::INSERT_VECTOR_ELT)
6766 if (NextInsertElt.getOperand(1) != SplatVal)
6768 StVal = NextInsertElt;
6770 unsigned OrigAlignment = St->getAlignment();
6771 unsigned EltOffset = NumVecElts == 4 ? 4 : 8;
6772 unsigned Alignment = std::min(OrigAlignment, EltOffset);
6774 // Create scalar stores. This is at least as good as the code sequence for a
6775 // split unaligned store wich is a dup.s, ext.b, and two stores.
6776 // Most of the time the three stores should be replaced by store pair
6777 // instructions (stp).
6779 SDValue BasePtr = St->getBasePtr();
6781 DAG.getStore(St->getChain(), DL, SplatVal, BasePtr, St->getPointerInfo(),
6782 St->isVolatile(), St->isNonTemporal(), St->getAlignment());
6784 unsigned Offset = EltOffset;
6785 while (--NumVecElts) {
6786 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
6787 DAG.getConstant(Offset, MVT::i64));
6788 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
6789 St->getPointerInfo(), St->isVolatile(),
6790 St->isNonTemporal(), Alignment);
6791 Offset += EltOffset;
6796 static SDValue performSTORECombine(SDNode *N,
6797 TargetLowering::DAGCombinerInfo &DCI,
6799 const ARM64Subtarget *Subtarget) {
6800 if (!DCI.isBeforeLegalize())
6803 StoreSDNode *S = cast<StoreSDNode>(N);
6804 if (S->isVolatile())
6807 // Cyclone has bad performance on unaligned 16B stores when crossing line and
6808 // page boundries. We want to split such stores.
6809 if (!Subtarget->isCyclone())
6812 // Don't split at Oz.
6813 MachineFunction &MF = DAG.getMachineFunction();
6814 bool IsMinSize = MF.getFunction()->getAttributes().hasAttribute(
6815 AttributeSet::FunctionIndex, Attribute::MinSize);
6819 SDValue StVal = S->getValue();
6820 EVT VT = StVal.getValueType();
6822 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
6823 // those up regresses performance on micro-benchmarks and olden/bh.
6824 if (!VT.isVector() || VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
6827 // Split unaligned 16B stores. They are terrible for performance.
6828 // Don't split stores with alignment of 1 or 2. Code that uses clang vector
6829 // extensions can use this to mark that it does not want splitting to happen
6830 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
6831 // eliminating alignment hazards is only 1 in 8 for alignment of 2.
6832 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
6833 S->getAlignment() <= 2)
6836 // If we get a splat of a scalar convert this vector store to a store of
6837 // scalars. They will be merged into store pairs thereby removing two
6839 SDValue ReplacedSplat = replaceSplatVectorStore(DAG, S);
6840 if (ReplacedSplat != SDValue())
6841 return ReplacedSplat;
6844 unsigned NumElts = VT.getVectorNumElements() / 2;
6845 // Split VT into two.
6847 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
6848 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
6849 DAG.getIntPtrConstant(0));
6850 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
6851 DAG.getIntPtrConstant(NumElts));
6852 SDValue BasePtr = S->getBasePtr();
6854 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
6855 S->isVolatile(), S->isNonTemporal(), S->getAlignment());
6856 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
6857 DAG.getConstant(8, MVT::i64));
6858 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
6859 S->getPointerInfo(), S->isVolatile(), S->isNonTemporal(),
6863 // Optimize compare with zero and branch.
6864 static SDValue performBRCONDCombine(SDNode *N,
6865 TargetLowering::DAGCombinerInfo &DCI,
6866 SelectionDAG &DAG) {
6867 SDValue Chain = N->getOperand(0);
6868 SDValue Dest = N->getOperand(1);
6869 SDValue CCVal = N->getOperand(2);
6870 SDValue Cmp = N->getOperand(3);
6872 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
6873 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
6874 if (CC != ARM64CC::EQ && CC != ARM64CC::NE)
6877 unsigned CmpOpc = Cmp.getOpcode();
6878 if (CmpOpc != ARM64ISD::ADDS && CmpOpc != ARM64ISD::SUBS)
6881 // Only attempt folding if there is only one use of the flag and no use of the
6883 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
6886 SDValue LHS = Cmp.getOperand(0);
6887 SDValue RHS = Cmp.getOperand(1);
6889 assert(LHS.getValueType() == RHS.getValueType() &&
6890 "Expected the value type to be the same for both operands!");
6891 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
6894 if (isa<ConstantSDNode>(LHS) && cast<ConstantSDNode>(LHS)->isNullValue())
6895 std::swap(LHS, RHS);
6897 if (!isa<ConstantSDNode>(RHS) || !cast<ConstantSDNode>(RHS)->isNullValue())
6900 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
6901 LHS.getOpcode() == ISD::SRL)
6904 // Fold the compare into the branch instruction.
6906 if (CC == ARM64CC::EQ)
6907 BR = DAG.getNode(ARM64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
6909 BR = DAG.getNode(ARM64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
6911 // Do not add new nodes to DAG combiner worklist.
6912 DCI.CombineTo(N, BR, false);
6917 // vselect (v1i1 setcc) ->
6918 // vselect (v1iXX setcc) (XX is the size of the compared operand type)
6919 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
6920 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
6922 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
6923 SDValue N0 = N->getOperand(0);
6924 EVT CCVT = N0.getValueType();
6926 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
6927 CCVT.getVectorElementType() != MVT::i1)
6930 EVT ResVT = N->getValueType(0);
6931 EVT CmpVT = N0.getOperand(0).getValueType();
6932 // Only combine when the result type is of the same size as the compared
6934 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
6937 SDValue IfTrue = N->getOperand(1);
6938 SDValue IfFalse = N->getOperand(2);
6940 DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
6941 N0.getOperand(0), N0.getOperand(1),
6942 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6943 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
6947 SDValue ARM64TargetLowering::PerformDAGCombine(SDNode *N,
6948 DAGCombinerInfo &DCI) const {
6949 SelectionDAG &DAG = DCI.DAG;
6950 switch (N->getOpcode()) {
6955 return performAddSubLongCombine(N, DCI, DAG);
6957 return performXorCombine(N, DAG, DCI, Subtarget);
6959 return performMulCombine(N, DAG, DCI, Subtarget);
6960 case ISD::SINT_TO_FP:
6961 case ISD::UINT_TO_FP:
6962 return performIntToFpCombine(N, DAG);
6964 return performORCombine(N, DCI, Subtarget);
6965 case ISD::INTRINSIC_WO_CHAIN:
6966 return performIntrinsicCombine(N, DCI, Subtarget);
6967 case ISD::ANY_EXTEND:
6968 case ISD::ZERO_EXTEND:
6969 case ISD::SIGN_EXTEND:
6970 return performExtendCombine(N, DCI, DAG);
6972 return performBitcastCombine(N, DCI, DAG);
6973 case ISD::CONCAT_VECTORS:
6974 return performConcatVectorsCombine(N, DCI, DAG);
6976 return performVSelectCombine(N, DCI.DAG);
6978 return performSTORECombine(N, DCI, DAG, Subtarget);
6979 case ARM64ISD::BRCOND:
6980 return performBRCONDCombine(N, DCI, DAG);
6985 // Check if the return value is used as only a return value, as otherwise
6986 // we can't perform a tail-call. In particular, we need to check for
6987 // target ISD nodes that are returns and any other "odd" constructs
6988 // that the generic analysis code won't necessarily catch.
6989 bool ARM64TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
6990 if (N->getNumValues() != 1)
6992 if (!N->hasNUsesOfValue(1, 0))
6995 SDValue TCChain = Chain;
6996 SDNode *Copy = *N->use_begin();
6997 if (Copy->getOpcode() == ISD::CopyToReg) {
6998 // If the copy has a glue operand, we conservatively assume it isn't safe to
6999 // perform a tail call.
7000 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
7003 TCChain = Copy->getOperand(0);
7004 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
7007 bool HasRet = false;
7008 for (SDNode *Node : Copy->uses()) {
7009 if (Node->getOpcode() != ARM64ISD::RET_FLAG)
7021 // Return whether the an instruction can potentially be optimized to a tail
7022 // call. This will cause the optimizers to attempt to move, or duplicate,
7023 // return instructions to help enable tail call optimizations for this
7025 bool ARM64TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
7026 if (!EnableARM64TailCalls)
7029 if (!CI->isTailCall())
7035 bool ARM64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
7037 ISD::MemIndexedMode &AM,
7039 SelectionDAG &DAG) const {
7040 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
7043 Base = Op->getOperand(0);
7044 // All of the indexed addressing mode instructions take a signed
7045 // 9 bit immediate offset.
7046 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
7047 int64_t RHSC = (int64_t)RHS->getZExtValue();
7048 if (RHSC >= 256 || RHSC <= -256)
7050 IsInc = (Op->getOpcode() == ISD::ADD);
7051 Offset = Op->getOperand(1);
7057 bool ARM64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
7059 ISD::MemIndexedMode &AM,
7060 SelectionDAG &DAG) const {
7063 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7064 VT = LD->getMemoryVT();
7065 Ptr = LD->getBasePtr();
7066 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7067 VT = ST->getMemoryVT();
7068 Ptr = ST->getBasePtr();
7073 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
7075 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
7079 bool ARM64TargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
7082 ISD::MemIndexedMode &AM,
7083 SelectionDAG &DAG) const {
7086 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7087 VT = LD->getMemoryVT();
7088 Ptr = LD->getBasePtr();
7089 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7090 VT = ST->getMemoryVT();
7091 Ptr = ST->getBasePtr();
7096 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
7098 // Post-indexing updates the base, so it's not a valid transform
7099 // if that's not the same as the load's pointer.
7102 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
7106 void ARM64TargetLowering::ReplaceNodeResults(SDNode *N,
7107 SmallVectorImpl<SDValue> &Results,
7108 SelectionDAG &DAG) const {
7109 switch (N->getOpcode()) {
7111 llvm_unreachable("Don't know how to custom expand this");
7112 case ISD::FP_TO_UINT:
7113 case ISD::FP_TO_SINT:
7114 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
7115 // Let normal code take care of it by not adding anything to Results.
7120 bool ARM64TargetLowering::shouldExpandAtomicInIR(Instruction *Inst) const {
7121 // Loads and stores less than 128-bits are already atomic; ones above that
7122 // are doomed anyway, so defer to the default libcall and blame the OS when
7124 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
7125 return SI->getValueOperand()->getType()->getPrimitiveSizeInBits() == 128;
7126 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
7127 return LI->getType()->getPrimitiveSizeInBits() == 128;
7129 // For the real atomic operations, we have ldxr/stxr up to 128 bits.
7130 return Inst->getType()->getPrimitiveSizeInBits() <= 128;
7133 Value *ARM64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
7134 AtomicOrdering Ord) const {
7135 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
7136 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
7138 Ord == Acquire || Ord == AcquireRelease || Ord == SequentiallyConsistent;
7140 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
7141 // intrinsic must return {i64, i64} and we have to recombine them into a
7142 // single i128 here.
7143 if (ValTy->getPrimitiveSizeInBits() == 128) {
7145 IsAcquire ? Intrinsic::arm64_ldaxp : Intrinsic::arm64_ldxp;
7146 Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int);
7148 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
7149 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
7151 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
7152 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
7153 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
7154 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
7155 return Builder.CreateOr(
7156 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
7159 Type *Tys[] = { Addr->getType() };
7161 IsAcquire ? Intrinsic::arm64_ldaxr : Intrinsic::arm64_ldxr;
7162 Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int, Tys);
7164 return Builder.CreateTruncOrBitCast(
7165 Builder.CreateCall(Ldxr, Addr),
7166 cast<PointerType>(Addr->getType())->getElementType());
7169 Value *ARM64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
7170 Value *Val, Value *Addr,
7171 AtomicOrdering Ord) const {
7172 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
7174 Ord == Release || Ord == AcquireRelease || Ord == SequentiallyConsistent;
7176 // Since the intrinsics must have legal type, the i128 intrinsics take two
7177 // parameters: "i64, i64". We must marshal Val into the appropriate form
7179 if (Val->getType()->getPrimitiveSizeInBits() == 128) {
7181 IsRelease ? Intrinsic::arm64_stlxp : Intrinsic::arm64_stxp;
7182 Function *Stxr = Intrinsic::getDeclaration(M, Int);
7183 Type *Int64Ty = Type::getInt64Ty(M->getContext());
7185 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
7186 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
7187 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
7188 return Builder.CreateCall3(Stxr, Lo, Hi, Addr);
7192 IsRelease ? Intrinsic::arm64_stlxr : Intrinsic::arm64_stxr;
7193 Type *Tys[] = { Addr->getType() };
7194 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
7196 return Builder.CreateCall2(
7197 Stxr, Builder.CreateZExtOrBitCast(
7198 Val, Stxr->getFunctionType()->getParamType(0)),