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 // We can pad out the smaller vector for free, so if it's part of a
3834 ShuffleSrcs[i] = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, SourceVecs[i],
3835 DAG.getUNDEF(SourceVecs[i].getValueType()));
3839 // Don't attempt to extract subvectors from BUILD_VECTOR sources
3840 // that expand or trunc the original value.
3841 // TODO: We can try to bitcast and ANY_EXTEND the result but
3842 // we need to consider the cost of vector ANY_EXTEND, and the
3843 // legality of all the types.
3844 if (SourceVecs[i].getValueType().getVectorElementType() !=
3845 VT.getVectorElementType())
3848 // Since only 64-bit and 128-bit vectors are legal on ARM and
3849 // we've eliminated the other cases...
3850 assert(SourceVecs[i].getValueType().getVectorNumElements() == 2 * NumElts &&
3851 "unexpected vector sizes in ReconstructShuffle");
3853 if (MaxElts[i] - MinElts[i] >= NumElts) {
3854 // Span too large for a VEXT to cope
3858 if (MinElts[i] >= NumElts) {
3859 // The extraction can just take the second half
3860 VEXTOffsets[i] = NumElts;
3862 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SourceVecs[i],
3863 DAG.getIntPtrConstant(NumElts));
3864 } else if (MaxElts[i] < NumElts) {
3865 // The extraction can just take the first half
3867 ShuffleSrcs[i] = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
3868 SourceVecs[i], DAG.getIntPtrConstant(0));
3870 // An actual VEXT is needed
3871 VEXTOffsets[i] = MinElts[i];
3872 SDValue VEXTSrc1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT,
3873 SourceVecs[i], DAG.getIntPtrConstant(0));
3875 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SourceVecs[i],
3876 DAG.getIntPtrConstant(NumElts));
3877 unsigned Imm = VEXTOffsets[i] * getExtFactor(VEXTSrc1);
3878 ShuffleSrcs[i] = DAG.getNode(ARM64ISD::EXT, dl, VT, VEXTSrc1, VEXTSrc2,
3879 DAG.getConstant(Imm, MVT::i32));
3883 SmallVector<int, 8> Mask;
3885 for (unsigned i = 0; i < NumElts; ++i) {
3886 SDValue Entry = Op.getOperand(i);
3887 if (Entry.getOpcode() == ISD::UNDEF) {
3892 SDValue ExtractVec = Entry.getOperand(0);
3894 cast<ConstantSDNode>(Op.getOperand(i).getOperand(1))->getSExtValue();
3895 if (ExtractVec == SourceVecs[0]) {
3896 Mask.push_back(ExtractElt - VEXTOffsets[0]);
3898 Mask.push_back(ExtractElt + NumElts - VEXTOffsets[1]);
3902 // Final check before we try to produce nonsense...
3903 if (isShuffleMaskLegal(Mask, VT))
3904 return DAG.getVectorShuffle(VT, dl, ShuffleSrcs[0], ShuffleSrcs[1],
3910 // check if an EXT instruction can handle the shuffle mask when the
3911 // vector sources of the shuffle are the same.
3912 static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
3913 unsigned NumElts = VT.getVectorNumElements();
3915 // Assume that the first shuffle index is not UNDEF. Fail if it is.
3921 // If this is a VEXT shuffle, the immediate value is the index of the first
3922 // element. The other shuffle indices must be the successive elements after
3924 unsigned ExpectedElt = Imm;
3925 for (unsigned i = 1; i < NumElts; ++i) {
3926 // Increment the expected index. If it wraps around, just follow it
3927 // back to index zero and keep going.
3929 if (ExpectedElt == NumElts)
3933 continue; // ignore UNDEF indices
3934 if (ExpectedElt != static_cast<unsigned>(M[i]))
3941 // check if an EXT instruction can handle the shuffle mask when the
3942 // vector sources of the shuffle are different.
3943 static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
3945 unsigned NumElts = VT.getVectorNumElements();
3948 // Assume that the first shuffle index is not UNDEF. Fail if it is.
3954 // If this is a VEXT shuffle, the immediate value is the index of the first
3955 // element. The other shuffle indices must be the successive elements after
3957 unsigned ExpectedElt = Imm;
3958 for (unsigned i = 1; i < NumElts; ++i) {
3959 // Increment the expected index. If it wraps around, it may still be
3960 // a VEXT but the source vectors must be swapped.
3962 if (ExpectedElt == NumElts * 2) {
3968 continue; // ignore UNDEF indices
3969 if (ExpectedElt != static_cast<unsigned>(M[i]))
3973 // Adjust the index value if the source operands will be swapped.
3980 /// isREVMask - Check if a vector shuffle corresponds to a REV
3981 /// instruction with the specified blocksize. (The order of the elements
3982 /// within each block of the vector is reversed.)
3983 static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
3984 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
3985 "Only possible block sizes for REV are: 16, 32, 64");
3987 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
3991 unsigned NumElts = VT.getVectorNumElements();
3992 unsigned BlockElts = M[0] + 1;
3993 // If the first shuffle index is UNDEF, be optimistic.
3995 BlockElts = BlockSize / EltSz;
3997 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
4000 for (unsigned i = 0; i < NumElts; ++i) {
4002 continue; // ignore UNDEF indices
4003 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
4010 static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4011 unsigned NumElts = VT.getVectorNumElements();
4012 WhichResult = (M[0] == 0 ? 0 : 1);
4013 unsigned Idx = WhichResult * NumElts / 2;
4014 for (unsigned i = 0; i != NumElts; i += 2) {
4015 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
4016 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
4024 static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4025 unsigned NumElts = VT.getVectorNumElements();
4026 WhichResult = (M[0] == 0 ? 0 : 1);
4027 for (unsigned i = 0; i != NumElts; ++i) {
4029 continue; // ignore UNDEF indices
4030 if ((unsigned)M[i] != 2 * i + WhichResult)
4037 static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4038 unsigned NumElts = VT.getVectorNumElements();
4039 WhichResult = (M[0] == 0 ? 0 : 1);
4040 for (unsigned i = 0; i < NumElts; i += 2) {
4041 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
4042 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
4048 /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
4049 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4050 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
4051 static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4052 unsigned NumElts = VT.getVectorNumElements();
4053 WhichResult = (M[0] == 0 ? 0 : 1);
4054 unsigned Idx = WhichResult * NumElts / 2;
4055 for (unsigned i = 0; i != NumElts; i += 2) {
4056 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
4057 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
4065 /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
4066 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4067 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
4068 static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4069 unsigned Half = VT.getVectorNumElements() / 2;
4070 WhichResult = (M[0] == 0 ? 0 : 1);
4071 for (unsigned j = 0; j != 2; ++j) {
4072 unsigned Idx = WhichResult;
4073 for (unsigned i = 0; i != Half; ++i) {
4074 int MIdx = M[i + j * Half];
4075 if (MIdx >= 0 && (unsigned)MIdx != Idx)
4084 /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
4085 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
4086 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
4087 static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
4088 unsigned NumElts = VT.getVectorNumElements();
4089 WhichResult = (M[0] == 0 ? 0 : 1);
4090 for (unsigned i = 0; i < NumElts; i += 2) {
4091 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
4092 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
4098 static bool isINSMask(ArrayRef<int> M, int NumInputElements,
4099 bool &DstIsLeft, int &Anomaly) {
4100 if (M.size() != static_cast<size_t>(NumInputElements))
4103 int NumLHSMatch = 0, NumRHSMatch = 0;
4104 int LastLHSMismatch = -1, LastRHSMismatch = -1;
4106 for (int i = 0; i < NumInputElements; ++i) {
4116 LastLHSMismatch = i;
4118 if (M[i] == i + NumInputElements)
4121 LastRHSMismatch = i;
4124 if (NumLHSMatch == NumInputElements - 1) {
4126 Anomaly = LastLHSMismatch;
4128 } else if (NumRHSMatch == NumInputElements - 1) {
4130 Anomaly = LastRHSMismatch;
4137 static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
4138 if (VT.getSizeInBits() != 128)
4141 unsigned NumElts = VT.getVectorNumElements();
4143 for (int I = 0, E = NumElts / 2; I != E; I++) {
4148 int Offset = NumElts / 2;
4149 for (int I = NumElts / 2, E = NumElts; I != E; I++) {
4150 if (Mask[I] != I + SplitLHS * Offset)
4157 static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
4159 EVT VT = Op.getValueType();
4160 SDValue V0 = Op.getOperand(0);
4161 SDValue V1 = Op.getOperand(1);
4162 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
4164 if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
4165 VT.getVectorElementType() != V1.getValueType().getVectorElementType())
4168 bool SplitV0 = V0.getValueType().getSizeInBits() == 128;
4170 if (!isConcatMask(Mask, VT, SplitV0))
4173 EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
4174 VT.getVectorNumElements() / 2);
4176 V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
4177 DAG.getConstant(0, MVT::i64));
4179 if (V1.getValueType().getSizeInBits() == 128) {
4180 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
4181 DAG.getConstant(0, MVT::i64));
4183 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
4186 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
4187 /// the specified operations to build the shuffle.
4188 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
4189 SDValue RHS, SelectionDAG &DAG,
4191 unsigned OpNum = (PFEntry >> 26) & 0x0F;
4192 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
4193 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
4196 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
4205 OP_VUZPL, // VUZP, left result
4206 OP_VUZPR, // VUZP, right result
4207 OP_VZIPL, // VZIP, left result
4208 OP_VZIPR, // VZIP, right result
4209 OP_VTRNL, // VTRN, left result
4210 OP_VTRNR // VTRN, right result
4213 if (OpNum == OP_COPY) {
4214 if (LHSID == (1 * 9 + 2) * 9 + 3)
4216 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
4220 SDValue OpLHS, OpRHS;
4221 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
4222 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
4223 EVT VT = OpLHS.getValueType();
4227 llvm_unreachable("Unknown shuffle opcode!");
4229 // VREV divides the vector in half and swaps within the half.
4230 if (VT.getVectorElementType() == MVT::i32 ||
4231 VT.getVectorElementType() == MVT::f32)
4232 return DAG.getNode(ARM64ISD::REV64, dl, VT, OpLHS);
4233 // vrev <4 x i16> -> REV32
4234 if (VT.getVectorElementType() == MVT::i16)
4235 return DAG.getNode(ARM64ISD::REV32, dl, VT, OpLHS);
4236 // vrev <4 x i8> -> REV16
4237 assert(VT.getVectorElementType() == MVT::i8);
4238 return DAG.getNode(ARM64ISD::REV16, dl, VT, OpLHS);
4243 EVT EltTy = VT.getVectorElementType();
4245 if (EltTy == MVT::i8)
4246 Opcode = ARM64ISD::DUPLANE8;
4247 else if (EltTy == MVT::i16)
4248 Opcode = ARM64ISD::DUPLANE16;
4249 else if (EltTy == MVT::i32 || EltTy == MVT::f32)
4250 Opcode = ARM64ISD::DUPLANE32;
4251 else if (EltTy == MVT::i64 || EltTy == MVT::f64)
4252 Opcode = ARM64ISD::DUPLANE64;
4254 llvm_unreachable("Invalid vector element type?");
4256 if (VT.getSizeInBits() == 64)
4257 OpLHS = WidenVector(OpLHS, DAG);
4258 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, MVT::i64);
4259 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
4264 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
4265 return DAG.getNode(ARM64ISD::EXT, dl, VT, OpLHS, OpRHS,
4266 DAG.getConstant(Imm, MVT::i32));
4269 return DAG.getNode(ARM64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS, OpRHS);
4271 return DAG.getNode(ARM64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS, OpRHS);
4273 return DAG.getNode(ARM64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS, OpRHS);
4275 return DAG.getNode(ARM64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS, OpRHS);
4277 return DAG.getNode(ARM64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS, OpRHS);
4279 return DAG.getNode(ARM64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS, OpRHS);
4283 static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
4284 SelectionDAG &DAG) {
4285 // Check to see if we can use the TBL instruction.
4286 SDValue V1 = Op.getOperand(0);
4287 SDValue V2 = Op.getOperand(1);
4290 EVT EltVT = Op.getValueType().getVectorElementType();
4291 unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
4293 SmallVector<SDValue, 8> TBLMask;
4294 for (int Val : ShuffleMask) {
4295 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
4296 unsigned Offset = Byte + Val * BytesPerElt;
4297 TBLMask.push_back(DAG.getConstant(Offset, MVT::i32));
4301 MVT IndexVT = MVT::v8i8;
4302 unsigned IndexLen = 8;
4303 if (Op.getValueType().getSizeInBits() == 128) {
4304 IndexVT = MVT::v16i8;
4308 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
4309 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
4312 if (V2.getNode()->getOpcode() == ISD::UNDEF) {
4314 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
4315 Shuffle = DAG.getNode(
4316 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
4317 DAG.getConstant(Intrinsic::arm64_neon_tbl1, MVT::i32), V1Cst,
4318 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT, &TBLMask[0], IndexLen));
4320 if (IndexLen == 8) {
4321 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
4322 Shuffle = DAG.getNode(
4323 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
4324 DAG.getConstant(Intrinsic::arm64_neon_tbl1, MVT::i32), V1Cst,
4325 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT, &TBLMask[0], IndexLen));
4327 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
4328 // cannot currently represent the register constraints on the input
4330 // Shuffle = DAG.getNode(ARM64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
4331 // DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
4332 // &TBLMask[0], IndexLen));
4333 Shuffle = DAG.getNode(
4334 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
4335 DAG.getConstant(Intrinsic::arm64_neon_tbl2, MVT::i32), V1Cst, V2Cst,
4336 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT, &TBLMask[0], IndexLen));
4339 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
4342 static unsigned getDUPLANEOp(EVT EltType) {
4343 if (EltType == MVT::i8)
4344 return ARM64ISD::DUPLANE8;
4345 if (EltType == MVT::i16)
4346 return ARM64ISD::DUPLANE16;
4347 if (EltType == MVT::i32 || EltType == MVT::f32)
4348 return ARM64ISD::DUPLANE32;
4349 if (EltType == MVT::i64 || EltType == MVT::f64)
4350 return ARM64ISD::DUPLANE64;
4352 llvm_unreachable("Invalid vector element type?");
4355 SDValue ARM64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
4356 SelectionDAG &DAG) const {
4358 EVT VT = Op.getValueType();
4360 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
4362 // Convert shuffles that are directly supported on NEON to target-specific
4363 // DAG nodes, instead of keeping them as shuffles and matching them again
4364 // during code selection. This is more efficient and avoids the possibility
4365 // of inconsistencies between legalization and selection.
4366 ArrayRef<int> ShuffleMask = SVN->getMask();
4368 SDValue V1 = Op.getOperand(0);
4369 SDValue V2 = Op.getOperand(1);
4371 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0],
4372 V1.getValueType().getSimpleVT())) {
4373 int Lane = SVN->getSplatIndex();
4374 // If this is undef splat, generate it via "just" vdup, if possible.
4378 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
4379 return DAG.getNode(ARM64ISD::DUP, dl, V1.getValueType(),
4381 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
4382 // constant. If so, we can just reference the lane's definition directly.
4383 if (V1.getOpcode() == ISD::BUILD_VECTOR &&
4384 !isa<ConstantSDNode>(V1.getOperand(Lane)))
4385 return DAG.getNode(ARM64ISD::DUP, dl, VT, V1.getOperand(Lane));
4387 // Otherwise, duplicate from the lane of the input vector.
4388 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
4390 // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
4391 // to make a vector of the same size as this SHUFFLE. We can ignore the
4392 // extract entirely, and canonicalise the concat using WidenVector.
4393 if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
4394 Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
4395 V1 = V1.getOperand(0);
4396 } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
4397 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
4398 Lane -= Idx * VT.getVectorNumElements() / 2;
4399 V1 = WidenVector(V1.getOperand(Idx), DAG);
4400 } else if (VT.getSizeInBits() == 64)
4401 V1 = WidenVector(V1, DAG);
4403 return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, MVT::i64));
4406 if (isREVMask(ShuffleMask, VT, 64))
4407 return DAG.getNode(ARM64ISD::REV64, dl, V1.getValueType(), V1, V2);
4408 if (isREVMask(ShuffleMask, VT, 32))
4409 return DAG.getNode(ARM64ISD::REV32, dl, V1.getValueType(), V1, V2);
4410 if (isREVMask(ShuffleMask, VT, 16))
4411 return DAG.getNode(ARM64ISD::REV16, dl, V1.getValueType(), V1, V2);
4413 bool ReverseEXT = false;
4415 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
4418 Imm *= getExtFactor(V1);
4419 return DAG.getNode(ARM64ISD::EXT, dl, V1.getValueType(), V1, V2,
4420 DAG.getConstant(Imm, MVT::i32));
4421 } else if (V2->getOpcode() == ISD::UNDEF &&
4422 isSingletonEXTMask(ShuffleMask, VT, Imm)) {
4423 Imm *= getExtFactor(V1);
4424 return DAG.getNode(ARM64ISD::EXT, dl, V1.getValueType(), V1, V1,
4425 DAG.getConstant(Imm, MVT::i32));
4428 unsigned WhichResult;
4429 if (isZIPMask(ShuffleMask, VT, WhichResult)) {
4430 unsigned Opc = (WhichResult == 0) ? ARM64ISD::ZIP1 : ARM64ISD::ZIP2;
4431 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
4433 if (isUZPMask(ShuffleMask, VT, WhichResult)) {
4434 unsigned Opc = (WhichResult == 0) ? ARM64ISD::UZP1 : ARM64ISD::UZP2;
4435 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
4437 if (isTRNMask(ShuffleMask, VT, WhichResult)) {
4438 unsigned Opc = (WhichResult == 0) ? ARM64ISD::TRN1 : ARM64ISD::TRN2;
4439 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
4442 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
4443 unsigned Opc = (WhichResult == 0) ? ARM64ISD::ZIP1 : ARM64ISD::ZIP2;
4444 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
4446 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
4447 unsigned Opc = (WhichResult == 0) ? ARM64ISD::UZP1 : ARM64ISD::UZP2;
4448 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
4450 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
4451 unsigned Opc = (WhichResult == 0) ? ARM64ISD::TRN1 : ARM64ISD::TRN2;
4452 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
4455 SDValue Concat = tryFormConcatFromShuffle(Op, DAG);
4456 if (Concat.getNode())
4461 int NumInputElements = V1.getValueType().getVectorNumElements();
4462 if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
4463 SDValue DstVec = DstIsLeft ? V1 : V2;
4464 SDValue DstLaneV = DAG.getConstant(Anomaly, MVT::i64);
4466 SDValue SrcVec = V1;
4467 int SrcLane = ShuffleMask[Anomaly];
4468 if (SrcLane >= NumInputElements) {
4470 SrcLane -= VT.getVectorNumElements();
4472 SDValue SrcLaneV = DAG.getConstant(SrcLane, MVT::i64);
4474 EVT ScalarVT = VT.getVectorElementType();
4475 if (ScalarVT.getSizeInBits() < 32)
4476 ScalarVT = MVT::i32;
4479 ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
4480 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
4484 // If the shuffle is not directly supported and it has 4 elements, use
4485 // the PerfectShuffle-generated table to synthesize it from other shuffles.
4486 unsigned NumElts = VT.getVectorNumElements();
4488 unsigned PFIndexes[4];
4489 for (unsigned i = 0; i != 4; ++i) {
4490 if (ShuffleMask[i] < 0)
4493 PFIndexes[i] = ShuffleMask[i];
4496 // Compute the index in the perfect shuffle table.
4497 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
4498 PFIndexes[2] * 9 + PFIndexes[3];
4499 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
4500 unsigned Cost = (PFEntry >> 30);
4503 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
4506 return GenerateTBL(Op, ShuffleMask, DAG);
4509 static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
4511 EVT VT = BVN->getValueType(0);
4512 APInt SplatBits, SplatUndef;
4513 unsigned SplatBitSize;
4515 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
4516 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
4518 for (unsigned i = 0; i < NumSplats; ++i) {
4519 CnstBits <<= SplatBitSize;
4520 UndefBits <<= SplatBitSize;
4521 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
4522 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
4531 SDValue ARM64TargetLowering::LowerVectorAND(SDValue Op,
4532 SelectionDAG &DAG) const {
4533 BuildVectorSDNode *BVN =
4534 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
4535 SDValue LHS = Op.getOperand(0);
4537 EVT VT = Op.getValueType();
4542 APInt CnstBits(VT.getSizeInBits(), 0);
4543 APInt UndefBits(VT.getSizeInBits(), 0);
4544 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
4545 // We only have BIC vector immediate instruction, which is and-not.
4546 CnstBits = ~CnstBits;
4548 // We make use of a little bit of goto ickiness in order to avoid having to
4549 // duplicate the immediate matching logic for the undef toggled case.
4550 bool SecondTry = false;
4553 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
4554 CnstBits = CnstBits.zextOrTrunc(64);
4555 uint64_t CnstVal = CnstBits.getZExtValue();
4557 if (ARM64_AM::isAdvSIMDModImmType1(CnstVal)) {
4558 CnstVal = ARM64_AM::encodeAdvSIMDModImmType1(CnstVal);
4559 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4560 SDValue Mov = DAG.getNode(ARM64ISD::BICi, dl, MovTy, LHS,
4561 DAG.getConstant(CnstVal, MVT::i32),
4562 DAG.getConstant(0, MVT::i32));
4563 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4566 if (ARM64_AM::isAdvSIMDModImmType2(CnstVal)) {
4567 CnstVal = ARM64_AM::encodeAdvSIMDModImmType2(CnstVal);
4568 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4569 SDValue Mov = DAG.getNode(ARM64ISD::BICi, dl, MovTy, LHS,
4570 DAG.getConstant(CnstVal, MVT::i32),
4571 DAG.getConstant(8, MVT::i32));
4572 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4575 if (ARM64_AM::isAdvSIMDModImmType3(CnstVal)) {
4576 CnstVal = ARM64_AM::encodeAdvSIMDModImmType3(CnstVal);
4577 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4578 SDValue Mov = DAG.getNode(ARM64ISD::BICi, dl, MovTy, LHS,
4579 DAG.getConstant(CnstVal, MVT::i32),
4580 DAG.getConstant(16, MVT::i32));
4581 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4584 if (ARM64_AM::isAdvSIMDModImmType4(CnstVal)) {
4585 CnstVal = ARM64_AM::encodeAdvSIMDModImmType4(CnstVal);
4586 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4587 SDValue Mov = DAG.getNode(ARM64ISD::BICi, dl, MovTy, LHS,
4588 DAG.getConstant(CnstVal, MVT::i32),
4589 DAG.getConstant(24, MVT::i32));
4590 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4593 if (ARM64_AM::isAdvSIMDModImmType5(CnstVal)) {
4594 CnstVal = ARM64_AM::encodeAdvSIMDModImmType5(CnstVal);
4595 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
4596 SDValue Mov = DAG.getNode(ARM64ISD::BICi, dl, MovTy, LHS,
4597 DAG.getConstant(CnstVal, MVT::i32),
4598 DAG.getConstant(0, MVT::i32));
4599 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4602 if (ARM64_AM::isAdvSIMDModImmType6(CnstVal)) {
4603 CnstVal = ARM64_AM::encodeAdvSIMDModImmType6(CnstVal);
4604 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
4605 SDValue Mov = DAG.getNode(ARM64ISD::BICi, dl, MovTy, LHS,
4606 DAG.getConstant(CnstVal, MVT::i32),
4607 DAG.getConstant(8, MVT::i32));
4608 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4615 CnstBits = ~UndefBits;
4619 // We can always fall back to a non-immediate AND.
4624 // Specialized code to quickly find if PotentialBVec is a BuildVector that
4625 // consists of only the same constant int value, returned in reference arg
4627 static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
4628 uint64_t &ConstVal) {
4629 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
4632 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
4635 EVT VT = Bvec->getValueType(0);
4636 unsigned NumElts = VT.getVectorNumElements();
4637 for (unsigned i = 1; i < NumElts; ++i)
4638 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
4640 ConstVal = FirstElt->getZExtValue();
4644 static unsigned getIntrinsicID(const SDNode *N) {
4645 unsigned Opcode = N->getOpcode();
4648 return Intrinsic::not_intrinsic;
4649 case ISD::INTRINSIC_WO_CHAIN: {
4650 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
4651 if (IID < Intrinsic::num_intrinsics)
4653 return Intrinsic::not_intrinsic;
4658 // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
4659 // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
4660 // BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
4661 // Also, logical shift right -> sri, with the same structure.
4662 static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
4663 EVT VT = N->getValueType(0);
4670 // Is the first op an AND?
4671 const SDValue And = N->getOperand(0);
4672 if (And.getOpcode() != ISD::AND)
4675 // Is the second op an shl or lshr?
4676 SDValue Shift = N->getOperand(1);
4677 // This will have been turned into: ARM64ISD::VSHL vector, #shift
4678 // or ARM64ISD::VLSHR vector, #shift
4679 unsigned ShiftOpc = Shift.getOpcode();
4680 if ((ShiftOpc != ARM64ISD::VSHL && ShiftOpc != ARM64ISD::VLSHR))
4682 bool IsShiftRight = ShiftOpc == ARM64ISD::VLSHR;
4684 // Is the shift amount constant?
4685 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
4689 // Is the and mask vector all constant?
4691 if (!isAllConstantBuildVector(And.getOperand(1), C1))
4694 // Is C1 == ~C2, taking into account how much one can shift elements of a
4696 uint64_t C2 = C2node->getZExtValue();
4697 unsigned ElemSizeInBits = VT.getVectorElementType().getSizeInBits();
4698 if (C2 > ElemSizeInBits)
4700 unsigned ElemMask = (1 << ElemSizeInBits) - 1;
4701 if ((C1 & ElemMask) != (~C2 & ElemMask))
4704 SDValue X = And.getOperand(0);
4705 SDValue Y = Shift.getOperand(0);
4708 IsShiftRight ? Intrinsic::arm64_neon_vsri : Intrinsic::arm64_neon_vsli;
4710 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
4711 DAG.getConstant(Intrin, MVT::i32), X, Y, Shift.getOperand(1));
4713 DEBUG(dbgs() << "arm64-lower: transformed: \n");
4714 DEBUG(N->dump(&DAG));
4715 DEBUG(dbgs() << "into: \n");
4716 DEBUG(ResultSLI->dump(&DAG));
4722 SDValue ARM64TargetLowering::LowerVectorOR(SDValue Op,
4723 SelectionDAG &DAG) const {
4724 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
4725 if (EnableARM64SlrGeneration) {
4726 SDValue Res = tryLowerToSLI(Op.getNode(), DAG);
4731 BuildVectorSDNode *BVN =
4732 dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
4733 SDValue LHS = Op.getOperand(1);
4735 EVT VT = Op.getValueType();
4737 // OR commutes, so try swapping the operands.
4739 LHS = Op.getOperand(0);
4740 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
4745 APInt CnstBits(VT.getSizeInBits(), 0);
4746 APInt UndefBits(VT.getSizeInBits(), 0);
4747 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
4748 // We make use of a little bit of goto ickiness in order to avoid having to
4749 // duplicate the immediate matching logic for the undef toggled case.
4750 bool SecondTry = false;
4753 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
4754 CnstBits = CnstBits.zextOrTrunc(64);
4755 uint64_t CnstVal = CnstBits.getZExtValue();
4757 if (ARM64_AM::isAdvSIMDModImmType1(CnstVal)) {
4758 CnstVal = ARM64_AM::encodeAdvSIMDModImmType1(CnstVal);
4759 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4760 SDValue Mov = DAG.getNode(ARM64ISD::ORRi, dl, MovTy, LHS,
4761 DAG.getConstant(CnstVal, MVT::i32),
4762 DAG.getConstant(0, MVT::i32));
4763 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4766 if (ARM64_AM::isAdvSIMDModImmType2(CnstVal)) {
4767 CnstVal = ARM64_AM::encodeAdvSIMDModImmType2(CnstVal);
4768 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4769 SDValue Mov = DAG.getNode(ARM64ISD::ORRi, dl, MovTy, LHS,
4770 DAG.getConstant(CnstVal, MVT::i32),
4771 DAG.getConstant(8, MVT::i32));
4772 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4775 if (ARM64_AM::isAdvSIMDModImmType3(CnstVal)) {
4776 CnstVal = ARM64_AM::encodeAdvSIMDModImmType3(CnstVal);
4777 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4778 SDValue Mov = DAG.getNode(ARM64ISD::ORRi, dl, MovTy, LHS,
4779 DAG.getConstant(CnstVal, MVT::i32),
4780 DAG.getConstant(16, MVT::i32));
4781 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4784 if (ARM64_AM::isAdvSIMDModImmType4(CnstVal)) {
4785 CnstVal = ARM64_AM::encodeAdvSIMDModImmType4(CnstVal);
4786 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4787 SDValue Mov = DAG.getNode(ARM64ISD::ORRi, dl, MovTy, LHS,
4788 DAG.getConstant(CnstVal, MVT::i32),
4789 DAG.getConstant(24, MVT::i32));
4790 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4793 if (ARM64_AM::isAdvSIMDModImmType5(CnstVal)) {
4794 CnstVal = ARM64_AM::encodeAdvSIMDModImmType5(CnstVal);
4795 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
4796 SDValue Mov = DAG.getNode(ARM64ISD::ORRi, dl, MovTy, LHS,
4797 DAG.getConstant(CnstVal, MVT::i32),
4798 DAG.getConstant(0, MVT::i32));
4799 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4802 if (ARM64_AM::isAdvSIMDModImmType6(CnstVal)) {
4803 CnstVal = ARM64_AM::encodeAdvSIMDModImmType6(CnstVal);
4804 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
4805 SDValue Mov = DAG.getNode(ARM64ISD::ORRi, dl, MovTy, LHS,
4806 DAG.getConstant(CnstVal, MVT::i32),
4807 DAG.getConstant(8, MVT::i32));
4808 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4815 CnstBits = UndefBits;
4819 // We can always fall back to a non-immediate OR.
4824 SDValue ARM64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
4825 SelectionDAG &DAG) const {
4826 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
4828 EVT VT = Op.getValueType();
4830 APInt CnstBits(VT.getSizeInBits(), 0);
4831 APInt UndefBits(VT.getSizeInBits(), 0);
4832 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
4833 // We make use of a little bit of goto ickiness in order to avoid having to
4834 // duplicate the immediate matching logic for the undef toggled case.
4835 bool SecondTry = false;
4838 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
4839 CnstBits = CnstBits.zextOrTrunc(64);
4840 uint64_t CnstVal = CnstBits.getZExtValue();
4842 // Certain magic vector constants (used to express things like NOT
4843 // and NEG) are passed through unmodified. This allows codegen patterns
4844 // for these operations to match. Special-purpose patterns will lower
4845 // these immediates to MOVIs if it proves necessary.
4846 if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL))
4849 // The many faces of MOVI...
4850 if (ARM64_AM::isAdvSIMDModImmType10(CnstVal)) {
4851 CnstVal = ARM64_AM::encodeAdvSIMDModImmType10(CnstVal);
4852 if (VT.getSizeInBits() == 128) {
4853 SDValue Mov = DAG.getNode(ARM64ISD::MOVIedit, dl, MVT::v2i64,
4854 DAG.getConstant(CnstVal, MVT::i32));
4855 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4858 // Support the V64 version via subregister insertion.
4859 SDValue Mov = DAG.getNode(ARM64ISD::MOVIedit, dl, MVT::f64,
4860 DAG.getConstant(CnstVal, MVT::i32));
4861 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4864 if (ARM64_AM::isAdvSIMDModImmType1(CnstVal)) {
4865 CnstVal = ARM64_AM::encodeAdvSIMDModImmType1(CnstVal);
4866 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4867 SDValue Mov = DAG.getNode(ARM64ISD::MOVIshift, dl, MovTy,
4868 DAG.getConstant(CnstVal, MVT::i32),
4869 DAG.getConstant(0, MVT::i32));
4870 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4873 if (ARM64_AM::isAdvSIMDModImmType2(CnstVal)) {
4874 CnstVal = ARM64_AM::encodeAdvSIMDModImmType2(CnstVal);
4875 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4876 SDValue Mov = DAG.getNode(ARM64ISD::MOVIshift, dl, MovTy,
4877 DAG.getConstant(CnstVal, MVT::i32),
4878 DAG.getConstant(8, MVT::i32));
4879 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4882 if (ARM64_AM::isAdvSIMDModImmType3(CnstVal)) {
4883 CnstVal = ARM64_AM::encodeAdvSIMDModImmType3(CnstVal);
4884 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4885 SDValue Mov = DAG.getNode(ARM64ISD::MOVIshift, dl, MovTy,
4886 DAG.getConstant(CnstVal, MVT::i32),
4887 DAG.getConstant(16, MVT::i32));
4888 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4891 if (ARM64_AM::isAdvSIMDModImmType4(CnstVal)) {
4892 CnstVal = ARM64_AM::encodeAdvSIMDModImmType4(CnstVal);
4893 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4894 SDValue Mov = DAG.getNode(ARM64ISD::MOVIshift, dl, MovTy,
4895 DAG.getConstant(CnstVal, MVT::i32),
4896 DAG.getConstant(24, MVT::i32));
4897 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4900 if (ARM64_AM::isAdvSIMDModImmType5(CnstVal)) {
4901 CnstVal = ARM64_AM::encodeAdvSIMDModImmType5(CnstVal);
4902 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
4903 SDValue Mov = DAG.getNode(ARM64ISD::MOVIshift, dl, MovTy,
4904 DAG.getConstant(CnstVal, MVT::i32),
4905 DAG.getConstant(0, MVT::i32));
4906 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4909 if (ARM64_AM::isAdvSIMDModImmType6(CnstVal)) {
4910 CnstVal = ARM64_AM::encodeAdvSIMDModImmType6(CnstVal);
4911 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
4912 SDValue Mov = DAG.getNode(ARM64ISD::MOVIshift, dl, MovTy,
4913 DAG.getConstant(CnstVal, MVT::i32),
4914 DAG.getConstant(8, MVT::i32));
4915 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4918 if (ARM64_AM::isAdvSIMDModImmType7(CnstVal)) {
4919 CnstVal = ARM64_AM::encodeAdvSIMDModImmType7(CnstVal);
4920 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4921 SDValue Mov = DAG.getNode(ARM64ISD::MOVImsl, dl, MovTy,
4922 DAG.getConstant(CnstVal, MVT::i32),
4923 DAG.getConstant(264, MVT::i32));
4924 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4927 if (ARM64_AM::isAdvSIMDModImmType8(CnstVal)) {
4928 CnstVal = ARM64_AM::encodeAdvSIMDModImmType8(CnstVal);
4929 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4930 SDValue Mov = DAG.getNode(ARM64ISD::MOVImsl, dl, MovTy,
4931 DAG.getConstant(CnstVal, MVT::i32),
4932 DAG.getConstant(272, MVT::i32));
4933 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4936 if (ARM64_AM::isAdvSIMDModImmType9(CnstVal)) {
4937 CnstVal = ARM64_AM::encodeAdvSIMDModImmType9(CnstVal);
4938 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
4939 SDValue Mov = DAG.getNode(ARM64ISD::MOVI, dl, MovTy,
4940 DAG.getConstant(CnstVal, MVT::i32));
4941 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4944 // The few faces of FMOV...
4945 if (ARM64_AM::isAdvSIMDModImmType11(CnstVal)) {
4946 CnstVal = ARM64_AM::encodeAdvSIMDModImmType11(CnstVal);
4947 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32;
4948 SDValue Mov = DAG.getNode(ARM64ISD::FMOV, dl, MovTy,
4949 DAG.getConstant(CnstVal, MVT::i32));
4950 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4953 if (ARM64_AM::isAdvSIMDModImmType12(CnstVal) &&
4954 VT.getSizeInBits() == 128) {
4955 CnstVal = ARM64_AM::encodeAdvSIMDModImmType12(CnstVal);
4956 SDValue Mov = DAG.getNode(ARM64ISD::FMOV, dl, MVT::v2f64,
4957 DAG.getConstant(CnstVal, MVT::i32));
4958 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4961 // The many faces of MVNI...
4963 if (ARM64_AM::isAdvSIMDModImmType1(CnstVal)) {
4964 CnstVal = ARM64_AM::encodeAdvSIMDModImmType1(CnstVal);
4965 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4966 SDValue Mov = DAG.getNode(ARM64ISD::MVNIshift, dl, MovTy,
4967 DAG.getConstant(CnstVal, MVT::i32),
4968 DAG.getConstant(0, MVT::i32));
4969 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4972 if (ARM64_AM::isAdvSIMDModImmType2(CnstVal)) {
4973 CnstVal = ARM64_AM::encodeAdvSIMDModImmType2(CnstVal);
4974 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4975 SDValue Mov = DAG.getNode(ARM64ISD::MVNIshift, dl, MovTy,
4976 DAG.getConstant(CnstVal, MVT::i32),
4977 DAG.getConstant(8, MVT::i32));
4978 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4981 if (ARM64_AM::isAdvSIMDModImmType3(CnstVal)) {
4982 CnstVal = ARM64_AM::encodeAdvSIMDModImmType3(CnstVal);
4983 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4984 SDValue Mov = DAG.getNode(ARM64ISD::MVNIshift, dl, MovTy,
4985 DAG.getConstant(CnstVal, MVT::i32),
4986 DAG.getConstant(16, MVT::i32));
4987 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4990 if (ARM64_AM::isAdvSIMDModImmType4(CnstVal)) {
4991 CnstVal = ARM64_AM::encodeAdvSIMDModImmType4(CnstVal);
4992 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
4993 SDValue Mov = DAG.getNode(ARM64ISD::MVNIshift, dl, MovTy,
4994 DAG.getConstant(CnstVal, MVT::i32),
4995 DAG.getConstant(24, MVT::i32));
4996 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
4999 if (ARM64_AM::isAdvSIMDModImmType5(CnstVal)) {
5000 CnstVal = ARM64_AM::encodeAdvSIMDModImmType5(CnstVal);
5001 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5002 SDValue Mov = DAG.getNode(ARM64ISD::MVNIshift, dl, MovTy,
5003 DAG.getConstant(CnstVal, MVT::i32),
5004 DAG.getConstant(0, MVT::i32));
5005 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5008 if (ARM64_AM::isAdvSIMDModImmType6(CnstVal)) {
5009 CnstVal = ARM64_AM::encodeAdvSIMDModImmType6(CnstVal);
5010 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5011 SDValue Mov = DAG.getNode(ARM64ISD::MVNIshift, dl, MovTy,
5012 DAG.getConstant(CnstVal, MVT::i32),
5013 DAG.getConstant(8, MVT::i32));
5014 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5017 if (ARM64_AM::isAdvSIMDModImmType7(CnstVal)) {
5018 CnstVal = ARM64_AM::encodeAdvSIMDModImmType7(CnstVal);
5019 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5020 SDValue Mov = DAG.getNode(ARM64ISD::MVNImsl, dl, MovTy,
5021 DAG.getConstant(CnstVal, MVT::i32),
5022 DAG.getConstant(264, MVT::i32));
5023 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5026 if (ARM64_AM::isAdvSIMDModImmType8(CnstVal)) {
5027 CnstVal = ARM64_AM::encodeAdvSIMDModImmType8(CnstVal);
5028 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5029 SDValue Mov = DAG.getNode(ARM64ISD::MVNImsl, dl, MovTy,
5030 DAG.getConstant(CnstVal, MVT::i32),
5031 DAG.getConstant(272, MVT::i32));
5032 return DAG.getNode(ISD::BITCAST, dl, VT, Mov);
5039 CnstBits = UndefBits;
5044 // Scan through the operands to find some interesting properties we can
5046 // 1) If only one value is used, we can use a DUP, or
5047 // 2) if only the low element is not undef, we can just insert that, or
5048 // 3) if only one constant value is used (w/ some non-constant lanes),
5049 // we can splat the constant value into the whole vector then fill
5050 // in the non-constant lanes.
5051 // 4) FIXME: If different constant values are used, but we can intelligently
5052 // select the values we'll be overwriting for the non-constant
5053 // lanes such that we can directly materialize the vector
5054 // some other way (MOVI, e.g.), we can be sneaky.
5055 unsigned NumElts = VT.getVectorNumElements();
5056 bool isOnlyLowElement = true;
5057 bool usesOnlyOneValue = true;
5058 bool usesOnlyOneConstantValue = true;
5059 bool isConstant = true;
5060 unsigned NumConstantLanes = 0;
5062 SDValue ConstantValue;
5063 for (unsigned i = 0; i < NumElts; ++i) {
5064 SDValue V = Op.getOperand(i);
5065 if (V.getOpcode() == ISD::UNDEF)
5068 isOnlyLowElement = false;
5069 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
5072 if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
5074 if (!ConstantValue.getNode())
5076 else if (ConstantValue != V)
5077 usesOnlyOneConstantValue = false;
5080 if (!Value.getNode())
5082 else if (V != Value)
5083 usesOnlyOneValue = false;
5086 if (!Value.getNode())
5087 return DAG.getUNDEF(VT);
5089 if (isOnlyLowElement)
5090 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
5092 // Use DUP for non-constant splats. For f32 constant splats, reduce to
5093 // i32 and try again.
5094 if (usesOnlyOneValue) {
5096 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5097 Value.getValueType() != VT)
5098 return DAG.getNode(ARM64ISD::DUP, dl, VT, Value);
5100 // This is actually a DUPLANExx operation, which keeps everything vectory.
5102 // DUPLANE works on 128-bit vectors, widen it if necessary.
5103 SDValue Lane = Value.getOperand(1);
5104 Value = Value.getOperand(0);
5105 if (Value.getValueType().getSizeInBits() == 64)
5106 Value = WidenVector(Value, DAG);
5108 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
5109 return DAG.getNode(Opcode, dl, VT, Value, Lane);
5112 if (VT.getVectorElementType().isFloatingPoint()) {
5113 SmallVector<SDValue, 8> Ops;
5115 (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
5116 for (unsigned i = 0; i < NumElts; ++i)
5117 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
5118 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
5119 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], NumElts);
5120 Val = LowerBUILD_VECTOR(Val, DAG);
5122 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
5126 // If there was only one constant value used and for more than one lane,
5127 // start by splatting that value, then replace the non-constant lanes. This
5128 // is better than the default, which will perform a separate initialization
5130 if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
5131 SDValue Val = DAG.getNode(ARM64ISD::DUP, dl, VT, ConstantValue);
5132 // Now insert the non-constant lanes.
5133 for (unsigned i = 0; i < NumElts; ++i) {
5134 SDValue V = Op.getOperand(i);
5135 SDValue LaneIdx = DAG.getConstant(i, MVT::i64);
5136 if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) {
5137 // Note that type legalization likely mucked about with the VT of the
5138 // source operand, so we may have to convert it here before inserting.
5139 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
5145 // If all elements are constants and the case above didn't get hit, fall back
5146 // to the default expansion, which will generate a load from the constant
5151 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
5153 SDValue shuffle = ReconstructShuffle(Op, DAG);
5154 if (shuffle != SDValue())
5158 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
5159 // know the default expansion would otherwise fall back on something even
5160 // worse. For a vector with one or two non-undef values, that's
5161 // scalar_to_vector for the elements followed by a shuffle (provided the
5162 // shuffle is valid for the target) and materialization element by element
5163 // on the stack followed by a load for everything else.
5164 if (!isConstant && !usesOnlyOneValue) {
5165 SDValue Vec = DAG.getUNDEF(VT);
5166 SDValue Op0 = Op.getOperand(0);
5167 unsigned ElemSize = VT.getVectorElementType().getSizeInBits();
5169 // For 32 and 64 bit types, use INSERT_SUBREG for lane zero to
5170 // a) Avoid a RMW dependency on the full vector register, and
5171 // b) Allow the register coalescer to fold away the copy if the
5172 // value is already in an S or D register.
5173 if (Op0.getOpcode() != ISD::UNDEF && (ElemSize == 32 || ElemSize == 64)) {
5174 unsigned SubIdx = ElemSize == 32 ? ARM64::ssub : ARM64::dsub;
5176 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl, VT, Vec, Op0,
5177 DAG.getTargetConstant(SubIdx, MVT::i32));
5178 Vec = SDValue(N, 0);
5181 for (; i < NumElts; ++i) {
5182 SDValue V = Op.getOperand(i);
5183 if (V.getOpcode() == ISD::UNDEF)
5185 SDValue LaneIdx = DAG.getConstant(i, MVT::i64);
5186 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
5191 // Just use the default expansion. We failed to find a better alternative.
5195 SDValue ARM64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
5196 SelectionDAG &DAG) const {
5197 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
5199 // Check for non-constant lane.
5200 if (!isa<ConstantSDNode>(Op.getOperand(2)))
5203 EVT VT = Op.getOperand(0).getValueType();
5205 // Insertion/extraction are legal for V128 types.
5206 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
5207 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64)
5210 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
5211 VT != MVT::v1i64 && VT != MVT::v2f32)
5214 // For V64 types, we perform insertion by expanding the value
5215 // to a V128 type and perform the insertion on that.
5217 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
5218 EVT WideTy = WideVec.getValueType();
5220 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
5221 Op.getOperand(1), Op.getOperand(2));
5222 // Re-narrow the resultant vector.
5223 return NarrowVector(Node, DAG);
5226 SDValue ARM64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
5227 SelectionDAG &DAG) const {
5228 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
5230 // Check for non-constant lane.
5231 if (!isa<ConstantSDNode>(Op.getOperand(1)))
5234 EVT VT = Op.getOperand(0).getValueType();
5236 // Insertion/extraction are legal for V128 types.
5237 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
5238 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64)
5241 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
5242 VT != MVT::v1i64 && VT != MVT::v2f32)
5245 // For V64 types, we perform extraction by expanding the value
5246 // to a V128 type and perform the extraction on that.
5248 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
5249 EVT WideTy = WideVec.getValueType();
5251 EVT ExtrTy = WideTy.getVectorElementType();
5252 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
5255 // For extractions, we just return the result directly.
5256 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
5260 SDValue ARM64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
5261 SelectionDAG &DAG) const {
5262 EVT VT = Op.getOperand(0).getValueType();
5268 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5271 unsigned Val = Cst->getZExtValue();
5273 unsigned Size = Op.getValueType().getSizeInBits();
5277 return DAG.getTargetExtractSubreg(ARM64::bsub, dl, Op.getValueType(),
5280 return DAG.getTargetExtractSubreg(ARM64::hsub, dl, Op.getValueType(),
5283 return DAG.getTargetExtractSubreg(ARM64::ssub, dl, Op.getValueType(),
5286 return DAG.getTargetExtractSubreg(ARM64::dsub, dl, Op.getValueType(),
5289 llvm_unreachable("Unexpected vector type in extract_subvector!");
5292 // If this is extracting the upper 64-bits of a 128-bit vector, we match
5294 if (Size == 64 && Val * VT.getVectorElementType().getSizeInBits() == 64)
5300 bool ARM64TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
5302 if (VT.getVectorNumElements() == 4 &&
5303 (VT.is128BitVector() || VT.is64BitVector())) {
5304 unsigned PFIndexes[4];
5305 for (unsigned i = 0; i != 4; ++i) {
5309 PFIndexes[i] = M[i];
5312 // Compute the index in the perfect shuffle table.
5313 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
5314 PFIndexes[2] * 9 + PFIndexes[3];
5315 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5316 unsigned Cost = (PFEntry >> 30);
5324 unsigned DummyUnsigned;
5326 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
5327 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
5328 isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
5329 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
5330 isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
5331 isZIPMask(M, VT, DummyUnsigned) ||
5332 isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
5333 isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
5334 isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
5335 isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
5336 isConcatMask(M, VT, VT.getSizeInBits() == 128));
5339 /// getVShiftImm - Check if this is a valid build_vector for the immediate
5340 /// operand of a vector shift operation, where all the elements of the
5341 /// build_vector must have the same constant integer value.
5342 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
5343 // Ignore bit_converts.
5344 while (Op.getOpcode() == ISD::BITCAST)
5345 Op = Op.getOperand(0);
5346 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
5347 APInt SplatBits, SplatUndef;
5348 unsigned SplatBitSize;
5350 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
5351 HasAnyUndefs, ElementBits) ||
5352 SplatBitSize > ElementBits)
5354 Cnt = SplatBits.getSExtValue();
5358 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
5359 /// operand of a vector shift left operation. That value must be in the range:
5360 /// 0 <= Value < ElementBits for a left shift; or
5361 /// 0 <= Value <= ElementBits for a long left shift.
5362 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
5363 assert(VT.isVector() && "vector shift count is not a vector type");
5364 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
5365 if (!getVShiftImm(Op, ElementBits, Cnt))
5367 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
5370 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
5371 /// operand of a vector shift right operation. For a shift opcode, the value
5372 /// is positive, but for an intrinsic the value count must be negative. The
5373 /// absolute value must be in the range:
5374 /// 1 <= |Value| <= ElementBits for a right shift; or
5375 /// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
5376 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
5378 assert(VT.isVector() && "vector shift count is not a vector type");
5379 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
5380 if (!getVShiftImm(Op, ElementBits, Cnt))
5384 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
5387 SDValue ARM64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
5388 SelectionDAG &DAG) const {
5389 EVT VT = Op.getValueType();
5393 if (!Op.getOperand(1).getValueType().isVector())
5395 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
5397 switch (Op.getOpcode()) {
5399 llvm_unreachable("unexpected shift opcode");
5402 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
5403 return DAG.getNode(ARM64ISD::VSHL, SDLoc(Op), VT, Op.getOperand(0),
5404 DAG.getConstant(Cnt, MVT::i32));
5405 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
5406 DAG.getConstant(Intrinsic::arm64_neon_ushl, MVT::i32),
5407 Op.getOperand(0), Op.getOperand(1));
5410 // Right shift immediate
5411 if (isVShiftRImm(Op.getOperand(1), VT, false, false, Cnt) &&
5414 (Op.getOpcode() == ISD::SRA) ? ARM64ISD::VASHR : ARM64ISD::VLSHR;
5415 return DAG.getNode(Opc, SDLoc(Op), VT, Op.getOperand(0),
5416 DAG.getConstant(Cnt, MVT::i32));
5419 // Right shift register. Note, there is not a shift right register
5420 // instruction, but the shift left register instruction takes a signed
5421 // value, where negative numbers specify a right shift.
5422 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::arm64_neon_sshl
5423 : Intrinsic::arm64_neon_ushl;
5424 // negate the shift amount
5425 SDValue NegShift = DAG.getNode(ARM64ISD::NEG, DL, VT, Op.getOperand(1));
5426 SDValue NegShiftLeft =
5427 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
5428 DAG.getConstant(Opc, MVT::i32), Op.getOperand(0), NegShift);
5429 return NegShiftLeft;
5435 static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
5436 ARM64CC::CondCode CC, bool NoNans, EVT VT,
5437 SDLoc dl, SelectionDAG &DAG) {
5438 EVT SrcVT = LHS.getValueType();
5440 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
5441 APInt CnstBits(VT.getSizeInBits(), 0);
5442 APInt UndefBits(VT.getSizeInBits(), 0);
5443 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
5444 bool IsZero = IsCnst && (CnstBits == 0);
5446 if (SrcVT.getVectorElementType().isFloatingPoint()) {
5453 Fcmeq = DAG.getNode(ARM64ISD::FCMEQz, dl, VT, LHS);
5455 Fcmeq = DAG.getNode(ARM64ISD::FCMEQ, dl, VT, LHS, RHS);
5456 return DAG.getNode(ARM64ISD::NOT, dl, VT, Fcmeq);
5460 return DAG.getNode(ARM64ISD::FCMEQz, dl, VT, LHS);
5461 return DAG.getNode(ARM64ISD::FCMEQ, dl, VT, LHS, RHS);
5464 return DAG.getNode(ARM64ISD::FCMGEz, dl, VT, LHS);
5465 return DAG.getNode(ARM64ISD::FCMGE, dl, VT, LHS, RHS);
5468 return DAG.getNode(ARM64ISD::FCMGTz, dl, VT, LHS);
5469 return DAG.getNode(ARM64ISD::FCMGT, dl, VT, LHS, RHS);
5472 return DAG.getNode(ARM64ISD::FCMLEz, dl, VT, LHS);
5473 return DAG.getNode(ARM64ISD::FCMGE, dl, VT, RHS, LHS);
5477 // If we ignore NaNs then we can use to the MI implementation.
5481 return DAG.getNode(ARM64ISD::FCMLTz, dl, VT, LHS);
5482 return DAG.getNode(ARM64ISD::FCMGT, dl, VT, RHS, LHS);
5492 Cmeq = DAG.getNode(ARM64ISD::CMEQz, dl, VT, LHS);
5494 Cmeq = DAG.getNode(ARM64ISD::CMEQ, dl, VT, LHS, RHS);
5495 return DAG.getNode(ARM64ISD::NOT, dl, VT, Cmeq);
5499 return DAG.getNode(ARM64ISD::CMEQz, dl, VT, LHS);
5500 return DAG.getNode(ARM64ISD::CMEQ, dl, VT, LHS, RHS);
5503 return DAG.getNode(ARM64ISD::CMGEz, dl, VT, LHS);
5504 return DAG.getNode(ARM64ISD::CMGE, dl, VT, LHS, RHS);
5507 return DAG.getNode(ARM64ISD::CMGTz, dl, VT, LHS);
5508 return DAG.getNode(ARM64ISD::CMGT, dl, VT, LHS, RHS);
5511 return DAG.getNode(ARM64ISD::CMLEz, dl, VT, LHS);
5512 return DAG.getNode(ARM64ISD::CMGE, dl, VT, RHS, LHS);
5514 return DAG.getNode(ARM64ISD::CMHS, dl, VT, RHS, LHS);
5516 return DAG.getNode(ARM64ISD::CMHI, dl, VT, RHS, LHS);
5519 return DAG.getNode(ARM64ISD::CMLTz, dl, VT, LHS);
5520 return DAG.getNode(ARM64ISD::CMGT, dl, VT, RHS, LHS);
5522 return DAG.getNode(ARM64ISD::CMHI, dl, VT, LHS, RHS);
5524 return DAG.getNode(ARM64ISD::CMHS, dl, VT, LHS, RHS);
5528 SDValue ARM64TargetLowering::LowerVSETCC(SDValue Op, SelectionDAG &DAG) const {
5529 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
5530 SDValue LHS = Op.getOperand(0);
5531 SDValue RHS = Op.getOperand(1);
5534 if (LHS.getValueType().getVectorElementType().isInteger()) {
5535 assert(LHS.getValueType() == RHS.getValueType());
5536 ARM64CC::CondCode ARM64CC = changeIntCCToARM64CC(CC);
5537 return EmitVectorComparison(LHS, RHS, ARM64CC, false, Op.getValueType(), dl,
5541 assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
5542 LHS.getValueType().getVectorElementType() == MVT::f64);
5544 // Unfortunately, the mapping of LLVM FP CC's onto ARM64 CC's isn't totally
5545 // clean. Some of them require two branches to implement.
5546 ARM64CC::CondCode CC1, CC2;
5548 changeVectorFPCCToARM64CC(CC, CC1, CC2, ShouldInvert);
5550 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
5552 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, Op.getValueType(), dl, DAG);
5556 if (CC2 != ARM64CC::AL) {
5558 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, Op.getValueType(), dl, DAG);
5559 if (!Cmp2.getNode())
5562 Cmp = DAG.getNode(ISD::OR, dl, Cmp.getValueType(), Cmp, Cmp2);
5566 return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
5571 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
5572 /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
5573 /// specified in the intrinsic calls.
5574 bool ARM64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
5576 unsigned Intrinsic) const {
5577 switch (Intrinsic) {
5578 case Intrinsic::arm64_neon_ld2:
5579 case Intrinsic::arm64_neon_ld3:
5580 case Intrinsic::arm64_neon_ld4:
5581 case Intrinsic::arm64_neon_ld2lane:
5582 case Intrinsic::arm64_neon_ld3lane:
5583 case Intrinsic::arm64_neon_ld4lane:
5584 case Intrinsic::arm64_neon_ld2r:
5585 case Intrinsic::arm64_neon_ld3r:
5586 case Intrinsic::arm64_neon_ld4r: {
5587 Info.opc = ISD::INTRINSIC_W_CHAIN;
5588 // Conservatively set memVT to the entire set of vectors loaded.
5589 uint64_t NumElts = getDataLayout()->getTypeAllocSize(I.getType()) / 8;
5590 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
5591 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
5594 Info.vol = false; // volatile loads with NEON intrinsics not supported
5595 Info.readMem = true;
5596 Info.writeMem = false;
5599 case Intrinsic::arm64_neon_st2:
5600 case Intrinsic::arm64_neon_st3:
5601 case Intrinsic::arm64_neon_st4:
5602 case Intrinsic::arm64_neon_st2lane:
5603 case Intrinsic::arm64_neon_st3lane:
5604 case Intrinsic::arm64_neon_st4lane: {
5605 Info.opc = ISD::INTRINSIC_VOID;
5606 // Conservatively set memVT to the entire set of vectors stored.
5607 unsigned NumElts = 0;
5608 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
5609 Type *ArgTy = I.getArgOperand(ArgI)->getType();
5610 if (!ArgTy->isVectorTy())
5612 NumElts += getDataLayout()->getTypeAllocSize(ArgTy) / 8;
5614 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
5615 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
5618 Info.vol = false; // volatile stores with NEON intrinsics not supported
5619 Info.readMem = false;
5620 Info.writeMem = true;
5623 case Intrinsic::arm64_ldaxr:
5624 case Intrinsic::arm64_ldxr: {
5625 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
5626 Info.opc = ISD::INTRINSIC_W_CHAIN;
5627 Info.memVT = MVT::getVT(PtrTy->getElementType());
5628 Info.ptrVal = I.getArgOperand(0);
5630 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
5632 Info.readMem = true;
5633 Info.writeMem = false;
5636 case Intrinsic::arm64_stlxr:
5637 case Intrinsic::arm64_stxr: {
5638 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
5639 Info.opc = ISD::INTRINSIC_W_CHAIN;
5640 Info.memVT = MVT::getVT(PtrTy->getElementType());
5641 Info.ptrVal = I.getArgOperand(1);
5643 Info.align = getDataLayout()->getABITypeAlignment(PtrTy->getElementType());
5645 Info.readMem = false;
5646 Info.writeMem = true;
5649 case Intrinsic::arm64_ldaxp:
5650 case Intrinsic::arm64_ldxp: {
5651 Info.opc = ISD::INTRINSIC_W_CHAIN;
5652 Info.memVT = MVT::i128;
5653 Info.ptrVal = I.getArgOperand(0);
5657 Info.readMem = true;
5658 Info.writeMem = false;
5661 case Intrinsic::arm64_stlxp:
5662 case Intrinsic::arm64_stxp: {
5663 Info.opc = ISD::INTRINSIC_W_CHAIN;
5664 Info.memVT = MVT::i128;
5665 Info.ptrVal = I.getArgOperand(2);
5669 Info.readMem = false;
5670 Info.writeMem = true;
5680 // Truncations from 64-bit GPR to 32-bit GPR is free.
5681 bool ARM64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
5682 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
5684 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
5685 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
5686 if (NumBits1 <= NumBits2)
5690 bool ARM64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
5691 if (!VT1.isInteger() || !VT2.isInteger())
5693 unsigned NumBits1 = VT1.getSizeInBits();
5694 unsigned NumBits2 = VT2.getSizeInBits();
5695 if (NumBits1 <= NumBits2)
5700 // All 32-bit GPR operations implicitly zero the high-half of the corresponding
5702 bool ARM64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
5703 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
5705 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
5706 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
5707 if (NumBits1 == 32 && NumBits2 == 64)
5711 bool ARM64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
5712 if (!VT1.isInteger() || !VT2.isInteger())
5714 unsigned NumBits1 = VT1.getSizeInBits();
5715 unsigned NumBits2 = VT2.getSizeInBits();
5716 if (NumBits1 == 32 && NumBits2 == 64)
5721 bool ARM64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
5722 EVT VT1 = Val.getValueType();
5723 if (isZExtFree(VT1, VT2)) {
5727 if (Val.getOpcode() != ISD::LOAD)
5730 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
5731 return (VT1.isSimple() && VT1.isInteger() && VT2.isSimple() &&
5732 VT2.isInteger() && VT1.getSizeInBits() <= 32);
5735 bool ARM64TargetLowering::hasPairedLoad(Type *LoadedType,
5736 unsigned &RequiredAligment) const {
5737 if (!LoadedType->isIntegerTy() && !LoadedType->isFloatTy())
5739 // Cyclone supports unaligned accesses.
5740 RequiredAligment = 0;
5741 unsigned NumBits = LoadedType->getPrimitiveSizeInBits();
5742 return NumBits == 32 || NumBits == 64;
5745 bool ARM64TargetLowering::hasPairedLoad(EVT LoadedType,
5746 unsigned &RequiredAligment) const {
5747 if (!LoadedType.isSimple() ||
5748 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
5750 // Cyclone supports unaligned accesses.
5751 RequiredAligment = 0;
5752 unsigned NumBits = LoadedType.getSizeInBits();
5753 return NumBits == 32 || NumBits == 64;
5756 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
5757 unsigned AlignCheck) {
5758 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
5759 (DstAlign == 0 || DstAlign % AlignCheck == 0));
5762 EVT ARM64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
5763 unsigned SrcAlign, bool IsMemset,
5764 bool ZeroMemset, bool MemcpyStrSrc,
5765 MachineFunction &MF) const {
5766 // Don't use AdvSIMD to implement 16-byte memset. It would have taken one
5767 // instruction to materialize the v2i64 zero and one store (with restrictive
5768 // addressing mode). Just do two i64 store of zero-registers.
5770 const Function *F = MF.getFunction();
5771 if (!IsMemset && Size >= 16 &&
5772 !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
5773 Attribute::NoImplicitFloat) &&
5774 (memOpAlign(SrcAlign, DstAlign, 16) ||
5775 (allowsUnalignedMemoryAccesses(MVT::v2i64, 0, &Fast) && Fast)))
5778 return Size >= 8 ? MVT::i64 : MVT::i32;
5781 // 12-bit optionally shifted immediates are legal for adds.
5782 bool ARM64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
5783 if ((Immed >> 12) == 0 || ((Immed & 0xfff) == 0 && Immed >> 24 == 0))
5788 // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
5789 // immediates is the same as for an add or a sub.
5790 bool ARM64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
5793 return isLegalAddImmediate(Immed);
5796 /// isLegalAddressingMode - Return true if the addressing mode represented
5797 /// by AM is legal for this target, for a load/store of the specified type.
5798 bool ARM64TargetLowering::isLegalAddressingMode(const AddrMode &AM,
5800 // ARM64 has five basic addressing modes:
5802 // reg + 9-bit signed offset
5803 // reg + SIZE_IN_BYTES * 12-bit unsigned offset
5805 // reg + SIZE_IN_BYTES * reg
5807 // No global is ever allowed as a base.
5811 // No reg+reg+imm addressing.
5812 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
5815 // check reg + imm case:
5816 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
5817 uint64_t NumBytes = 0;
5818 if (Ty->isSized()) {
5819 uint64_t NumBits = getDataLayout()->getTypeSizeInBits(Ty);
5820 NumBytes = NumBits / 8;
5821 if (!isPowerOf2_64(NumBits))
5826 int64_t Offset = AM.BaseOffs;
5828 // 9-bit signed offset
5829 if (Offset >= -(1LL << 9) && Offset <= (1LL << 9) - 1)
5832 // 12-bit unsigned offset
5833 unsigned shift = Log2_64(NumBytes);
5834 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
5835 // Must be a multiple of NumBytes (NumBytes is a power of 2)
5836 (Offset >> shift) << shift == Offset)
5841 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
5843 if (!AM.Scale || AM.Scale == 1 ||
5844 (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes))
5849 int ARM64TargetLowering::getScalingFactorCost(const AddrMode &AM,
5851 // Scaling factors are not free at all.
5852 // Operands | Rt Latency
5853 // -------------------------------------------
5855 // -------------------------------------------
5856 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5
5857 // Rt, [Xn, Wm, <extend> #imm] |
5858 if (isLegalAddressingMode(AM, Ty))
5859 // Scale represents reg2 * scale, thus account for 1 if
5860 // it is not equal to 0 or 1.
5861 return AM.Scale != 0 && AM.Scale != 1;
5865 bool ARM64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
5866 VT = VT.getScalarType();
5871 switch (VT.getSimpleVT().SimpleTy) {
5883 ARM64TargetLowering::getScratchRegisters(CallingConv::ID) const {
5884 // LR is a callee-save register, but we must treat it as clobbered by any call
5885 // site. Hence we include LR in the scratch registers, which are in turn added
5886 // as implicit-defs for stackmaps and patchpoints.
5887 static const MCPhysReg ScratchRegs[] = {
5888 ARM64::X16, ARM64::X17, ARM64::LR, 0
5893 bool ARM64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
5895 assert(Ty->isIntegerTy());
5897 unsigned BitSize = Ty->getPrimitiveSizeInBits();
5901 int64_t Val = Imm.getSExtValue();
5902 if (Val == 0 || ARM64_AM::isLogicalImmediate(Val, BitSize))
5905 if ((int64_t)Val < 0)
5908 Val &= (1LL << 32) - 1;
5910 unsigned LZ = countLeadingZeros((uint64_t)Val);
5911 unsigned Shift = (63 - LZ) / 16;
5912 // MOVZ is free so return true for one or fewer MOVK.
5913 return (Shift < 3) ? true : false;
5916 // Generate SUBS and CSEL for integer abs.
5917 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
5918 EVT VT = N->getValueType(0);
5920 SDValue N0 = N->getOperand(0);
5921 SDValue N1 = N->getOperand(1);
5924 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
5925 // and change it to SUB and CSEL.
5926 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
5927 N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
5928 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
5929 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
5930 if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
5931 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, VT),
5933 // Generate SUBS & CSEL.
5935 DAG.getNode(ARM64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
5936 N0.getOperand(0), DAG.getConstant(0, VT));
5937 return DAG.getNode(ARM64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
5938 DAG.getConstant(ARM64CC::PL, MVT::i32),
5939 SDValue(Cmp.getNode(), 1));
5944 // performXorCombine - Attempts to handle integer ABS.
5945 static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
5946 TargetLowering::DAGCombinerInfo &DCI,
5947 const ARM64Subtarget *Subtarget) {
5948 if (DCI.isBeforeLegalizeOps())
5951 return performIntegerAbsCombine(N, DAG);
5954 static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
5955 TargetLowering::DAGCombinerInfo &DCI,
5956 const ARM64Subtarget *Subtarget) {
5957 if (DCI.isBeforeLegalizeOps())
5960 // Multiplication of a power of two plus/minus one can be done more
5961 // cheaply as as shift+add/sub. For now, this is true unilaterally. If
5962 // future CPUs have a cheaper MADD instruction, this may need to be
5963 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
5964 // 64-bit is 5 cycles, so this is always a win.
5965 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
5966 APInt Value = C->getAPIntValue();
5967 EVT VT = N->getValueType(0);
5968 APInt VP1 = Value + 1;
5969 if (VP1.isPowerOf2()) {
5970 // Multiplying by one less than a power of two, replace with a shift
5972 SDValue ShiftedVal =
5973 DAG.getNode(ISD::SHL, SDLoc(N), VT, N->getOperand(0),
5974 DAG.getConstant(VP1.logBase2(), MVT::i64));
5975 return DAG.getNode(ISD::SUB, SDLoc(N), VT, ShiftedVal, N->getOperand(0));
5977 APInt VM1 = Value - 1;
5978 if (VM1.isPowerOf2()) {
5979 // Multiplying by one more than a power of two, replace with a shift
5981 SDValue ShiftedVal =
5982 DAG.getNode(ISD::SHL, SDLoc(N), VT, N->getOperand(0),
5983 DAG.getConstant(VM1.logBase2(), MVT::i64));
5984 return DAG.getNode(ISD::ADD, SDLoc(N), VT, ShiftedVal, N->getOperand(0));
5990 static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG) {
5991 EVT VT = N->getValueType(0);
5992 if (VT != MVT::f32 && VT != MVT::f64)
5994 // Only optimize when the source and destination types have the same width.
5995 if (VT.getSizeInBits() != N->getOperand(0).getValueType().getSizeInBits())
5998 // If the result of an integer load is only used by an integer-to-float
5999 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
6000 // This eliminates an "integer-to-vector-move UOP and improve throughput.
6001 SDValue N0 = N->getOperand(0);
6002 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6003 // Do not change the width of a volatile load.
6004 !cast<LoadSDNode>(N0)->isVolatile()) {
6005 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6006 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
6007 LN0->getPointerInfo(), LN0->isVolatile(),
6008 LN0->isNonTemporal(), LN0->isInvariant(),
6009 LN0->getAlignment());
6011 // Make sure successors of the original load stay after it by updating them
6012 // to use the new Chain.
6013 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
6016 (N->getOpcode() == ISD::SINT_TO_FP) ? ARM64ISD::SITOF : ARM64ISD::UITOF;
6017 return DAG.getNode(Opcode, SDLoc(N), VT, Load);
6023 /// An EXTR instruction is made up of two shifts, ORed together. This helper
6024 /// searches for and classifies those shifts.
6025 static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
6027 if (N.getOpcode() == ISD::SHL)
6029 else if (N.getOpcode() == ISD::SRL)
6034 if (!isa<ConstantSDNode>(N.getOperand(1)))
6037 ShiftAmount = N->getConstantOperandVal(1);
6038 Src = N->getOperand(0);
6042 /// EXTR instruction extracts a contiguous chunk of bits from two existing
6043 /// registers viewed as a high/low pair. This function looks for the pattern:
6044 /// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an
6045 /// EXTR. Can't quite be done in TableGen because the two immediates aren't
6047 static SDValue tryCombineToEXTR(SDNode *N,
6048 TargetLowering::DAGCombinerInfo &DCI) {
6049 SelectionDAG &DAG = DCI.DAG;
6051 EVT VT = N->getValueType(0);
6053 assert(N->getOpcode() == ISD::OR && "Unexpected root");
6055 if (VT != MVT::i32 && VT != MVT::i64)
6059 uint32_t ShiftLHS = 0;
6061 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
6065 uint32_t ShiftRHS = 0;
6067 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
6070 // If they're both trying to come from the high part of the register, they're
6071 // not really an EXTR.
6072 if (LHSFromHi == RHSFromHi)
6075 if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
6079 std::swap(LHS, RHS);
6080 std::swap(ShiftLHS, ShiftRHS);
6083 return DAG.getNode(ARM64ISD::EXTR, DL, VT, LHS, RHS,
6084 DAG.getConstant(ShiftRHS, MVT::i64));
6087 static SDValue tryCombineToBSL(SDNode *N,
6088 TargetLowering::DAGCombinerInfo &DCI) {
6089 EVT VT = N->getValueType(0);
6090 SelectionDAG &DAG = DCI.DAG;
6096 SDValue N0 = N->getOperand(0);
6097 if (N0.getOpcode() != ISD::AND)
6100 SDValue N1 = N->getOperand(1);
6101 if (N1.getOpcode() != ISD::AND)
6104 // We only have to look for constant vectors here since the general, variable
6105 // case can be handled in TableGen.
6106 unsigned Bits = VT.getVectorElementType().getSizeInBits();
6107 uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
6108 for (int i = 1; i >= 0; --i)
6109 for (int j = 1; j >= 0; --j) {
6110 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
6111 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
6115 bool FoundMatch = true;
6116 for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
6117 ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
6118 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
6120 CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
6127 return DAG.getNode(ARM64ISD::BSL, DL, VT, SDValue(BVN0, 0),
6128 N0->getOperand(1 - i), N1->getOperand(1 - j));
6134 static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
6135 const ARM64Subtarget *Subtarget) {
6136 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
6137 if (!EnableARM64ExtrGeneration)
6139 SelectionDAG &DAG = DCI.DAG;
6140 EVT VT = N->getValueType(0);
6142 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
6145 SDValue Res = tryCombineToEXTR(N, DCI);
6149 Res = tryCombineToBSL(N, DCI);
6156 static SDValue performBitcastCombine(SDNode *N,
6157 TargetLowering::DAGCombinerInfo &DCI,
6158 SelectionDAG &DAG) {
6159 // Wait 'til after everything is legalized to try this. That way we have
6160 // legal vector types and such.
6161 if (DCI.isBeforeLegalizeOps())
6164 // Remove extraneous bitcasts around an extract_subvector.
6166 // (v4i16 (bitconvert
6167 // (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
6169 // (extract_subvector ((v8i16 ...), (i64 4)))
6171 // Only interested in 64-bit vectors as the ultimate result.
6172 EVT VT = N->getValueType(0);
6175 if (VT.getSimpleVT().getSizeInBits() != 64)
6177 // Is the operand an extract_subvector starting at the beginning or halfway
6178 // point of the vector? A low half may also come through as an
6179 // EXTRACT_SUBREG, so look for that, too.
6180 SDValue Op0 = N->getOperand(0);
6181 if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
6182 !(Op0->isMachineOpcode() &&
6183 Op0->getMachineOpcode() == ARM64::EXTRACT_SUBREG))
6185 uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
6186 if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
6187 if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
6189 } else if (Op0->getMachineOpcode() == ARM64::EXTRACT_SUBREG) {
6190 if (idx != ARM64::dsub)
6192 // The dsub reference is equivalent to a lane zero subvector reference.
6195 // Look through the bitcast of the input to the extract.
6196 if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
6198 SDValue Source = Op0->getOperand(0)->getOperand(0);
6199 // If the source type has twice the number of elements as our destination
6200 // type, we know this is an extract of the high or low half of the vector.
6201 EVT SVT = Source->getValueType(0);
6202 if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
6205 DEBUG(dbgs() << "arm64-lower: bitcast extract_subvector simplification\n");
6207 // Create the simplified form to just extract the low or high half of the
6208 // vector directly rather than bothering with the bitcasts.
6210 unsigned NumElements = VT.getVectorNumElements();
6212 SDValue HalfIdx = DAG.getConstant(NumElements, MVT::i64);
6213 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
6215 SDValue SubReg = DAG.getTargetConstant(ARM64::dsub, MVT::i32);
6216 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
6222 static SDValue performConcatVectorsCombine(SDNode *N,
6223 TargetLowering::DAGCombinerInfo &DCI,
6224 SelectionDAG &DAG) {
6225 // Wait 'til after everything is legalized to try this. That way we have
6226 // legal vector types and such.
6227 if (DCI.isBeforeLegalizeOps())
6231 EVT VT = N->getValueType(0);
6233 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
6234 // splat. The indexed instructions are going to be expecting a DUPLANE64, so
6235 // canonicalise to that.
6236 if (N->getOperand(0) == N->getOperand(1) && VT.getVectorNumElements() == 2) {
6237 assert(VT.getVectorElementType().getSizeInBits() == 64);
6238 return DAG.getNode(ARM64ISD::DUPLANE64, dl, VT,
6239 WidenVector(N->getOperand(0), DAG),
6240 DAG.getConstant(0, MVT::i64));
6243 // Canonicalise concat_vectors so that the right-hand vector has as few
6244 // bit-casts as possible before its real operation. The primary matching
6245 // destination for these operations will be the narrowing "2" instructions,
6246 // which depend on the operation being performed on this right-hand vector.
6248 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS))))
6250 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
6252 SDValue Op1 = N->getOperand(1);
6253 if (Op1->getOpcode() != ISD::BITCAST)
6255 SDValue RHS = Op1->getOperand(0);
6256 MVT RHSTy = RHS.getValueType().getSimpleVT();
6257 // If the RHS is not a vector, this is not the pattern we're looking for.
6258 if (!RHSTy.isVector())
6261 DEBUG(dbgs() << "arm64-lower: concat_vectors bitcast simplification\n");
6263 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
6264 RHSTy.getVectorNumElements() * 2);
6266 ISD::BITCAST, dl, VT,
6267 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
6268 DAG.getNode(ISD::BITCAST, dl, RHSTy, N->getOperand(0)), RHS));
6271 static SDValue tryCombineFixedPointConvert(SDNode *N,
6272 TargetLowering::DAGCombinerInfo &DCI,
6273 SelectionDAG &DAG) {
6274 // Wait 'til after everything is legalized to try this. That way we have
6275 // legal vector types and such.
6276 if (DCI.isBeforeLegalizeOps())
6278 // Transform a scalar conversion of a value from a lane extract into a
6279 // lane extract of a vector conversion. E.g., from foo1 to foo2:
6280 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
6281 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
6283 // The second form interacts better with instruction selection and the
6284 // register allocator to avoid cross-class register copies that aren't
6285 // coalescable due to a lane reference.
6287 // Check the operand and see if it originates from a lane extract.
6288 SDValue Op1 = N->getOperand(1);
6289 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
6290 // Yep, no additional predication needed. Perform the transform.
6291 SDValue IID = N->getOperand(0);
6292 SDValue Shift = N->getOperand(2);
6293 SDValue Vec = Op1.getOperand(0);
6294 SDValue Lane = Op1.getOperand(1);
6295 EVT ResTy = N->getValueType(0);
6299 // The vector width should be 128 bits by the time we get here, even
6300 // if it started as 64 bits (the extract_vector handling will have
6302 assert(Vec.getValueType().getSizeInBits() == 128 &&
6303 "unexpected vector size on extract_vector_elt!");
6304 if (Vec.getValueType() == MVT::v4i32)
6305 VecResTy = MVT::v4f32;
6306 else if (Vec.getValueType() == MVT::v2i64)
6307 VecResTy = MVT::v2f64;
6309 assert(0 && "unexpected vector type!");
6312 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
6313 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
6318 // AArch64 high-vector "long" operations are formed by performing the non-high
6319 // version on an extract_subvector of each operand which gets the high half:
6321 // (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
6323 // However, there are cases which don't have an extract_high explicitly, but
6324 // have another operation that can be made compatible with one for free. For
6327 // (dupv64 scalar) --> (extract_high (dup128 scalar))
6329 // This routine does the actual conversion of such DUPs, once outer routines
6330 // have determined that everything else is in order.
6331 static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
6332 // We can handle most types of duplicate, but the lane ones have an extra
6333 // operand saying *which* lane, so we need to know.
6335 switch (N.getOpcode()) {
6339 case ARM64ISD::DUPLANE8:
6340 case ARM64ISD::DUPLANE16:
6341 case ARM64ISD::DUPLANE32:
6342 case ARM64ISD::DUPLANE64:
6349 MVT NarrowTy = N.getSimpleValueType();
6350 if (!NarrowTy.is64BitVector())
6353 MVT ElementTy = NarrowTy.getVectorElementType();
6354 unsigned NumElems = NarrowTy.getVectorNumElements();
6355 MVT NewDUPVT = MVT::getVectorVT(ElementTy, NumElems * 2);
6359 NewDUP = DAG.getNode(N.getOpcode(), SDLoc(N), NewDUPVT, N.getOperand(0),
6362 NewDUP = DAG.getNode(ARM64ISD::DUP, SDLoc(N), NewDUPVT, N.getOperand(0));
6364 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N.getNode()), NarrowTy,
6365 NewDUP, DAG.getConstant(NumElems, MVT::i64));
6368 static bool isEssentiallyExtractSubvector(SDValue N) {
6369 if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
6372 return N.getOpcode() == ISD::BITCAST &&
6373 N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
6376 /// \brief Helper structure to keep track of ISD::SET_CC operands.
6377 struct GenericSetCCInfo {
6378 const SDValue *Opnd0;
6379 const SDValue *Opnd1;
6383 /// \brief Helper structure to keep track of a SET_CC lowered into ARM64 code.
6384 struct ARM64SetCCInfo {
6386 ARM64CC::CondCode CC;
6389 /// \brief Helper structure to keep track of SetCC information.
6391 GenericSetCCInfo Generic;
6392 ARM64SetCCInfo ARM64;
6395 /// \brief Helper structure to be able to read SetCC information.
6396 /// If set to true, IsARM64 field, Info is a ARM64SetCCInfo, otherwise Info is
6397 /// a GenericSetCCInfo.
6398 struct SetCCInfoAndKind {
6403 /// \brief Check whether or not \p Op is a SET_CC operation, either a generic or
6405 /// ARM64 lowered one.
6406 /// \p SetCCInfo is filled accordingly.
6407 /// \post SetCCInfo is meanginfull only when this function returns true.
6408 /// \return True when Op is a kind of SET_CC operation.
6409 static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
6410 // If this is a setcc, this is straight forward.
6411 if (Op.getOpcode() == ISD::SETCC) {
6412 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
6413 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
6414 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6415 SetCCInfo.IsARM64 = false;
6418 // Otherwise, check if this is a matching csel instruction.
6422 if (Op.getOpcode() != ARM64ISD::CSEL)
6424 // Set the information about the operands.
6425 // TODO: we want the operands of the Cmp not the csel
6426 SetCCInfo.Info.ARM64.Cmp = &Op.getOperand(3);
6427 SetCCInfo.IsARM64 = true;
6428 SetCCInfo.Info.ARM64.CC = static_cast<ARM64CC::CondCode>(
6429 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
6431 // Check that the operands matches the constraints:
6432 // (1) Both operands must be constants.
6433 // (2) One must be 1 and the other must be 0.
6434 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
6435 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6438 if (!TValue || !FValue)
6442 if (!TValue->isOne()) {
6443 // Update the comparison when we are interested in !cc.
6444 std::swap(TValue, FValue);
6445 SetCCInfo.Info.ARM64.CC =
6446 ARM64CC::getInvertedCondCode(SetCCInfo.Info.ARM64.CC);
6448 return TValue->isOne() && FValue->isNullValue();
6451 // The folding we want to perform is:
6452 // (add x, (setcc cc ...) )
6454 // (csel x, (add x, 1), !cc ...)
6456 // The latter will get matched to a CSINC instruction.
6457 static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
6458 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
6459 SDValue LHS = Op->getOperand(0);
6460 SDValue RHS = Op->getOperand(1);
6461 SetCCInfoAndKind InfoAndKind;
6463 // If neither operand is a SET_CC, give up.
6464 if (!isSetCC(LHS, InfoAndKind)) {
6465 std::swap(LHS, RHS);
6466 if (!isSetCC(LHS, InfoAndKind))
6470 // FIXME: This could be generatized to work for FP comparisons.
6471 EVT CmpVT = InfoAndKind.IsARM64
6472 ? InfoAndKind.Info.ARM64.Cmp->getOperand(0).getValueType()
6473 : InfoAndKind.Info.Generic.Opnd0->getValueType();
6474 if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
6480 if (InfoAndKind.IsARM64) {
6481 CCVal = DAG.getConstant(
6482 ARM64CC::getInvertedCondCode(InfoAndKind.Info.ARM64.CC), MVT::i32);
6483 Cmp = *InfoAndKind.Info.ARM64.Cmp;
6485 Cmp = getARM64Cmp(*InfoAndKind.Info.Generic.Opnd0,
6486 *InfoAndKind.Info.Generic.Opnd1,
6487 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
6490 EVT VT = Op->getValueType(0);
6491 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, VT));
6492 return DAG.getNode(ARM64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
6495 // The basic add/sub long vector instructions have variants with "2" on the end
6496 // which act on the high-half of their inputs. They are normally matched by
6499 // (add (zeroext (extract_high LHS)),
6500 // (zeroext (extract_high RHS)))
6501 // -> uaddl2 vD, vN, vM
6503 // However, if one of the extracts is something like a duplicate, this
6504 // instruction can still be used profitably. This function puts the DAG into a
6505 // more appropriate form for those patterns to trigger.
6506 static SDValue performAddSubLongCombine(SDNode *N,
6507 TargetLowering::DAGCombinerInfo &DCI,
6508 SelectionDAG &DAG) {
6509 if (DCI.isBeforeLegalizeOps())
6512 MVT VT = N->getSimpleValueType(0);
6513 if (!VT.is128BitVector()) {
6514 if (N->getOpcode() == ISD::ADD)
6515 return performSetccAddFolding(N, DAG);
6519 // Make sure both branches are extended in the same way.
6520 SDValue LHS = N->getOperand(0);
6521 SDValue RHS = N->getOperand(1);
6522 if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
6523 LHS.getOpcode() != ISD::SIGN_EXTEND) ||
6524 LHS.getOpcode() != RHS.getOpcode())
6527 unsigned ExtType = LHS.getOpcode();
6529 // It's not worth doing if at least one of the inputs isn't already an
6530 // extract, but we don't know which it'll be so we have to try both.
6531 if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
6532 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
6536 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
6537 } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
6538 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
6542 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
6545 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
6548 // Massage DAGs which we can use the high-half "long" operations on into
6549 // something isel will recognize better. E.g.
6551 // (arm64_neon_umull (extract_high vec) (dupv64 scalar)) -->
6552 // (arm64_neon_umull (extract_high (v2i64 vec)))
6553 // (extract_high (v2i64 (dup128 scalar)))))
6555 static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
6556 TargetLowering::DAGCombinerInfo &DCI,
6557 SelectionDAG &DAG) {
6558 if (DCI.isBeforeLegalizeOps())
6561 SDValue LHS = N->getOperand(1);
6562 SDValue RHS = N->getOperand(2);
6563 assert(LHS.getValueType().is64BitVector() &&
6564 RHS.getValueType().is64BitVector() &&
6565 "unexpected shape for long operation");
6567 // Either node could be a DUP, but it's not worth doing both of them (you'd
6568 // just as well use the non-high version) so look for a corresponding extract
6569 // operation on the other "wing".
6570 if (isEssentiallyExtractSubvector(LHS)) {
6571 RHS = tryExtendDUPToExtractHigh(RHS, DAG);
6574 } else if (isEssentiallyExtractSubvector(RHS)) {
6575 LHS = tryExtendDUPToExtractHigh(LHS, DAG);
6580 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
6581 N->getOperand(0), LHS, RHS);
6584 static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
6585 MVT ElemTy = N->getSimpleValueType(0).getScalarType();
6586 unsigned ElemBits = ElemTy.getSizeInBits();
6588 int64_t ShiftAmount;
6589 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
6590 APInt SplatValue, SplatUndef;
6591 unsigned SplatBitSize;
6593 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
6594 HasAnyUndefs, ElemBits) ||
6595 SplatBitSize != ElemBits)
6598 ShiftAmount = SplatValue.getSExtValue();
6599 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
6600 ShiftAmount = CVN->getSExtValue();
6608 llvm_unreachable("Unknown shift intrinsic");
6609 case Intrinsic::arm64_neon_sqshl:
6610 Opcode = ARM64ISD::SQSHL_I;
6611 IsRightShift = false;
6613 case Intrinsic::arm64_neon_uqshl:
6614 Opcode = ARM64ISD::UQSHL_I;
6615 IsRightShift = false;
6617 case Intrinsic::arm64_neon_srshl:
6618 Opcode = ARM64ISD::SRSHR_I;
6619 IsRightShift = true;
6621 case Intrinsic::arm64_neon_urshl:
6622 Opcode = ARM64ISD::URSHR_I;
6623 IsRightShift = true;
6625 case Intrinsic::arm64_neon_sqshlu:
6626 Opcode = ARM64ISD::SQSHLU_I;
6627 IsRightShift = false;
6631 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits)
6632 return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), N->getOperand(1),
6633 DAG.getConstant(-ShiftAmount, MVT::i32));
6634 else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount <= ElemBits)
6635 return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), N->getOperand(1),
6636 DAG.getConstant(ShiftAmount, MVT::i32));
6641 // The CRC32[BH] instructions ignore the high bits of their data operand. Since
6642 // the intrinsics must be legal and take an i32, this means there's almost
6643 // certainly going to be a zext in the DAG which we can eliminate.
6644 static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
6645 SDValue AndN = N->getOperand(2);
6646 if (AndN.getOpcode() != ISD::AND)
6649 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
6650 if (!CMask || CMask->getZExtValue() != Mask)
6653 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
6654 N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
6657 static SDValue performIntrinsicCombine(SDNode *N,
6658 TargetLowering::DAGCombinerInfo &DCI,
6659 const ARM64Subtarget *Subtarget) {
6660 SelectionDAG &DAG = DCI.DAG;
6661 unsigned IID = getIntrinsicID(N);
6665 case Intrinsic::arm64_neon_vcvtfxs2fp:
6666 case Intrinsic::arm64_neon_vcvtfxu2fp:
6667 return tryCombineFixedPointConvert(N, DCI, DAG);
6669 case Intrinsic::arm64_neon_fmax:
6670 return DAG.getNode(ARM64ISD::FMAX, SDLoc(N), N->getValueType(0),
6671 N->getOperand(1), N->getOperand(2));
6672 case Intrinsic::arm64_neon_fmin:
6673 return DAG.getNode(ARM64ISD::FMIN, SDLoc(N), N->getValueType(0),
6674 N->getOperand(1), N->getOperand(2));
6675 case Intrinsic::arm64_neon_smull:
6676 case Intrinsic::arm64_neon_umull:
6677 case Intrinsic::arm64_neon_pmull:
6678 case Intrinsic::arm64_neon_sqdmull:
6679 return tryCombineLongOpWithDup(IID, N, DCI, DAG);
6680 case Intrinsic::arm64_neon_sqshl:
6681 case Intrinsic::arm64_neon_uqshl:
6682 case Intrinsic::arm64_neon_sqshlu:
6683 case Intrinsic::arm64_neon_srshl:
6684 case Intrinsic::arm64_neon_urshl:
6685 return tryCombineShiftImm(IID, N, DAG);
6686 case Intrinsic::arm64_crc32b:
6687 case Intrinsic::arm64_crc32cb:
6688 return tryCombineCRC32(0xff, N, DAG);
6689 case Intrinsic::arm64_crc32h:
6690 case Intrinsic::arm64_crc32ch:
6691 return tryCombineCRC32(0xffff, N, DAG);
6696 static SDValue performExtendCombine(SDNode *N,
6697 TargetLowering::DAGCombinerInfo &DCI,
6698 SelectionDAG &DAG) {
6699 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
6700 // we can convert that DUP into another extract_high (of a bigger DUP), which
6701 // helps the backend to decide that an sabdl2 would be useful, saving a real
6702 // extract_high operation.
6703 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
6704 N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
6705 SDNode *ABDNode = N->getOperand(0).getNode();
6706 unsigned IID = getIntrinsicID(ABDNode);
6707 if (IID == Intrinsic::arm64_neon_sabd ||
6708 IID == Intrinsic::arm64_neon_uabd) {
6709 SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
6710 if (!NewABD.getNode())
6713 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
6718 // This is effectively a custom type legalization for ARM64.
6720 // Type legalization will split an extend of a small, legal, type to a larger
6721 // illegal type by first splitting the destination type, often creating
6722 // illegal source types, which then get legalized in isel-confusing ways,
6723 // leading to really terrible codegen. E.g.,
6724 // %result = v8i32 sext v8i8 %value
6726 // %losrc = extract_subreg %value, ...
6727 // %hisrc = extract_subreg %value, ...
6728 // %lo = v4i32 sext v4i8 %losrc
6729 // %hi = v4i32 sext v4i8 %hisrc
6730 // Things go rapidly downhill from there.
6732 // For ARM64, the [sz]ext vector instructions can only go up one element
6733 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
6734 // take two instructions.
6736 // This implies that the most efficient way to do the extend from v8i8
6737 // to two v4i32 values is to first extend the v8i8 to v8i16, then do
6738 // the normal splitting to happen for the v8i16->v8i32.
6740 // This is pre-legalization to catch some cases where the default
6741 // type legalization will create ill-tempered code.
6742 if (!DCI.isBeforeLegalizeOps())
6745 // We're only interested in cleaning things up for non-legal vector types
6746 // here. If both the source and destination are legal, things will just
6747 // work naturally without any fiddling.
6748 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6749 EVT ResVT = N->getValueType(0);
6750 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
6752 // If the vector type isn't a simple VT, it's beyond the scope of what
6753 // we're worried about here. Let legalization do its thing and hope for
6755 if (!ResVT.isSimple())
6758 SDValue Src = N->getOperand(0);
6759 MVT SrcVT = Src->getValueType(0).getSimpleVT();
6760 // If the source VT is a 64-bit vector, we can play games and get the
6761 // better results we want.
6762 if (SrcVT.getSizeInBits() != 64)
6765 unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits();
6766 unsigned ElementCount = SrcVT.getVectorNumElements();
6767 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
6769 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
6771 // Now split the rest of the operation into two halves, each with a 64
6775 unsigned NumElements = ResVT.getVectorNumElements();
6776 assert(!(NumElements & 1) && "Splitting vector, but not in half!");
6777 LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
6778 ResVT.getVectorElementType(), NumElements / 2);
6780 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
6781 LoVT.getVectorNumElements());
6782 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
6783 DAG.getIntPtrConstant(0));
6784 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
6785 DAG.getIntPtrConstant(InNVT.getVectorNumElements()));
6786 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
6787 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
6789 // Now combine the parts back together so we still have a single result
6790 // like the combiner expects.
6791 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
6794 /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
6795 /// value. The load store optimizer pass will merge them to store pair stores.
6796 /// This has better performance than a splat of the scalar followed by a split
6797 /// vector store. Even if the stores are not merged it is four stores vs a dup,
6798 /// followed by an ext.b and two stores.
6799 static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode *St) {
6800 SDValue StVal = St->getValue();
6801 EVT VT = StVal.getValueType();
6803 // Don't replace floating point stores, they possibly won't be transformed to
6804 // stp because of the store pair suppress pass.
6805 if (VT.isFloatingPoint())
6808 // Check for insert vector elements.
6809 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
6812 // We can express a splat as store pair(s) for 2 or 4 elements.
6813 unsigned NumVecElts = VT.getVectorNumElements();
6814 if (NumVecElts != 4 && NumVecElts != 2)
6816 SDValue SplatVal = StVal.getOperand(1);
6817 unsigned RemainInsertElts = NumVecElts - 1;
6819 // Check that this is a splat.
6820 while (--RemainInsertElts) {
6821 SDValue NextInsertElt = StVal.getOperand(0);
6822 if (NextInsertElt.getOpcode() != ISD::INSERT_VECTOR_ELT)
6824 if (NextInsertElt.getOperand(1) != SplatVal)
6826 StVal = NextInsertElt;
6828 unsigned OrigAlignment = St->getAlignment();
6829 unsigned EltOffset = NumVecElts == 4 ? 4 : 8;
6830 unsigned Alignment = std::min(OrigAlignment, EltOffset);
6832 // Create scalar stores. This is at least as good as the code sequence for a
6833 // split unaligned store wich is a dup.s, ext.b, and two stores.
6834 // Most of the time the three stores should be replaced by store pair
6835 // instructions (stp).
6837 SDValue BasePtr = St->getBasePtr();
6839 DAG.getStore(St->getChain(), DL, SplatVal, BasePtr, St->getPointerInfo(),
6840 St->isVolatile(), St->isNonTemporal(), St->getAlignment());
6842 unsigned Offset = EltOffset;
6843 while (--NumVecElts) {
6844 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
6845 DAG.getConstant(Offset, MVT::i64));
6846 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
6847 St->getPointerInfo(), St->isVolatile(),
6848 St->isNonTemporal(), Alignment);
6849 Offset += EltOffset;
6854 static SDValue performSTORECombine(SDNode *N,
6855 TargetLowering::DAGCombinerInfo &DCI,
6857 const ARM64Subtarget *Subtarget) {
6858 if (!DCI.isBeforeLegalize())
6861 StoreSDNode *S = cast<StoreSDNode>(N);
6862 if (S->isVolatile())
6865 // Cyclone has bad performance on unaligned 16B stores when crossing line and
6866 // page boundries. We want to split such stores.
6867 if (!Subtarget->isCyclone())
6870 // Don't split at Oz.
6871 MachineFunction &MF = DAG.getMachineFunction();
6872 bool IsMinSize = MF.getFunction()->getAttributes().hasAttribute(
6873 AttributeSet::FunctionIndex, Attribute::MinSize);
6877 SDValue StVal = S->getValue();
6878 EVT VT = StVal.getValueType();
6880 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
6881 // those up regresses performance on micro-benchmarks and olden/bh.
6882 if (!VT.isVector() || VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
6885 // Split unaligned 16B stores. They are terrible for performance.
6886 // Don't split stores with alignment of 1 or 2. Code that uses clang vector
6887 // extensions can use this to mark that it does not want splitting to happen
6888 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
6889 // eliminating alignment hazards is only 1 in 8 for alignment of 2.
6890 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
6891 S->getAlignment() <= 2)
6894 // If we get a splat of a scalar convert this vector store to a store of
6895 // scalars. They will be merged into store pairs thereby removing two
6897 SDValue ReplacedSplat = replaceSplatVectorStore(DAG, S);
6898 if (ReplacedSplat != SDValue())
6899 return ReplacedSplat;
6902 unsigned NumElts = VT.getVectorNumElements() / 2;
6903 // Split VT into two.
6905 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
6906 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
6907 DAG.getIntPtrConstant(0));
6908 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
6909 DAG.getIntPtrConstant(NumElts));
6910 SDValue BasePtr = S->getBasePtr();
6912 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
6913 S->isVolatile(), S->isNonTemporal(), S->getAlignment());
6914 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
6915 DAG.getConstant(8, MVT::i64));
6916 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
6917 S->getPointerInfo(), S->isVolatile(), S->isNonTemporal(),
6921 // Optimize compare with zero and branch.
6922 static SDValue performBRCONDCombine(SDNode *N,
6923 TargetLowering::DAGCombinerInfo &DCI,
6924 SelectionDAG &DAG) {
6925 SDValue Chain = N->getOperand(0);
6926 SDValue Dest = N->getOperand(1);
6927 SDValue CCVal = N->getOperand(2);
6928 SDValue Cmp = N->getOperand(3);
6930 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
6931 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
6932 if (CC != ARM64CC::EQ && CC != ARM64CC::NE)
6935 unsigned CmpOpc = Cmp.getOpcode();
6936 if (CmpOpc != ARM64ISD::ADDS && CmpOpc != ARM64ISD::SUBS)
6939 // Only attempt folding if there is only one use of the flag and no use of the
6941 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
6944 SDValue LHS = Cmp.getOperand(0);
6945 SDValue RHS = Cmp.getOperand(1);
6947 assert(LHS.getValueType() == RHS.getValueType() &&
6948 "Expected the value type to be the same for both operands!");
6949 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
6952 if (isa<ConstantSDNode>(LHS) && cast<ConstantSDNode>(LHS)->isNullValue())
6953 std::swap(LHS, RHS);
6955 if (!isa<ConstantSDNode>(RHS) || !cast<ConstantSDNode>(RHS)->isNullValue())
6958 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
6959 LHS.getOpcode() == ISD::SRL)
6962 // Fold the compare into the branch instruction.
6964 if (CC == ARM64CC::EQ)
6965 BR = DAG.getNode(ARM64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
6967 BR = DAG.getNode(ARM64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
6969 // Do not add new nodes to DAG combiner worklist.
6970 DCI.CombineTo(N, BR, false);
6975 // vselect (v1i1 setcc) ->
6976 // vselect (v1iXX setcc) (XX is the size of the compared operand type)
6977 // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
6978 // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
6980 static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
6981 SDValue N0 = N->getOperand(0);
6982 EVT CCVT = N0.getValueType();
6984 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
6985 CCVT.getVectorElementType() != MVT::i1)
6988 EVT ResVT = N->getValueType(0);
6989 EVT CmpVT = N0.getOperand(0).getValueType();
6990 // Only combine when the result type is of the same size as the compared
6992 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
6995 SDValue IfTrue = N->getOperand(1);
6996 SDValue IfFalse = N->getOperand(2);
6998 DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
6999 N0.getOperand(0), N0.getOperand(1),
7000 cast<CondCodeSDNode>(N0.getOperand(2))->get());
7001 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
7005 SDValue ARM64TargetLowering::PerformDAGCombine(SDNode *N,
7006 DAGCombinerInfo &DCI) const {
7007 SelectionDAG &DAG = DCI.DAG;
7008 switch (N->getOpcode()) {
7013 return performAddSubLongCombine(N, DCI, DAG);
7015 return performXorCombine(N, DAG, DCI, Subtarget);
7017 return performMulCombine(N, DAG, DCI, Subtarget);
7018 case ISD::SINT_TO_FP:
7019 case ISD::UINT_TO_FP:
7020 return performIntToFpCombine(N, DAG);
7022 return performORCombine(N, DCI, Subtarget);
7023 case ISD::INTRINSIC_WO_CHAIN:
7024 return performIntrinsicCombine(N, DCI, Subtarget);
7025 case ISD::ANY_EXTEND:
7026 case ISD::ZERO_EXTEND:
7027 case ISD::SIGN_EXTEND:
7028 return performExtendCombine(N, DCI, DAG);
7030 return performBitcastCombine(N, DCI, DAG);
7031 case ISD::CONCAT_VECTORS:
7032 return performConcatVectorsCombine(N, DCI, DAG);
7034 return performVSelectCombine(N, DCI.DAG);
7036 return performSTORECombine(N, DCI, DAG, Subtarget);
7037 case ARM64ISD::BRCOND:
7038 return performBRCONDCombine(N, DCI, DAG);
7043 // Check if the return value is used as only a return value, as otherwise
7044 // we can't perform a tail-call. In particular, we need to check for
7045 // target ISD nodes that are returns and any other "odd" constructs
7046 // that the generic analysis code won't necessarily catch.
7047 bool ARM64TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
7048 if (N->getNumValues() != 1)
7050 if (!N->hasNUsesOfValue(1, 0))
7053 SDValue TCChain = Chain;
7054 SDNode *Copy = *N->use_begin();
7055 if (Copy->getOpcode() == ISD::CopyToReg) {
7056 // If the copy has a glue operand, we conservatively assume it isn't safe to
7057 // perform a tail call.
7058 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
7061 TCChain = Copy->getOperand(0);
7062 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
7065 bool HasRet = false;
7066 for (SDNode *Node : Copy->uses()) {
7067 if (Node->getOpcode() != ARM64ISD::RET_FLAG)
7079 // Return whether the an instruction can potentially be optimized to a tail
7080 // call. This will cause the optimizers to attempt to move, or duplicate,
7081 // return instructions to help enable tail call optimizations for this
7083 bool ARM64TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
7084 if (!EnableARM64TailCalls)
7087 if (!CI->isTailCall())
7093 bool ARM64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
7095 ISD::MemIndexedMode &AM,
7097 SelectionDAG &DAG) const {
7098 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
7101 Base = Op->getOperand(0);
7102 // All of the indexed addressing mode instructions take a signed
7103 // 9 bit immediate offset.
7104 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
7105 int64_t RHSC = (int64_t)RHS->getZExtValue();
7106 if (RHSC >= 256 || RHSC <= -256)
7108 IsInc = (Op->getOpcode() == ISD::ADD);
7109 Offset = Op->getOperand(1);
7115 bool ARM64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
7117 ISD::MemIndexedMode &AM,
7118 SelectionDAG &DAG) const {
7121 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7122 VT = LD->getMemoryVT();
7123 Ptr = LD->getBasePtr();
7124 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7125 VT = ST->getMemoryVT();
7126 Ptr = ST->getBasePtr();
7131 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
7133 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
7137 bool ARM64TargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
7140 ISD::MemIndexedMode &AM,
7141 SelectionDAG &DAG) const {
7144 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7145 VT = LD->getMemoryVT();
7146 Ptr = LD->getBasePtr();
7147 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7148 VT = ST->getMemoryVT();
7149 Ptr = ST->getBasePtr();
7154 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
7156 // Post-indexing updates the base, so it's not a valid transform
7157 // if that's not the same as the load's pointer.
7160 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
7164 void ARM64TargetLowering::ReplaceNodeResults(SDNode *N,
7165 SmallVectorImpl<SDValue> &Results,
7166 SelectionDAG &DAG) const {
7167 switch (N->getOpcode()) {
7169 llvm_unreachable("Don't know how to custom expand this");
7170 case ISD::FP_TO_UINT:
7171 case ISD::FP_TO_SINT:
7172 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
7173 // Let normal code take care of it by not adding anything to Results.
7178 bool ARM64TargetLowering::shouldExpandAtomicInIR(Instruction *Inst) const {
7179 // Loads and stores less than 128-bits are already atomic; ones above that
7180 // are doomed anyway, so defer to the default libcall and blame the OS when
7182 if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
7183 return SI->getValueOperand()->getType()->getPrimitiveSizeInBits() == 128;
7184 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
7185 return LI->getType()->getPrimitiveSizeInBits() == 128;
7187 // For the real atomic operations, we have ldxr/stxr up to 128 bits.
7188 return Inst->getType()->getPrimitiveSizeInBits() <= 128;
7191 Value *ARM64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
7192 AtomicOrdering Ord) const {
7193 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
7194 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
7196 Ord == Acquire || Ord == AcquireRelease || Ord == SequentiallyConsistent;
7198 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
7199 // intrinsic must return {i64, i64} and we have to recombine them into a
7200 // single i128 here.
7201 if (ValTy->getPrimitiveSizeInBits() == 128) {
7203 IsAcquire ? Intrinsic::arm64_ldaxp : Intrinsic::arm64_ldxp;
7204 Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int);
7206 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
7207 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
7209 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
7210 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
7211 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
7212 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
7213 return Builder.CreateOr(
7214 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
7217 Type *Tys[] = { Addr->getType() };
7219 IsAcquire ? Intrinsic::arm64_ldaxr : Intrinsic::arm64_ldxr;
7220 Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int, Tys);
7222 return Builder.CreateTruncOrBitCast(
7223 Builder.CreateCall(Ldxr, Addr),
7224 cast<PointerType>(Addr->getType())->getElementType());
7227 Value *ARM64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
7228 Value *Val, Value *Addr,
7229 AtomicOrdering Ord) const {
7230 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
7232 Ord == Release || Ord == AcquireRelease || Ord == SequentiallyConsistent;
7234 // Since the intrinsics must have legal type, the i128 intrinsics take two
7235 // parameters: "i64, i64". We must marshal Val into the appropriate form
7237 if (Val->getType()->getPrimitiveSizeInBits() == 128) {
7239 IsRelease ? Intrinsic::arm64_stlxp : Intrinsic::arm64_stxp;
7240 Function *Stxr = Intrinsic::getDeclaration(M, Int);
7241 Type *Int64Ty = Type::getInt64Ty(M->getContext());
7243 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
7244 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
7245 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
7246 return Builder.CreateCall3(Stxr, Lo, Hi, Addr);
7250 IsRelease ? Intrinsic::arm64_stlxr : Intrinsic::arm64_stxr;
7251 Type *Tys[] = { Addr->getType() };
7252 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
7254 return Builder.CreateCall2(
7255 Stxr, Builder.CreateZExtOrBitCast(
7256 Val, Stxr->getFunctionType()->getParamType(0)),