blob: b1c290b2f2befcc3af181ee7525dfbaf780c6e01 [file] [log] [blame]
Tim Northover3b0846e2014-05-24 12:50:23 +00001//===-- AArch64ISelLowering.cpp - AArch64 DAG Lowering Implementation ----===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the AArch64TargetLowering class.
11//
12//===----------------------------------------------------------------------===//
13
14#include "AArch64ISelLowering.h"
Tim Northover3c55cca2014-11-27 21:02:42 +000015#include "AArch64CallingConvention.h"
Benjamin Kramer1f8930e2014-07-25 11:42:14 +000016#include "AArch64MachineFunctionInfo.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000017#include "AArch64PerfectShuffle.h"
18#include "AArch64Subtarget.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000019#include "AArch64TargetMachine.h"
20#include "AArch64TargetObjectFile.h"
21#include "MCTargetDesc/AArch64AddressingModes.h"
22#include "llvm/ADT/Statistic.h"
23#include "llvm/CodeGen/CallingConvLower.h"
24#include "llvm/CodeGen/MachineFrameInfo.h"
25#include "llvm/CodeGen/MachineInstrBuilder.h"
26#include "llvm/CodeGen/MachineRegisterInfo.h"
27#include "llvm/IR/Function.h"
David Blaikie457343d2015-05-21 21:12:43 +000028#include "llvm/IR/GetElementPtrTypeIterator.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000029#include "llvm/IR/Intrinsics.h"
30#include "llvm/IR/Type.h"
31#include "llvm/Support/CommandLine.h"
32#include "llvm/Support/Debug.h"
33#include "llvm/Support/ErrorHandling.h"
34#include "llvm/Support/raw_ostream.h"
35#include "llvm/Target/TargetOptions.h"
36using namespace llvm;
37
38#define DEBUG_TYPE "aarch64-lower"
39
40STATISTIC(NumTailCalls, "Number of tail calls");
41STATISTIC(NumShiftInserts, "Number of vector shift inserts");
42
Tim Northover3b0846e2014-05-24 12:50:23 +000043// Place holder until extr generation is tested fully.
44static cl::opt<bool>
45EnableAArch64ExtrGeneration("aarch64-extr-generation", cl::Hidden,
46 cl::desc("Allow AArch64 (or (shift)(shift))->extract"),
47 cl::init(true));
48
49static cl::opt<bool>
50EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden,
Kristof Beylsaea84612015-03-04 09:12:08 +000051 cl::desc("Allow AArch64 SLI/SRI formation"),
52 cl::init(false));
53
54// FIXME: The necessary dtprel relocations don't seem to be supported
55// well in the GNU bfd and gold linkers at the moment. Therefore, by
56// default, for now, fall back to GeneralDynamic code generation.
57cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration(
58 "aarch64-elf-ldtls-generation", cl::Hidden,
59 cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
60 cl::init(false));
Tim Northover3b0846e2014-05-24 12:50:23 +000061
Matthias Braunaf7d7702015-07-16 20:02:37 +000062/// Value type used for condition codes.
63static const MVT MVT_CC = MVT::i32;
64
Eric Christopher905f12d2015-01-29 00:19:42 +000065AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
66 const AArch64Subtarget &STI)
67 : TargetLowering(TM), Subtarget(&STI) {
Tim Northover3b0846e2014-05-24 12:50:23 +000068
69 // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
70 // we have to make something up. Arbitrarily, choose ZeroOrOne.
71 setBooleanContents(ZeroOrOneBooleanContent);
72 // When comparing vectors the result sets the different elements in the
73 // vector to all-one or all-zero.
74 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
75
76 // Set up the register classes.
77 addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
78 addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
79
80 if (Subtarget->hasFPARMv8()) {
81 addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
82 addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
83 addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
84 addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
85 }
86
87 if (Subtarget->hasNEON()) {
88 addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
89 addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
90 // Someone set us up the NEON.
91 addDRTypeForNEON(MVT::v2f32);
92 addDRTypeForNEON(MVT::v8i8);
93 addDRTypeForNEON(MVT::v4i16);
94 addDRTypeForNEON(MVT::v2i32);
95 addDRTypeForNEON(MVT::v1i64);
96 addDRTypeForNEON(MVT::v1f64);
Oliver Stannard89d15422014-08-27 16:16:04 +000097 addDRTypeForNEON(MVT::v4f16);
Tim Northover3b0846e2014-05-24 12:50:23 +000098
99 addQRTypeForNEON(MVT::v4f32);
100 addQRTypeForNEON(MVT::v2f64);
101 addQRTypeForNEON(MVT::v16i8);
102 addQRTypeForNEON(MVT::v8i16);
103 addQRTypeForNEON(MVT::v4i32);
104 addQRTypeForNEON(MVT::v2i64);
Oliver Stannard89d15422014-08-27 16:16:04 +0000105 addQRTypeForNEON(MVT::v8f16);
Tim Northover3b0846e2014-05-24 12:50:23 +0000106 }
107
108 // Compute derived properties from the register classes
Eric Christopher23a3a7c2015-02-26 00:00:24 +0000109 computeRegisterProperties(Subtarget->getRegisterInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +0000110
111 // Provide all sorts of operation actions
112 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
113 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
114 setOperationAction(ISD::SETCC, MVT::i32, Custom);
115 setOperationAction(ISD::SETCC, MVT::i64, Custom);
116 setOperationAction(ISD::SETCC, MVT::f32, Custom);
117 setOperationAction(ISD::SETCC, MVT::f64, Custom);
118 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
119 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
120 setOperationAction(ISD::BR_CC, MVT::i64, Custom);
121 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
122 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
123 setOperationAction(ISD::SELECT, MVT::i32, Custom);
124 setOperationAction(ISD::SELECT, MVT::i64, Custom);
125 setOperationAction(ISD::SELECT, MVT::f32, Custom);
126 setOperationAction(ISD::SELECT, MVT::f64, Custom);
127 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
128 setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
129 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
130 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
131 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
132 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
133
134 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
135 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
136 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
137
138 setOperationAction(ISD::FREM, MVT::f32, Expand);
139 setOperationAction(ISD::FREM, MVT::f64, Expand);
140 setOperationAction(ISD::FREM, MVT::f80, Expand);
141
142 // Custom lowering hooks are needed for XOR
143 // to fold it into CSINC/CSINV.
144 setOperationAction(ISD::XOR, MVT::i32, Custom);
145 setOperationAction(ISD::XOR, MVT::i64, Custom);
146
147 // Virtually no operation on f128 is legal, but LLVM can't expand them when
148 // there's a valid register class, so we need custom operations in most cases.
149 setOperationAction(ISD::FABS, MVT::f128, Expand);
150 setOperationAction(ISD::FADD, MVT::f128, Custom);
151 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
152 setOperationAction(ISD::FCOS, MVT::f128, Expand);
153 setOperationAction(ISD::FDIV, MVT::f128, Custom);
154 setOperationAction(ISD::FMA, MVT::f128, Expand);
155 setOperationAction(ISD::FMUL, MVT::f128, Custom);
156 setOperationAction(ISD::FNEG, MVT::f128, Expand);
157 setOperationAction(ISD::FPOW, MVT::f128, Expand);
158 setOperationAction(ISD::FREM, MVT::f128, Expand);
159 setOperationAction(ISD::FRINT, MVT::f128, Expand);
160 setOperationAction(ISD::FSIN, MVT::f128, Expand);
161 setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
162 setOperationAction(ISD::FSQRT, MVT::f128, Expand);
163 setOperationAction(ISD::FSUB, MVT::f128, Custom);
164 setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
165 setOperationAction(ISD::SETCC, MVT::f128, Custom);
166 setOperationAction(ISD::BR_CC, MVT::f128, Custom);
167 setOperationAction(ISD::SELECT, MVT::f128, Custom);
168 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
169 setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
170
171 // Lowering for many of the conversions is actually specified by the non-f128
172 // type. The LowerXXX function will be trivial when f128 isn't involved.
173 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
174 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
175 setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
176 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
177 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
178 setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
179 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
180 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
181 setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
182 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
183 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
184 setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
185 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
186 setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
187
188 // Variable arguments.
189 setOperationAction(ISD::VASTART, MVT::Other, Custom);
190 setOperationAction(ISD::VAARG, MVT::Other, Custom);
191 setOperationAction(ISD::VACOPY, MVT::Other, Custom);
192 setOperationAction(ISD::VAEND, MVT::Other, Expand);
193
194 // Variable-sized objects.
195 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
196 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
197 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
198
199 // Exception handling.
200 // FIXME: These are guesses. Has this been defined yet?
201 setExceptionPointerRegister(AArch64::X0);
202 setExceptionSelectorRegister(AArch64::X1);
203
204 // Constant pool entries
205 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
206
207 // BlockAddress
208 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
209
210 // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
211 setOperationAction(ISD::ADDC, MVT::i32, Custom);
212 setOperationAction(ISD::ADDE, MVT::i32, Custom);
213 setOperationAction(ISD::SUBC, MVT::i32, Custom);
214 setOperationAction(ISD::SUBE, MVT::i32, Custom);
215 setOperationAction(ISD::ADDC, MVT::i64, Custom);
216 setOperationAction(ISD::ADDE, MVT::i64, Custom);
217 setOperationAction(ISD::SUBC, MVT::i64, Custom);
218 setOperationAction(ISD::SUBE, MVT::i64, Custom);
219
220 // AArch64 lacks both left-rotate and popcount instructions.
221 setOperationAction(ISD::ROTL, MVT::i32, Expand);
222 setOperationAction(ISD::ROTL, MVT::i64, Expand);
223
224 // AArch64 doesn't have {U|S}MUL_LOHI.
225 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
226 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
227
228
229 // Expand the undefined-at-zero variants to cttz/ctlz to their defined-at-zero
230 // counterparts, which AArch64 supports directly.
231 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
232 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
233 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
234 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
235
236 setOperationAction(ISD::CTPOP, MVT::i32, Custom);
237 setOperationAction(ISD::CTPOP, MVT::i64, Custom);
238
239 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
240 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
241 setOperationAction(ISD::SREM, MVT::i32, Expand);
242 setOperationAction(ISD::SREM, MVT::i64, Expand);
243 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
244 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
245 setOperationAction(ISD::UREM, MVT::i32, Expand);
246 setOperationAction(ISD::UREM, MVT::i64, Expand);
247
248 // Custom lower Add/Sub/Mul with overflow.
249 setOperationAction(ISD::SADDO, MVT::i32, Custom);
250 setOperationAction(ISD::SADDO, MVT::i64, Custom);
251 setOperationAction(ISD::UADDO, MVT::i32, Custom);
252 setOperationAction(ISD::UADDO, MVT::i64, Custom);
253 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
254 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
255 setOperationAction(ISD::USUBO, MVT::i32, Custom);
256 setOperationAction(ISD::USUBO, MVT::i64, Custom);
257 setOperationAction(ISD::SMULO, MVT::i32, Custom);
258 setOperationAction(ISD::SMULO, MVT::i64, Custom);
259 setOperationAction(ISD::UMULO, MVT::i32, Custom);
260 setOperationAction(ISD::UMULO, MVT::i64, Custom);
261
262 setOperationAction(ISD::FSIN, MVT::f32, Expand);
263 setOperationAction(ISD::FSIN, MVT::f64, Expand);
264 setOperationAction(ISD::FCOS, MVT::f32, Expand);
265 setOperationAction(ISD::FCOS, MVT::f64, Expand);
266 setOperationAction(ISD::FPOW, MVT::f32, Expand);
267 setOperationAction(ISD::FPOW, MVT::f64, Expand);
268 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
269 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
270
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +0000271 // f16 is a storage-only type, always promote it to f32.
272 setOperationAction(ISD::SETCC, MVT::f16, Promote);
273 setOperationAction(ISD::BR_CC, MVT::f16, Promote);
274 setOperationAction(ISD::SELECT_CC, MVT::f16, Promote);
275 setOperationAction(ISD::SELECT, MVT::f16, Promote);
276 setOperationAction(ISD::FADD, MVT::f16, Promote);
277 setOperationAction(ISD::FSUB, MVT::f16, Promote);
278 setOperationAction(ISD::FMUL, MVT::f16, Promote);
279 setOperationAction(ISD::FDIV, MVT::f16, Promote);
280 setOperationAction(ISD::FREM, MVT::f16, Promote);
281 setOperationAction(ISD::FMA, MVT::f16, Promote);
282 setOperationAction(ISD::FNEG, MVT::f16, Promote);
283 setOperationAction(ISD::FABS, MVT::f16, Promote);
284 setOperationAction(ISD::FCEIL, MVT::f16, Promote);
285 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote);
286 setOperationAction(ISD::FCOS, MVT::f16, Promote);
287 setOperationAction(ISD::FFLOOR, MVT::f16, Promote);
288 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote);
289 setOperationAction(ISD::FPOW, MVT::f16, Promote);
290 setOperationAction(ISD::FPOWI, MVT::f16, Promote);
291 setOperationAction(ISD::FRINT, MVT::f16, Promote);
292 setOperationAction(ISD::FSIN, MVT::f16, Promote);
293 setOperationAction(ISD::FSINCOS, MVT::f16, Promote);
294 setOperationAction(ISD::FSQRT, MVT::f16, Promote);
295 setOperationAction(ISD::FEXP, MVT::f16, Promote);
296 setOperationAction(ISD::FEXP2, MVT::f16, Promote);
297 setOperationAction(ISD::FLOG, MVT::f16, Promote);
298 setOperationAction(ISD::FLOG2, MVT::f16, Promote);
299 setOperationAction(ISD::FLOG10, MVT::f16, Promote);
300 setOperationAction(ISD::FROUND, MVT::f16, Promote);
301 setOperationAction(ISD::FTRUNC, MVT::f16, Promote);
302 setOperationAction(ISD::FMINNUM, MVT::f16, Promote);
303 setOperationAction(ISD::FMAXNUM, MVT::f16, Promote);
James Molloy63be1982015-08-14 09:08:50 +0000304 setOperationAction(ISD::FMINNAN, MVT::f16, Promote);
305 setOperationAction(ISD::FMAXNAN, MVT::f16, Promote);
Oliver Stannardf5469be2014-08-18 14:22:39 +0000306
Oliver Stannard89d15422014-08-27 16:16:04 +0000307 // v4f16 is also a storage-only type, so promote it to v4f32 when that is
308 // known to be safe.
309 setOperationAction(ISD::FADD, MVT::v4f16, Promote);
310 setOperationAction(ISD::FSUB, MVT::v4f16, Promote);
311 setOperationAction(ISD::FMUL, MVT::v4f16, Promote);
312 setOperationAction(ISD::FDIV, MVT::v4f16, Promote);
313 setOperationAction(ISD::FP_EXTEND, MVT::v4f16, Promote);
314 setOperationAction(ISD::FP_ROUND, MVT::v4f16, Promote);
315 AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32);
316 AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32);
317 AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32);
318 AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32);
319 AddPromotedToType(ISD::FP_EXTEND, MVT::v4f16, MVT::v4f32);
320 AddPromotedToType(ISD::FP_ROUND, MVT::v4f16, MVT::v4f32);
321
322 // Expand all other v4f16 operations.
323 // FIXME: We could generate better code by promoting some operations to
324 // a pair of v4f32s
325 setOperationAction(ISD::FABS, MVT::v4f16, Expand);
326 setOperationAction(ISD::FCEIL, MVT::v4f16, Expand);
327 setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand);
328 setOperationAction(ISD::FCOS, MVT::v4f16, Expand);
329 setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand);
330 setOperationAction(ISD::FMA, MVT::v4f16, Expand);
331 setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand);
332 setOperationAction(ISD::FNEG, MVT::v4f16, Expand);
333 setOperationAction(ISD::FPOW, MVT::v4f16, Expand);
334 setOperationAction(ISD::FPOWI, MVT::v4f16, Expand);
335 setOperationAction(ISD::FREM, MVT::v4f16, Expand);
336 setOperationAction(ISD::FROUND, MVT::v4f16, Expand);
337 setOperationAction(ISD::FRINT, MVT::v4f16, Expand);
338 setOperationAction(ISD::FSIN, MVT::v4f16, Expand);
339 setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand);
340 setOperationAction(ISD::FSQRT, MVT::v4f16, Expand);
341 setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand);
342 setOperationAction(ISD::SETCC, MVT::v4f16, Expand);
343 setOperationAction(ISD::BR_CC, MVT::v4f16, Expand);
344 setOperationAction(ISD::SELECT, MVT::v4f16, Expand);
345 setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand);
346 setOperationAction(ISD::FEXP, MVT::v4f16, Expand);
347 setOperationAction(ISD::FEXP2, MVT::v4f16, Expand);
348 setOperationAction(ISD::FLOG, MVT::v4f16, Expand);
349 setOperationAction(ISD::FLOG2, MVT::v4f16, Expand);
350 setOperationAction(ISD::FLOG10, MVT::v4f16, Expand);
351
352
353 // v8f16 is also a storage-only type, so expand it.
354 setOperationAction(ISD::FABS, MVT::v8f16, Expand);
355 setOperationAction(ISD::FADD, MVT::v8f16, Expand);
356 setOperationAction(ISD::FCEIL, MVT::v8f16, Expand);
357 setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand);
358 setOperationAction(ISD::FCOS, MVT::v8f16, Expand);
359 setOperationAction(ISD::FDIV, MVT::v8f16, Expand);
360 setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand);
361 setOperationAction(ISD::FMA, MVT::v8f16, Expand);
362 setOperationAction(ISD::FMUL, MVT::v8f16, Expand);
363 setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand);
364 setOperationAction(ISD::FNEG, MVT::v8f16, Expand);
365 setOperationAction(ISD::FPOW, MVT::v8f16, Expand);
366 setOperationAction(ISD::FPOWI, MVT::v8f16, Expand);
367 setOperationAction(ISD::FREM, MVT::v8f16, Expand);
368 setOperationAction(ISD::FROUND, MVT::v8f16, Expand);
369 setOperationAction(ISD::FRINT, MVT::v8f16, Expand);
370 setOperationAction(ISD::FSIN, MVT::v8f16, Expand);
371 setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
372 setOperationAction(ISD::FSQRT, MVT::v8f16, Expand);
373 setOperationAction(ISD::FSUB, MVT::v8f16, Expand);
374 setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand);
375 setOperationAction(ISD::SETCC, MVT::v8f16, Expand);
376 setOperationAction(ISD::BR_CC, MVT::v8f16, Expand);
377 setOperationAction(ISD::SELECT, MVT::v8f16, Expand);
378 setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand);
379 setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand);
380 setOperationAction(ISD::FEXP, MVT::v8f16, Expand);
381 setOperationAction(ISD::FEXP2, MVT::v8f16, Expand);
382 setOperationAction(ISD::FLOG, MVT::v8f16, Expand);
383 setOperationAction(ISD::FLOG2, MVT::v8f16, Expand);
384 setOperationAction(ISD::FLOG10, MVT::v8f16, Expand);
385
Tim Northover3b0846e2014-05-24 12:50:23 +0000386 // AArch64 has implementations of a lot of rounding-like FP operations.
Benjamin Kramer57a3d082015-03-08 16:07:39 +0000387 for (MVT Ty : {MVT::f32, MVT::f64}) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000388 setOperationAction(ISD::FFLOOR, Ty, Legal);
389 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
390 setOperationAction(ISD::FCEIL, Ty, Legal);
391 setOperationAction(ISD::FRINT, Ty, Legal);
392 setOperationAction(ISD::FTRUNC, Ty, Legal);
393 setOperationAction(ISD::FROUND, Ty, Legal);
James Molloyb7b2a1e2015-08-11 12:06:37 +0000394 setOperationAction(ISD::FMINNUM, Ty, Legal);
395 setOperationAction(ISD::FMAXNUM, Ty, Legal);
James Molloy88edc822015-08-17 07:13:20 +0000396 setOperationAction(ISD::FMINNAN, Ty, Legal);
397 setOperationAction(ISD::FMAXNAN, Ty, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000398 }
399
400 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
401
402 if (Subtarget->isTargetMachO()) {
403 // For iOS, we don't want to the normal expansion of a libcall to
404 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
405 // traffic.
406 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
407 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
408 } else {
409 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
410 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
411 }
412
Juergen Ributzka23266502014-12-10 19:43:32 +0000413 // Make floating-point constants legal for the large code model, so they don't
414 // become loads from the constant pool.
415 if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
416 setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
417 setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
418 }
419
Tim Northover3b0846e2014-05-24 12:50:23 +0000420 // AArch64 does not have floating-point extending loads, i1 sign-extending
421 // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000422 for (MVT VT : MVT::fp_valuetypes()) {
423 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
424 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
425 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
426 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
427 }
428 for (MVT VT : MVT::integer_valuetypes())
429 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
430
Tim Northover3b0846e2014-05-24 12:50:23 +0000431 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
432 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
433 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
434 setTruncStoreAction(MVT::f128, MVT::f80, Expand);
435 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
436 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
437 setTruncStoreAction(MVT::f128, MVT::f16, Expand);
Tim Northoverf8bfe212014-07-18 13:07:05 +0000438
439 setOperationAction(ISD::BITCAST, MVT::i16, Custom);
440 setOperationAction(ISD::BITCAST, MVT::f16, Custom);
441
Tim Northover3b0846e2014-05-24 12:50:23 +0000442 // Indexed loads and stores are supported.
443 for (unsigned im = (unsigned)ISD::PRE_INC;
444 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
445 setIndexedLoadAction(im, MVT::i8, Legal);
446 setIndexedLoadAction(im, MVT::i16, Legal);
447 setIndexedLoadAction(im, MVT::i32, Legal);
448 setIndexedLoadAction(im, MVT::i64, Legal);
449 setIndexedLoadAction(im, MVT::f64, Legal);
450 setIndexedLoadAction(im, MVT::f32, Legal);
Ahmed Bougachae0e12db2015-08-04 01:29:38 +0000451 setIndexedLoadAction(im, MVT::f16, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000452 setIndexedStoreAction(im, MVT::i8, Legal);
453 setIndexedStoreAction(im, MVT::i16, Legal);
454 setIndexedStoreAction(im, MVT::i32, Legal);
455 setIndexedStoreAction(im, MVT::i64, Legal);
456 setIndexedStoreAction(im, MVT::f64, Legal);
457 setIndexedStoreAction(im, MVT::f32, Legal);
Ahmed Bougachae0e12db2015-08-04 01:29:38 +0000458 setIndexedStoreAction(im, MVT::f16, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000459 }
460
461 // Trap.
462 setOperationAction(ISD::TRAP, MVT::Other, Legal);
463
464 // We combine OR nodes for bitfield operations.
465 setTargetDAGCombine(ISD::OR);
466
467 // Vector add and sub nodes may conceal a high-half opportunity.
468 // Also, try to fold ADD into CSINC/CSINV..
469 setTargetDAGCombine(ISD::ADD);
470 setTargetDAGCombine(ISD::SUB);
471
472 setTargetDAGCombine(ISD::XOR);
473 setTargetDAGCombine(ISD::SINT_TO_FP);
474 setTargetDAGCombine(ISD::UINT_TO_FP);
475
476 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
477
478 setTargetDAGCombine(ISD::ANY_EXTEND);
479 setTargetDAGCombine(ISD::ZERO_EXTEND);
480 setTargetDAGCombine(ISD::SIGN_EXTEND);
481 setTargetDAGCombine(ISD::BITCAST);
482 setTargetDAGCombine(ISD::CONCAT_VECTORS);
483 setTargetDAGCombine(ISD::STORE);
484
485 setTargetDAGCombine(ISD::MUL);
486
487 setTargetDAGCombine(ISD::SELECT);
488 setTargetDAGCombine(ISD::VSELECT);
489
490 setTargetDAGCombine(ISD::INTRINSIC_VOID);
491 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
492 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
493
494 MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 8;
495 MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 4;
496 MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = 4;
497
498 setStackPointerRegisterToSaveRestore(AArch64::SP);
499
500 setSchedulingPreference(Sched::Hybrid);
501
502 // Enable TBZ/TBNZ
503 MaskAndBranchFoldingIsLegal = true;
Quentin Colombet6843ac42015-03-31 20:52:32 +0000504 EnableExtLdPromotion = true;
Tim Northover3b0846e2014-05-24 12:50:23 +0000505
506 setMinFunctionAlignment(2);
507
Tim Northover3b0846e2014-05-24 12:50:23 +0000508 setHasExtractBitsInsn(true);
509
Adhemerval Zanella7bc33192015-07-28 13:03:31 +0000510 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
511
Tim Northover3b0846e2014-05-24 12:50:23 +0000512 if (Subtarget->hasNEON()) {
513 // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
514 // silliness like this:
515 setOperationAction(ISD::FABS, MVT::v1f64, Expand);
516 setOperationAction(ISD::FADD, MVT::v1f64, Expand);
517 setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
518 setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
519 setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
520 setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
521 setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
522 setOperationAction(ISD::FMA, MVT::v1f64, Expand);
523 setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
524 setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
525 setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
526 setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
527 setOperationAction(ISD::FREM, MVT::v1f64, Expand);
528 setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
529 setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
530 setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
531 setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
532 setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
533 setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
534 setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
535 setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
536 setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
537 setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
538 setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
539 setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
540
541 setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
542 setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
543 setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
544 setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
545 setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
546
547 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
548
549 // AArch64 doesn't have a direct vector ->f32 conversion instructions for
550 // elements smaller than i32, so promote the input to i32 first.
551 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Promote);
552 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Promote);
553 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Promote);
554 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Promote);
Pirama Arumuga Nainarb1881532015-04-23 17:16:27 +0000555 // i8 and i16 vector elements also need promotion to i32 for v8i8 or v8i16
556 // -> v8f16 conversions.
557 setOperationAction(ISD::SINT_TO_FP, MVT::v8i8, Promote);
558 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Promote);
559 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
560 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Promote);
Tim Northover3b0846e2014-05-24 12:50:23 +0000561 // Similarly, there is no direct i32 -> f64 vector conversion instruction.
562 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
563 setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
564 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
565 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
Pirama Arumuga Nainarb1881532015-04-23 17:16:27 +0000566 // Or, direct i32 -> f16 vector conversion. Set it so custom, so the
567 // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
568 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
569 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000570
571 // AArch64 doesn't have MUL.2d:
572 setOperationAction(ISD::MUL, MVT::v2i64, Expand);
Chad Rosierd9d0f862014-10-08 02:31:24 +0000573 // Custom handling for some quad-vector types to detect MULL.
574 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
575 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
576 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
577
Tim Northover3b0846e2014-05-24 12:50:23 +0000578 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
579 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
580 // Likewise, narrowing and extending vector loads/stores aren't handled
581 // directly.
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000582 for (MVT VT : MVT::vector_valuetypes()) {
583 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000584
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000585 setOperationAction(ISD::MULHS, VT, Expand);
586 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
587 setOperationAction(ISD::MULHU, VT, Expand);
588 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000589
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000590 setOperationAction(ISD::BSWAP, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000591
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000592 for (MVT InnerVT : MVT::vector_valuetypes()) {
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000593 setTruncStoreAction(VT, InnerVT, Expand);
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000594 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
595 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
596 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
597 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000598 }
599
600 // AArch64 has implementations of a lot of rounding-like FP operations.
Benjamin Kramer57a3d082015-03-08 16:07:39 +0000601 for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000602 setOperationAction(ISD::FFLOOR, Ty, Legal);
603 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
604 setOperationAction(ISD::FCEIL, Ty, Legal);
605 setOperationAction(ISD::FRINT, Ty, Legal);
606 setOperationAction(ISD::FTRUNC, Ty, Legal);
607 setOperationAction(ISD::FROUND, Ty, Legal);
608 }
609 }
James Molloyf089ab72014-08-06 10:42:18 +0000610
611 // Prefer likely predicted branches to selects on out-of-order cores.
612 if (Subtarget->isCortexA57())
613 PredictableSelectIsExpensive = true;
Tim Northover3b0846e2014-05-24 12:50:23 +0000614}
615
616void AArch64TargetLowering::addTypeForNEON(EVT VT, EVT PromotedBitwiseVT) {
Jiangning Liu08f4cda2014-08-29 01:31:42 +0000617 if (VT == MVT::v2f32 || VT == MVT::v4f16) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000618 setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
619 AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i32);
620
621 setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
622 AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i32);
Jiangning Liu08f4cda2014-08-29 01:31:42 +0000623 } else if (VT == MVT::v2f64 || VT == MVT::v4f32 || VT == MVT::v8f16) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000624 setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
625 AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i64);
626
627 setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
628 AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i64);
629 }
630
631 // Mark vector float intrinsics as expand.
632 if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
633 setOperationAction(ISD::FSIN, VT.getSimpleVT(), Expand);
634 setOperationAction(ISD::FCOS, VT.getSimpleVT(), Expand);
635 setOperationAction(ISD::FPOWI, VT.getSimpleVT(), Expand);
636 setOperationAction(ISD::FPOW, VT.getSimpleVT(), Expand);
637 setOperationAction(ISD::FLOG, VT.getSimpleVT(), Expand);
638 setOperationAction(ISD::FLOG2, VT.getSimpleVT(), Expand);
639 setOperationAction(ISD::FLOG10, VT.getSimpleVT(), Expand);
640 setOperationAction(ISD::FEXP, VT.getSimpleVT(), Expand);
641 setOperationAction(ISD::FEXP2, VT.getSimpleVT(), Expand);
Ahmed Bougachab0ae36f2015-08-04 00:42:34 +0000642
643 // But we do support custom-lowering for FCOPYSIGN.
644 setOperationAction(ISD::FCOPYSIGN, VT.getSimpleVT(), Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000645 }
646
647 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT.getSimpleVT(), Custom);
648 setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getSimpleVT(), Custom);
649 setOperationAction(ISD::BUILD_VECTOR, VT.getSimpleVT(), Custom);
650 setOperationAction(ISD::VECTOR_SHUFFLE, VT.getSimpleVT(), Custom);
651 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT.getSimpleVT(), Custom);
652 setOperationAction(ISD::SRA, VT.getSimpleVT(), Custom);
653 setOperationAction(ISD::SRL, VT.getSimpleVT(), Custom);
654 setOperationAction(ISD::SHL, VT.getSimpleVT(), Custom);
655 setOperationAction(ISD::AND, VT.getSimpleVT(), Custom);
656 setOperationAction(ISD::OR, VT.getSimpleVT(), Custom);
657 setOperationAction(ISD::SETCC, VT.getSimpleVT(), Custom);
658 setOperationAction(ISD::CONCAT_VECTORS, VT.getSimpleVT(), Legal);
659
660 setOperationAction(ISD::SELECT, VT.getSimpleVT(), Expand);
661 setOperationAction(ISD::SELECT_CC, VT.getSimpleVT(), Expand);
662 setOperationAction(ISD::VSELECT, VT.getSimpleVT(), Expand);
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000663 for (MVT InnerVT : MVT::all_valuetypes())
664 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT.getSimpleVT(), Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000665
666 // CNT supports only B element sizes.
667 if (VT != MVT::v8i8 && VT != MVT::v16i8)
668 setOperationAction(ISD::CTPOP, VT.getSimpleVT(), Expand);
669
670 setOperationAction(ISD::UDIV, VT.getSimpleVT(), Expand);
671 setOperationAction(ISD::SDIV, VT.getSimpleVT(), Expand);
672 setOperationAction(ISD::UREM, VT.getSimpleVT(), Expand);
673 setOperationAction(ISD::SREM, VT.getSimpleVT(), Expand);
674 setOperationAction(ISD::FREM, VT.getSimpleVT(), Expand);
675
676 setOperationAction(ISD::FP_TO_SINT, VT.getSimpleVT(), Custom);
677 setOperationAction(ISD::FP_TO_UINT, VT.getSimpleVT(), Custom);
678
James Molloyfaf4e3c2015-07-17 17:10:45 +0000679 // [SU][MIN|MAX] and [SU]ABSDIFF are available for all NEON types apart from
680 // i64.
James Molloycfb04432015-05-15 16:15:57 +0000681 if (!VT.isFloatingPoint() &&
682 VT.getSimpleVT() != MVT::v2i64 && VT.getSimpleVT() != MVT::v1i64)
James Molloyfaf4e3c2015-07-17 17:10:45 +0000683 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX,
684 ISD::SABSDIFF, ISD::UABSDIFF})
James Molloycfb04432015-05-15 16:15:57 +0000685 setOperationAction(Opcode, VT.getSimpleVT(), Legal);
686
James Molloy63be1982015-08-14 09:08:50 +0000687 // F[MIN|MAX][NUM|NAN] are available for all FP NEON types (not f16 though!).
688 if (VT.isFloatingPoint() && VT.getVectorElementType() != MVT::f16)
James Molloyb7b2a1e2015-08-11 12:06:37 +0000689 for (unsigned Opcode : {ISD::FMINNAN, ISD::FMAXNAN,
690 ISD::FMINNUM, ISD::FMAXNUM})
James Molloyedf38f02015-08-11 12:06:33 +0000691 setOperationAction(Opcode, VT.getSimpleVT(), Legal);
692
Tim Northover3b0846e2014-05-24 12:50:23 +0000693 if (Subtarget->isLittleEndian()) {
694 for (unsigned im = (unsigned)ISD::PRE_INC;
695 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
696 setIndexedLoadAction(im, VT.getSimpleVT(), Legal);
697 setIndexedStoreAction(im, VT.getSimpleVT(), Legal);
698 }
699 }
700}
701
702void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
703 addRegisterClass(VT, &AArch64::FPR64RegClass);
704 addTypeForNEON(VT, MVT::v2i32);
705}
706
707void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
708 addRegisterClass(VT, &AArch64::FPR128RegClass);
709 addTypeForNEON(VT, MVT::v4i32);
710}
711
Mehdi Amini44ede332015-07-09 02:09:04 +0000712EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
713 EVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +0000714 if (!VT.isVector())
715 return MVT::i32;
716 return VT.changeVectorElementTypeToInteger();
717}
718
719/// computeKnownBitsForTargetNode - Determine which of the bits specified in
720/// Mask are known to be either zero or one and return them in the
721/// KnownZero/KnownOne bitsets.
722void AArch64TargetLowering::computeKnownBitsForTargetNode(
723 const SDValue Op, APInt &KnownZero, APInt &KnownOne,
724 const SelectionDAG &DAG, unsigned Depth) const {
725 switch (Op.getOpcode()) {
726 default:
727 break;
728 case AArch64ISD::CSEL: {
729 APInt KnownZero2, KnownOne2;
730 DAG.computeKnownBits(Op->getOperand(0), KnownZero, KnownOne, Depth + 1);
731 DAG.computeKnownBits(Op->getOperand(1), KnownZero2, KnownOne2, Depth + 1);
732 KnownZero &= KnownZero2;
733 KnownOne &= KnownOne2;
734 break;
735 }
736 case ISD::INTRINSIC_W_CHAIN: {
737 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
738 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
739 switch (IntID) {
740 default: return;
741 case Intrinsic::aarch64_ldaxr:
742 case Intrinsic::aarch64_ldxr: {
743 unsigned BitWidth = KnownOne.getBitWidth();
744 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
745 unsigned MemBits = VT.getScalarType().getSizeInBits();
746 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
747 return;
748 }
749 }
750 break;
751 }
752 case ISD::INTRINSIC_WO_CHAIN:
753 case ISD::INTRINSIC_VOID: {
754 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
755 switch (IntNo) {
756 default:
757 break;
758 case Intrinsic::aarch64_neon_umaxv:
759 case Intrinsic::aarch64_neon_uminv: {
760 // Figure out the datatype of the vector operand. The UMINV instruction
761 // will zero extend the result, so we can mark as known zero all the
762 // bits larger than the element datatype. 32-bit or larget doesn't need
763 // this as those are legal types and will be handled by isel directly.
764 MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
765 unsigned BitWidth = KnownZero.getBitWidth();
766 if (VT == MVT::v8i8 || VT == MVT::v16i8) {
767 assert(BitWidth >= 8 && "Unexpected width!");
768 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
769 KnownZero |= Mask;
770 } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
771 assert(BitWidth >= 16 && "Unexpected width!");
772 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
773 KnownZero |= Mask;
774 }
775 break;
776 } break;
777 }
778 }
779 }
780}
781
Mehdi Aminieaabc512015-07-09 15:12:23 +0000782MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
783 EVT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +0000784 return MVT::i64;
785}
786
Akira Hatanakaf53b0402015-07-29 14:17:26 +0000787bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
788 unsigned AddrSpace,
789 unsigned Align,
790 bool *Fast) const {
791 if (Subtarget->requiresStrictAlign())
792 return false;
793 // FIXME: True for Cyclone, but not necessary others.
794 if (Fast)
795 *Fast = true;
796 return true;
797}
798
Tim Northover3b0846e2014-05-24 12:50:23 +0000799FastISel *
800AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
801 const TargetLibraryInfo *libInfo) const {
802 return AArch64::createFastISel(funcInfo, libInfo);
803}
804
805const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
Matthias Braund04893f2015-05-07 21:33:59 +0000806 switch ((AArch64ISD::NodeType)Opcode) {
807 case AArch64ISD::FIRST_NUMBER: break;
Tim Northover3b0846e2014-05-24 12:50:23 +0000808 case AArch64ISD::CALL: return "AArch64ISD::CALL";
809 case AArch64ISD::ADRP: return "AArch64ISD::ADRP";
810 case AArch64ISD::ADDlow: return "AArch64ISD::ADDlow";
811 case AArch64ISD::LOADgot: return "AArch64ISD::LOADgot";
812 case AArch64ISD::RET_FLAG: return "AArch64ISD::RET_FLAG";
813 case AArch64ISD::BRCOND: return "AArch64ISD::BRCOND";
814 case AArch64ISD::CSEL: return "AArch64ISD::CSEL";
815 case AArch64ISD::FCSEL: return "AArch64ISD::FCSEL";
816 case AArch64ISD::CSINV: return "AArch64ISD::CSINV";
817 case AArch64ISD::CSNEG: return "AArch64ISD::CSNEG";
818 case AArch64ISD::CSINC: return "AArch64ISD::CSINC";
819 case AArch64ISD::THREAD_POINTER: return "AArch64ISD::THREAD_POINTER";
Kristof Beylsaea84612015-03-04 09:12:08 +0000820 case AArch64ISD::TLSDESC_CALLSEQ: return "AArch64ISD::TLSDESC_CALLSEQ";
Tim Northover3b0846e2014-05-24 12:50:23 +0000821 case AArch64ISD::ADC: return "AArch64ISD::ADC";
822 case AArch64ISD::SBC: return "AArch64ISD::SBC";
823 case AArch64ISD::ADDS: return "AArch64ISD::ADDS";
824 case AArch64ISD::SUBS: return "AArch64ISD::SUBS";
825 case AArch64ISD::ADCS: return "AArch64ISD::ADCS";
826 case AArch64ISD::SBCS: return "AArch64ISD::SBCS";
827 case AArch64ISD::ANDS: return "AArch64ISD::ANDS";
Matthias Braunaf7d7702015-07-16 20:02:37 +0000828 case AArch64ISD::CCMP: return "AArch64ISD::CCMP";
829 case AArch64ISD::CCMN: return "AArch64ISD::CCMN";
830 case AArch64ISD::FCCMP: return "AArch64ISD::FCCMP";
Tim Northover3b0846e2014-05-24 12:50:23 +0000831 case AArch64ISD::FCMP: return "AArch64ISD::FCMP";
Tim Northover3b0846e2014-05-24 12:50:23 +0000832 case AArch64ISD::DUP: return "AArch64ISD::DUP";
833 case AArch64ISD::DUPLANE8: return "AArch64ISD::DUPLANE8";
834 case AArch64ISD::DUPLANE16: return "AArch64ISD::DUPLANE16";
835 case AArch64ISD::DUPLANE32: return "AArch64ISD::DUPLANE32";
836 case AArch64ISD::DUPLANE64: return "AArch64ISD::DUPLANE64";
837 case AArch64ISD::MOVI: return "AArch64ISD::MOVI";
838 case AArch64ISD::MOVIshift: return "AArch64ISD::MOVIshift";
839 case AArch64ISD::MOVIedit: return "AArch64ISD::MOVIedit";
840 case AArch64ISD::MOVImsl: return "AArch64ISD::MOVImsl";
841 case AArch64ISD::FMOV: return "AArch64ISD::FMOV";
842 case AArch64ISD::MVNIshift: return "AArch64ISD::MVNIshift";
843 case AArch64ISD::MVNImsl: return "AArch64ISD::MVNImsl";
844 case AArch64ISD::BICi: return "AArch64ISD::BICi";
845 case AArch64ISD::ORRi: return "AArch64ISD::ORRi";
846 case AArch64ISD::BSL: return "AArch64ISD::BSL";
847 case AArch64ISD::NEG: return "AArch64ISD::NEG";
848 case AArch64ISD::EXTR: return "AArch64ISD::EXTR";
849 case AArch64ISD::ZIP1: return "AArch64ISD::ZIP1";
850 case AArch64ISD::ZIP2: return "AArch64ISD::ZIP2";
851 case AArch64ISD::UZP1: return "AArch64ISD::UZP1";
852 case AArch64ISD::UZP2: return "AArch64ISD::UZP2";
853 case AArch64ISD::TRN1: return "AArch64ISD::TRN1";
854 case AArch64ISD::TRN2: return "AArch64ISD::TRN2";
855 case AArch64ISD::REV16: return "AArch64ISD::REV16";
856 case AArch64ISD::REV32: return "AArch64ISD::REV32";
857 case AArch64ISD::REV64: return "AArch64ISD::REV64";
858 case AArch64ISD::EXT: return "AArch64ISD::EXT";
859 case AArch64ISD::VSHL: return "AArch64ISD::VSHL";
860 case AArch64ISD::VLSHR: return "AArch64ISD::VLSHR";
861 case AArch64ISD::VASHR: return "AArch64ISD::VASHR";
862 case AArch64ISD::CMEQ: return "AArch64ISD::CMEQ";
863 case AArch64ISD::CMGE: return "AArch64ISD::CMGE";
864 case AArch64ISD::CMGT: return "AArch64ISD::CMGT";
865 case AArch64ISD::CMHI: return "AArch64ISD::CMHI";
866 case AArch64ISD::CMHS: return "AArch64ISD::CMHS";
867 case AArch64ISD::FCMEQ: return "AArch64ISD::FCMEQ";
868 case AArch64ISD::FCMGE: return "AArch64ISD::FCMGE";
869 case AArch64ISD::FCMGT: return "AArch64ISD::FCMGT";
870 case AArch64ISD::CMEQz: return "AArch64ISD::CMEQz";
871 case AArch64ISD::CMGEz: return "AArch64ISD::CMGEz";
872 case AArch64ISD::CMGTz: return "AArch64ISD::CMGTz";
873 case AArch64ISD::CMLEz: return "AArch64ISD::CMLEz";
874 case AArch64ISD::CMLTz: return "AArch64ISD::CMLTz";
875 case AArch64ISD::FCMEQz: return "AArch64ISD::FCMEQz";
876 case AArch64ISD::FCMGEz: return "AArch64ISD::FCMGEz";
877 case AArch64ISD::FCMGTz: return "AArch64ISD::FCMGTz";
878 case AArch64ISD::FCMLEz: return "AArch64ISD::FCMLEz";
879 case AArch64ISD::FCMLTz: return "AArch64ISD::FCMLTz";
Ahmed Bougachafab58922015-03-10 20:45:38 +0000880 case AArch64ISD::SADDV: return "AArch64ISD::SADDV";
881 case AArch64ISD::UADDV: return "AArch64ISD::UADDV";
882 case AArch64ISD::SMINV: return "AArch64ISD::SMINV";
883 case AArch64ISD::UMINV: return "AArch64ISD::UMINV";
884 case AArch64ISD::SMAXV: return "AArch64ISD::SMAXV";
885 case AArch64ISD::UMAXV: return "AArch64ISD::UMAXV";
Tim Northover3b0846e2014-05-24 12:50:23 +0000886 case AArch64ISD::NOT: return "AArch64ISD::NOT";
887 case AArch64ISD::BIT: return "AArch64ISD::BIT";
888 case AArch64ISD::CBZ: return "AArch64ISD::CBZ";
889 case AArch64ISD::CBNZ: return "AArch64ISD::CBNZ";
890 case AArch64ISD::TBZ: return "AArch64ISD::TBZ";
891 case AArch64ISD::TBNZ: return "AArch64ISD::TBNZ";
892 case AArch64ISD::TC_RETURN: return "AArch64ISD::TC_RETURN";
Matthias Braund04893f2015-05-07 21:33:59 +0000893 case AArch64ISD::PREFETCH: return "AArch64ISD::PREFETCH";
Tim Northover3b0846e2014-05-24 12:50:23 +0000894 case AArch64ISD::SITOF: return "AArch64ISD::SITOF";
895 case AArch64ISD::UITOF: return "AArch64ISD::UITOF";
Asiri Rathnayake530b3ed2014-10-01 09:59:45 +0000896 case AArch64ISD::NVCAST: return "AArch64ISD::NVCAST";
Tim Northover3b0846e2014-05-24 12:50:23 +0000897 case AArch64ISD::SQSHL_I: return "AArch64ISD::SQSHL_I";
898 case AArch64ISD::UQSHL_I: return "AArch64ISD::UQSHL_I";
899 case AArch64ISD::SRSHR_I: return "AArch64ISD::SRSHR_I";
900 case AArch64ISD::URSHR_I: return "AArch64ISD::URSHR_I";
901 case AArch64ISD::SQSHLU_I: return "AArch64ISD::SQSHLU_I";
902 case AArch64ISD::WrapperLarge: return "AArch64ISD::WrapperLarge";
903 case AArch64ISD::LD2post: return "AArch64ISD::LD2post";
904 case AArch64ISD::LD3post: return "AArch64ISD::LD3post";
905 case AArch64ISD::LD4post: return "AArch64ISD::LD4post";
906 case AArch64ISD::ST2post: return "AArch64ISD::ST2post";
907 case AArch64ISD::ST3post: return "AArch64ISD::ST3post";
908 case AArch64ISD::ST4post: return "AArch64ISD::ST4post";
909 case AArch64ISD::LD1x2post: return "AArch64ISD::LD1x2post";
910 case AArch64ISD::LD1x3post: return "AArch64ISD::LD1x3post";
911 case AArch64ISD::LD1x4post: return "AArch64ISD::LD1x4post";
912 case AArch64ISD::ST1x2post: return "AArch64ISD::ST1x2post";
913 case AArch64ISD::ST1x3post: return "AArch64ISD::ST1x3post";
914 case AArch64ISD::ST1x4post: return "AArch64ISD::ST1x4post";
915 case AArch64ISD::LD1DUPpost: return "AArch64ISD::LD1DUPpost";
916 case AArch64ISD::LD2DUPpost: return "AArch64ISD::LD2DUPpost";
917 case AArch64ISD::LD3DUPpost: return "AArch64ISD::LD3DUPpost";
918 case AArch64ISD::LD4DUPpost: return "AArch64ISD::LD4DUPpost";
919 case AArch64ISD::LD1LANEpost: return "AArch64ISD::LD1LANEpost";
920 case AArch64ISD::LD2LANEpost: return "AArch64ISD::LD2LANEpost";
921 case AArch64ISD::LD3LANEpost: return "AArch64ISD::LD3LANEpost";
922 case AArch64ISD::LD4LANEpost: return "AArch64ISD::LD4LANEpost";
923 case AArch64ISD::ST2LANEpost: return "AArch64ISD::ST2LANEpost";
924 case AArch64ISD::ST3LANEpost: return "AArch64ISD::ST3LANEpost";
925 case AArch64ISD::ST4LANEpost: return "AArch64ISD::ST4LANEpost";
Chad Rosierd9d0f862014-10-08 02:31:24 +0000926 case AArch64ISD::SMULL: return "AArch64ISD::SMULL";
927 case AArch64ISD::UMULL: return "AArch64ISD::UMULL";
Tim Northover3b0846e2014-05-24 12:50:23 +0000928 }
Matthias Braund04893f2015-05-07 21:33:59 +0000929 return nullptr;
Tim Northover3b0846e2014-05-24 12:50:23 +0000930}
931
932MachineBasicBlock *
933AArch64TargetLowering::EmitF128CSEL(MachineInstr *MI,
934 MachineBasicBlock *MBB) const {
935 // We materialise the F128CSEL pseudo-instruction as some control flow and a
936 // phi node:
937
938 // OrigBB:
939 // [... previous instrs leading to comparison ...]
940 // b.ne TrueBB
941 // b EndBB
942 // TrueBB:
943 // ; Fallthrough
944 // EndBB:
945 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
946
Tim Northover3b0846e2014-05-24 12:50:23 +0000947 MachineFunction *MF = MBB->getParent();
Eric Christopher905f12d2015-01-29 00:19:42 +0000948 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +0000949 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
950 DebugLoc DL = MI->getDebugLoc();
951 MachineFunction::iterator It = MBB;
952 ++It;
953
954 unsigned DestReg = MI->getOperand(0).getReg();
955 unsigned IfTrueReg = MI->getOperand(1).getReg();
956 unsigned IfFalseReg = MI->getOperand(2).getReg();
957 unsigned CondCode = MI->getOperand(3).getImm();
958 bool NZCVKilled = MI->getOperand(4).isKill();
959
960 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
961 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
962 MF->insert(It, TrueBB);
963 MF->insert(It, EndBB);
964
965 // Transfer rest of current basic-block to EndBB
966 EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
967 MBB->end());
968 EndBB->transferSuccessorsAndUpdatePHIs(MBB);
969
970 BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
971 BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
972 MBB->addSuccessor(TrueBB);
973 MBB->addSuccessor(EndBB);
974
975 // TrueBB falls through to the end.
976 TrueBB->addSuccessor(EndBB);
977
978 if (!NZCVKilled) {
979 TrueBB->addLiveIn(AArch64::NZCV);
980 EndBB->addLiveIn(AArch64::NZCV);
981 }
982
983 BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
984 .addReg(IfTrueReg)
985 .addMBB(TrueBB)
986 .addReg(IfFalseReg)
987 .addMBB(MBB);
988
989 MI->eraseFromParent();
990 return EndBB;
991}
992
993MachineBasicBlock *
994AArch64TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
995 MachineBasicBlock *BB) const {
996 switch (MI->getOpcode()) {
997 default:
998#ifndef NDEBUG
999 MI->dump();
1000#endif
Craig Topper35b2f752014-06-19 06:10:58 +00001001 llvm_unreachable("Unexpected instruction for custom inserter!");
Tim Northover3b0846e2014-05-24 12:50:23 +00001002
1003 case AArch64::F128CSEL:
1004 return EmitF128CSEL(MI, BB);
1005
1006 case TargetOpcode::STACKMAP:
1007 case TargetOpcode::PATCHPOINT:
1008 return emitPatchPoint(MI, BB);
1009 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001010}
1011
1012//===----------------------------------------------------------------------===//
1013// AArch64 Lowering private implementation.
1014//===----------------------------------------------------------------------===//
1015
1016//===----------------------------------------------------------------------===//
1017// Lowering Code
1018//===----------------------------------------------------------------------===//
1019
1020/// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1021/// CC
1022static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1023 switch (CC) {
1024 default:
1025 llvm_unreachable("Unknown condition code!");
1026 case ISD::SETNE:
1027 return AArch64CC::NE;
1028 case ISD::SETEQ:
1029 return AArch64CC::EQ;
1030 case ISD::SETGT:
1031 return AArch64CC::GT;
1032 case ISD::SETGE:
1033 return AArch64CC::GE;
1034 case ISD::SETLT:
1035 return AArch64CC::LT;
1036 case ISD::SETLE:
1037 return AArch64CC::LE;
1038 case ISD::SETUGT:
1039 return AArch64CC::HI;
1040 case ISD::SETUGE:
1041 return AArch64CC::HS;
1042 case ISD::SETULT:
1043 return AArch64CC::LO;
1044 case ISD::SETULE:
1045 return AArch64CC::LS;
1046 }
1047}
1048
1049/// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1050static void changeFPCCToAArch64CC(ISD::CondCode CC,
1051 AArch64CC::CondCode &CondCode,
1052 AArch64CC::CondCode &CondCode2) {
1053 CondCode2 = AArch64CC::AL;
1054 switch (CC) {
1055 default:
1056 llvm_unreachable("Unknown FP condition!");
1057 case ISD::SETEQ:
1058 case ISD::SETOEQ:
1059 CondCode = AArch64CC::EQ;
1060 break;
1061 case ISD::SETGT:
1062 case ISD::SETOGT:
1063 CondCode = AArch64CC::GT;
1064 break;
1065 case ISD::SETGE:
1066 case ISD::SETOGE:
1067 CondCode = AArch64CC::GE;
1068 break;
1069 case ISD::SETOLT:
1070 CondCode = AArch64CC::MI;
1071 break;
1072 case ISD::SETOLE:
1073 CondCode = AArch64CC::LS;
1074 break;
1075 case ISD::SETONE:
1076 CondCode = AArch64CC::MI;
1077 CondCode2 = AArch64CC::GT;
1078 break;
1079 case ISD::SETO:
1080 CondCode = AArch64CC::VC;
1081 break;
1082 case ISD::SETUO:
1083 CondCode = AArch64CC::VS;
1084 break;
1085 case ISD::SETUEQ:
1086 CondCode = AArch64CC::EQ;
1087 CondCode2 = AArch64CC::VS;
1088 break;
1089 case ISD::SETUGT:
1090 CondCode = AArch64CC::HI;
1091 break;
1092 case ISD::SETUGE:
1093 CondCode = AArch64CC::PL;
1094 break;
1095 case ISD::SETLT:
1096 case ISD::SETULT:
1097 CondCode = AArch64CC::LT;
1098 break;
1099 case ISD::SETLE:
1100 case ISD::SETULE:
1101 CondCode = AArch64CC::LE;
1102 break;
1103 case ISD::SETNE:
1104 case ISD::SETUNE:
1105 CondCode = AArch64CC::NE;
1106 break;
1107 }
1108}
1109
1110/// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1111/// CC usable with the vector instructions. Fewer operations are available
1112/// without a real NZCV register, so we have to use less efficient combinations
1113/// to get the same effect.
1114static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1115 AArch64CC::CondCode &CondCode,
1116 AArch64CC::CondCode &CondCode2,
1117 bool &Invert) {
1118 Invert = false;
1119 switch (CC) {
1120 default:
1121 // Mostly the scalar mappings work fine.
1122 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1123 break;
1124 case ISD::SETUO:
1125 Invert = true; // Fallthrough
1126 case ISD::SETO:
1127 CondCode = AArch64CC::MI;
1128 CondCode2 = AArch64CC::GE;
1129 break;
1130 case ISD::SETUEQ:
1131 case ISD::SETULT:
1132 case ISD::SETULE:
1133 case ISD::SETUGT:
1134 case ISD::SETUGE:
1135 // All of the compare-mask comparisons are ordered, but we can switch
1136 // between the two by a double inversion. E.g. ULE == !OGT.
1137 Invert = true;
1138 changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1139 break;
1140 }
1141}
1142
1143static bool isLegalArithImmed(uint64_t C) {
1144 // Matches AArch64DAGToDAGISel::SelectArithImmed().
1145 return (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1146}
1147
1148static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1149 SDLoc dl, SelectionDAG &DAG) {
1150 EVT VT = LHS.getValueType();
1151
1152 if (VT.isFloatingPoint())
1153 return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
1154
1155 // The CMP instruction is just an alias for SUBS, and representing it as
1156 // SUBS means that it's possible to get CSE with subtract operations.
1157 // A later phase can perform the optimization of setting the destination
1158 // register to WZR/XZR if it ends up being unused.
1159 unsigned Opcode = AArch64ISD::SUBS;
1160
1161 if (RHS.getOpcode() == ISD::SUB && isa<ConstantSDNode>(RHS.getOperand(0)) &&
1162 cast<ConstantSDNode>(RHS.getOperand(0))->getZExtValue() == 0 &&
1163 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1164 // We'd like to combine a (CMP op1, (sub 0, op2) into a CMN instruction on
1165 // the grounds that "op1 - (-op2) == op1 + op2". However, the C and V flags
1166 // can be set differently by this operation. It comes down to whether
1167 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1168 // everything is fine. If not then the optimization is wrong. Thus general
1169 // comparisons are only valid if op2 != 0.
1170
1171 // So, finally, the only LLVM-native comparisons that don't mention C and V
1172 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1173 // the absence of information about op2.
1174 Opcode = AArch64ISD::ADDS;
1175 RHS = RHS.getOperand(1);
1176 } else if (LHS.getOpcode() == ISD::AND && isa<ConstantSDNode>(RHS) &&
1177 cast<ConstantSDNode>(RHS)->getZExtValue() == 0 &&
1178 !isUnsignedIntSetCC(CC)) {
1179 // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1180 // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1181 // of the signed comparisons.
1182 Opcode = AArch64ISD::ANDS;
1183 RHS = LHS.getOperand(1);
1184 LHS = LHS.getOperand(0);
1185 }
1186
Matthias Braunaf7d7702015-07-16 20:02:37 +00001187 return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
Tim Northover3b0846e2014-05-24 12:50:23 +00001188 .getValue(1);
1189}
1190
Matthias Braunaf7d7702015-07-16 20:02:37 +00001191/// \defgroup AArch64CCMP CMP;CCMP matching
1192///
1193/// These functions deal with the formation of CMP;CCMP;... sequences.
1194/// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1195/// a comparison. They set the NZCV flags to a predefined value if their
1196/// predicate is false. This allows to express arbitrary conjunctions, for
1197/// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B))))"
1198/// expressed as:
1199/// cmp A
1200/// ccmp B, inv(CB), CA
1201/// check for CB flags
1202///
1203/// In general we can create code for arbitrary "... (and (and A B) C)"
1204/// sequences. We can also implement some "or" expressions, because "(or A B)"
1205/// is equivalent to "not (and (not A) (not B))" and we can implement some
1206/// negation operations:
1207/// We can negate the results of a single comparison by inverting the flags
1208/// used when the predicate fails and inverting the flags tested in the next
1209/// instruction; We can also negate the results of the whole previous
1210/// conditional compare sequence by inverting the flags tested in the next
1211/// instruction. However there is no way to negate the result of a partial
1212/// sequence.
1213///
1214/// Therefore on encountering an "or" expression we can negate the subtree on
1215/// one side and have to be able to push the negate to the leafs of the subtree
1216/// on the other side (see also the comments in code). As complete example:
1217/// "or (or (setCA (cmp A)) (setCB (cmp B)))
1218/// (and (setCC (cmp C)) (setCD (cmp D)))"
1219/// is transformed to
1220/// "not (and (not (and (setCC (cmp C)) (setCC (cmp D))))
1221/// (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1222/// and implemented as:
1223/// cmp C
1224/// ccmp D, inv(CD), CC
1225/// ccmp A, CA, inv(CD)
1226/// ccmp B, CB, inv(CA)
1227/// check for CB flags
1228/// A counterexample is "or (and A B) (and C D)" which cannot be implemented
1229/// by conditional compare sequences.
1230/// @{
1231
Geoff Berrye41c2df2015-07-20 22:03:52 +00001232/// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001233static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1234 ISD::CondCode CC, SDValue CCOp,
1235 SDValue Condition, unsigned NZCV,
1236 SDLoc DL, SelectionDAG &DAG) {
1237 unsigned Opcode = 0;
1238 if (LHS.getValueType().isFloatingPoint())
1239 Opcode = AArch64ISD::FCCMP;
1240 else if (RHS.getOpcode() == ISD::SUB) {
1241 SDValue SubOp0 = RHS.getOperand(0);
1242 if (const ConstantSDNode *SubOp0C = dyn_cast<ConstantSDNode>(SubOp0))
1243 if (SubOp0C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1244 // See emitComparison() on why we can only do this for SETEQ and SETNE.
1245 Opcode = AArch64ISD::CCMN;
1246 RHS = RHS.getOperand(1);
1247 }
1248 }
1249 if (Opcode == 0)
1250 Opcode = AArch64ISD::CCMP;
1251
1252 SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1253 return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1254}
1255
1256/// Returns true if @p Val is a tree of AND/OR/SETCC operations.
1257/// CanPushNegate is set to true if we can push a negate operation through
1258/// the tree in a was that we are left with AND operations and negate operations
1259/// at the leafs only. i.e. "not (or (or x y) z)" can be changed to
1260/// "and (and (not x) (not y)) (not z)"; "not (or (and x y) z)" cannot be
1261/// brought into such a form.
1262static bool isConjunctionDisjunctionTree(const SDValue Val, bool &CanPushNegate,
1263 unsigned Depth = 0) {
1264 if (!Val.hasOneUse())
1265 return false;
1266 unsigned Opcode = Val->getOpcode();
1267 if (Opcode == ISD::SETCC) {
1268 CanPushNegate = true;
1269 return true;
1270 }
1271 // Protect against stack overflow.
1272 if (Depth > 15)
1273 return false;
1274 if (Opcode == ISD::AND || Opcode == ISD::OR) {
1275 SDValue O0 = Val->getOperand(0);
1276 SDValue O1 = Val->getOperand(1);
1277 bool CanPushNegateL;
1278 if (!isConjunctionDisjunctionTree(O0, CanPushNegateL, Depth+1))
1279 return false;
1280 bool CanPushNegateR;
1281 if (!isConjunctionDisjunctionTree(O1, CanPushNegateR, Depth+1))
1282 return false;
1283 // We cannot push a negate through an AND operation (it would become an OR),
1284 // we can however change a (not (or x y)) to (and (not x) (not y)) if we can
1285 // push the negate through the x/y subtrees.
1286 CanPushNegate = (Opcode == ISD::OR) && CanPushNegateL && CanPushNegateR;
1287 return true;
1288 }
1289 return false;
1290}
1291
1292/// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1293/// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1294/// Tries to transform the given i1 producing node @p Val to a series compare
1295/// and conditional compare operations. @returns an NZCV flags producing node
1296/// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1297/// transformation was not possible.
1298/// On recursive invocations @p PushNegate may be set to true to have negation
1299/// effects pushed to the tree leafs; @p Predicate is an NZCV flag predicate
1300/// for the comparisons in the current subtree; @p Depth limits the search
1301/// depth to avoid stack overflow.
1302static SDValue emitConjunctionDisjunctionTree(SelectionDAG &DAG, SDValue Val,
1303 AArch64CC::CondCode &OutCC, bool PushNegate = false,
1304 SDValue CCOp = SDValue(), AArch64CC::CondCode Predicate = AArch64CC::AL,
1305 unsigned Depth = 0) {
1306 // We're at a tree leaf, produce a conditional comparison operation.
1307 unsigned Opcode = Val->getOpcode();
1308 if (Opcode == ISD::SETCC) {
1309 SDValue LHS = Val->getOperand(0);
1310 SDValue RHS = Val->getOperand(1);
1311 ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1312 bool isInteger = LHS.getValueType().isInteger();
1313 if (PushNegate)
1314 CC = getSetCCInverse(CC, isInteger);
1315 SDLoc DL(Val);
1316 // Determine OutCC and handle FP special case.
1317 if (isInteger) {
1318 OutCC = changeIntCCToAArch64CC(CC);
1319 } else {
1320 assert(LHS.getValueType().isFloatingPoint());
1321 AArch64CC::CondCode ExtraCC;
1322 changeFPCCToAArch64CC(CC, OutCC, ExtraCC);
1323 // Surpisingly some floating point conditions can't be tested with a
1324 // single condition code. Construct an additional comparison in this case.
1325 // See comment below on how we deal with OR conditions.
1326 if (ExtraCC != AArch64CC::AL) {
1327 SDValue ExtraCmp;
1328 if (!CCOp.getNode())
1329 ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
1330 else {
1331 SDValue ConditionOp = DAG.getConstant(Predicate, DL, MVT_CC);
1332 // Note that we want the inverse of ExtraCC, so NZCV is not inversed.
1333 unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(ExtraCC);
1334 ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, ConditionOp,
1335 NZCV, DL, DAG);
1336 }
1337 CCOp = ExtraCmp;
1338 Predicate = AArch64CC::getInvertedCondCode(ExtraCC);
1339 OutCC = AArch64CC::getInvertedCondCode(OutCC);
1340 }
1341 }
1342
1343 // Produce a normal comparison if we are first in the chain
1344 if (!CCOp.getNode())
1345 return emitComparison(LHS, RHS, CC, DL, DAG);
1346 // Otherwise produce a ccmp.
1347 SDValue ConditionOp = DAG.getConstant(Predicate, DL, MVT_CC);
1348 AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1349 unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
1350 return emitConditionalComparison(LHS, RHS, CC, CCOp, ConditionOp, NZCV, DL,
1351 DAG);
Matthias Braun266204b2015-08-20 23:33:31 +00001352 } else if ((Opcode != ISD::AND && Opcode != ISD::OR) || !Val->hasOneUse())
Matthias Braunaf7d7702015-07-16 20:02:37 +00001353 return SDValue();
1354
1355 assert((Opcode == ISD::OR || !PushNegate)
1356 && "Can only push negate through OR operation");
1357
1358 // Check if both sides can be transformed.
1359 SDValue LHS = Val->getOperand(0);
1360 SDValue RHS = Val->getOperand(1);
1361 bool CanPushNegateL;
1362 if (!isConjunctionDisjunctionTree(LHS, CanPushNegateL, Depth+1))
1363 return SDValue();
1364 bool CanPushNegateR;
1365 if (!isConjunctionDisjunctionTree(RHS, CanPushNegateR, Depth+1))
1366 return SDValue();
1367
1368 // Do we need to negate our operands?
1369 bool NegateOperands = Opcode == ISD::OR;
1370 // We can negate the results of all previous operations by inverting the
1371 // predicate flags giving us a free negation for one side. For the other side
1372 // we need to be able to push the negation to the leafs of the tree.
1373 if (NegateOperands) {
1374 if (!CanPushNegateL && !CanPushNegateR)
1375 return SDValue();
1376 // Order the side where we can push the negate through to LHS.
Matthias Braun46e56392015-08-20 23:33:34 +00001377 if (!CanPushNegateL && CanPushNegateR)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001378 std::swap(LHS, RHS);
Matthias Braun46e56392015-08-20 23:33:34 +00001379 } else {
1380 bool NeedsNegOutL = LHS->getOpcode() == ISD::OR;
1381 bool NeedsNegOutR = RHS->getOpcode() == ISD::OR;
1382 if (NeedsNegOutL && NeedsNegOutR)
1383 return SDValue();
1384 // Order the side where we need to negate the output flags to RHS so it
1385 // gets emitted first.
1386 if (NeedsNegOutL)
1387 std::swap(LHS, RHS);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001388 }
1389
1390 // Emit RHS. If we want to negate the tree we only need to push a negate
1391 // through if we are already in a PushNegate case, otherwise we can negate
1392 // the "flags to test" afterwards.
1393 AArch64CC::CondCode RHSCC;
1394 SDValue CmpR = emitConjunctionDisjunctionTree(DAG, RHS, RHSCC, PushNegate,
1395 CCOp, Predicate, Depth+1);
1396 if (NegateOperands && !PushNegate)
1397 RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
1398 // Emit LHS. We must push the negate through if we need to negate it.
1399 SDValue CmpL = emitConjunctionDisjunctionTree(DAG, LHS, OutCC, NegateOperands,
1400 CmpR, RHSCC, Depth+1);
1401 // If we transformed an OR to and AND then we have to negate the result
1402 // (or absorb a PushNegate resulting in a double negation).
1403 if (Opcode == ISD::OR && !PushNegate)
1404 OutCC = AArch64CC::getInvertedCondCode(OutCC);
1405 return CmpL;
1406}
1407
1408/// @}
1409
Tim Northover3b0846e2014-05-24 12:50:23 +00001410static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1411 SDValue &AArch64cc, SelectionDAG &DAG, SDLoc dl) {
1412 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1413 EVT VT = RHS.getValueType();
1414 uint64_t C = RHSC->getZExtValue();
1415 if (!isLegalArithImmed(C)) {
1416 // Constant does not fit, try adjusting it by one?
1417 switch (CC) {
1418 default:
1419 break;
1420 case ISD::SETLT:
1421 case ISD::SETGE:
1422 if ((VT == MVT::i32 && C != 0x80000000 &&
1423 isLegalArithImmed((uint32_t)(C - 1))) ||
1424 (VT == MVT::i64 && C != 0x80000000ULL &&
1425 isLegalArithImmed(C - 1ULL))) {
1426 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1427 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001428 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001429 }
1430 break;
1431 case ISD::SETULT:
1432 case ISD::SETUGE:
1433 if ((VT == MVT::i32 && C != 0 &&
1434 isLegalArithImmed((uint32_t)(C - 1))) ||
1435 (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1436 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1437 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001438 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001439 }
1440 break;
1441 case ISD::SETLE:
1442 case ISD::SETGT:
Oliver Stannard269a275c2014-11-03 15:28:40 +00001443 if ((VT == MVT::i32 && C != INT32_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001444 isLegalArithImmed((uint32_t)(C + 1))) ||
Oliver Stannard269a275c2014-11-03 15:28:40 +00001445 (VT == MVT::i64 && C != INT64_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001446 isLegalArithImmed(C + 1ULL))) {
1447 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1448 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001449 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001450 }
1451 break;
1452 case ISD::SETULE:
1453 case ISD::SETUGT:
Oliver Stannard269a275c2014-11-03 15:28:40 +00001454 if ((VT == MVT::i32 && C != UINT32_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001455 isLegalArithImmed((uint32_t)(C + 1))) ||
Oliver Stannard269a275c2014-11-03 15:28:40 +00001456 (VT == MVT::i64 && C != UINT64_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001457 isLegalArithImmed(C + 1ULL))) {
1458 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1459 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001460 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001461 }
1462 break;
1463 }
1464 }
1465 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001466 SDValue Cmp;
1467 AArch64CC::CondCode AArch64CC;
David Xuee978202014-08-28 04:59:53 +00001468 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001469 const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
1470
1471 // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
1472 // For the i8 operand, the largest immediate is 255, so this can be easily
1473 // encoded in the compare instruction. For the i16 operand, however, the
1474 // largest immediate cannot be encoded in the compare.
1475 // Therefore, use a sign extending load and cmn to avoid materializing the
1476 // -1 constant. For example,
1477 // movz w1, #65535
1478 // ldrh w0, [x0, #0]
1479 // cmp w0, w1
1480 // >
1481 // ldrsh w0, [x0, #0]
1482 // cmn w0, #1
1483 // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
1484 // if and only if (sext LHS) == (sext RHS). The checks are in place to
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001485 // ensure both the LHS and RHS are truly zero extended and to make sure the
Matthias Braunaf7d7702015-07-16 20:02:37 +00001486 // transformation is profitable.
1487 if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
1488 cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
1489 cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
1490 LHS.getNode()->hasNUsesOfValue(1, 0)) {
1491 int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
1492 if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
1493 SDValue SExt =
1494 DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
1495 DAG.getValueType(MVT::i16));
1496 Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
1497 RHS.getValueType()),
1498 CC, dl, DAG);
1499 AArch64CC = changeIntCCToAArch64CC(CC);
1500 }
1501 }
1502
1503 if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
1504 if ((Cmp = emitConjunctionDisjunctionTree(DAG, LHS, AArch64CC))) {
1505 if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
1506 AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
David Xuee978202014-08-28 04:59:53 +00001507 }
1508 }
1509 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001510
1511 if (!Cmp) {
1512 Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
1513 AArch64CC = changeIntCCToAArch64CC(CC);
1514 }
1515 AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
Tim Northover3b0846e2014-05-24 12:50:23 +00001516 return Cmp;
1517}
1518
1519static std::pair<SDValue, SDValue>
1520getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
1521 assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
1522 "Unsupported value type");
1523 SDValue Value, Overflow;
1524 SDLoc DL(Op);
1525 SDValue LHS = Op.getOperand(0);
1526 SDValue RHS = Op.getOperand(1);
1527 unsigned Opc = 0;
1528 switch (Op.getOpcode()) {
1529 default:
1530 llvm_unreachable("Unknown overflow instruction!");
1531 case ISD::SADDO:
1532 Opc = AArch64ISD::ADDS;
1533 CC = AArch64CC::VS;
1534 break;
1535 case ISD::UADDO:
1536 Opc = AArch64ISD::ADDS;
1537 CC = AArch64CC::HS;
1538 break;
1539 case ISD::SSUBO:
1540 Opc = AArch64ISD::SUBS;
1541 CC = AArch64CC::VS;
1542 break;
1543 case ISD::USUBO:
1544 Opc = AArch64ISD::SUBS;
1545 CC = AArch64CC::LO;
1546 break;
1547 // Multiply needs a little bit extra work.
1548 case ISD::SMULO:
1549 case ISD::UMULO: {
1550 CC = AArch64CC::NE;
David Blaikie186d2cb2015-03-24 16:24:01 +00001551 bool IsSigned = Op.getOpcode() == ISD::SMULO;
Tim Northover3b0846e2014-05-24 12:50:23 +00001552 if (Op.getValueType() == MVT::i32) {
1553 unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1554 // For a 32 bit multiply with overflow check we want the instruction
1555 // selector to generate a widening multiply (SMADDL/UMADDL). For that we
1556 // need to generate the following pattern:
1557 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
1558 LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
1559 RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
1560 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1561 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001562 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001563 // On AArch64 the upper 32 bits are always zero extended for a 32 bit
1564 // operation. We need to clear out the upper 32 bits, because we used a
1565 // widening multiply that wrote all 64 bits. In the end this should be a
1566 // noop.
1567 Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
1568 if (IsSigned) {
1569 // The signed overflow check requires more than just a simple check for
1570 // any bit set in the upper 32 bits of the result. These bits could be
1571 // just the sign bits of a negative number. To perform the overflow
1572 // check we have to arithmetic shift right the 32nd bit of the result by
1573 // 31 bits. Then we compare the result to the upper 32 bits.
1574 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001575 DAG.getConstant(32, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001576 UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
1577 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001578 DAG.getConstant(31, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001579 // It is important that LowerBits is last, otherwise the arithmetic
1580 // shift will not be folded into the compare (SUBS).
1581 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
1582 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1583 .getValue(1);
1584 } else {
1585 // The overflow check for unsigned multiply is easy. We only need to
1586 // check if any of the upper 32 bits are set. This can be done with a
1587 // CMP (shifted register). For that we need to generate the following
1588 // pattern:
1589 // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
1590 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001591 DAG.getConstant(32, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001592 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1593 Overflow =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001594 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1595 DAG.getConstant(0, DL, MVT::i64),
Tim Northover3b0846e2014-05-24 12:50:23 +00001596 UpperBits).getValue(1);
1597 }
1598 break;
1599 }
1600 assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
1601 // For the 64 bit multiply
1602 Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1603 if (IsSigned) {
1604 SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
1605 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001606 DAG.getConstant(63, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001607 // It is important that LowerBits is last, otherwise the arithmetic
1608 // shift will not be folded into the compare (SUBS).
1609 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1610 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1611 .getValue(1);
1612 } else {
1613 SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
1614 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1615 Overflow =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001616 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1617 DAG.getConstant(0, DL, MVT::i64),
Tim Northover3b0846e2014-05-24 12:50:23 +00001618 UpperBits).getValue(1);
1619 }
1620 break;
1621 }
1622 } // switch (...)
1623
1624 if (Opc) {
1625 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
1626
1627 // Emit the AArch64 operation with overflow check.
1628 Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
1629 Overflow = Value.getValue(1);
1630 }
1631 return std::make_pair(Value, Overflow);
1632}
1633
1634SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
1635 RTLIB::Libcall Call) const {
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00001636 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
Tim Northover3b0846e2014-05-24 12:50:23 +00001637 return makeLibCall(DAG, Call, MVT::f128, &Ops[0], Ops.size(), false,
1638 SDLoc(Op)).first;
1639}
1640
1641static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
1642 SDValue Sel = Op.getOperand(0);
1643 SDValue Other = Op.getOperand(1);
1644
1645 // If neither operand is a SELECT_CC, give up.
1646 if (Sel.getOpcode() != ISD::SELECT_CC)
1647 std::swap(Sel, Other);
1648 if (Sel.getOpcode() != ISD::SELECT_CC)
1649 return Op;
1650
1651 // The folding we want to perform is:
1652 // (xor x, (select_cc a, b, cc, 0, -1) )
1653 // -->
1654 // (csel x, (xor x, -1), cc ...)
1655 //
1656 // The latter will get matched to a CSINV instruction.
1657
1658 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
1659 SDValue LHS = Sel.getOperand(0);
1660 SDValue RHS = Sel.getOperand(1);
1661 SDValue TVal = Sel.getOperand(2);
1662 SDValue FVal = Sel.getOperand(3);
1663 SDLoc dl(Sel);
1664
1665 // FIXME: This could be generalized to non-integer comparisons.
1666 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
1667 return Op;
1668
1669 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
1670 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
1671
Eric Christopher572e03a2015-06-19 01:53:21 +00001672 // The values aren't constants, this isn't the pattern we're looking for.
Tim Northover3b0846e2014-05-24 12:50:23 +00001673 if (!CFVal || !CTVal)
1674 return Op;
1675
1676 // We can commute the SELECT_CC by inverting the condition. This
1677 // might be needed to make this fit into a CSINV pattern.
1678 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
1679 std::swap(TVal, FVal);
1680 std::swap(CTVal, CFVal);
1681 CC = ISD::getSetCCInverse(CC, true);
1682 }
1683
1684 // If the constants line up, perform the transform!
1685 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
1686 SDValue CCVal;
1687 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
1688
1689 FVal = Other;
1690 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001691 DAG.getConstant(-1ULL, dl, Other.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00001692
1693 return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
1694 CCVal, Cmp);
1695 }
1696
1697 return Op;
1698}
1699
1700static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
1701 EVT VT = Op.getValueType();
1702
1703 // Let legalize expand this if it isn't a legal type yet.
1704 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
1705 return SDValue();
1706
1707 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
1708
1709 unsigned Opc;
1710 bool ExtraOp = false;
1711 switch (Op.getOpcode()) {
1712 default:
Craig Topper2a30d782014-06-18 05:05:13 +00001713 llvm_unreachable("Invalid code");
Tim Northover3b0846e2014-05-24 12:50:23 +00001714 case ISD::ADDC:
1715 Opc = AArch64ISD::ADDS;
1716 break;
1717 case ISD::SUBC:
1718 Opc = AArch64ISD::SUBS;
1719 break;
1720 case ISD::ADDE:
1721 Opc = AArch64ISD::ADCS;
1722 ExtraOp = true;
1723 break;
1724 case ISD::SUBE:
1725 Opc = AArch64ISD::SBCS;
1726 ExtraOp = true;
1727 break;
1728 }
1729
1730 if (!ExtraOp)
1731 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
1732 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
1733 Op.getOperand(2));
1734}
1735
1736static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
1737 // Let legalize expand this if it isn't a legal type yet.
1738 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
1739 return SDValue();
1740
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001741 SDLoc dl(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00001742 AArch64CC::CondCode CC;
1743 // The actual operation that sets the overflow or carry flag.
1744 SDValue Value, Overflow;
1745 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
1746
1747 // We use 0 and 1 as false and true values.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001748 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
1749 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00001750
1751 // We use an inverted condition, because the conditional select is inverted
1752 // too. This will allow it to be selected to a single instruction:
1753 // CSINC Wd, WZR, WZR, invert(cond).
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001754 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
1755 Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
Tim Northover3b0846e2014-05-24 12:50:23 +00001756 CCVal, Overflow);
1757
1758 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001759 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
Tim Northover3b0846e2014-05-24 12:50:23 +00001760}
1761
1762// Prefetch operands are:
1763// 1: Address to prefetch
1764// 2: bool isWrite
1765// 3: int locality (0 = no locality ... 3 = extreme locality)
1766// 4: bool isDataCache
1767static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
1768 SDLoc DL(Op);
1769 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
1770 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
Yi Konge56de692014-08-05 12:46:47 +00001771 unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00001772
1773 bool IsStream = !Locality;
1774 // When the locality number is set
1775 if (Locality) {
1776 // The front-end should have filtered out the out-of-range values
1777 assert(Locality <= 3 && "Prefetch locality out-of-range");
1778 // The locality degree is the opposite of the cache speed.
1779 // Put the number the other way around.
1780 // The encoding starts at 0 for level 1
1781 Locality = 3 - Locality;
1782 }
1783
1784 // built the mask value encoding the expected behavior.
1785 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit
Yi Konge56de692014-08-05 12:46:47 +00001786 (!IsData << 3) | // IsDataCache bit
Tim Northover3b0846e2014-05-24 12:50:23 +00001787 (Locality << 1) | // Cache level bits
1788 (unsigned)IsStream; // Stream bit
1789 return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001790 DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00001791}
1792
1793SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
1794 SelectionDAG &DAG) const {
1795 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
1796
1797 RTLIB::Libcall LC;
1798 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
1799
1800 return LowerF128Call(Op, DAG, LC);
1801}
1802
1803SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
1804 SelectionDAG &DAG) const {
1805 if (Op.getOperand(0).getValueType() != MVT::f128) {
1806 // It's legal except when f128 is involved
1807 return Op;
1808 }
1809
1810 RTLIB::Libcall LC;
1811 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
1812
1813 // FP_ROUND node has a second operand indicating whether it is known to be
1814 // precise. That doesn't take part in the LibCall so we can't directly use
1815 // LowerF128Call.
1816 SDValue SrcVal = Op.getOperand(0);
1817 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
1818 /*isSigned*/ false, SDLoc(Op)).first;
1819}
1820
1821static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
1822 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1823 // Any additional optimization in this function should be recorded
1824 // in the cost tables.
1825 EVT InVT = Op.getOperand(0).getValueType();
1826 EVT VT = Op.getValueType();
1827
Tim Northoverdbecc3b2014-06-15 09:27:15 +00001828 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001829 SDLoc dl(Op);
1830 SDValue Cv =
1831 DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
1832 Op.getOperand(0));
1833 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
Tim Northoverdbecc3b2014-06-15 09:27:15 +00001834 }
1835
1836 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001837 SDLoc dl(Op);
Oliver Stannard89d15422014-08-27 16:16:04 +00001838 MVT ExtVT =
1839 MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
1840 VT.getVectorNumElements());
1841 SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
Tim Northover3b0846e2014-05-24 12:50:23 +00001842 return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
1843 }
1844
1845 // Type changing conversions are illegal.
Tim Northoverdbecc3b2014-06-15 09:27:15 +00001846 return Op;
Tim Northover3b0846e2014-05-24 12:50:23 +00001847}
1848
1849SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
1850 SelectionDAG &DAG) const {
1851 if (Op.getOperand(0).getValueType().isVector())
1852 return LowerVectorFP_TO_INT(Op, DAG);
1853
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00001854 // f16 conversions are promoted to f32.
1855 if (Op.getOperand(0).getValueType() == MVT::f16) {
1856 SDLoc dl(Op);
1857 return DAG.getNode(
1858 Op.getOpcode(), dl, Op.getValueType(),
1859 DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
1860 }
1861
Tim Northover3b0846e2014-05-24 12:50:23 +00001862 if (Op.getOperand(0).getValueType() != MVT::f128) {
1863 // It's legal except when f128 is involved
1864 return Op;
1865 }
1866
1867 RTLIB::Libcall LC;
1868 if (Op.getOpcode() == ISD::FP_TO_SINT)
1869 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
1870 else
1871 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
1872
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00001873 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
Tim Northover3b0846e2014-05-24 12:50:23 +00001874 return makeLibCall(DAG, LC, Op.getValueType(), &Ops[0], Ops.size(), false,
1875 SDLoc(Op)).first;
1876}
1877
1878static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
1879 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1880 // Any additional optimization in this function should be recorded
1881 // in the cost tables.
1882 EVT VT = Op.getValueType();
1883 SDLoc dl(Op);
1884 SDValue In = Op.getOperand(0);
1885 EVT InVT = In.getValueType();
1886
Tim Northoveref0d7602014-06-15 09:27:06 +00001887 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
1888 MVT CastVT =
1889 MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
1890 InVT.getVectorNumElements());
1891 In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001892 return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
Tim Northover3b0846e2014-05-24 12:50:23 +00001893 }
1894
Tim Northoveref0d7602014-06-15 09:27:06 +00001895 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
1896 unsigned CastOpc =
1897 Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1898 EVT CastVT = VT.changeVectorElementTypeToInteger();
1899 In = DAG.getNode(CastOpc, dl, CastVT, In);
1900 return DAG.getNode(Op.getOpcode(), dl, VT, In);
Tim Northover3b0846e2014-05-24 12:50:23 +00001901 }
1902
Tim Northoveref0d7602014-06-15 09:27:06 +00001903 return Op;
Tim Northover3b0846e2014-05-24 12:50:23 +00001904}
1905
1906SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
1907 SelectionDAG &DAG) const {
1908 if (Op.getValueType().isVector())
1909 return LowerVectorINT_TO_FP(Op, DAG);
1910
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00001911 // f16 conversions are promoted to f32.
1912 if (Op.getValueType() == MVT::f16) {
1913 SDLoc dl(Op);
1914 return DAG.getNode(
1915 ISD::FP_ROUND, dl, MVT::f16,
1916 DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001917 DAG.getIntPtrConstant(0, dl));
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00001918 }
1919
Tim Northover3b0846e2014-05-24 12:50:23 +00001920 // i128 conversions are libcalls.
1921 if (Op.getOperand(0).getValueType() == MVT::i128)
1922 return SDValue();
1923
1924 // Other conversions are legal, unless it's to the completely software-based
1925 // fp128.
1926 if (Op.getValueType() != MVT::f128)
1927 return Op;
1928
1929 RTLIB::Libcall LC;
1930 if (Op.getOpcode() == ISD::SINT_TO_FP)
1931 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
1932 else
1933 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
1934
1935 return LowerF128Call(Op, DAG, LC);
1936}
1937
1938SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
1939 SelectionDAG &DAG) const {
1940 // For iOS, we want to call an alternative entry point: __sincos_stret,
1941 // which returns the values in two S / D registers.
1942 SDLoc dl(Op);
1943 SDValue Arg = Op.getOperand(0);
1944 EVT ArgVT = Arg.getValueType();
1945 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
1946
1947 ArgListTy Args;
1948 ArgListEntry Entry;
1949
1950 Entry.Node = Arg;
1951 Entry.Ty = ArgTy;
1952 Entry.isSExt = false;
1953 Entry.isZExt = false;
1954 Args.push_back(Entry);
1955
1956 const char *LibcallName =
1957 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
Mehdi Amini44ede332015-07-09 02:09:04 +00001958 SDValue Callee =
1959 DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00001960
Reid Kleckner343c3952014-11-20 23:51:47 +00001961 StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
Tim Northover3b0846e2014-05-24 12:50:23 +00001962 TargetLowering::CallLoweringInfo CLI(DAG);
1963 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
Juergen Ributzka3bd03c72014-07-01 22:01:54 +00001964 .setCallee(CallingConv::Fast, RetTy, Callee, std::move(Args), 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00001965
1966 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1967 return CallResult.first;
1968}
1969
Tim Northoverf8bfe212014-07-18 13:07:05 +00001970static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
1971 if (Op.getValueType() != MVT::f16)
1972 return SDValue();
1973
1974 assert(Op.getOperand(0).getValueType() == MVT::i16);
1975 SDLoc DL(Op);
1976
1977 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
1978 Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
1979 return SDValue(
1980 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001981 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
Tim Northoverf8bfe212014-07-18 13:07:05 +00001982 0);
1983}
1984
Chad Rosierd9d0f862014-10-08 02:31:24 +00001985static EVT getExtensionTo64Bits(const EVT &OrigVT) {
1986 if (OrigVT.getSizeInBits() >= 64)
1987 return OrigVT;
1988
1989 assert(OrigVT.isSimple() && "Expecting a simple value type");
1990
1991 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
1992 switch (OrigSimpleTy) {
1993 default: llvm_unreachable("Unexpected Vector Type");
1994 case MVT::v2i8:
1995 case MVT::v2i16:
1996 return MVT::v2i32;
1997 case MVT::v4i8:
1998 return MVT::v4i16;
1999 }
2000}
2001
2002static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2003 const EVT &OrigTy,
2004 const EVT &ExtTy,
2005 unsigned ExtOpcode) {
2006 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2007 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2008 // 64-bits we need to insert a new extension so that it will be 64-bits.
2009 assert(ExtTy.is128BitVector() && "Unexpected extension size");
2010 if (OrigTy.getSizeInBits() >= 64)
2011 return N;
2012
2013 // Must extend size to at least 64 bits to be used as an operand for VMULL.
2014 EVT NewVT = getExtensionTo64Bits(OrigTy);
2015
2016 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2017}
2018
2019static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2020 bool isSigned) {
2021 EVT VT = N->getValueType(0);
2022
2023 if (N->getOpcode() != ISD::BUILD_VECTOR)
2024 return false;
2025
Pete Cooper3af9a252015-06-26 18:17:36 +00002026 for (const SDValue &Elt : N->op_values()) {
Chad Rosierd9d0f862014-10-08 02:31:24 +00002027 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
2028 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
2029 unsigned HalfSize = EltSize / 2;
2030 if (isSigned) {
2031 if (!isIntN(HalfSize, C->getSExtValue()))
2032 return false;
2033 } else {
2034 if (!isUIntN(HalfSize, C->getZExtValue()))
2035 return false;
2036 }
2037 continue;
2038 }
2039 return false;
2040 }
2041
2042 return true;
2043}
2044
2045static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2046 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2047 return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2048 N->getOperand(0)->getValueType(0),
2049 N->getValueType(0),
2050 N->getOpcode());
2051
2052 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2053 EVT VT = N->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002054 SDLoc dl(N);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002055 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
2056 unsigned NumElts = VT.getVectorNumElements();
2057 MVT TruncVT = MVT::getIntegerVT(EltSize);
2058 SmallVector<SDValue, 8> Ops;
2059 for (unsigned i = 0; i != NumElts; ++i) {
2060 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2061 const APInt &CInt = C->getAPIntValue();
2062 // Element types smaller than 32 bits are not legal, so use i32 elements.
2063 // The values are implicitly truncated so sext vs. zext doesn't matter.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002064 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
Chad Rosierd9d0f862014-10-08 02:31:24 +00002065 }
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002066 return DAG.getNode(ISD::BUILD_VECTOR, dl,
Chad Rosierd9d0f862014-10-08 02:31:24 +00002067 MVT::getVectorVT(TruncVT, NumElts), Ops);
2068}
2069
2070static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
2071 if (N->getOpcode() == ISD::SIGN_EXTEND)
2072 return true;
2073 if (isExtendedBUILD_VECTOR(N, DAG, true))
2074 return true;
2075 return false;
2076}
2077
2078static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
2079 if (N->getOpcode() == ISD::ZERO_EXTEND)
2080 return true;
2081 if (isExtendedBUILD_VECTOR(N, DAG, false))
2082 return true;
2083 return false;
2084}
2085
2086static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2087 unsigned Opcode = N->getOpcode();
2088 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2089 SDNode *N0 = N->getOperand(0).getNode();
2090 SDNode *N1 = N->getOperand(1).getNode();
2091 return N0->hasOneUse() && N1->hasOneUse() &&
2092 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2093 }
2094 return false;
2095}
2096
2097static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2098 unsigned Opcode = N->getOpcode();
2099 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2100 SDNode *N0 = N->getOperand(0).getNode();
2101 SDNode *N1 = N->getOperand(1).getNode();
2102 return N0->hasOneUse() && N1->hasOneUse() &&
2103 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2104 }
2105 return false;
2106}
2107
2108static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2109 // Multiplications are only custom-lowered for 128-bit vectors so that
2110 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
2111 EVT VT = Op.getValueType();
2112 assert(VT.is128BitVector() && VT.isInteger() &&
2113 "unexpected type for custom-lowering ISD::MUL");
2114 SDNode *N0 = Op.getOperand(0).getNode();
2115 SDNode *N1 = Op.getOperand(1).getNode();
2116 unsigned NewOpc = 0;
2117 bool isMLA = false;
2118 bool isN0SExt = isSignExtended(N0, DAG);
2119 bool isN1SExt = isSignExtended(N1, DAG);
2120 if (isN0SExt && isN1SExt)
2121 NewOpc = AArch64ISD::SMULL;
2122 else {
2123 bool isN0ZExt = isZeroExtended(N0, DAG);
2124 bool isN1ZExt = isZeroExtended(N1, DAG);
2125 if (isN0ZExt && isN1ZExt)
2126 NewOpc = AArch64ISD::UMULL;
2127 else if (isN1SExt || isN1ZExt) {
2128 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2129 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2130 if (isN1SExt && isAddSubSExt(N0, DAG)) {
2131 NewOpc = AArch64ISD::SMULL;
2132 isMLA = true;
2133 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2134 NewOpc = AArch64ISD::UMULL;
2135 isMLA = true;
2136 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2137 std::swap(N0, N1);
2138 NewOpc = AArch64ISD::UMULL;
2139 isMLA = true;
2140 }
2141 }
2142
2143 if (!NewOpc) {
2144 if (VT == MVT::v2i64)
2145 // Fall through to expand this. It is not legal.
2146 return SDValue();
2147 else
2148 // Other vector multiplications are legal.
2149 return Op;
2150 }
2151 }
2152
2153 // Legalize to a S/UMULL instruction
2154 SDLoc DL(Op);
2155 SDValue Op0;
2156 SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2157 if (!isMLA) {
2158 Op0 = skipExtensionForVectorMULL(N0, DAG);
2159 assert(Op0.getValueType().is64BitVector() &&
2160 Op1.getValueType().is64BitVector() &&
2161 "unexpected types for extended operands to VMULL");
2162 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2163 }
2164 // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2165 // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2166 // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2167 SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2168 SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2169 EVT Op1VT = Op1.getValueType();
2170 return DAG.getNode(N0->getOpcode(), DL, VT,
2171 DAG.getNode(NewOpc, DL, VT,
2172 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2173 DAG.getNode(NewOpc, DL, VT,
2174 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2175}
Tim Northoverf8bfe212014-07-18 13:07:05 +00002176
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002177SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2178 SelectionDAG &DAG) const {
2179 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2180 SDLoc dl(Op);
2181 switch (IntNo) {
2182 default: return SDValue(); // Don't custom lower most intrinsics.
2183 case Intrinsic::aarch64_thread_pointer: {
2184 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2185 return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
2186 }
Silviu Barangadb1ddb32015-08-26 11:11:14 +00002187 case Intrinsic::aarch64_neon_smax:
2188 return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
2189 Op.getOperand(1), Op.getOperand(2));
2190 case Intrinsic::aarch64_neon_umax:
2191 return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
2192 Op.getOperand(1), Op.getOperand(2));
2193 case Intrinsic::aarch64_neon_smin:
2194 return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
2195 Op.getOperand(1), Op.getOperand(2));
2196 case Intrinsic::aarch64_neon_umin:
2197 return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
2198 Op.getOperand(1), Op.getOperand(2));
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002199 }
2200}
2201
Tim Northover3b0846e2014-05-24 12:50:23 +00002202SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
2203 SelectionDAG &DAG) const {
2204 switch (Op.getOpcode()) {
2205 default:
2206 llvm_unreachable("unimplemented operand");
2207 return SDValue();
Tim Northoverf8bfe212014-07-18 13:07:05 +00002208 case ISD::BITCAST:
2209 return LowerBITCAST(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002210 case ISD::GlobalAddress:
2211 return LowerGlobalAddress(Op, DAG);
2212 case ISD::GlobalTLSAddress:
2213 return LowerGlobalTLSAddress(Op, DAG);
2214 case ISD::SETCC:
2215 return LowerSETCC(Op, DAG);
2216 case ISD::BR_CC:
2217 return LowerBR_CC(Op, DAG);
2218 case ISD::SELECT:
2219 return LowerSELECT(Op, DAG);
2220 case ISD::SELECT_CC:
2221 return LowerSELECT_CC(Op, DAG);
2222 case ISD::JumpTable:
2223 return LowerJumpTable(Op, DAG);
2224 case ISD::ConstantPool:
2225 return LowerConstantPool(Op, DAG);
2226 case ISD::BlockAddress:
2227 return LowerBlockAddress(Op, DAG);
2228 case ISD::VASTART:
2229 return LowerVASTART(Op, DAG);
2230 case ISD::VACOPY:
2231 return LowerVACOPY(Op, DAG);
2232 case ISD::VAARG:
2233 return LowerVAARG(Op, DAG);
2234 case ISD::ADDC:
2235 case ISD::ADDE:
2236 case ISD::SUBC:
2237 case ISD::SUBE:
2238 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
2239 case ISD::SADDO:
2240 case ISD::UADDO:
2241 case ISD::SSUBO:
2242 case ISD::USUBO:
2243 case ISD::SMULO:
2244 case ISD::UMULO:
2245 return LowerXALUO(Op, DAG);
2246 case ISD::FADD:
2247 return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
2248 case ISD::FSUB:
2249 return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
2250 case ISD::FMUL:
2251 return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
2252 case ISD::FDIV:
2253 return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
2254 case ISD::FP_ROUND:
2255 return LowerFP_ROUND(Op, DAG);
2256 case ISD::FP_EXTEND:
2257 return LowerFP_EXTEND(Op, DAG);
2258 case ISD::FRAMEADDR:
2259 return LowerFRAMEADDR(Op, DAG);
2260 case ISD::RETURNADDR:
2261 return LowerRETURNADDR(Op, DAG);
2262 case ISD::INSERT_VECTOR_ELT:
2263 return LowerINSERT_VECTOR_ELT(Op, DAG);
2264 case ISD::EXTRACT_VECTOR_ELT:
2265 return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2266 case ISD::BUILD_VECTOR:
2267 return LowerBUILD_VECTOR(Op, DAG);
2268 case ISD::VECTOR_SHUFFLE:
2269 return LowerVECTOR_SHUFFLE(Op, DAG);
2270 case ISD::EXTRACT_SUBVECTOR:
2271 return LowerEXTRACT_SUBVECTOR(Op, DAG);
2272 case ISD::SRA:
2273 case ISD::SRL:
2274 case ISD::SHL:
2275 return LowerVectorSRA_SRL_SHL(Op, DAG);
2276 case ISD::SHL_PARTS:
2277 return LowerShiftLeftParts(Op, DAG);
2278 case ISD::SRL_PARTS:
2279 case ISD::SRA_PARTS:
2280 return LowerShiftRightParts(Op, DAG);
2281 case ISD::CTPOP:
2282 return LowerCTPOP(Op, DAG);
2283 case ISD::FCOPYSIGN:
2284 return LowerFCOPYSIGN(Op, DAG);
2285 case ISD::AND:
2286 return LowerVectorAND(Op, DAG);
2287 case ISD::OR:
2288 return LowerVectorOR(Op, DAG);
2289 case ISD::XOR:
2290 return LowerXOR(Op, DAG);
2291 case ISD::PREFETCH:
2292 return LowerPREFETCH(Op, DAG);
2293 case ISD::SINT_TO_FP:
2294 case ISD::UINT_TO_FP:
2295 return LowerINT_TO_FP(Op, DAG);
2296 case ISD::FP_TO_SINT:
2297 case ISD::FP_TO_UINT:
2298 return LowerFP_TO_INT(Op, DAG);
2299 case ISD::FSINCOS:
2300 return LowerFSINCOS(Op, DAG);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002301 case ISD::MUL:
2302 return LowerMUL(Op, DAG);
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002303 case ISD::INTRINSIC_WO_CHAIN:
2304 return LowerINTRINSIC_WO_CHAIN(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002305 }
2306}
2307
2308/// getFunctionAlignment - Return the Log2 alignment of this function.
2309unsigned AArch64TargetLowering::getFunctionAlignment(const Function *F) const {
2310 return 2;
2311}
2312
2313//===----------------------------------------------------------------------===//
2314// Calling Convention Implementation
2315//===----------------------------------------------------------------------===//
2316
2317#include "AArch64GenCallingConv.inc"
2318
Robin Morisset039781e2014-08-29 21:53:01 +00002319/// Selects the correct CCAssignFn for a given CallingConvention value.
Tim Northover3b0846e2014-05-24 12:50:23 +00002320CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2321 bool IsVarArg) const {
2322 switch (CC) {
2323 default:
2324 llvm_unreachable("Unsupported calling convention.");
2325 case CallingConv::WebKit_JS:
2326 return CC_AArch64_WebKit_JS;
Greg Fitzgeraldfa78d082015-01-19 17:40:05 +00002327 case CallingConv::GHC:
2328 return CC_AArch64_GHC;
Tim Northover3b0846e2014-05-24 12:50:23 +00002329 case CallingConv::C:
2330 case CallingConv::Fast:
2331 if (!Subtarget->isTargetDarwin())
2332 return CC_AArch64_AAPCS;
2333 return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
2334 }
2335}
2336
2337SDValue AArch64TargetLowering::LowerFormalArguments(
2338 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2339 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2340 SmallVectorImpl<SDValue> &InVals) const {
2341 MachineFunction &MF = DAG.getMachineFunction();
2342 MachineFrameInfo *MFI = MF.getFrameInfo();
2343
2344 // Assign locations to all of the incoming arguments.
2345 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002346 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2347 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002348
2349 // At this point, Ins[].VT may already be promoted to i32. To correctly
2350 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2351 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2352 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
2353 // we use a special version of AnalyzeFormalArguments to pass in ValVT and
2354 // LocVT.
2355 unsigned NumArgs = Ins.size();
2356 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2357 unsigned CurArgIdx = 0;
2358 for (unsigned i = 0; i != NumArgs; ++i) {
2359 MVT ValVT = Ins[i].VT;
Andrew Trick05938a52015-02-16 18:10:47 +00002360 if (Ins[i].isOrigArg()) {
2361 std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
2362 CurArgIdx = Ins[i].getOrigArgIndex();
Tim Northover3b0846e2014-05-24 12:50:23 +00002363
Andrew Trick05938a52015-02-16 18:10:47 +00002364 // Get type of the original argument.
Mehdi Amini44ede332015-07-09 02:09:04 +00002365 EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
2366 /*AllowUnknown*/ true);
Andrew Trick05938a52015-02-16 18:10:47 +00002367 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
2368 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2369 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2370 ValVT = MVT::i8;
2371 else if (ActualMVT == MVT::i16)
2372 ValVT = MVT::i16;
2373 }
Tim Northover3b0846e2014-05-24 12:50:23 +00002374 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2375 bool Res =
Tim Northover47e003c2014-05-26 17:21:53 +00002376 AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00002377 assert(!Res && "Call operand has unhandled type");
2378 (void)Res;
2379 }
2380 assert(ArgLocs.size() == Ins.size());
2381 SmallVector<SDValue, 16> ArgValues;
2382 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2383 CCValAssign &VA = ArgLocs[i];
2384
2385 if (Ins[i].Flags.isByVal()) {
2386 // Byval is used for HFAs in the PCS, but the system should work in a
2387 // non-compliant manner for larger structs.
Mehdi Amini44ede332015-07-09 02:09:04 +00002388 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00002389 int Size = Ins[i].Flags.getByValSize();
2390 unsigned NumRegs = (Size + 7) / 8;
2391
2392 // FIXME: This works on big-endian for composite byvals, which are the common
2393 // case. It should also work for fundamental types too.
2394 unsigned FrameIdx =
2395 MFI->CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
Mehdi Amini44ede332015-07-09 02:09:04 +00002396 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00002397 InVals.push_back(FrameIdxN);
2398
2399 continue;
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002400 }
2401
2402 if (VA.isRegLoc()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00002403 // Arguments stored in registers.
2404 EVT RegVT = VA.getLocVT();
2405
2406 SDValue ArgValue;
2407 const TargetRegisterClass *RC;
2408
2409 if (RegVT == MVT::i32)
2410 RC = &AArch64::GPR32RegClass;
2411 else if (RegVT == MVT::i64)
2412 RC = &AArch64::GPR64RegClass;
Oliver Stannard6eda6ff2014-07-11 13:33:46 +00002413 else if (RegVT == MVT::f16)
2414 RC = &AArch64::FPR16RegClass;
Tim Northover3b0846e2014-05-24 12:50:23 +00002415 else if (RegVT == MVT::f32)
2416 RC = &AArch64::FPR32RegClass;
2417 else if (RegVT == MVT::f64 || RegVT.is64BitVector())
2418 RC = &AArch64::FPR64RegClass;
2419 else if (RegVT == MVT::f128 || RegVT.is128BitVector())
2420 RC = &AArch64::FPR128RegClass;
2421 else
2422 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2423
2424 // Transform the arguments in physical registers into virtual ones.
2425 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2426 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2427
2428 // If this is an 8, 16 or 32-bit value, it is really passed promoted
2429 // to 64 bits. Insert an assert[sz]ext to capture this, then
2430 // truncate to the right size.
2431 switch (VA.getLocInfo()) {
2432 default:
2433 llvm_unreachable("Unknown loc info!");
2434 case CCValAssign::Full:
2435 break;
2436 case CCValAssign::BCvt:
2437 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
2438 break;
Tim Northover47e003c2014-05-26 17:21:53 +00002439 case CCValAssign::AExt:
Tim Northover3b0846e2014-05-24 12:50:23 +00002440 case CCValAssign::SExt:
Tim Northover3b0846e2014-05-24 12:50:23 +00002441 case CCValAssign::ZExt:
Tim Northover47e003c2014-05-26 17:21:53 +00002442 // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
2443 // nodes after our lowering.
2444 assert(RegVT == Ins[i].VT && "incorrect register location selected");
Tim Northover3b0846e2014-05-24 12:50:23 +00002445 break;
2446 }
2447
2448 InVals.push_back(ArgValue);
2449
2450 } else { // VA.isRegLoc()
2451 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
2452 unsigned ArgOffset = VA.getLocMemOffset();
Amara Emerson82da7d02014-08-15 14:29:57 +00002453 unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
Tim Northover3b0846e2014-05-24 12:50:23 +00002454
2455 uint32_t BEAlign = 0;
Tim Northover293d4142014-12-03 17:49:26 +00002456 if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
2457 !Ins[i].Flags.isInConsecutiveRegs())
Tim Northover3b0846e2014-05-24 12:50:23 +00002458 BEAlign = 8 - ArgSize;
2459
2460 int FI = MFI->CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
2461
2462 // Create load nodes to retrieve arguments from the stack.
Mehdi Amini44ede332015-07-09 02:09:04 +00002463 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00002464 SDValue ArgValue;
2465
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002466 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
Tim Northover47e003c2014-05-26 17:21:53 +00002467 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002468 MVT MemVT = VA.getValVT();
2469
Tim Northover47e003c2014-05-26 17:21:53 +00002470 switch (VA.getLocInfo()) {
2471 default:
2472 break;
Tim Northover6890add2014-06-03 13:54:53 +00002473 case CCValAssign::BCvt:
2474 MemVT = VA.getLocVT();
2475 break;
Tim Northover47e003c2014-05-26 17:21:53 +00002476 case CCValAssign::SExt:
2477 ExtType = ISD::SEXTLOAD;
2478 break;
2479 case CCValAssign::ZExt:
2480 ExtType = ISD::ZEXTLOAD;
2481 break;
2482 case CCValAssign::AExt:
2483 ExtType = ISD::EXTLOAD;
2484 break;
Tim Northover3b0846e2014-05-24 12:50:23 +00002485 }
2486
Alex Lorenze40c8a22015-08-11 23:09:45 +00002487 ArgValue = DAG.getExtLoad(
2488 ExtType, DL, VA.getLocVT(), Chain, FIN,
2489 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
2490 MemVT, false, false, false, 0);
Tim Northover47e003c2014-05-26 17:21:53 +00002491
Tim Northover3b0846e2014-05-24 12:50:23 +00002492 InVals.push_back(ArgValue);
2493 }
2494 }
2495
2496 // varargs
2497 if (isVarArg) {
2498 if (!Subtarget->isTargetDarwin()) {
2499 // The AAPCS variadic function ABI is identical to the non-variadic
2500 // one. As a result there may be more arguments in registers and we should
2501 // save them for future reference.
2502 saveVarArgRegisters(CCInfo, DAG, DL, Chain);
2503 }
2504
2505 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
2506 // This will point to the next argument passed via stack.
2507 unsigned StackOffset = CCInfo.getNextStackOffset();
2508 // We currently pass all varargs at 8-byte alignment.
2509 StackOffset = ((StackOffset + 7) & ~7);
2510 AFI->setVarArgsStackIndex(MFI->CreateFixedObject(4, StackOffset, true));
2511 }
2512
2513 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2514 unsigned StackArgSize = CCInfo.getNextStackOffset();
2515 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2516 if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
2517 // This is a non-standard ABI so by fiat I say we're allowed to make full
2518 // use of the stack area to be popped, which must be aligned to 16 bytes in
2519 // any case:
2520 StackArgSize = RoundUpToAlignment(StackArgSize, 16);
2521
2522 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
2523 // a multiple of 16.
2524 FuncInfo->setArgumentStackToRestore(StackArgSize);
2525
2526 // This realignment carries over to the available bytes below. Our own
2527 // callers will guarantee the space is free by giving an aligned value to
2528 // CALLSEQ_START.
2529 }
2530 // Even if we're not expected to free up the space, it's useful to know how
2531 // much is there while considering tail calls (because we can reuse it).
2532 FuncInfo->setBytesInStackArgArea(StackArgSize);
2533
2534 return Chain;
2535}
2536
2537void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
2538 SelectionDAG &DAG, SDLoc DL,
2539 SDValue &Chain) const {
2540 MachineFunction &MF = DAG.getMachineFunction();
2541 MachineFrameInfo *MFI = MF.getFrameInfo();
2542 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Mehdi Amini44ede332015-07-09 02:09:04 +00002543 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00002544
2545 SmallVector<SDValue, 8> MemOps;
2546
2547 static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
2548 AArch64::X3, AArch64::X4, AArch64::X5,
2549 AArch64::X6, AArch64::X7 };
2550 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
Tim Northover3b6b7ca2015-02-21 02:11:17 +00002551 unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
Tim Northover3b0846e2014-05-24 12:50:23 +00002552
2553 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
2554 int GPRIdx = 0;
2555 if (GPRSaveSize != 0) {
2556 GPRIdx = MFI->CreateStackObject(GPRSaveSize, 8, false);
2557
Mehdi Amini44ede332015-07-09 02:09:04 +00002558 SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00002559
2560 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
2561 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
2562 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
Alex Lorenze40c8a22015-08-11 23:09:45 +00002563 SDValue Store = DAG.getStore(
2564 Val.getValue(1), DL, Val, FIN,
2565 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8), false,
2566 false, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00002567 MemOps.push_back(Store);
Mehdi Amini44ede332015-07-09 02:09:04 +00002568 FIN =
2569 DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00002570 }
2571 }
2572 FuncInfo->setVarArgsGPRIndex(GPRIdx);
2573 FuncInfo->setVarArgsGPRSize(GPRSaveSize);
2574
2575 if (Subtarget->hasFPARMv8()) {
2576 static const MCPhysReg FPRArgRegs[] = {
2577 AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
2578 AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
2579 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
Tim Northover3b6b7ca2015-02-21 02:11:17 +00002580 unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
Tim Northover3b0846e2014-05-24 12:50:23 +00002581
2582 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
2583 int FPRIdx = 0;
2584 if (FPRSaveSize != 0) {
2585 FPRIdx = MFI->CreateStackObject(FPRSaveSize, 16, false);
2586
Mehdi Amini44ede332015-07-09 02:09:04 +00002587 SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00002588
2589 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
2590 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
2591 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
2592
Alex Lorenze40c8a22015-08-11 23:09:45 +00002593 SDValue Store = DAG.getStore(
2594 Val.getValue(1), DL, Val, FIN,
2595 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16),
2596 false, false, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00002597 MemOps.push_back(Store);
Mehdi Amini44ede332015-07-09 02:09:04 +00002598 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
2599 DAG.getConstant(16, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00002600 }
2601 }
2602 FuncInfo->setVarArgsFPRIndex(FPRIdx);
2603 FuncInfo->setVarArgsFPRSize(FPRSaveSize);
2604 }
2605
2606 if (!MemOps.empty()) {
2607 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
2608 }
2609}
2610
2611/// LowerCallResult - Lower the result values of a call into the
2612/// appropriate copies out of appropriate physical registers.
2613SDValue AArch64TargetLowering::LowerCallResult(
2614 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
2615 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2616 SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
2617 SDValue ThisVal) const {
2618 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
2619 ? RetCC_AArch64_WebKit_JS
2620 : RetCC_AArch64_AAPCS;
2621 // Assign locations to each value returned by this call.
2622 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002623 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2624 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002625 CCInfo.AnalyzeCallResult(Ins, RetCC);
2626
2627 // Copy all of the result registers out of their specified physreg.
2628 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2629 CCValAssign VA = RVLocs[i];
2630
2631 // Pass 'this' value directly from the argument to return value, to avoid
2632 // reg unit interference
2633 if (i == 0 && isThisReturn) {
2634 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
2635 "unexpected return calling convention register assignment");
2636 InVals.push_back(ThisVal);
2637 continue;
2638 }
2639
2640 SDValue Val =
2641 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2642 Chain = Val.getValue(1);
2643 InFlag = Val.getValue(2);
2644
2645 switch (VA.getLocInfo()) {
2646 default:
2647 llvm_unreachable("Unknown loc info!");
2648 case CCValAssign::Full:
2649 break;
2650 case CCValAssign::BCvt:
2651 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2652 break;
2653 }
2654
2655 InVals.push_back(Val);
2656 }
2657
2658 return Chain;
2659}
2660
2661bool AArch64TargetLowering::isEligibleForTailCallOptimization(
2662 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
2663 bool isCalleeStructRet, bool isCallerStructRet,
2664 const SmallVectorImpl<ISD::OutputArg> &Outs,
2665 const SmallVectorImpl<SDValue> &OutVals,
2666 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2667 // For CallingConv::C this function knows whether the ABI needs
2668 // changing. That's not true for other conventions so they will have to opt in
2669 // manually.
2670 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
2671 return false;
2672
2673 const MachineFunction &MF = DAG.getMachineFunction();
2674 const Function *CallerF = MF.getFunction();
2675 CallingConv::ID CallerCC = CallerF->getCallingConv();
2676 bool CCMatch = CallerCC == CalleeCC;
2677
2678 // Byval parameters hand the function a pointer directly into the stack area
2679 // we want to reuse during a tail call. Working around this *is* possible (see
2680 // X86) but less efficient and uglier in LowerCall.
2681 for (Function::const_arg_iterator i = CallerF->arg_begin(),
2682 e = CallerF->arg_end();
2683 i != e; ++i)
2684 if (i->hasByValAttr())
2685 return false;
2686
2687 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2688 if (IsTailCallConvention(CalleeCC) && CCMatch)
2689 return true;
2690 return false;
2691 }
2692
Oliver Stannard12993dd2014-08-18 12:42:15 +00002693 // Externally-defined functions with weak linkage should not be
2694 // tail-called on AArch64 when the OS does not support dynamic
2695 // pre-emption of symbols, as the AAELF spec requires normal calls
2696 // to undefined weak functions to be replaced with a NOP or jump to the
2697 // next instruction. The behaviour of branch instructions in this
2698 // situation (as used for tail calls) is implementation-defined, so we
2699 // cannot rely on the linker replacing the tail call with a return.
2700 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2701 const GlobalValue *GV = G->getGlobal();
Daniel Sandersc81f4502015-06-16 15:44:21 +00002702 const Triple &TT = getTargetMachine().getTargetTriple();
Saleem Abdulrasool67f72992015-01-03 21:35:00 +00002703 if (GV->hasExternalWeakLinkage() &&
2704 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
Oliver Stannard12993dd2014-08-18 12:42:15 +00002705 return false;
2706 }
2707
Tim Northover3b0846e2014-05-24 12:50:23 +00002708 // Now we search for cases where we can use a tail call without changing the
2709 // ABI. Sibcall is used in some places (particularly gcc) to refer to this
2710 // concept.
2711
2712 // I want anyone implementing a new calling convention to think long and hard
2713 // about this assert.
2714 assert((!isVarArg || CalleeCC == CallingConv::C) &&
2715 "Unexpected variadic calling convention");
2716
2717 if (isVarArg && !Outs.empty()) {
2718 // At least two cases here: if caller is fastcc then we can't have any
2719 // memory arguments (we'd be expected to clean up the stack afterwards). If
2720 // caller is C then we could potentially use its argument area.
2721
2722 // FIXME: for now we take the most conservative of these in both cases:
2723 // disallow all variadic memory operands.
2724 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002725 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2726 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002727
2728 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
Pete Cooper7be8f8f2015-08-03 19:04:32 +00002729 for (const CCValAssign &ArgLoc : ArgLocs)
2730 if (!ArgLoc.isRegLoc())
Tim Northover3b0846e2014-05-24 12:50:23 +00002731 return false;
2732 }
2733
2734 // If the calling conventions do not match, then we'd better make sure the
2735 // results are returned in the same way as what the caller expects.
2736 if (!CCMatch) {
2737 SmallVector<CCValAssign, 16> RVLocs1;
Eric Christopherb5217502014-08-06 18:45:26 +00002738 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2739 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002740 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForCall(CalleeCC, isVarArg));
2741
2742 SmallVector<CCValAssign, 16> RVLocs2;
Eric Christopherb5217502014-08-06 18:45:26 +00002743 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2744 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002745 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForCall(CallerCC, isVarArg));
2746
2747 if (RVLocs1.size() != RVLocs2.size())
2748 return false;
2749 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2750 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2751 return false;
2752 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2753 return false;
2754 if (RVLocs1[i].isRegLoc()) {
2755 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2756 return false;
2757 } else {
2758 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2759 return false;
2760 }
2761 }
2762 }
2763
2764 // Nothing more to check if the callee is taking no arguments
2765 if (Outs.empty())
2766 return true;
2767
2768 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002769 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2770 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002771
2772 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2773
2774 const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2775
2776 // If the stack arguments for this call would fit into our own save area then
2777 // the call can be made tail.
2778 return CCInfo.getNextStackOffset() <= FuncInfo->getBytesInStackArgArea();
2779}
2780
2781SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
2782 SelectionDAG &DAG,
2783 MachineFrameInfo *MFI,
2784 int ClobberedFI) const {
2785 SmallVector<SDValue, 8> ArgChains;
2786 int64_t FirstByte = MFI->getObjectOffset(ClobberedFI);
2787 int64_t LastByte = FirstByte + MFI->getObjectSize(ClobberedFI) - 1;
2788
2789 // Include the original chain at the beginning of the list. When this is
2790 // used by target LowerCall hooks, this helps legalize find the
2791 // CALLSEQ_BEGIN node.
2792 ArgChains.push_back(Chain);
2793
2794 // Add a chain value for each stack argument corresponding
2795 for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
2796 UE = DAG.getEntryNode().getNode()->use_end();
2797 U != UE; ++U)
2798 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
2799 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
2800 if (FI->getIndex() < 0) {
2801 int64_t InFirstByte = MFI->getObjectOffset(FI->getIndex());
2802 int64_t InLastByte = InFirstByte;
2803 InLastByte += MFI->getObjectSize(FI->getIndex()) - 1;
2804
2805 if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
2806 (FirstByte <= InFirstByte && InFirstByte <= LastByte))
2807 ArgChains.push_back(SDValue(L, 1));
2808 }
2809
2810 // Build a tokenfactor for all the chains.
2811 return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
2812}
2813
2814bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
2815 bool TailCallOpt) const {
2816 return CallCC == CallingConv::Fast && TailCallOpt;
2817}
2818
2819bool AArch64TargetLowering::IsTailCallConvention(CallingConv::ID CallCC) const {
2820 return CallCC == CallingConv::Fast;
2821}
2822
2823/// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
2824/// and add input and output parameter nodes.
2825SDValue
2826AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
2827 SmallVectorImpl<SDValue> &InVals) const {
2828 SelectionDAG &DAG = CLI.DAG;
2829 SDLoc &DL = CLI.DL;
2830 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2831 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2832 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2833 SDValue Chain = CLI.Chain;
2834 SDValue Callee = CLI.Callee;
2835 bool &IsTailCall = CLI.IsTailCall;
2836 CallingConv::ID CallConv = CLI.CallConv;
2837 bool IsVarArg = CLI.IsVarArg;
2838
2839 MachineFunction &MF = DAG.getMachineFunction();
2840 bool IsStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
2841 bool IsThisReturn = false;
2842
2843 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2844 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2845 bool IsSibCall = false;
2846
2847 if (IsTailCall) {
2848 // Check if it's really possible to do a tail call.
2849 IsTailCall = isEligibleForTailCallOptimization(
2850 Callee, CallConv, IsVarArg, IsStructRet,
2851 MF.getFunction()->hasStructRetAttr(), Outs, OutVals, Ins, DAG);
2852 if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
2853 report_fatal_error("failed to perform tail call elimination on a call "
2854 "site marked musttail");
2855
2856 // A sibling call is one where we're under the usual C ABI and not planning
2857 // to change that but can still do a tail call:
2858 if (!TailCallOpt && IsTailCall)
2859 IsSibCall = true;
2860
2861 if (IsTailCall)
2862 ++NumTailCalls;
2863 }
2864
2865 // Analyze operands of the call, assigning locations to each operand.
2866 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002867 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
2868 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002869
2870 if (IsVarArg) {
2871 // Handle fixed and variable vector arguments differently.
2872 // Variable vector arguments always go into memory.
2873 unsigned NumArgs = Outs.size();
2874
2875 for (unsigned i = 0; i != NumArgs; ++i) {
2876 MVT ArgVT = Outs[i].VT;
2877 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2878 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
2879 /*IsVarArg=*/ !Outs[i].IsFixed);
2880 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
2881 assert(!Res && "Call operand has unhandled type");
2882 (void)Res;
2883 }
2884 } else {
2885 // At this point, Outs[].VT may already be promoted to i32. To correctly
2886 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2887 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2888 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
2889 // we use a special version of AnalyzeCallOperands to pass in ValVT and
2890 // LocVT.
2891 unsigned NumArgs = Outs.size();
2892 for (unsigned i = 0; i != NumArgs; ++i) {
2893 MVT ValVT = Outs[i].VT;
2894 // Get type of the original argument.
Mehdi Amini44ede332015-07-09 02:09:04 +00002895 EVT ActualVT = getValueType(DAG.getDataLayout(),
2896 CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
Tim Northover3b0846e2014-05-24 12:50:23 +00002897 /*AllowUnknown*/ true);
2898 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
2899 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2900 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
Tim Northover3b0846e2014-05-24 12:50:23 +00002901 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
Tim Northover47e003c2014-05-26 17:21:53 +00002902 ValVT = MVT::i8;
Tim Northover3b0846e2014-05-24 12:50:23 +00002903 else if (ActualMVT == MVT::i16)
Tim Northover47e003c2014-05-26 17:21:53 +00002904 ValVT = MVT::i16;
Tim Northover3b0846e2014-05-24 12:50:23 +00002905
2906 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
Tim Northover47e003c2014-05-26 17:21:53 +00002907 bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00002908 assert(!Res && "Call operand has unhandled type");
2909 (void)Res;
2910 }
2911 }
2912
2913 // Get a count of how many bytes are to be pushed on the stack.
2914 unsigned NumBytes = CCInfo.getNextStackOffset();
2915
2916 if (IsSibCall) {
2917 // Since we're not changing the ABI to make this a tail call, the memory
2918 // operands are already available in the caller's incoming argument space.
2919 NumBytes = 0;
2920 }
2921
2922 // FPDiff is the byte offset of the call's argument area from the callee's.
2923 // Stores to callee stack arguments will be placed in FixedStackSlots offset
2924 // by this amount for a tail call. In a sibling call it must be 0 because the
2925 // caller will deallocate the entire stack and the callee still expects its
2926 // arguments to begin at SP+0. Completely unused for non-tail calls.
2927 int FPDiff = 0;
2928
2929 if (IsTailCall && !IsSibCall) {
2930 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
2931
2932 // Since callee will pop argument stack as a tail call, we must keep the
2933 // popped size 16-byte aligned.
2934 NumBytes = RoundUpToAlignment(NumBytes, 16);
2935
2936 // FPDiff will be negative if this tail call requires more space than we
2937 // would automatically have in our incoming argument space. Positive if we
2938 // can actually shrink the stack.
2939 FPDiff = NumReusableBytes - NumBytes;
2940
2941 // The stack pointer must be 16-byte aligned at all times it's used for a
2942 // memory operation, which in practice means at *all* times and in
2943 // particular across call boundaries. Therefore our own arguments started at
2944 // a 16-byte aligned SP and the delta applied for the tail call should
2945 // satisfy the same constraint.
2946 assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
2947 }
2948
2949 // Adjust the stack pointer for the new arguments...
2950 // These operations are automatically eliminated by the prolog/epilog pass
2951 if (!IsSibCall)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002952 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, DL,
2953 true),
2954 DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00002955
Mehdi Amini44ede332015-07-09 02:09:04 +00002956 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
2957 getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00002958
2959 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2960 SmallVector<SDValue, 8> MemOpChains;
Mehdi Amini44ede332015-07-09 02:09:04 +00002961 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00002962
2963 // Walk the register/memloc assignments, inserting copies/loads.
2964 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
2965 ++i, ++realArgIdx) {
2966 CCValAssign &VA = ArgLocs[i];
2967 SDValue Arg = OutVals[realArgIdx];
2968 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2969
2970 // Promote the value if needed.
2971 switch (VA.getLocInfo()) {
2972 default:
2973 llvm_unreachable("Unknown loc info!");
2974 case CCValAssign::Full:
2975 break;
2976 case CCValAssign::SExt:
2977 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2978 break;
2979 case CCValAssign::ZExt:
2980 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2981 break;
2982 case CCValAssign::AExt:
Tim Northover68ae5032014-05-26 17:22:07 +00002983 if (Outs[realArgIdx].ArgVT == MVT::i1) {
2984 // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
2985 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
2986 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
2987 }
Tim Northover3b0846e2014-05-24 12:50:23 +00002988 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2989 break;
2990 case CCValAssign::BCvt:
2991 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2992 break;
2993 case CCValAssign::FPExt:
2994 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
2995 break;
2996 }
2997
2998 if (VA.isRegLoc()) {
2999 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i64) {
3000 assert(VA.getLocVT() == MVT::i64 &&
3001 "unexpected calling convention register assignment");
3002 assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
3003 "unexpected use of 'returned'");
3004 IsThisReturn = true;
3005 }
3006 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3007 } else {
3008 assert(VA.isMemLoc());
3009
3010 SDValue DstAddr;
3011 MachinePointerInfo DstInfo;
3012
3013 // FIXME: This works on big-endian for composite byvals, which are the
3014 // common case. It should also work for fundamental types too.
3015 uint32_t BEAlign = 0;
3016 unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
Amara Emerson82da7d02014-08-15 14:29:57 +00003017 : VA.getValVT().getSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00003018 OpSize = (OpSize + 7) / 8;
Tim Northover293d4142014-12-03 17:49:26 +00003019 if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
3020 !Flags.isInConsecutiveRegs()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003021 if (OpSize < 8)
3022 BEAlign = 8 - OpSize;
3023 }
3024 unsigned LocMemOffset = VA.getLocMemOffset();
3025 int32_t Offset = LocMemOffset + BEAlign;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003026 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
Mehdi Amini44ede332015-07-09 02:09:04 +00003027 PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
Tim Northover3b0846e2014-05-24 12:50:23 +00003028
3029 if (IsTailCall) {
3030 Offset = Offset + FPDiff;
3031 int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3032
Mehdi Amini44ede332015-07-09 02:09:04 +00003033 DstAddr = DAG.getFrameIndex(FI, PtrVT);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003034 DstInfo =
3035 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
Tim Northover3b0846e2014-05-24 12:50:23 +00003036
3037 // Make sure any stack arguments overlapping with where we're storing
3038 // are loaded before this eventual operation. Otherwise they'll be
3039 // clobbered.
3040 Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
3041 } else {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003042 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003043
Mehdi Amini44ede332015-07-09 02:09:04 +00003044 DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003045 DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
3046 LocMemOffset);
Tim Northover3b0846e2014-05-24 12:50:23 +00003047 }
3048
3049 if (Outs[i].Flags.isByVal()) {
3050 SDValue SizeNode =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003051 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00003052 SDValue Cpy = DAG.getMemcpy(
3053 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
Krzysztof Parzyszeka46c36b2015-04-13 17:16:45 +00003054 /*isVol = */ false, /*AlwaysInline = */ false,
3055 /*isTailCall = */ false,
3056 DstInfo, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00003057
3058 MemOpChains.push_back(Cpy);
3059 } else {
3060 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
3061 // promoted to a legal register type i32, we should truncate Arg back to
3062 // i1/i8/i16.
Tim Northover6890add2014-06-03 13:54:53 +00003063 if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
3064 VA.getValVT() == MVT::i16)
3065 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
Tim Northover3b0846e2014-05-24 12:50:23 +00003066
3067 SDValue Store =
3068 DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, false, false, 0);
3069 MemOpChains.push_back(Store);
3070 }
3071 }
3072 }
3073
3074 if (!MemOpChains.empty())
3075 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3076
3077 // Build a sequence of copy-to-reg nodes chained together with token chain
3078 // and flag operands which copy the outgoing args into the appropriate regs.
3079 SDValue InFlag;
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003080 for (auto &RegToPass : RegsToPass) {
3081 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3082 RegToPass.second, InFlag);
Tim Northover3b0846e2014-05-24 12:50:23 +00003083 InFlag = Chain.getValue(1);
3084 }
3085
3086 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3087 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3088 // node so that legalize doesn't hack it.
3089 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3090 Subtarget->isTargetMachO()) {
3091 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3092 const GlobalValue *GV = G->getGlobal();
3093 bool InternalLinkage = GV->hasInternalLinkage();
3094 if (InternalLinkage)
Mehdi Amini44ede332015-07-09 02:09:04 +00003095 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00003096 else {
Mehdi Amini44ede332015-07-09 02:09:04 +00003097 Callee =
3098 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT);
3099 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
Tim Northover3b0846e2014-05-24 12:50:23 +00003100 }
3101 } else if (ExternalSymbolSDNode *S =
3102 dyn_cast<ExternalSymbolSDNode>(Callee)) {
3103 const char *Sym = S->getSymbol();
Mehdi Amini44ede332015-07-09 02:09:04 +00003104 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
3105 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
Tim Northover3b0846e2014-05-24 12:50:23 +00003106 }
3107 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3108 const GlobalValue *GV = G->getGlobal();
Mehdi Amini44ede332015-07-09 02:09:04 +00003109 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00003110 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3111 const char *Sym = S->getSymbol();
Mehdi Amini44ede332015-07-09 02:09:04 +00003112 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00003113 }
3114
3115 // We don't usually want to end the call-sequence here because we would tidy
3116 // the frame up *after* the call, however in the ABI-changing tail-call case
3117 // we've carefully laid out the parameters so that when sp is reset they'll be
3118 // in the correct location.
3119 if (IsTailCall && !IsSibCall) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003120 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3121 DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003122 InFlag = Chain.getValue(1);
3123 }
3124
3125 std::vector<SDValue> Ops;
3126 Ops.push_back(Chain);
3127 Ops.push_back(Callee);
3128
3129 if (IsTailCall) {
3130 // Each tail call may have to adjust the stack by a different amount, so
3131 // this information must travel along with the operation for eventual
3132 // consumption by emitEpilogue.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003133 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00003134 }
3135
3136 // Add argument registers to the end of the list so that they are known live
3137 // into the call.
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003138 for (auto &RegToPass : RegsToPass)
3139 Ops.push_back(DAG.getRegister(RegToPass.first,
3140 RegToPass.second.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00003141
3142 // Add a register mask operand representing the call-preserved registers.
3143 const uint32_t *Mask;
Eric Christopher905f12d2015-01-29 00:19:42 +00003144 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00003145 if (IsThisReturn) {
3146 // For 'this' returns, use the X0-preserving mask if applicable
Eric Christopher9deb75d2015-03-11 22:42:13 +00003147 Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003148 if (!Mask) {
3149 IsThisReturn = false;
Eric Christopher9deb75d2015-03-11 22:42:13 +00003150 Mask = TRI->getCallPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003151 }
3152 } else
Eric Christopher9deb75d2015-03-11 22:42:13 +00003153 Mask = TRI->getCallPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003154
3155 assert(Mask && "Missing call preserved mask for calling convention");
3156 Ops.push_back(DAG.getRegisterMask(Mask));
3157
3158 if (InFlag.getNode())
3159 Ops.push_back(InFlag);
3160
3161 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3162
3163 // If we're doing a tall call, use a TC_RETURN here rather than an
3164 // actual call instruction.
Arnold Schwaighoferf54b73d2015-05-08 23:52:00 +00003165 if (IsTailCall) {
3166 MF.getFrameInfo()->setHasTailCall();
Tim Northover3b0846e2014-05-24 12:50:23 +00003167 return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
Arnold Schwaighoferf54b73d2015-05-08 23:52:00 +00003168 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003169
3170 // Returns a chain and a flag for retval copy to use.
3171 Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
3172 InFlag = Chain.getValue(1);
3173
3174 uint64_t CalleePopBytes = DoesCalleeRestoreStack(CallConv, TailCallOpt)
3175 ? RoundUpToAlignment(NumBytes, 16)
3176 : 0;
3177
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003178 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3179 DAG.getIntPtrConstant(CalleePopBytes, DL, true),
Tim Northover3b0846e2014-05-24 12:50:23 +00003180 InFlag, DL);
3181 if (!Ins.empty())
3182 InFlag = Chain.getValue(1);
3183
3184 // Handle result values, copying them out of physregs into vregs that we
3185 // return.
3186 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3187 InVals, IsThisReturn,
3188 IsThisReturn ? OutVals[0] : SDValue());
3189}
3190
3191bool AArch64TargetLowering::CanLowerReturn(
3192 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
3193 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
3194 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3195 ? RetCC_AArch64_WebKit_JS
3196 : RetCC_AArch64_AAPCS;
3197 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003198 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
Tim Northover3b0846e2014-05-24 12:50:23 +00003199 return CCInfo.CheckReturn(Outs, RetCC);
3200}
3201
3202SDValue
3203AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3204 bool isVarArg,
3205 const SmallVectorImpl<ISD::OutputArg> &Outs,
3206 const SmallVectorImpl<SDValue> &OutVals,
3207 SDLoc DL, SelectionDAG &DAG) const {
3208 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3209 ? RetCC_AArch64_WebKit_JS
3210 : RetCC_AArch64_AAPCS;
3211 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003212 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3213 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00003214 CCInfo.AnalyzeReturn(Outs, RetCC);
3215
3216 // Copy the result values into the output registers.
3217 SDValue Flag;
3218 SmallVector<SDValue, 4> RetOps(1, Chain);
3219 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
3220 ++i, ++realRVLocIdx) {
3221 CCValAssign &VA = RVLocs[i];
3222 assert(VA.isRegLoc() && "Can only return in registers!");
3223 SDValue Arg = OutVals[realRVLocIdx];
3224
3225 switch (VA.getLocInfo()) {
3226 default:
3227 llvm_unreachable("Unknown loc info!");
3228 case CCValAssign::Full:
Tim Northover68ae5032014-05-26 17:22:07 +00003229 if (Outs[i].ArgVT == MVT::i1) {
3230 // AAPCS requires i1 to be zero-extended to i8 by the producer of the
3231 // value. This is strictly redundant on Darwin (which uses "zeroext
3232 // i1"), but will be optimised out before ISel.
3233 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3234 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3235 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003236 break;
3237 case CCValAssign::BCvt:
3238 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3239 break;
3240 }
3241
3242 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
3243 Flag = Chain.getValue(1);
3244 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3245 }
3246
3247 RetOps[0] = Chain; // Update chain.
3248
3249 // Add the flag if we have it.
3250 if (Flag.getNode())
3251 RetOps.push_back(Flag);
3252
3253 return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
3254}
3255
3256//===----------------------------------------------------------------------===//
3257// Other Lowering Code
3258//===----------------------------------------------------------------------===//
3259
3260SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
3261 SelectionDAG &DAG) const {
Mehdi Amini44ede332015-07-09 02:09:04 +00003262 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003263 SDLoc DL(Op);
Asiri Rathnayake369c0302014-09-10 13:54:38 +00003264 const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
3265 const GlobalValue *GV = GN->getGlobal();
Tim Northover3b0846e2014-05-24 12:50:23 +00003266 unsigned char OpFlags =
3267 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
3268
3269 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
3270 "unexpected offset in global node");
3271
3272 // This also catched the large code model case for Darwin.
3273 if ((OpFlags & AArch64II::MO_GOT) != 0) {
3274 SDValue GotAddr = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
3275 // FIXME: Once remat is capable of dealing with instructions with register
3276 // operands, expand this into two nodes instead of using a wrapper node.
3277 return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
3278 }
3279
Asiri Rathnayake369c0302014-09-10 13:54:38 +00003280 if ((OpFlags & AArch64II::MO_CONSTPOOL) != 0) {
3281 assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
3282 "use of MO_CONSTPOOL only supported on small model");
3283 SDValue Hi = DAG.getTargetConstantPool(GV, PtrVT, 0, 0, AArch64II::MO_PAGE);
3284 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3285 unsigned char LoFlags = AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
3286 SDValue Lo = DAG.getTargetConstantPool(GV, PtrVT, 0, 0, LoFlags);
3287 SDValue PoolAddr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003288 SDValue GlobalAddr = DAG.getLoad(
3289 PtrVT, DL, DAG.getEntryNode(), PoolAddr,
3290 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
3291 /*isVolatile=*/false,
3292 /*isNonTemporal=*/true,
3293 /*isInvariant=*/true, 8);
Asiri Rathnayake369c0302014-09-10 13:54:38 +00003294 if (GN->getOffset() != 0)
3295 return DAG.getNode(ISD::ADD, DL, PtrVT, GlobalAddr,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003296 DAG.getConstant(GN->getOffset(), DL, PtrVT));
Asiri Rathnayake369c0302014-09-10 13:54:38 +00003297 return GlobalAddr;
3298 }
3299
Tim Northover3b0846e2014-05-24 12:50:23 +00003300 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
3301 const unsigned char MO_NC = AArch64II::MO_NC;
3302 return DAG.getNode(
3303 AArch64ISD::WrapperLarge, DL, PtrVT,
3304 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G3),
3305 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
3306 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
3307 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
3308 } else {
3309 // Use ADRP/ADD or ADRP/LDR for everything else: the small model on ELF and
3310 // the only correct model on Darwin.
3311 SDValue Hi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
3312 OpFlags | AArch64II::MO_PAGE);
3313 unsigned char LoFlags = OpFlags | AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
3314 SDValue Lo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, LoFlags);
3315
3316 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3317 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3318 }
3319}
3320
3321/// \brief Convert a TLS address reference into the correct sequence of loads
3322/// and calls to compute the variable's address (for Darwin, currently) and
3323/// return an SDValue containing the final node.
3324
3325/// Darwin only has one TLS scheme which must be capable of dealing with the
3326/// fully general situation, in the worst case. This means:
3327/// + "extern __thread" declaration.
3328/// + Defined in a possibly unknown dynamic library.
3329///
3330/// The general system is that each __thread variable has a [3 x i64] descriptor
3331/// which contains information used by the runtime to calculate the address. The
3332/// only part of this the compiler needs to know about is the first xword, which
3333/// contains a function pointer that must be called with the address of the
3334/// entire descriptor in "x0".
3335///
3336/// Since this descriptor may be in a different unit, in general even the
3337/// descriptor must be accessed via an indirect load. The "ideal" code sequence
3338/// is:
3339/// adrp x0, _var@TLVPPAGE
3340/// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor
3341/// ldr x1, [x0] ; x1 contains 1st entry of descriptor,
3342/// ; the function pointer
3343/// blr x1 ; Uses descriptor address in x0
3344/// ; Address of _var is now in x0.
3345///
3346/// If the address of _var's descriptor *is* known to the linker, then it can
3347/// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
3348/// a slight efficiency gain.
3349SDValue
3350AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
3351 SelectionDAG &DAG) const {
3352 assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
3353
3354 SDLoc DL(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00003355 MVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003356 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3357
3358 SDValue TLVPAddr =
3359 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3360 SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
3361
3362 // The first entry in the descriptor is a function pointer that we must call
3363 // to obtain the address of the variable.
3364 SDValue Chain = DAG.getEntryNode();
3365 SDValue FuncTLVGet =
Alex Lorenze40c8a22015-08-11 23:09:45 +00003366 DAG.getLoad(MVT::i64, DL, Chain, DescAddr,
3367 MachinePointerInfo::getGOT(DAG.getMachineFunction()), false,
3368 true, true, 8);
Tim Northover3b0846e2014-05-24 12:50:23 +00003369 Chain = FuncTLVGet.getValue(1);
3370
3371 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3372 MFI->setAdjustsStack(true);
3373
3374 // TLS calls preserve all registers except those that absolutely must be
3375 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
3376 // silly).
Eric Christopher6c901622015-01-28 03:51:33 +00003377 const uint32_t *Mask =
Eric Christopher905f12d2015-01-29 00:19:42 +00003378 Subtarget->getRegisterInfo()->getTLSCallPreservedMask();
Tim Northover3b0846e2014-05-24 12:50:23 +00003379
3380 // Finally, we can make the call. This is just a degenerate version of a
3381 // normal AArch64 call node: x0 takes the address of the descriptor, and
3382 // returns the address of the variable in this thread.
3383 Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
3384 Chain =
3385 DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3386 Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
3387 DAG.getRegisterMask(Mask), Chain.getValue(1));
3388 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
3389}
3390
3391/// When accessing thread-local variables under either the general-dynamic or
3392/// local-dynamic system, we make a "TLS-descriptor" call. The variable will
3393/// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
Kristof Beylsaea84612015-03-04 09:12:08 +00003394/// is a function pointer to carry out the resolution.
Tim Northover3b0846e2014-05-24 12:50:23 +00003395///
Kristof Beylsaea84612015-03-04 09:12:08 +00003396/// The sequence is:
3397/// adrp x0, :tlsdesc:var
3398/// ldr x1, [x0, #:tlsdesc_lo12:var]
3399/// add x0, x0, #:tlsdesc_lo12:var
3400/// .tlsdesccall var
3401/// blr x1
3402/// (TPIDR_EL0 offset now in x0)
Tim Northover3b0846e2014-05-24 12:50:23 +00003403///
Kristof Beylsaea84612015-03-04 09:12:08 +00003404/// The above sequence must be produced unscheduled, to enable the linker to
3405/// optimize/relax this sequence.
3406/// Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
3407/// above sequence, and expanded really late in the compilation flow, to ensure
3408/// the sequence is produced as per above.
3409SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr, SDLoc DL,
3410 SelectionDAG &DAG) const {
Mehdi Amini44ede332015-07-09 02:09:04 +00003411 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003412
Kristof Beylsaea84612015-03-04 09:12:08 +00003413 SDValue Chain = DAG.getEntryNode();
Tim Northover3b0846e2014-05-24 12:50:23 +00003414 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
Kristof Beylsaea84612015-03-04 09:12:08 +00003415
3416 SmallVector<SDValue, 2> Ops;
3417 Ops.push_back(Chain);
3418 Ops.push_back(SymAddr);
3419
3420 Chain = DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, Ops);
3421 SDValue Glue = Chain.getValue(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00003422
3423 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
3424}
3425
3426SDValue
3427AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
3428 SelectionDAG &DAG) const {
3429 assert(Subtarget->isTargetELF() && "This function expects an ELF target");
3430 assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
3431 "ELF TLS only supported in small memory model");
Kristof Beylsaea84612015-03-04 09:12:08 +00003432 // Different choices can be made for the maximum size of the TLS area for a
3433 // module. For the small address model, the default TLS size is 16MiB and the
3434 // maximum TLS size is 4GiB.
3435 // FIXME: add -mtls-size command line option and make it control the 16MiB
3436 // vs. 4GiB code sequence generation.
Tim Northover3b0846e2014-05-24 12:50:23 +00003437 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3438
3439 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
Chih-Hung Hsieh1e859582015-07-28 16:24:05 +00003440
3441 if (DAG.getTarget().Options.EmulatedTLS)
3442 return LowerToTLSEmulatedModel(GA, DAG);
3443
Kristof Beylsaea84612015-03-04 09:12:08 +00003444 if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
3445 if (Model == TLSModel::LocalDynamic)
3446 Model = TLSModel::GeneralDynamic;
3447 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003448
3449 SDValue TPOff;
Mehdi Amini44ede332015-07-09 02:09:04 +00003450 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003451 SDLoc DL(Op);
3452 const GlobalValue *GV = GA->getGlobal();
3453
3454 SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
3455
3456 if (Model == TLSModel::LocalExec) {
3457 SDValue HiVar = DAG.getTargetGlobalAddress(
Kristof Beylsaea84612015-03-04 09:12:08 +00003458 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
Tim Northover3b0846e2014-05-24 12:50:23 +00003459 SDValue LoVar = DAG.getTargetGlobalAddress(
3460 GV, DL, PtrVT, 0,
Kristof Beylsaea84612015-03-04 09:12:08 +00003461 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
Tim Northover3b0846e2014-05-24 12:50:23 +00003462
Kristof Beylsaea84612015-03-04 09:12:08 +00003463 SDValue TPWithOff_lo =
3464 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003465 HiVar,
3466 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003467 0);
3468 SDValue TPWithOff =
3469 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003470 LoVar,
3471 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003472 0);
3473 return TPWithOff;
Tim Northover3b0846e2014-05-24 12:50:23 +00003474 } else if (Model == TLSModel::InitialExec) {
3475 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3476 TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
3477 } else if (Model == TLSModel::LocalDynamic) {
3478 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
3479 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
3480 // the beginning of the module's TLS region, followed by a DTPREL offset
3481 // calculation.
3482
3483 // These accesses will need deduplicating if there's more than one.
3484 AArch64FunctionInfo *MFI =
3485 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
3486 MFI->incNumLocalDynamicTLSAccesses();
3487
Tim Northover3b0846e2014-05-24 12:50:23 +00003488 // The call needs a relocation too for linker relaxation. It doesn't make
3489 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3490 // the address.
3491 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
3492 AArch64II::MO_TLS);
3493
3494 // Now we can calculate the offset from TPIDR_EL0 to this module's
3495 // thread-local area.
Kristof Beylsaea84612015-03-04 09:12:08 +00003496 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00003497
3498 // Now use :dtprel_whatever: operations to calculate this variable's offset
3499 // in its thread-storage area.
3500 SDValue HiVar = DAG.getTargetGlobalAddress(
Kristof Beylsaea84612015-03-04 09:12:08 +00003501 GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
Tim Northover3b0846e2014-05-24 12:50:23 +00003502 SDValue LoVar = DAG.getTargetGlobalAddress(
3503 GV, DL, MVT::i64, 0,
Tim Northover3b0846e2014-05-24 12:50:23 +00003504 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3505
Kristof Beylsaea84612015-03-04 09:12:08 +00003506 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003507 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003508 0);
3509 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003510 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003511 0);
3512 } else if (Model == TLSModel::GeneralDynamic) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003513 // The call needs a relocation too for linker relaxation. It doesn't make
3514 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3515 // the address.
3516 SDValue SymAddr =
3517 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3518
3519 // Finally we can make a call to calculate the offset from tpidr_el0.
Kristof Beylsaea84612015-03-04 09:12:08 +00003520 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00003521 } else
3522 llvm_unreachable("Unsupported ELF TLS access model");
3523
3524 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
3525}
3526
3527SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
3528 SelectionDAG &DAG) const {
3529 if (Subtarget->isTargetDarwin())
3530 return LowerDarwinGlobalTLSAddress(Op, DAG);
3531 else if (Subtarget->isTargetELF())
3532 return LowerELFGlobalTLSAddress(Op, DAG);
3533
3534 llvm_unreachable("Unexpected platform trying to use TLS");
3535}
3536SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3537 SDValue Chain = Op.getOperand(0);
3538 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3539 SDValue LHS = Op.getOperand(2);
3540 SDValue RHS = Op.getOperand(3);
3541 SDValue Dest = Op.getOperand(4);
3542 SDLoc dl(Op);
3543
3544 // Handle f128 first, since lowering it will result in comparing the return
3545 // value of a libcall against zero, which is just what the rest of LowerBR_CC
3546 // is expecting to deal with.
3547 if (LHS.getValueType() == MVT::f128) {
3548 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3549
3550 // If softenSetCCOperands returned a scalar, we need to compare the result
3551 // against zero to select between true and false values.
3552 if (!RHS.getNode()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003553 RHS = DAG.getConstant(0, dl, LHS.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00003554 CC = ISD::SETNE;
3555 }
3556 }
3557
3558 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
3559 // instruction.
3560 unsigned Opc = LHS.getOpcode();
3561 if (LHS.getResNo() == 1 && isa<ConstantSDNode>(RHS) &&
3562 cast<ConstantSDNode>(RHS)->isOne() &&
3563 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3564 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
3565 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
3566 "Unexpected condition code.");
3567 // Only lower legal XALUO ops.
3568 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
3569 return SDValue();
3570
3571 // The actual operation with overflow check.
3572 AArch64CC::CondCode OFCC;
3573 SDValue Value, Overflow;
3574 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
3575
3576 if (CC == ISD::SETNE)
3577 OFCC = getInvertedCondCode(OFCC);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003578 SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003579
Ahmed Bougachadf956a22015-02-06 23:15:39 +00003580 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3581 Overflow);
Tim Northover3b0846e2014-05-24 12:50:23 +00003582 }
3583
3584 if (LHS.getValueType().isInteger()) {
3585 assert((LHS.getValueType() == RHS.getValueType()) &&
3586 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3587
3588 // If the RHS of the comparison is zero, we can potentially fold this
3589 // to a specialized branch.
3590 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
3591 if (RHSC && RHSC->getZExtValue() == 0) {
3592 if (CC == ISD::SETEQ) {
3593 // See if we can use a TBZ to fold in an AND as well.
3594 // TBZ has a smaller branch displacement than CBZ. If the offset is
3595 // out of bounds, a late MI-layer pass rewrites branches.
3596 // 403.gcc is an example that hits this case.
3597 if (LHS.getOpcode() == ISD::AND &&
3598 isa<ConstantSDNode>(LHS.getOperand(1)) &&
3599 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3600 SDValue Test = LHS.getOperand(0);
3601 uint64_t Mask = LHS.getConstantOperandVal(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00003602 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003603 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3604 Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00003605 }
3606
3607 return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
3608 } else if (CC == ISD::SETNE) {
3609 // See if we can use a TBZ to fold in an AND as well.
3610 // TBZ has a smaller branch displacement than CBZ. If the offset is
3611 // out of bounds, a late MI-layer pass rewrites branches.
3612 // 403.gcc is an example that hits this case.
3613 if (LHS.getOpcode() == ISD::AND &&
3614 isa<ConstantSDNode>(LHS.getOperand(1)) &&
3615 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3616 SDValue Test = LHS.getOperand(0);
3617 uint64_t Mask = LHS.getConstantOperandVal(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00003618 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003619 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3620 Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00003621 }
3622
3623 return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
Chad Rosier579c02c2014-08-01 14:48:56 +00003624 } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
3625 // Don't combine AND since emitComparison converts the AND to an ANDS
3626 // (a.k.a. TST) and the test in the test bit and branch instruction
3627 // becomes redundant. This would also increase register pressure.
3628 uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
3629 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003630 DAG.getConstant(Mask, dl, MVT::i64), Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00003631 }
3632 }
Chad Rosier579c02c2014-08-01 14:48:56 +00003633 if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
3634 LHS.getOpcode() != ISD::AND) {
3635 // Don't combine AND since emitComparison converts the AND to an ANDS
3636 // (a.k.a. TST) and the test in the test bit and branch instruction
3637 // becomes redundant. This would also increase register pressure.
3638 uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
3639 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003640 DAG.getConstant(Mask, dl, MVT::i64), Dest);
Chad Rosier579c02c2014-08-01 14:48:56 +00003641 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003642
3643 SDValue CCVal;
3644 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3645 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3646 Cmp);
3647 }
3648
3649 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3650
3651 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
3652 // clean. Some of them require two branches to implement.
3653 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3654 AArch64CC::CondCode CC1, CC2;
3655 changeFPCCToAArch64CC(CC, CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003656 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003657 SDValue BR1 =
3658 DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
3659 if (CC2 != AArch64CC::AL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003660 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003661 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
3662 Cmp);
3663 }
3664
3665 return BR1;
3666}
3667
3668SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
3669 SelectionDAG &DAG) const {
3670 EVT VT = Op.getValueType();
3671 SDLoc DL(Op);
3672
3673 SDValue In1 = Op.getOperand(0);
3674 SDValue In2 = Op.getOperand(1);
3675 EVT SrcVT = In2.getValueType();
Ahmed Bougacha2a97b1b2015-08-13 01:13:56 +00003676
3677 if (SrcVT.bitsLT(VT))
3678 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
3679 else if (SrcVT.bitsGT(VT))
3680 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
Tim Northover3b0846e2014-05-24 12:50:23 +00003681
3682 EVT VecVT;
3683 EVT EltVT;
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00003684 uint64_t EltMask;
3685 SDValue VecVal1, VecVal2;
Tim Northover3b0846e2014-05-24 12:50:23 +00003686 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
3687 EltVT = MVT::i32;
Ahmed Bougachab0ae36f2015-08-04 00:42:34 +00003688 VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00003689 EltMask = 0x80000000ULL;
Tim Northover3b0846e2014-05-24 12:50:23 +00003690
3691 if (!VT.isVector()) {
3692 VecVal1 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3693 DAG.getUNDEF(VecVT), In1);
3694 VecVal2 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3695 DAG.getUNDEF(VecVT), In2);
3696 } else {
3697 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3698 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3699 }
3700 } else if (VT == MVT::f64 || VT == MVT::v2f64) {
3701 EltVT = MVT::i64;
3702 VecVT = MVT::v2i64;
3703
Eric Christopher572e03a2015-06-19 01:53:21 +00003704 // We want to materialize a mask with the high bit set, but the AdvSIMD
Tim Northover3b0846e2014-05-24 12:50:23 +00003705 // immediate moves cannot materialize that in a single instruction for
3706 // 64-bit elements. Instead, materialize zero and then negate it.
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00003707 EltMask = 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00003708
3709 if (!VT.isVector()) {
3710 VecVal1 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3711 DAG.getUNDEF(VecVT), In1);
3712 VecVal2 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3713 DAG.getUNDEF(VecVT), In2);
3714 } else {
3715 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3716 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3717 }
3718 } else {
3719 llvm_unreachable("Invalid type for copysign!");
3720 }
3721
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003722 SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00003723
3724 // If we couldn't materialize the mask above, then the mask vector will be
3725 // the zero vector, and we need to negate it here.
3726 if (VT == MVT::f64 || VT == MVT::v2f64) {
3727 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
3728 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
3729 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
3730 }
3731
3732 SDValue Sel =
3733 DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
3734
3735 if (VT == MVT::f32)
3736 return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
3737 else if (VT == MVT::f64)
3738 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
3739 else
3740 return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
3741}
3742
3743SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
Duncan P. N. Exon Smith003bb7d2015-02-14 02:09:06 +00003744 if (DAG.getMachineFunction().getFunction()->hasFnAttribute(
3745 Attribute::NoImplicitFloat))
Tim Northover3b0846e2014-05-24 12:50:23 +00003746 return SDValue();
3747
Weiming Zhao7a2d1562014-11-19 00:29:14 +00003748 if (!Subtarget->hasNEON())
3749 return SDValue();
3750
Tim Northover3b0846e2014-05-24 12:50:23 +00003751 // While there is no integer popcount instruction, it can
3752 // be more efficiently lowered to the following sequence that uses
3753 // AdvSIMD registers/instructions as long as the copies to/from
3754 // the AdvSIMD registers are cheap.
3755 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd
3756 // CNT V0.8B, V0.8B // 8xbyte pop-counts
3757 // ADDV B0, V0.8B // sum 8xbyte pop-counts
3758 // UMOV X0, V0.B[0] // copy byte result back to integer reg
3759 SDValue Val = Op.getOperand(0);
3760 SDLoc DL(Op);
3761 EVT VT = Op.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00003762
Hao Liue0335d72015-01-30 02:13:53 +00003763 if (VT == MVT::i32)
3764 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
3765 Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
Tim Northover3b0846e2014-05-24 12:50:23 +00003766
Hao Liue0335d72015-01-30 02:13:53 +00003767 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
Tim Northover3b0846e2014-05-24 12:50:23 +00003768 SDValue UaddLV = DAG.getNode(
3769 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003770 DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
Tim Northover3b0846e2014-05-24 12:50:23 +00003771
3772 if (VT == MVT::i64)
3773 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
3774 return UaddLV;
3775}
3776
3777SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3778
3779 if (Op.getValueType().isVector())
3780 return LowerVSETCC(Op, DAG);
3781
3782 SDValue LHS = Op.getOperand(0);
3783 SDValue RHS = Op.getOperand(1);
3784 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3785 SDLoc dl(Op);
3786
3787 // We chose ZeroOrOneBooleanContents, so use zero and one.
3788 EVT VT = Op.getValueType();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003789 SDValue TVal = DAG.getConstant(1, dl, VT);
3790 SDValue FVal = DAG.getConstant(0, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00003791
3792 // Handle f128 first, since one possible outcome is a normal integer
3793 // comparison which gets picked up by the next if statement.
3794 if (LHS.getValueType() == MVT::f128) {
3795 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3796
3797 // If softenSetCCOperands returned a scalar, use it.
3798 if (!RHS.getNode()) {
3799 assert(LHS.getValueType() == Op.getValueType() &&
3800 "Unexpected setcc expansion!");
3801 return LHS;
3802 }
3803 }
3804
3805 if (LHS.getValueType().isInteger()) {
3806 SDValue CCVal;
3807 SDValue Cmp =
3808 getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
3809
3810 // Note that we inverted the condition above, so we reverse the order of
3811 // the true and false operands here. This will allow the setcc to be
3812 // matched to a single CSINC instruction.
3813 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
3814 }
3815
3816 // Now we know we're dealing with FP values.
3817 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3818
3819 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
3820 // and do the comparison.
3821 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3822
3823 AArch64CC::CondCode CC1, CC2;
3824 changeFPCCToAArch64CC(CC, CC1, CC2);
3825 if (CC2 == AArch64CC::AL) {
3826 changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003827 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003828
3829 // Note that we inverted the condition above, so we reverse the order of
3830 // the true and false operands here. This will allow the setcc to be
3831 // matched to a single CSINC instruction.
3832 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
3833 } else {
3834 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
3835 // totally clean. Some of them require two CSELs to implement. As is in
3836 // this case, we emit the first CSEL and then emit a second using the output
3837 // of the first as the RHS. We're effectively OR'ing the two CC's together.
3838
3839 // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003840 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003841 SDValue CS1 =
3842 DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3843
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003844 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003845 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3846 }
3847}
3848
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00003849SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
3850 SDValue RHS, SDValue TVal,
3851 SDValue FVal, SDLoc dl,
Tim Northover3b0846e2014-05-24 12:50:23 +00003852 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00003853 // Handle f128 first, because it will result in a comparison of some RTLIB
3854 // call result against zero.
3855 if (LHS.getValueType() == MVT::f128) {
3856 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3857
3858 // If softenSetCCOperands returned a scalar, we need to compare the result
3859 // against zero to select between true and false values.
3860 if (!RHS.getNode()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003861 RHS = DAG.getConstant(0, dl, LHS.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00003862 CC = ISD::SETNE;
3863 }
3864 }
3865
3866 // Handle integers first.
3867 if (LHS.getValueType().isInteger()) {
3868 assert((LHS.getValueType() == RHS.getValueType()) &&
3869 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3870
3871 unsigned Opcode = AArch64ISD::CSEL;
3872
3873 // If both the TVal and the FVal are constants, see if we can swap them in
3874 // order to for a CSINV or CSINC out of them.
3875 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
3876 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
3877
3878 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
3879 std::swap(TVal, FVal);
3880 std::swap(CTVal, CFVal);
3881 CC = ISD::getSetCCInverse(CC, true);
3882 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
3883 std::swap(TVal, FVal);
3884 std::swap(CTVal, CFVal);
3885 CC = ISD::getSetCCInverse(CC, true);
3886 } else if (TVal.getOpcode() == ISD::XOR) {
3887 // If TVal is a NOT we want to swap TVal and FVal so that we can match
3888 // with a CSINV rather than a CSEL.
3889 ConstantSDNode *CVal = dyn_cast<ConstantSDNode>(TVal.getOperand(1));
3890
3891 if (CVal && CVal->isAllOnesValue()) {
3892 std::swap(TVal, FVal);
3893 std::swap(CTVal, CFVal);
3894 CC = ISD::getSetCCInverse(CC, true);
3895 }
3896 } else if (TVal.getOpcode() == ISD::SUB) {
3897 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
3898 // that we can match with a CSNEG rather than a CSEL.
3899 ConstantSDNode *CVal = dyn_cast<ConstantSDNode>(TVal.getOperand(0));
3900
3901 if (CVal && CVal->isNullValue()) {
3902 std::swap(TVal, FVal);
3903 std::swap(CTVal, CFVal);
3904 CC = ISD::getSetCCInverse(CC, true);
3905 }
3906 } else if (CTVal && CFVal) {
3907 const int64_t TrueVal = CTVal->getSExtValue();
3908 const int64_t FalseVal = CFVal->getSExtValue();
3909 bool Swap = false;
3910
3911 // If both TVal and FVal are constants, see if FVal is the
3912 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
3913 // instead of a CSEL in that case.
3914 if (TrueVal == ~FalseVal) {
3915 Opcode = AArch64ISD::CSINV;
3916 } else if (TrueVal == -FalseVal) {
3917 Opcode = AArch64ISD::CSNEG;
3918 } else if (TVal.getValueType() == MVT::i32) {
3919 // If our operands are only 32-bit wide, make sure we use 32-bit
3920 // arithmetic for the check whether we can use CSINC. This ensures that
3921 // the addition in the check will wrap around properly in case there is
3922 // an overflow (which would not be the case if we do the check with
3923 // 64-bit arithmetic).
3924 const uint32_t TrueVal32 = CTVal->getZExtValue();
3925 const uint32_t FalseVal32 = CFVal->getZExtValue();
3926
3927 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
3928 Opcode = AArch64ISD::CSINC;
3929
3930 if (TrueVal32 > FalseVal32) {
3931 Swap = true;
3932 }
3933 }
3934 // 64-bit check whether we can use CSINC.
3935 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
3936 Opcode = AArch64ISD::CSINC;
3937
3938 if (TrueVal > FalseVal) {
3939 Swap = true;
3940 }
3941 }
3942
3943 // Swap TVal and FVal if necessary.
3944 if (Swap) {
3945 std::swap(TVal, FVal);
3946 std::swap(CTVal, CFVal);
3947 CC = ISD::getSetCCInverse(CC, true);
3948 }
3949
3950 if (Opcode != AArch64ISD::CSEL) {
3951 // Drop FVal since we can get its value by simply inverting/negating
3952 // TVal.
3953 FVal = TVal;
3954 }
3955 }
3956
3957 SDValue CCVal;
3958 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3959
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00003960 EVT VT = TVal.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00003961 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
3962 }
3963
3964 // Now we know we're dealing with FP values.
3965 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3966 assert(LHS.getValueType() == RHS.getValueType());
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00003967 EVT VT = TVal.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00003968 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3969
3970 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
3971 // clean. Some of them require two CSELs to implement.
3972 AArch64CC::CondCode CC1, CC2;
3973 changeFPCCToAArch64CC(CC, CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003974 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003975 SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3976
3977 // If we need a second CSEL, emit it, using the output of the first as the
3978 // RHS. We're effectively OR'ing the two CC's together.
3979 if (CC2 != AArch64CC::AL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003980 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003981 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3982 }
3983
3984 // Otherwise, return the output of the first CSEL.
3985 return CS1;
3986}
3987
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00003988SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
3989 SelectionDAG &DAG) const {
3990 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3991 SDValue LHS = Op.getOperand(0);
3992 SDValue RHS = Op.getOperand(1);
3993 SDValue TVal = Op.getOperand(2);
3994 SDValue FVal = Op.getOperand(3);
3995 SDLoc DL(Op);
3996 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
3997}
3998
3999SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
4000 SelectionDAG &DAG) const {
4001 SDValue CCVal = Op->getOperand(0);
4002 SDValue TVal = Op->getOperand(1);
4003 SDValue FVal = Op->getOperand(2);
4004 SDLoc DL(Op);
4005
4006 unsigned Opc = CCVal.getOpcode();
4007 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
4008 // instruction.
4009 if (CCVal.getResNo() == 1 &&
4010 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4011 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
4012 // Only lower legal XALUO ops.
4013 if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
4014 return SDValue();
4015
4016 AArch64CC::CondCode OFCC;
4017 SDValue Value, Overflow;
4018 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004019 SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004020
4021 return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
4022 CCVal, Overflow);
4023 }
4024
4025 // Lower it the same way as we would lower a SELECT_CC node.
4026 ISD::CondCode CC;
4027 SDValue LHS, RHS;
4028 if (CCVal.getOpcode() == ISD::SETCC) {
4029 LHS = CCVal.getOperand(0);
4030 RHS = CCVal.getOperand(1);
4031 CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
4032 } else {
4033 LHS = CCVal;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004034 RHS = DAG.getConstant(0, DL, CCVal.getValueType());
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004035 CC = ISD::SETNE;
4036 }
4037 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4038}
4039
Tim Northover3b0846e2014-05-24 12:50:23 +00004040SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
4041 SelectionDAG &DAG) const {
4042 // Jump table entries as PC relative offsets. No additional tweaking
4043 // is necessary here. Just get the address of the jump table.
4044 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00004045 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004046 SDLoc DL(Op);
4047
4048 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4049 !Subtarget->isTargetMachO()) {
4050 const unsigned char MO_NC = AArch64II::MO_NC;
4051 return DAG.getNode(
4052 AArch64ISD::WrapperLarge, DL, PtrVT,
4053 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G3),
4054 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G2 | MO_NC),
4055 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G1 | MO_NC),
4056 DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4057 AArch64II::MO_G0 | MO_NC));
4058 }
4059
4060 SDValue Hi =
4061 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_PAGE);
4062 SDValue Lo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4063 AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4064 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4065 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4066}
4067
4068SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
4069 SelectionDAG &DAG) const {
4070 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00004071 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004072 SDLoc DL(Op);
4073
4074 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4075 // Use the GOT for the large code model on iOS.
4076 if (Subtarget->isTargetMachO()) {
4077 SDValue GotAddr = DAG.getTargetConstantPool(
4078 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4079 AArch64II::MO_GOT);
4080 return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
4081 }
4082
4083 const unsigned char MO_NC = AArch64II::MO_NC;
4084 return DAG.getNode(
4085 AArch64ISD::WrapperLarge, DL, PtrVT,
4086 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4087 CP->getOffset(), AArch64II::MO_G3),
4088 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4089 CP->getOffset(), AArch64II::MO_G2 | MO_NC),
4090 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4091 CP->getOffset(), AArch64II::MO_G1 | MO_NC),
4092 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4093 CP->getOffset(), AArch64II::MO_G0 | MO_NC));
4094 } else {
4095 // Use ADRP/ADD or ADRP/LDR for everything else: the small memory model on
4096 // ELF, the only valid one on Darwin.
4097 SDValue Hi =
4098 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4099 CP->getOffset(), AArch64II::MO_PAGE);
4100 SDValue Lo = DAG.getTargetConstantPool(
4101 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4102 AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4103
4104 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4105 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4106 }
4107}
4108
4109SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
4110 SelectionDAG &DAG) const {
4111 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
Mehdi Amini44ede332015-07-09 02:09:04 +00004112 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004113 SDLoc DL(Op);
4114 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4115 !Subtarget->isTargetMachO()) {
4116 const unsigned char MO_NC = AArch64II::MO_NC;
4117 return DAG.getNode(
4118 AArch64ISD::WrapperLarge, DL, PtrVT,
4119 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G3),
4120 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
4121 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
4122 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
4123 } else {
4124 SDValue Hi = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGE);
4125 SDValue Lo = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGEOFF |
4126 AArch64II::MO_NC);
4127 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4128 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4129 }
4130}
4131
4132SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
4133 SelectionDAG &DAG) const {
4134 AArch64FunctionInfo *FuncInfo =
4135 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4136
4137 SDLoc DL(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00004138 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
4139 getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00004140 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4141 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
4142 MachinePointerInfo(SV), false, false, 0);
4143}
4144
4145SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
4146 SelectionDAG &DAG) const {
4147 // The layout of the va_list struct is specified in the AArch64 Procedure Call
4148 // Standard, section B.3.
4149 MachineFunction &MF = DAG.getMachineFunction();
4150 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Mehdi Amini44ede332015-07-09 02:09:04 +00004151 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004152 SDLoc DL(Op);
4153
4154 SDValue Chain = Op.getOperand(0);
4155 SDValue VAList = Op.getOperand(1);
4156 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4157 SmallVector<SDValue, 4> MemOps;
4158
4159 // void *__stack at offset 0
Mehdi Amini44ede332015-07-09 02:09:04 +00004160 SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004161 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
4162 MachinePointerInfo(SV), false, false, 8));
4163
4164 // void *__gr_top at offset 8
4165 int GPRSize = FuncInfo->getVarArgsGPRSize();
4166 if (GPRSize > 0) {
4167 SDValue GRTop, GRTopAddr;
4168
Mehdi Amini44ede332015-07-09 02:09:04 +00004169 GRTopAddr =
4170 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004171
Mehdi Amini44ede332015-07-09 02:09:04 +00004172 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
4173 GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
4174 DAG.getConstant(GPRSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004175
4176 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
4177 MachinePointerInfo(SV, 8), false, false, 8));
4178 }
4179
4180 // void *__vr_top at offset 16
4181 int FPRSize = FuncInfo->getVarArgsFPRSize();
4182 if (FPRSize > 0) {
4183 SDValue VRTop, VRTopAddr;
Mehdi Amini44ede332015-07-09 02:09:04 +00004184 VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4185 DAG.getConstant(16, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004186
Mehdi Amini44ede332015-07-09 02:09:04 +00004187 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
4188 VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
4189 DAG.getConstant(FPRSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004190
4191 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
4192 MachinePointerInfo(SV, 16), false, false, 8));
4193 }
4194
4195 // int __gr_offs at offset 24
Mehdi Amini44ede332015-07-09 02:09:04 +00004196 SDValue GROffsAddr =
4197 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004198 MemOps.push_back(DAG.getStore(Chain, DL,
4199 DAG.getConstant(-GPRSize, DL, MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00004200 GROffsAddr, MachinePointerInfo(SV, 24), false,
4201 false, 4));
4202
4203 // int __vr_offs at offset 28
Mehdi Amini44ede332015-07-09 02:09:04 +00004204 SDValue VROffsAddr =
4205 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004206 MemOps.push_back(DAG.getStore(Chain, DL,
4207 DAG.getConstant(-FPRSize, DL, MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00004208 VROffsAddr, MachinePointerInfo(SV, 28), false,
4209 false, 4));
4210
4211 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
4212}
4213
4214SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
4215 SelectionDAG &DAG) const {
4216 return Subtarget->isTargetDarwin() ? LowerDarwin_VASTART(Op, DAG)
4217 : LowerAAPCS_VASTART(Op, DAG);
4218}
4219
4220SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
4221 SelectionDAG &DAG) const {
4222 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
4223 // pointer.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004224 SDLoc DL(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00004225 unsigned VaListSize = Subtarget->isTargetDarwin() ? 8 : 32;
4226 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4227 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4228
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004229 return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1),
4230 Op.getOperand(2),
4231 DAG.getConstant(VaListSize, DL, MVT::i32),
Krzysztof Parzyszeka46c36b2015-04-13 17:16:45 +00004232 8, false, false, false, MachinePointerInfo(DestSV),
Tim Northover3b0846e2014-05-24 12:50:23 +00004233 MachinePointerInfo(SrcSV));
4234}
4235
4236SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
4237 assert(Subtarget->isTargetDarwin() &&
4238 "automatic va_arg instruction only works on Darwin");
4239
4240 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4241 EVT VT = Op.getValueType();
4242 SDLoc DL(Op);
4243 SDValue Chain = Op.getOperand(0);
4244 SDValue Addr = Op.getOperand(1);
4245 unsigned Align = Op.getConstantOperandVal(3);
Mehdi Amini44ede332015-07-09 02:09:04 +00004246 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004247
Mehdi Amini44ede332015-07-09 02:09:04 +00004248 SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V),
4249 false, false, false, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00004250 Chain = VAList.getValue(1);
4251
4252 if (Align > 8) {
4253 assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
Mehdi Amini44ede332015-07-09 02:09:04 +00004254 VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4255 DAG.getConstant(Align - 1, DL, PtrVT));
4256 VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
4257 DAG.getConstant(-(int64_t)Align, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004258 }
4259
4260 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
Mehdi Amini44ede332015-07-09 02:09:04 +00004261 uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
Tim Northover3b0846e2014-05-24 12:50:23 +00004262
4263 // Scalar integer and FP values smaller than 64 bits are implicitly extended
4264 // up to 64 bits. At the very least, we have to increase the striding of the
4265 // vaargs list to match this, and for FP values we need to introduce
4266 // FP_ROUND nodes as well.
4267 if (VT.isInteger() && !VT.isVector())
4268 ArgSize = 8;
4269 bool NeedFPTrunc = false;
4270 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
4271 ArgSize = 8;
4272 NeedFPTrunc = true;
4273 }
4274
4275 // Increment the pointer, VAList, to the next vaarg
Mehdi Amini44ede332015-07-09 02:09:04 +00004276 SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4277 DAG.getConstant(ArgSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004278 // Store the incremented VAList to the legalized pointer
4279 SDValue APStore = DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V),
4280 false, false, 0);
4281
4282 // Load the actual argument out of the pointer VAList
4283 if (NeedFPTrunc) {
4284 // Load the value as an f64.
4285 SDValue WideFP = DAG.getLoad(MVT::f64, DL, APStore, VAList,
4286 MachinePointerInfo(), false, false, false, 0);
4287 // Round the value down to an f32.
4288 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004289 DAG.getIntPtrConstant(1, DL));
Tim Northover3b0846e2014-05-24 12:50:23 +00004290 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
4291 // Merge the rounded value with the chain output of the load.
4292 return DAG.getMergeValues(Ops, DL);
4293 }
4294
4295 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo(), false,
4296 false, false, 0);
4297}
4298
4299SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
4300 SelectionDAG &DAG) const {
4301 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4302 MFI->setFrameAddressIsTaken(true);
4303
4304 EVT VT = Op.getValueType();
4305 SDLoc DL(Op);
4306 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4307 SDValue FrameAddr =
4308 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
4309 while (Depth--)
4310 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
4311 MachinePointerInfo(), false, false, false, 0);
4312 return FrameAddr;
4313}
4314
4315// FIXME? Maybe this could be a TableGen attribute on some registers and
4316// this table could be generated automatically from RegInfo.
Pat Gavlina717f252015-07-09 17:40:29 +00004317unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT,
4318 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004319 unsigned Reg = StringSwitch<unsigned>(RegName)
4320 .Case("sp", AArch64::SP)
4321 .Default(0);
4322 if (Reg)
4323 return Reg;
Luke Cheeseman85fd06d2015-06-01 12:02:47 +00004324 report_fatal_error(Twine("Invalid register name \""
4325 + StringRef(RegName) + "\"."));
Tim Northover3b0846e2014-05-24 12:50:23 +00004326}
4327
4328SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
4329 SelectionDAG &DAG) const {
4330 MachineFunction &MF = DAG.getMachineFunction();
4331 MachineFrameInfo *MFI = MF.getFrameInfo();
4332 MFI->setReturnAddressIsTaken(true);
4333
4334 EVT VT = Op.getValueType();
4335 SDLoc DL(Op);
4336 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4337 if (Depth) {
4338 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
Mehdi Amini44ede332015-07-09 02:09:04 +00004339 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00004340 return DAG.getLoad(VT, DL, DAG.getEntryNode(),
4341 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
4342 MachinePointerInfo(), false, false, false, 0);
4343 }
4344
4345 // Return LR, which contains the return address. Mark it an implicit live-in.
4346 unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
4347 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4348}
4349
4350/// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4351/// i64 values and take a 2 x i64 value to shift plus a shift amount.
4352SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
4353 SelectionDAG &DAG) const {
4354 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4355 EVT VT = Op.getValueType();
4356 unsigned VTBits = VT.getSizeInBits();
4357 SDLoc dl(Op);
4358 SDValue ShOpLo = Op.getOperand(0);
4359 SDValue ShOpHi = Op.getOperand(1);
4360 SDValue ShAmt = Op.getOperand(2);
4361 SDValue ARMcc;
4362 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4363
4364 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4365
4366 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004367 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
Tim Northover3b0846e2014-05-24 12:50:23 +00004368 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4369 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004370 DAG.getConstant(VTBits, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00004371 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4372
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004373 SDValue Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64),
Tim Northover3b0846e2014-05-24 12:50:23 +00004374 ISD::SETGE, dl, DAG);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004375 SDValue CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004376
4377 SDValue FalseValLo = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4378 SDValue TrueValLo = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4379 SDValue Lo =
4380 DAG.getNode(AArch64ISD::CSEL, dl, VT, TrueValLo, FalseValLo, CCVal, Cmp);
4381
4382 // AArch64 shifts larger than the register width are wrapped rather than
4383 // clamped, so we can't just emit "hi >> x".
4384 SDValue FalseValHi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4385 SDValue TrueValHi = Opc == ISD::SRA
4386 ? DAG.getNode(Opc, dl, VT, ShOpHi,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004387 DAG.getConstant(VTBits - 1, dl,
4388 MVT::i64))
4389 : DAG.getConstant(0, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004390 SDValue Hi =
4391 DAG.getNode(AArch64ISD::CSEL, dl, VT, TrueValHi, FalseValHi, CCVal, Cmp);
4392
4393 SDValue Ops[2] = { Lo, Hi };
4394 return DAG.getMergeValues(Ops, dl);
4395}
4396
4397/// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4398/// i64 values and take a 2 x i64 value to shift plus a shift amount.
4399SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
4400 SelectionDAG &DAG) const {
4401 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4402 EVT VT = Op.getValueType();
4403 unsigned VTBits = VT.getSizeInBits();
4404 SDLoc dl(Op);
4405 SDValue ShOpLo = Op.getOperand(0);
4406 SDValue ShOpHi = Op.getOperand(1);
4407 SDValue ShAmt = Op.getOperand(2);
4408 SDValue ARMcc;
4409
4410 assert(Op.getOpcode() == ISD::SHL_PARTS);
4411 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004412 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
Tim Northover3b0846e2014-05-24 12:50:23 +00004413 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4414 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004415 DAG.getConstant(VTBits, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00004416 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4417 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4418
4419 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4420
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004421 SDValue Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64),
Tim Northover3b0846e2014-05-24 12:50:23 +00004422 ISD::SETGE, dl, DAG);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004423 SDValue CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004424 SDValue Hi =
4425 DAG.getNode(AArch64ISD::CSEL, dl, VT, Tmp3, FalseVal, CCVal, Cmp);
4426
4427 // AArch64 shifts of larger than register sizes are wrapped rather than
4428 // clamped, so we can't just emit "lo << a" if a is too big.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004429 SDValue TrueValLo = DAG.getConstant(0, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004430 SDValue FalseValLo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4431 SDValue Lo =
4432 DAG.getNode(AArch64ISD::CSEL, dl, VT, TrueValLo, FalseValLo, CCVal, Cmp);
4433
4434 SDValue Ops[2] = { Lo, Hi };
4435 return DAG.getMergeValues(Ops, dl);
4436}
4437
4438bool AArch64TargetLowering::isOffsetFoldingLegal(
4439 const GlobalAddressSDNode *GA) const {
4440 // The AArch64 target doesn't support folding offsets into global addresses.
4441 return false;
4442}
4443
4444bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4445 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
4446 // FIXME: We should be able to handle f128 as well with a clever lowering.
4447 if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32))
4448 return true;
4449
4450 if (VT == MVT::f64)
4451 return AArch64_AM::getFP64Imm(Imm) != -1;
4452 else if (VT == MVT::f32)
4453 return AArch64_AM::getFP32Imm(Imm) != -1;
4454 return false;
4455}
4456
4457//===----------------------------------------------------------------------===//
4458// AArch64 Optimization Hooks
4459//===----------------------------------------------------------------------===//
4460
4461//===----------------------------------------------------------------------===//
4462// AArch64 Inline Assembly Support
4463//===----------------------------------------------------------------------===//
4464
4465// Table of Constraints
4466// TODO: This is the current set of constraints supported by ARM for the
4467// compiler, not all of them may make sense, e.g. S may be difficult to support.
4468//
4469// r - A general register
4470// w - An FP/SIMD register of some size in the range v0-v31
4471// x - An FP/SIMD register of some size in the range v0-v15
4472// I - Constant that can be used with an ADD instruction
4473// J - Constant that can be used with a SUB instruction
4474// K - Constant that can be used with a 32-bit logical instruction
4475// L - Constant that can be used with a 64-bit logical instruction
4476// M - Constant that can be used as a 32-bit MOV immediate
4477// N - Constant that can be used as a 64-bit MOV immediate
4478// Q - A memory reference with base register and no offset
4479// S - A symbolic address
4480// Y - Floating point constant zero
4481// Z - Integer constant zero
4482//
4483// Note that general register operands will be output using their 64-bit x
4484// register name, whatever the size of the variable, unless the asm operand
4485// is prefixed by the %w modifier. Floating-point and SIMD register operands
4486// will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
4487// %q modifier.
4488
4489/// getConstraintType - Given a constraint letter, return the type of
4490/// constraint it is for this target.
4491AArch64TargetLowering::ConstraintType
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00004492AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004493 if (Constraint.size() == 1) {
4494 switch (Constraint[0]) {
4495 default:
4496 break;
4497 case 'z':
4498 return C_Other;
4499 case 'x':
4500 case 'w':
4501 return C_RegisterClass;
4502 // An address with a single base register. Due to the way we
4503 // currently handle addresses it is the same as 'r'.
4504 case 'Q':
4505 return C_Memory;
4506 }
4507 }
4508 return TargetLowering::getConstraintType(Constraint);
4509}
4510
4511/// Examine constraint type and operand type and determine a weight value.
4512/// This object must already have been set up with the operand type
4513/// and the current alternative constraint selected.
4514TargetLowering::ConstraintWeight
4515AArch64TargetLowering::getSingleConstraintMatchWeight(
4516 AsmOperandInfo &info, const char *constraint) const {
4517 ConstraintWeight weight = CW_Invalid;
4518 Value *CallOperandVal = info.CallOperandVal;
4519 // If we don't have a value, we can't do a match,
4520 // but allow it at the lowest weight.
4521 if (!CallOperandVal)
4522 return CW_Default;
4523 Type *type = CallOperandVal->getType();
4524 // Look at the constraint type.
4525 switch (*constraint) {
4526 default:
4527 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
4528 break;
4529 case 'x':
4530 case 'w':
4531 if (type->isFloatingPointTy() || type->isVectorTy())
4532 weight = CW_Register;
4533 break;
4534 case 'z':
4535 weight = CW_Constant;
4536 break;
4537 }
4538 return weight;
4539}
4540
4541std::pair<unsigned, const TargetRegisterClass *>
4542AArch64TargetLowering::getRegForInlineAsmConstraint(
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00004543 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004544 if (Constraint.size() == 1) {
4545 switch (Constraint[0]) {
4546 case 'r':
4547 if (VT.getSizeInBits() == 64)
4548 return std::make_pair(0U, &AArch64::GPR64commonRegClass);
4549 return std::make_pair(0U, &AArch64::GPR32commonRegClass);
4550 case 'w':
4551 if (VT == MVT::f32)
4552 return std::make_pair(0U, &AArch64::FPR32RegClass);
4553 if (VT.getSizeInBits() == 64)
4554 return std::make_pair(0U, &AArch64::FPR64RegClass);
4555 if (VT.getSizeInBits() == 128)
4556 return std::make_pair(0U, &AArch64::FPR128RegClass);
4557 break;
4558 // The instructions that this constraint is designed for can
4559 // only take 128-bit registers so just use that regclass.
4560 case 'x':
4561 if (VT.getSizeInBits() == 128)
4562 return std::make_pair(0U, &AArch64::FPR128_loRegClass);
4563 break;
4564 }
4565 }
4566 if (StringRef("{cc}").equals_lower(Constraint))
4567 return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
4568
4569 // Use the default implementation in TargetLowering to convert the register
4570 // constraint into a member of a register class.
4571 std::pair<unsigned, const TargetRegisterClass *> Res;
Eric Christopher11e4df72015-02-26 22:38:43 +00004572 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004573
4574 // Not found as a standard register?
4575 if (!Res.second) {
4576 unsigned Size = Constraint.size();
4577 if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
4578 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00004579 int RegNo;
4580 bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
4581 if (!Failed && RegNo >= 0 && RegNo <= 31) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004582 // v0 - v31 are aliases of q0 - q31.
4583 // By default we'll emit v0-v31 for this unless there's a modifier where
4584 // we'll emit the correct register as well.
4585 Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
4586 Res.second = &AArch64::FPR128RegClass;
4587 }
4588 }
4589 }
4590
4591 return Res;
4592}
4593
4594/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
4595/// vector. If it is invalid, don't add anything to Ops.
4596void AArch64TargetLowering::LowerAsmOperandForConstraint(
4597 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
4598 SelectionDAG &DAG) const {
4599 SDValue Result;
4600
4601 // Currently only support length 1 constraints.
4602 if (Constraint.length() != 1)
4603 return;
4604
4605 char ConstraintLetter = Constraint[0];
4606 switch (ConstraintLetter) {
4607 default:
4608 break;
4609
4610 // This set of constraints deal with valid constants for various instructions.
4611 // Validate and return a target constant for them if we can.
4612 case 'z': {
4613 // 'z' maps to xzr or wzr so it needs an input of 0.
4614 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4615 if (!C || C->getZExtValue() != 0)
4616 return;
4617
4618 if (Op.getValueType() == MVT::i64)
4619 Result = DAG.getRegister(AArch64::XZR, MVT::i64);
4620 else
4621 Result = DAG.getRegister(AArch64::WZR, MVT::i32);
4622 break;
4623 }
4624
4625 case 'I':
4626 case 'J':
4627 case 'K':
4628 case 'L':
4629 case 'M':
4630 case 'N':
4631 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4632 if (!C)
4633 return;
4634
4635 // Grab the value and do some validation.
4636 uint64_t CVal = C->getZExtValue();
4637 switch (ConstraintLetter) {
4638 // The I constraint applies only to simple ADD or SUB immediate operands:
4639 // i.e. 0 to 4095 with optional shift by 12
4640 // The J constraint applies only to ADD or SUB immediates that would be
4641 // valid when negated, i.e. if [an add pattern] were to be output as a SUB
4642 // instruction [or vice versa], in other words -1 to -4095 with optional
4643 // left shift by 12.
4644 case 'I':
4645 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
4646 break;
4647 return;
4648 case 'J': {
4649 uint64_t NVal = -C->getSExtValue();
Tim Northover2c46beb2014-07-27 07:10:29 +00004650 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
4651 CVal = C->getSExtValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00004652 break;
Tim Northover2c46beb2014-07-27 07:10:29 +00004653 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004654 return;
4655 }
4656 // The K and L constraints apply *only* to logical immediates, including
4657 // what used to be the MOVI alias for ORR (though the MOVI alias has now
4658 // been removed and MOV should be used). So these constraints have to
4659 // distinguish between bit patterns that are valid 32-bit or 64-bit
4660 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
4661 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
4662 // versa.
4663 case 'K':
4664 if (AArch64_AM::isLogicalImmediate(CVal, 32))
4665 break;
4666 return;
4667 case 'L':
4668 if (AArch64_AM::isLogicalImmediate(CVal, 64))
4669 break;
4670 return;
4671 // The M and N constraints are a superset of K and L respectively, for use
4672 // with the MOV (immediate) alias. As well as the logical immediates they
4673 // also match 32 or 64-bit immediates that can be loaded either using a
4674 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
4675 // (M) or 64-bit 0x1234000000000000 (N) etc.
4676 // As a note some of this code is liberally stolen from the asm parser.
4677 case 'M': {
4678 if (!isUInt<32>(CVal))
4679 return;
4680 if (AArch64_AM::isLogicalImmediate(CVal, 32))
4681 break;
4682 if ((CVal & 0xFFFF) == CVal)
4683 break;
4684 if ((CVal & 0xFFFF0000ULL) == CVal)
4685 break;
4686 uint64_t NCVal = ~(uint32_t)CVal;
4687 if ((NCVal & 0xFFFFULL) == NCVal)
4688 break;
4689 if ((NCVal & 0xFFFF0000ULL) == NCVal)
4690 break;
4691 return;
4692 }
4693 case 'N': {
4694 if (AArch64_AM::isLogicalImmediate(CVal, 64))
4695 break;
4696 if ((CVal & 0xFFFFULL) == CVal)
4697 break;
4698 if ((CVal & 0xFFFF0000ULL) == CVal)
4699 break;
4700 if ((CVal & 0xFFFF00000000ULL) == CVal)
4701 break;
4702 if ((CVal & 0xFFFF000000000000ULL) == CVal)
4703 break;
4704 uint64_t NCVal = ~CVal;
4705 if ((NCVal & 0xFFFFULL) == NCVal)
4706 break;
4707 if ((NCVal & 0xFFFF0000ULL) == NCVal)
4708 break;
4709 if ((NCVal & 0xFFFF00000000ULL) == NCVal)
4710 break;
4711 if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
4712 break;
4713 return;
4714 }
4715 default:
4716 return;
4717 }
4718
4719 // All assembler immediates are 64-bit integers.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004720 Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00004721 break;
4722 }
4723
4724 if (Result.getNode()) {
4725 Ops.push_back(Result);
4726 return;
4727 }
4728
4729 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
4730}
4731
4732//===----------------------------------------------------------------------===//
4733// AArch64 Advanced SIMD Support
4734//===----------------------------------------------------------------------===//
4735
4736/// WidenVector - Given a value in the V64 register class, produce the
4737/// equivalent value in the V128 register class.
4738static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
4739 EVT VT = V64Reg.getValueType();
4740 unsigned NarrowSize = VT.getVectorNumElements();
4741 MVT EltTy = VT.getVectorElementType().getSimpleVT();
4742 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
4743 SDLoc DL(V64Reg);
4744
4745 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004746 V64Reg, DAG.getConstant(0, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00004747}
4748
4749/// getExtFactor - Determine the adjustment factor for the position when
4750/// generating an "extract from vector registers" instruction.
4751static unsigned getExtFactor(SDValue &V) {
4752 EVT EltType = V.getValueType().getVectorElementType();
4753 return EltType.getSizeInBits() / 8;
4754}
4755
4756/// NarrowVector - Given a value in the V128 register class, produce the
4757/// equivalent value in the V64 register class.
4758static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
4759 EVT VT = V128Reg.getValueType();
4760 unsigned WideSize = VT.getVectorNumElements();
4761 MVT EltTy = VT.getVectorElementType().getSimpleVT();
4762 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
4763 SDLoc DL(V128Reg);
4764
4765 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
4766}
4767
4768// Gather data to see if the operation can be modelled as a
4769// shuffle in combination with VEXTs.
4770SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
4771 SelectionDAG &DAG) const {
Kevin Qinf0ec9af2014-06-18 05:54:42 +00004772 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
Tim Northover3b0846e2014-05-24 12:50:23 +00004773 SDLoc dl(Op);
4774 EVT VT = Op.getValueType();
4775 unsigned NumElts = VT.getVectorNumElements();
4776
Tim Northover7324e842014-07-24 15:39:55 +00004777 struct ShuffleSourceInfo {
4778 SDValue Vec;
4779 unsigned MinElt;
4780 unsigned MaxElt;
Tim Northover3b0846e2014-05-24 12:50:23 +00004781
Tim Northover7324e842014-07-24 15:39:55 +00004782 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
4783 // be compatible with the shuffle we intend to construct. As a result
4784 // ShuffleVec will be some sliding window into the original Vec.
4785 SDValue ShuffleVec;
4786
4787 // Code should guarantee that element i in Vec starts at element "WindowBase
4788 // + i * WindowScale in ShuffleVec".
4789 int WindowBase;
4790 int WindowScale;
4791
4792 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
4793 ShuffleSourceInfo(SDValue Vec)
4794 : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
4795 WindowScale(1) {}
4796 };
4797
4798 // First gather all vectors used as an immediate source for this BUILD_VECTOR
4799 // node.
4800 SmallVector<ShuffleSourceInfo, 2> Sources;
Tim Northover3b0846e2014-05-24 12:50:23 +00004801 for (unsigned i = 0; i < NumElts; ++i) {
4802 SDValue V = Op.getOperand(i);
4803 if (V.getOpcode() == ISD::UNDEF)
4804 continue;
4805 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4806 // A shuffle can only come from building a vector from various
4807 // elements of other vectors.
4808 return SDValue();
4809 }
4810
Tim Northover7324e842014-07-24 15:39:55 +00004811 // Add this element source to the list if it's not already there.
Tim Northover3b0846e2014-05-24 12:50:23 +00004812 SDValue SourceVec = V.getOperand(0);
Tim Northover7324e842014-07-24 15:39:55 +00004813 auto Source = std::find(Sources.begin(), Sources.end(), SourceVec);
4814 if (Source == Sources.end())
James Molloyf497d552014-10-17 17:06:31 +00004815 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
Tim Northover3b0846e2014-05-24 12:50:23 +00004816
Tim Northover7324e842014-07-24 15:39:55 +00004817 // Update the minimum and maximum lane number seen.
4818 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4819 Source->MinElt = std::min(Source->MinElt, EltNo);
4820 Source->MaxElt = std::max(Source->MaxElt, EltNo);
Tim Northover3b0846e2014-05-24 12:50:23 +00004821 }
4822
4823 // Currently only do something sane when at most two source vectors
Tim Northover7324e842014-07-24 15:39:55 +00004824 // are involved.
4825 if (Sources.size() > 2)
Tim Northover3b0846e2014-05-24 12:50:23 +00004826 return SDValue();
4827
Kevin Qin9a2a2c52014-07-24 02:05:42 +00004828 // Find out the smallest element size among result and two sources, and use
4829 // it as element size to build the shuffle_vector.
4830 EVT SmallestEltTy = VT.getVectorElementType();
Tim Northover7324e842014-07-24 15:39:55 +00004831 for (auto &Source : Sources) {
4832 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00004833 if (SrcEltTy.bitsLT(SmallestEltTy)) {
4834 SmallestEltTy = SrcEltTy;
4835 }
4836 }
4837 unsigned ResMultiplier =
4838 VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00004839 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
4840 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
Tim Northover3b0846e2014-05-24 12:50:23 +00004841
Tim Northover7324e842014-07-24 15:39:55 +00004842 // If the source vector is too wide or too narrow, we may nevertheless be able
4843 // to construct a compatible shuffle either by concatenating it with UNDEF or
4844 // extracting a suitable range of elements.
4845 for (auto &Src : Sources) {
4846 EVT SrcVT = Src.ShuffleVec.getValueType();
Kevin Qinf0ec9af2014-06-18 05:54:42 +00004847
Tim Northover7324e842014-07-24 15:39:55 +00004848 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
Tim Northover3b0846e2014-05-24 12:50:23 +00004849 continue;
Tim Northover7324e842014-07-24 15:39:55 +00004850
4851 // This stage of the search produces a source with the same element type as
4852 // the original, but with a total width matching the BUILD_VECTOR output.
4853 EVT EltVT = SrcVT.getVectorElementType();
James Molloyf497d552014-10-17 17:06:31 +00004854 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
4855 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
Tim Northover7324e842014-07-24 15:39:55 +00004856
4857 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
4858 assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00004859 // We can pad out the smaller vector for free, so if it's part of a
4860 // shuffle...
Tim Northover7324e842014-07-24 15:39:55 +00004861 Src.ShuffleVec =
4862 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
4863 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00004864 continue;
4865 }
4866
Tim Northover7324e842014-07-24 15:39:55 +00004867 assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00004868
James Molloyf497d552014-10-17 17:06:31 +00004869 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004870 // Span too large for a VEXT to cope
4871 return SDValue();
4872 }
4873
James Molloyf497d552014-10-17 17:06:31 +00004874 if (Src.MinElt >= NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004875 // The extraction can just take the second half
Tim Northover7324e842014-07-24 15:39:55 +00004876 Src.ShuffleVec =
4877 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004878 DAG.getConstant(NumSrcElts, dl, MVT::i64));
James Molloyf497d552014-10-17 17:06:31 +00004879 Src.WindowBase = -NumSrcElts;
4880 } else if (Src.MaxElt < NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004881 // The extraction can just take the first half
Tim Northover5e84fe32014-12-06 00:33:37 +00004882 Src.ShuffleVec =
4883 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004884 DAG.getConstant(0, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00004885 } else {
4886 // An actual VEXT is needed
Tim Northover5e84fe32014-12-06 00:33:37 +00004887 SDValue VEXTSrc1 =
4888 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004889 DAG.getConstant(0, dl, MVT::i64));
Tim Northover7324e842014-07-24 15:39:55 +00004890 SDValue VEXTSrc2 =
4891 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004892 DAG.getConstant(NumSrcElts, dl, MVT::i64));
Tim Northover7324e842014-07-24 15:39:55 +00004893 unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
4894
4895 Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004896 VEXTSrc2,
4897 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover7324e842014-07-24 15:39:55 +00004898 Src.WindowBase = -Src.MinElt;
Tim Northover3b0846e2014-05-24 12:50:23 +00004899 }
4900 }
4901
Tim Northover7324e842014-07-24 15:39:55 +00004902 // Another possible incompatibility occurs from the vector element types. We
4903 // can fix this by bitcasting the source vectors to the same type we intend
4904 // for the shuffle.
4905 for (auto &Src : Sources) {
4906 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
4907 if (SrcEltTy == SmallestEltTy)
4908 continue;
4909 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
4910 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
4911 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
4912 Src.WindowBase *= Src.WindowScale;
4913 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004914
Tim Northover7324e842014-07-24 15:39:55 +00004915 // Final sanity check before we try to actually produce a shuffle.
4916 DEBUG(
4917 for (auto Src : Sources)
4918 assert(Src.ShuffleVec.getValueType() == ShuffleVT);
4919 );
4920
4921 // The stars all align, our next step is to produce the mask for the shuffle.
4922 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
4923 int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00004924 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004925 SDValue Entry = Op.getOperand(i);
Tim Northover7324e842014-07-24 15:39:55 +00004926 if (Entry.getOpcode() == ISD::UNDEF)
4927 continue;
Tim Northover3b0846e2014-05-24 12:50:23 +00004928
Tim Northover7324e842014-07-24 15:39:55 +00004929 auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0));
4930 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
4931
4932 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
4933 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
4934 // segment.
4935 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
4936 int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
4937 VT.getVectorElementType().getSizeInBits());
4938 int LanesDefined = BitsDefined / BitsPerShuffleLane;
4939
4940 // This source is expected to fill ResMultiplier lanes of the final shuffle,
4941 // starting at the appropriate offset.
4942 int *LaneMask = &Mask[i * ResMultiplier];
4943
4944 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
4945 ExtractBase += NumElts * (Src - Sources.begin());
4946 for (int j = 0; j < LanesDefined; ++j)
4947 LaneMask[j] = ExtractBase + j;
Tim Northover3b0846e2014-05-24 12:50:23 +00004948 }
4949
4950 // Final check before we try to produce nonsense...
Tim Northover7324e842014-07-24 15:39:55 +00004951 if (!isShuffleMaskLegal(Mask, ShuffleVT))
4952 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00004953
Tim Northover7324e842014-07-24 15:39:55 +00004954 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
4955 for (unsigned i = 0; i < Sources.size(); ++i)
4956 ShuffleOps[i] = Sources[i].ShuffleVec;
4957
4958 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
4959 ShuffleOps[1], &Mask[0]);
4960 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
Tim Northover3b0846e2014-05-24 12:50:23 +00004961}
4962
4963// check if an EXT instruction can handle the shuffle mask when the
4964// vector sources of the shuffle are the same.
4965static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4966 unsigned NumElts = VT.getVectorNumElements();
4967
4968 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4969 if (M[0] < 0)
4970 return false;
4971
4972 Imm = M[0];
4973
4974 // If this is a VEXT shuffle, the immediate value is the index of the first
4975 // element. The other shuffle indices must be the successive elements after
4976 // the first one.
4977 unsigned ExpectedElt = Imm;
4978 for (unsigned i = 1; i < NumElts; ++i) {
4979 // Increment the expected index. If it wraps around, just follow it
4980 // back to index zero and keep going.
4981 ++ExpectedElt;
4982 if (ExpectedElt == NumElts)
4983 ExpectedElt = 0;
4984
4985 if (M[i] < 0)
4986 continue; // ignore UNDEF indices
4987 if (ExpectedElt != static_cast<unsigned>(M[i]))
4988 return false;
4989 }
4990
4991 return true;
4992}
4993
4994// check if an EXT instruction can handle the shuffle mask when the
4995// vector sources of the shuffle are different.
4996static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
4997 unsigned &Imm) {
4998 // Look for the first non-undef element.
4999 const int *FirstRealElt = std::find_if(M.begin(), M.end(),
5000 [](int Elt) {return Elt >= 0;});
5001
5002 // Benefit form APInt to handle overflow when calculating expected element.
5003 unsigned NumElts = VT.getVectorNumElements();
5004 unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
5005 APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
5006 // The following shuffle indices must be the successive elements after the
5007 // first real element.
5008 const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
5009 [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
5010 if (FirstWrongElt != M.end())
5011 return false;
5012
5013 // The index of an EXT is the first element if it is not UNDEF.
5014 // Watch out for the beginning UNDEFs. The EXT index should be the expected
5015 // value of the first element. E.g.
5016 // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
5017 // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
5018 // ExpectedElt is the last mask index plus 1.
5019 Imm = ExpectedElt.getZExtValue();
5020
5021 // There are two difference cases requiring to reverse input vectors.
5022 // For example, for vector <4 x i32> we have the following cases,
5023 // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
5024 // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
5025 // For both cases, we finally use mask <5, 6, 7, 0>, which requires
5026 // to reverse two input vectors.
5027 if (Imm < NumElts)
5028 ReverseEXT = true;
5029 else
5030 Imm -= NumElts;
5031
5032 return true;
5033}
5034
5035/// isREVMask - Check if a vector shuffle corresponds to a REV
5036/// instruction with the specified blocksize. (The order of the elements
5037/// within each block of the vector is reversed.)
5038static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5039 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
5040 "Only possible block sizes for REV are: 16, 32, 64");
5041
5042 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5043 if (EltSz == 64)
5044 return false;
5045
5046 unsigned NumElts = VT.getVectorNumElements();
5047 unsigned BlockElts = M[0] + 1;
5048 // If the first shuffle index is UNDEF, be optimistic.
5049 if (M[0] < 0)
5050 BlockElts = BlockSize / EltSz;
5051
5052 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5053 return false;
5054
5055 for (unsigned i = 0; i < NumElts; ++i) {
5056 if (M[i] < 0)
5057 continue; // ignore UNDEF indices
5058 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
5059 return false;
5060 }
5061
5062 return true;
5063}
5064
5065static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5066 unsigned NumElts = VT.getVectorNumElements();
5067 WhichResult = (M[0] == 0 ? 0 : 1);
5068 unsigned Idx = WhichResult * NumElts / 2;
5069 for (unsigned i = 0; i != NumElts; i += 2) {
5070 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5071 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
5072 return false;
5073 Idx += 1;
5074 }
5075
5076 return true;
5077}
5078
5079static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5080 unsigned NumElts = VT.getVectorNumElements();
5081 WhichResult = (M[0] == 0 ? 0 : 1);
5082 for (unsigned i = 0; i != NumElts; ++i) {
5083 if (M[i] < 0)
5084 continue; // ignore UNDEF indices
5085 if ((unsigned)M[i] != 2 * i + WhichResult)
5086 return false;
5087 }
5088
5089 return true;
5090}
5091
5092static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5093 unsigned NumElts = VT.getVectorNumElements();
5094 WhichResult = (M[0] == 0 ? 0 : 1);
5095 for (unsigned i = 0; i < NumElts; i += 2) {
5096 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5097 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
5098 return false;
5099 }
5100 return true;
5101}
5102
5103/// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
5104/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5105/// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5106static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5107 unsigned NumElts = VT.getVectorNumElements();
5108 WhichResult = (M[0] == 0 ? 0 : 1);
5109 unsigned Idx = WhichResult * NumElts / 2;
5110 for (unsigned i = 0; i != NumElts; i += 2) {
5111 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5112 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
5113 return false;
5114 Idx += 1;
5115 }
5116
5117 return true;
5118}
5119
5120/// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
5121/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5122/// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5123static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5124 unsigned Half = VT.getVectorNumElements() / 2;
5125 WhichResult = (M[0] == 0 ? 0 : 1);
5126 for (unsigned j = 0; j != 2; ++j) {
5127 unsigned Idx = WhichResult;
5128 for (unsigned i = 0; i != Half; ++i) {
5129 int MIdx = M[i + j * Half];
5130 if (MIdx >= 0 && (unsigned)MIdx != Idx)
5131 return false;
5132 Idx += 2;
5133 }
5134 }
5135
5136 return true;
5137}
5138
5139/// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
5140/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5141/// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5142static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5143 unsigned NumElts = VT.getVectorNumElements();
5144 WhichResult = (M[0] == 0 ? 0 : 1);
5145 for (unsigned i = 0; i < NumElts; i += 2) {
5146 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5147 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
5148 return false;
5149 }
5150 return true;
5151}
5152
5153static bool isINSMask(ArrayRef<int> M, int NumInputElements,
5154 bool &DstIsLeft, int &Anomaly) {
5155 if (M.size() != static_cast<size_t>(NumInputElements))
5156 return false;
5157
5158 int NumLHSMatch = 0, NumRHSMatch = 0;
5159 int LastLHSMismatch = -1, LastRHSMismatch = -1;
5160
5161 for (int i = 0; i < NumInputElements; ++i) {
5162 if (M[i] == -1) {
5163 ++NumLHSMatch;
5164 ++NumRHSMatch;
5165 continue;
5166 }
5167
5168 if (M[i] == i)
5169 ++NumLHSMatch;
5170 else
5171 LastLHSMismatch = i;
5172
5173 if (M[i] == i + NumInputElements)
5174 ++NumRHSMatch;
5175 else
5176 LastRHSMismatch = i;
5177 }
5178
5179 if (NumLHSMatch == NumInputElements - 1) {
5180 DstIsLeft = true;
5181 Anomaly = LastLHSMismatch;
5182 return true;
5183 } else if (NumRHSMatch == NumInputElements - 1) {
5184 DstIsLeft = false;
5185 Anomaly = LastRHSMismatch;
5186 return true;
5187 }
5188
5189 return false;
5190}
5191
5192static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
5193 if (VT.getSizeInBits() != 128)
5194 return false;
5195
5196 unsigned NumElts = VT.getVectorNumElements();
5197
5198 for (int I = 0, E = NumElts / 2; I != E; I++) {
5199 if (Mask[I] != I)
5200 return false;
5201 }
5202
5203 int Offset = NumElts / 2;
5204 for (int I = NumElts / 2, E = NumElts; I != E; I++) {
5205 if (Mask[I] != I + SplitLHS * Offset)
5206 return false;
5207 }
5208
5209 return true;
5210}
5211
5212static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
5213 SDLoc DL(Op);
5214 EVT VT = Op.getValueType();
5215 SDValue V0 = Op.getOperand(0);
5216 SDValue V1 = Op.getOperand(1);
5217 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
5218
5219 if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
5220 VT.getVectorElementType() != V1.getValueType().getVectorElementType())
5221 return SDValue();
5222
5223 bool SplitV0 = V0.getValueType().getSizeInBits() == 128;
5224
5225 if (!isConcatMask(Mask, VT, SplitV0))
5226 return SDValue();
5227
5228 EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
5229 VT.getVectorNumElements() / 2);
5230 if (SplitV0) {
5231 V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005232 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005233 }
5234 if (V1.getValueType().getSizeInBits() == 128) {
5235 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005236 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005237 }
5238 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
5239}
5240
5241/// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5242/// the specified operations to build the shuffle.
5243static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5244 SDValue RHS, SelectionDAG &DAG,
5245 SDLoc dl) {
5246 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5247 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
5248 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
5249
5250 enum {
5251 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5252 OP_VREV,
5253 OP_VDUP0,
5254 OP_VDUP1,
5255 OP_VDUP2,
5256 OP_VDUP3,
5257 OP_VEXT1,
5258 OP_VEXT2,
5259 OP_VEXT3,
5260 OP_VUZPL, // VUZP, left result
5261 OP_VUZPR, // VUZP, right result
5262 OP_VZIPL, // VZIP, left result
5263 OP_VZIPR, // VZIP, right result
5264 OP_VTRNL, // VTRN, left result
5265 OP_VTRNR // VTRN, right result
5266 };
5267
5268 if (OpNum == OP_COPY) {
5269 if (LHSID == (1 * 9 + 2) * 9 + 3)
5270 return LHS;
5271 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
5272 return RHS;
5273 }
5274
5275 SDValue OpLHS, OpRHS;
5276 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5277 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5278 EVT VT = OpLHS.getValueType();
5279
5280 switch (OpNum) {
5281 default:
5282 llvm_unreachable("Unknown shuffle opcode!");
5283 case OP_VREV:
5284 // VREV divides the vector in half and swaps within the half.
5285 if (VT.getVectorElementType() == MVT::i32 ||
5286 VT.getVectorElementType() == MVT::f32)
5287 return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
5288 // vrev <4 x i16> -> REV32
Oliver Stannard89d15422014-08-27 16:16:04 +00005289 if (VT.getVectorElementType() == MVT::i16 ||
5290 VT.getVectorElementType() == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00005291 return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
5292 // vrev <4 x i8> -> REV16
5293 assert(VT.getVectorElementType() == MVT::i8);
5294 return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
5295 case OP_VDUP0:
5296 case OP_VDUP1:
5297 case OP_VDUP2:
5298 case OP_VDUP3: {
5299 EVT EltTy = VT.getVectorElementType();
5300 unsigned Opcode;
5301 if (EltTy == MVT::i8)
5302 Opcode = AArch64ISD::DUPLANE8;
Ahmed Bougacha941420d2015-04-16 23:57:07 +00005303 else if (EltTy == MVT::i16 || EltTy == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00005304 Opcode = AArch64ISD::DUPLANE16;
5305 else if (EltTy == MVT::i32 || EltTy == MVT::f32)
5306 Opcode = AArch64ISD::DUPLANE32;
5307 else if (EltTy == MVT::i64 || EltTy == MVT::f64)
5308 Opcode = AArch64ISD::DUPLANE64;
5309 else
5310 llvm_unreachable("Invalid vector element type?");
5311
5312 if (VT.getSizeInBits() == 64)
5313 OpLHS = WidenVector(OpLHS, DAG);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005314 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00005315 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
5316 }
5317 case OP_VEXT1:
5318 case OP_VEXT2:
5319 case OP_VEXT3: {
5320 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
5321 return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005322 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005323 }
5324 case OP_VUZPL:
5325 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
5326 OpRHS);
5327 case OP_VUZPR:
5328 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
5329 OpRHS);
5330 case OP_VZIPL:
5331 return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
5332 OpRHS);
5333 case OP_VZIPR:
5334 return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
5335 OpRHS);
5336 case OP_VTRNL:
5337 return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
5338 OpRHS);
5339 case OP_VTRNR:
5340 return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
5341 OpRHS);
5342 }
5343}
5344
5345static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
5346 SelectionDAG &DAG) {
5347 // Check to see if we can use the TBL instruction.
5348 SDValue V1 = Op.getOperand(0);
5349 SDValue V2 = Op.getOperand(1);
5350 SDLoc DL(Op);
5351
5352 EVT EltVT = Op.getValueType().getVectorElementType();
5353 unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
5354
5355 SmallVector<SDValue, 8> TBLMask;
5356 for (int Val : ShuffleMask) {
5357 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
5358 unsigned Offset = Byte + Val * BytesPerElt;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005359 TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005360 }
5361 }
5362
5363 MVT IndexVT = MVT::v8i8;
5364 unsigned IndexLen = 8;
5365 if (Op.getValueType().getSizeInBits() == 128) {
5366 IndexVT = MVT::v16i8;
5367 IndexLen = 16;
5368 }
5369
5370 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
5371 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
5372
5373 SDValue Shuffle;
5374 if (V2.getNode()->getOpcode() == ISD::UNDEF) {
5375 if (IndexLen == 8)
5376 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
5377 Shuffle = DAG.getNode(
5378 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005379 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
Tim Northover3b0846e2014-05-24 12:50:23 +00005380 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5381 makeArrayRef(TBLMask.data(), IndexLen)));
5382 } else {
5383 if (IndexLen == 8) {
5384 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
5385 Shuffle = DAG.getNode(
5386 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005387 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
Tim Northover3b0846e2014-05-24 12:50:23 +00005388 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5389 makeArrayRef(TBLMask.data(), IndexLen)));
5390 } else {
5391 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
5392 // cannot currently represent the register constraints on the input
5393 // table registers.
5394 // Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
5395 // DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5396 // &TBLMask[0], IndexLen));
5397 Shuffle = DAG.getNode(
5398 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005399 DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32),
5400 V1Cst, V2Cst,
Tim Northover3b0846e2014-05-24 12:50:23 +00005401 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5402 makeArrayRef(TBLMask.data(), IndexLen)));
5403 }
5404 }
5405 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
5406}
5407
5408static unsigned getDUPLANEOp(EVT EltType) {
5409 if (EltType == MVT::i8)
5410 return AArch64ISD::DUPLANE8;
Oliver Stannard89d15422014-08-27 16:16:04 +00005411 if (EltType == MVT::i16 || EltType == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00005412 return AArch64ISD::DUPLANE16;
5413 if (EltType == MVT::i32 || EltType == MVT::f32)
5414 return AArch64ISD::DUPLANE32;
5415 if (EltType == MVT::i64 || EltType == MVT::f64)
5416 return AArch64ISD::DUPLANE64;
5417
5418 llvm_unreachable("Invalid vector element type?");
5419}
5420
5421SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5422 SelectionDAG &DAG) const {
5423 SDLoc dl(Op);
5424 EVT VT = Op.getValueType();
5425
5426 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5427
5428 // Convert shuffles that are directly supported on NEON to target-specific
5429 // DAG nodes, instead of keeping them as shuffles and matching them again
5430 // during code selection. This is more efficient and avoids the possibility
5431 // of inconsistencies between legalization and selection.
5432 ArrayRef<int> ShuffleMask = SVN->getMask();
5433
5434 SDValue V1 = Op.getOperand(0);
5435 SDValue V2 = Op.getOperand(1);
5436
5437 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0],
5438 V1.getValueType().getSimpleVT())) {
5439 int Lane = SVN->getSplatIndex();
5440 // If this is undef splat, generate it via "just" vdup, if possible.
5441 if (Lane == -1)
5442 Lane = 0;
5443
5444 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
5445 return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
5446 V1.getOperand(0));
5447 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
5448 // constant. If so, we can just reference the lane's definition directly.
5449 if (V1.getOpcode() == ISD::BUILD_VECTOR &&
5450 !isa<ConstantSDNode>(V1.getOperand(Lane)))
5451 return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
5452
5453 // Otherwise, duplicate from the lane of the input vector.
5454 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
5455
5456 // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
5457 // to make a vector of the same size as this SHUFFLE. We can ignore the
5458 // extract entirely, and canonicalise the concat using WidenVector.
5459 if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
5460 Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
5461 V1 = V1.getOperand(0);
5462 } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
5463 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
5464 Lane -= Idx * VT.getVectorNumElements() / 2;
5465 V1 = WidenVector(V1.getOperand(Idx), DAG);
5466 } else if (VT.getSizeInBits() == 64)
5467 V1 = WidenVector(V1, DAG);
5468
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005469 return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005470 }
5471
5472 if (isREVMask(ShuffleMask, VT, 64))
5473 return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
5474 if (isREVMask(ShuffleMask, VT, 32))
5475 return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
5476 if (isREVMask(ShuffleMask, VT, 16))
5477 return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
5478
5479 bool ReverseEXT = false;
5480 unsigned Imm;
5481 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
5482 if (ReverseEXT)
5483 std::swap(V1, V2);
5484 Imm *= getExtFactor(V1);
5485 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005486 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005487 } else if (V2->getOpcode() == ISD::UNDEF &&
5488 isSingletonEXTMask(ShuffleMask, VT, Imm)) {
5489 Imm *= getExtFactor(V1);
5490 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005491 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005492 }
5493
5494 unsigned WhichResult;
5495 if (isZIPMask(ShuffleMask, VT, WhichResult)) {
5496 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5497 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5498 }
5499 if (isUZPMask(ShuffleMask, VT, WhichResult)) {
5500 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5501 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5502 }
5503 if (isTRNMask(ShuffleMask, VT, WhichResult)) {
5504 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5505 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5506 }
5507
5508 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5509 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5510 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5511 }
5512 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5513 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5514 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5515 }
5516 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5517 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5518 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5519 }
5520
5521 SDValue Concat = tryFormConcatFromShuffle(Op, DAG);
5522 if (Concat.getNode())
5523 return Concat;
5524
5525 bool DstIsLeft;
5526 int Anomaly;
5527 int NumInputElements = V1.getValueType().getVectorNumElements();
5528 if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
5529 SDValue DstVec = DstIsLeft ? V1 : V2;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005530 SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00005531
5532 SDValue SrcVec = V1;
5533 int SrcLane = ShuffleMask[Anomaly];
5534 if (SrcLane >= NumInputElements) {
5535 SrcVec = V2;
5536 SrcLane -= VT.getVectorNumElements();
5537 }
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005538 SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00005539
5540 EVT ScalarVT = VT.getVectorElementType();
Oliver Stannard89d15422014-08-27 16:16:04 +00005541
5542 if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00005543 ScalarVT = MVT::i32;
5544
5545 return DAG.getNode(
5546 ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5547 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
5548 DstLaneV);
5549 }
5550
5551 // If the shuffle is not directly supported and it has 4 elements, use
5552 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5553 unsigned NumElts = VT.getVectorNumElements();
5554 if (NumElts == 4) {
5555 unsigned PFIndexes[4];
5556 for (unsigned i = 0; i != 4; ++i) {
5557 if (ShuffleMask[i] < 0)
5558 PFIndexes[i] = 8;
5559 else
5560 PFIndexes[i] = ShuffleMask[i];
5561 }
5562
5563 // Compute the index in the perfect shuffle table.
5564 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
5565 PFIndexes[2] * 9 + PFIndexes[3];
5566 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5567 unsigned Cost = (PFEntry >> 30);
5568
5569 if (Cost <= 4)
5570 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5571 }
5572
5573 return GenerateTBL(Op, ShuffleMask, DAG);
5574}
5575
5576static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
5577 APInt &UndefBits) {
5578 EVT VT = BVN->getValueType(0);
5579 APInt SplatBits, SplatUndef;
5580 unsigned SplatBitSize;
5581 bool HasAnyUndefs;
5582 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5583 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
5584
5585 for (unsigned i = 0; i < NumSplats; ++i) {
5586 CnstBits <<= SplatBitSize;
5587 UndefBits <<= SplatBitSize;
5588 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
5589 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
5590 }
5591
5592 return true;
5593 }
5594
5595 return false;
5596}
5597
5598SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op,
5599 SelectionDAG &DAG) const {
5600 BuildVectorSDNode *BVN =
5601 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5602 SDValue LHS = Op.getOperand(0);
5603 SDLoc dl(Op);
5604 EVT VT = Op.getValueType();
5605
5606 if (!BVN)
5607 return Op;
5608
5609 APInt CnstBits(VT.getSizeInBits(), 0);
5610 APInt UndefBits(VT.getSizeInBits(), 0);
5611 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5612 // We only have BIC vector immediate instruction, which is and-not.
5613 CnstBits = ~CnstBits;
5614
5615 // We make use of a little bit of goto ickiness in order to avoid having to
5616 // duplicate the immediate matching logic for the undef toggled case.
5617 bool SecondTry = false;
5618 AttemptModImm:
5619
5620 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5621 CnstBits = CnstBits.zextOrTrunc(64);
5622 uint64_t CnstVal = CnstBits.getZExtValue();
5623
5624 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5625 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5626 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5627 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005628 DAG.getConstant(CnstVal, dl, MVT::i32),
5629 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005630 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005631 }
5632
5633 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5634 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5635 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5636 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005637 DAG.getConstant(CnstVal, dl, MVT::i32),
5638 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005639 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005640 }
5641
5642 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5643 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5644 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5645 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005646 DAG.getConstant(CnstVal, dl, MVT::i32),
5647 DAG.getConstant(16, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005648 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005649 }
5650
5651 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5652 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5653 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5654 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005655 DAG.getConstant(CnstVal, dl, MVT::i32),
5656 DAG.getConstant(24, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005657 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005658 }
5659
5660 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5661 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5662 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5663 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005664 DAG.getConstant(CnstVal, dl, MVT::i32),
5665 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005666 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005667 }
5668
5669 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5670 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5671 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5672 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005673 DAG.getConstant(CnstVal, dl, MVT::i32),
5674 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005675 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005676 }
5677 }
5678
5679 if (SecondTry)
5680 goto FailedModImm;
5681 SecondTry = true;
5682 CnstBits = ~UndefBits;
5683 goto AttemptModImm;
5684 }
5685
5686// We can always fall back to a non-immediate AND.
5687FailedModImm:
5688 return Op;
5689}
5690
5691// Specialized code to quickly find if PotentialBVec is a BuildVector that
5692// consists of only the same constant int value, returned in reference arg
5693// ConstVal
5694static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
5695 uint64_t &ConstVal) {
5696 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
5697 if (!Bvec)
5698 return false;
5699 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
5700 if (!FirstElt)
5701 return false;
5702 EVT VT = Bvec->getValueType(0);
5703 unsigned NumElts = VT.getVectorNumElements();
5704 for (unsigned i = 1; i < NumElts; ++i)
5705 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
5706 return false;
5707 ConstVal = FirstElt->getZExtValue();
5708 return true;
5709}
5710
5711static unsigned getIntrinsicID(const SDNode *N) {
5712 unsigned Opcode = N->getOpcode();
5713 switch (Opcode) {
5714 default:
5715 return Intrinsic::not_intrinsic;
5716 case ISD::INTRINSIC_WO_CHAIN: {
5717 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
5718 if (IID < Intrinsic::num_intrinsics)
5719 return IID;
5720 return Intrinsic::not_intrinsic;
5721 }
5722 }
5723}
5724
5725// Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
5726// to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
5727// BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
5728// Also, logical shift right -> sri, with the same structure.
5729static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
5730 EVT VT = N->getValueType(0);
5731
5732 if (!VT.isVector())
5733 return SDValue();
5734
5735 SDLoc DL(N);
5736
5737 // Is the first op an AND?
5738 const SDValue And = N->getOperand(0);
5739 if (And.getOpcode() != ISD::AND)
5740 return SDValue();
5741
5742 // Is the second op an shl or lshr?
5743 SDValue Shift = N->getOperand(1);
5744 // This will have been turned into: AArch64ISD::VSHL vector, #shift
5745 // or AArch64ISD::VLSHR vector, #shift
5746 unsigned ShiftOpc = Shift.getOpcode();
5747 if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
5748 return SDValue();
5749 bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
5750
5751 // Is the shift amount constant?
5752 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
5753 if (!C2node)
5754 return SDValue();
5755
5756 // Is the and mask vector all constant?
5757 uint64_t C1;
5758 if (!isAllConstantBuildVector(And.getOperand(1), C1))
5759 return SDValue();
5760
5761 // Is C1 == ~C2, taking into account how much one can shift elements of a
5762 // particular size?
5763 uint64_t C2 = C2node->getZExtValue();
5764 unsigned ElemSizeInBits = VT.getVectorElementType().getSizeInBits();
5765 if (C2 > ElemSizeInBits)
5766 return SDValue();
5767 unsigned ElemMask = (1 << ElemSizeInBits) - 1;
5768 if ((C1 & ElemMask) != (~C2 & ElemMask))
5769 return SDValue();
5770
5771 SDValue X = And.getOperand(0);
5772 SDValue Y = Shift.getOperand(0);
5773
5774 unsigned Intrin =
5775 IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
5776 SDValue ResultSLI =
5777 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005778 DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
5779 Shift.getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00005780
5781 DEBUG(dbgs() << "aarch64-lower: transformed: \n");
5782 DEBUG(N->dump(&DAG));
5783 DEBUG(dbgs() << "into: \n");
5784 DEBUG(ResultSLI->dump(&DAG));
5785
5786 ++NumShiftInserts;
5787 return ResultSLI;
5788}
5789
5790SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
5791 SelectionDAG &DAG) const {
5792 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
5793 if (EnableAArch64SlrGeneration) {
5794 SDValue Res = tryLowerToSLI(Op.getNode(), DAG);
5795 if (Res.getNode())
5796 return Res;
5797 }
5798
5799 BuildVectorSDNode *BVN =
5800 dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
5801 SDValue LHS = Op.getOperand(1);
5802 SDLoc dl(Op);
5803 EVT VT = Op.getValueType();
5804
5805 // OR commutes, so try swapping the operands.
5806 if (!BVN) {
5807 LHS = Op.getOperand(0);
5808 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5809 }
5810 if (!BVN)
5811 return Op;
5812
5813 APInt CnstBits(VT.getSizeInBits(), 0);
5814 APInt UndefBits(VT.getSizeInBits(), 0);
5815 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5816 // We make use of a little bit of goto ickiness in order to avoid having to
5817 // duplicate the immediate matching logic for the undef toggled case.
5818 bool SecondTry = false;
5819 AttemptModImm:
5820
5821 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5822 CnstBits = CnstBits.zextOrTrunc(64);
5823 uint64_t CnstVal = CnstBits.getZExtValue();
5824
5825 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5826 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5827 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5828 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005829 DAG.getConstant(CnstVal, dl, MVT::i32),
5830 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005831 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005832 }
5833
5834 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5835 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5836 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5837 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005838 DAG.getConstant(CnstVal, dl, MVT::i32),
5839 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005840 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005841 }
5842
5843 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5844 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5845 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5846 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005847 DAG.getConstant(CnstVal, dl, MVT::i32),
5848 DAG.getConstant(16, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005849 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005850 }
5851
5852 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5853 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5854 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5855 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005856 DAG.getConstant(CnstVal, dl, MVT::i32),
5857 DAG.getConstant(24, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005858 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005859 }
5860
5861 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5862 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5863 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5864 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005865 DAG.getConstant(CnstVal, dl, MVT::i32),
5866 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005867 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005868 }
5869
5870 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5871 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5872 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5873 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005874 DAG.getConstant(CnstVal, dl, MVT::i32),
5875 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005876 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005877 }
5878 }
5879
5880 if (SecondTry)
5881 goto FailedModImm;
5882 SecondTry = true;
5883 CnstBits = UndefBits;
5884 goto AttemptModImm;
5885 }
5886
5887// We can always fall back to a non-immediate OR.
5888FailedModImm:
5889 return Op;
5890}
5891
Kevin Qin4473c192014-07-07 02:45:40 +00005892// Normalize the operands of BUILD_VECTOR. The value of constant operands will
5893// be truncated to fit element width.
5894static SDValue NormalizeBuildVector(SDValue Op,
5895 SelectionDAG &DAG) {
5896 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
Tim Northover3b0846e2014-05-24 12:50:23 +00005897 SDLoc dl(Op);
5898 EVT VT = Op.getValueType();
Kevin Qin4473c192014-07-07 02:45:40 +00005899 EVT EltTy= VT.getVectorElementType();
5900
5901 if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
5902 return Op;
5903
5904 SmallVector<SDValue, 16> Ops;
Pete Cooper7be8f8f2015-08-03 19:04:32 +00005905 for (SDValue Lane : Op->ops()) {
5906 if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
Kevin Qin4473c192014-07-07 02:45:40 +00005907 APInt LowBits(EltTy.getSizeInBits(),
Pete Cooper7be8f8f2015-08-03 19:04:32 +00005908 CstLane->getZExtValue());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005909 Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
Kevin Qin4473c192014-07-07 02:45:40 +00005910 }
5911 Ops.push_back(Lane);
5912 }
5913 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5914}
5915
5916SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
5917 SelectionDAG &DAG) const {
5918 SDLoc dl(Op);
5919 EVT VT = Op.getValueType();
5920 Op = NormalizeBuildVector(Op, DAG);
5921 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
Tim Northover3b0846e2014-05-24 12:50:23 +00005922
5923 APInt CnstBits(VT.getSizeInBits(), 0);
5924 APInt UndefBits(VT.getSizeInBits(), 0);
5925 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5926 // We make use of a little bit of goto ickiness in order to avoid having to
5927 // duplicate the immediate matching logic for the undef toggled case.
5928 bool SecondTry = false;
5929 AttemptModImm:
5930
5931 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5932 CnstBits = CnstBits.zextOrTrunc(64);
5933 uint64_t CnstVal = CnstBits.getZExtValue();
5934
5935 // Certain magic vector constants (used to express things like NOT
5936 // and NEG) are passed through unmodified. This allows codegen patterns
5937 // for these operations to match. Special-purpose patterns will lower
5938 // these immediates to MOVIs if it proves necessary.
5939 if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL))
5940 return Op;
5941
5942 // The many faces of MOVI...
5943 if (AArch64_AM::isAdvSIMDModImmType10(CnstVal)) {
5944 CnstVal = AArch64_AM::encodeAdvSIMDModImmType10(CnstVal);
5945 if (VT.getSizeInBits() == 128) {
5946 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::v2i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005947 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00005948 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005949 }
5950
5951 // Support the V64 version via subregister insertion.
5952 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::f64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005953 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00005954 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005955 }
5956
5957 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5958 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5959 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5960 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005961 DAG.getConstant(CnstVal, dl, MVT::i32),
5962 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00005963 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005964 }
5965
5966 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5967 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5968 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5969 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005970 DAG.getConstant(CnstVal, dl, MVT::i32),
5971 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00005972 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005973 }
5974
5975 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5976 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5977 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5978 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005979 DAG.getConstant(CnstVal, dl, MVT::i32),
5980 DAG.getConstant(16, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00005981 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005982 }
5983
5984 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5985 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5986 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5987 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005988 DAG.getConstant(CnstVal, dl, MVT::i32),
5989 DAG.getConstant(24, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00005990 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005991 }
5992
5993 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5994 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5995 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5996 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005997 DAG.getConstant(CnstVal, dl, MVT::i32),
5998 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00005999 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006000 }
6001
6002 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6003 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6004 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6005 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006006 DAG.getConstant(CnstVal, dl, MVT::i32),
6007 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006008 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006009 }
6010
6011 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6012 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6013 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6014 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006015 DAG.getConstant(CnstVal, dl, MVT::i32),
6016 DAG.getConstant(264, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006017 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006018 }
6019
6020 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6021 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6022 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6023 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006024 DAG.getConstant(CnstVal, dl, MVT::i32),
6025 DAG.getConstant(272, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006026 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006027 }
6028
6029 if (AArch64_AM::isAdvSIMDModImmType9(CnstVal)) {
6030 CnstVal = AArch64_AM::encodeAdvSIMDModImmType9(CnstVal);
6031 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
6032 SDValue Mov = DAG.getNode(AArch64ISD::MOVI, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006033 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006034 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006035 }
6036
6037 // The few faces of FMOV...
6038 if (AArch64_AM::isAdvSIMDModImmType11(CnstVal)) {
6039 CnstVal = AArch64_AM::encodeAdvSIMDModImmType11(CnstVal);
6040 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32;
6041 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006042 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006043 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006044 }
6045
6046 if (AArch64_AM::isAdvSIMDModImmType12(CnstVal) &&
6047 VT.getSizeInBits() == 128) {
6048 CnstVal = AArch64_AM::encodeAdvSIMDModImmType12(CnstVal);
6049 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MVT::v2f64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006050 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006051 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006052 }
6053
6054 // The many faces of MVNI...
6055 CnstVal = ~CnstVal;
6056 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6057 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6058 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6059 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006060 DAG.getConstant(CnstVal, dl, MVT::i32),
6061 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006062 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006063 }
6064
6065 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6066 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6067 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6068 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006069 DAG.getConstant(CnstVal, dl, MVT::i32),
6070 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006071 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006072 }
6073
6074 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6075 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6076 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6077 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006078 DAG.getConstant(CnstVal, dl, MVT::i32),
6079 DAG.getConstant(16, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006080 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006081 }
6082
6083 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6084 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6085 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6086 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006087 DAG.getConstant(CnstVal, dl, MVT::i32),
6088 DAG.getConstant(24, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006089 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006090 }
6091
6092 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6093 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6094 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6095 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006096 DAG.getConstant(CnstVal, dl, MVT::i32),
6097 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006098 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006099 }
6100
6101 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6102 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6103 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6104 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006105 DAG.getConstant(CnstVal, dl, MVT::i32),
6106 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006107 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006108 }
6109
6110 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6111 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6112 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6113 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006114 DAG.getConstant(CnstVal, dl, MVT::i32),
6115 DAG.getConstant(264, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006116 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006117 }
6118
6119 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6120 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6121 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6122 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006123 DAG.getConstant(CnstVal, dl, MVT::i32),
6124 DAG.getConstant(272, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006125 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006126 }
6127 }
6128
6129 if (SecondTry)
6130 goto FailedModImm;
6131 SecondTry = true;
6132 CnstBits = UndefBits;
6133 goto AttemptModImm;
6134 }
6135FailedModImm:
6136
6137 // Scan through the operands to find some interesting properties we can
6138 // exploit:
6139 // 1) If only one value is used, we can use a DUP, or
6140 // 2) if only the low element is not undef, we can just insert that, or
6141 // 3) if only one constant value is used (w/ some non-constant lanes),
6142 // we can splat the constant value into the whole vector then fill
6143 // in the non-constant lanes.
6144 // 4) FIXME: If different constant values are used, but we can intelligently
6145 // select the values we'll be overwriting for the non-constant
6146 // lanes such that we can directly materialize the vector
6147 // some other way (MOVI, e.g.), we can be sneaky.
6148 unsigned NumElts = VT.getVectorNumElements();
6149 bool isOnlyLowElement = true;
6150 bool usesOnlyOneValue = true;
6151 bool usesOnlyOneConstantValue = true;
6152 bool isConstant = true;
6153 unsigned NumConstantLanes = 0;
6154 SDValue Value;
6155 SDValue ConstantValue;
6156 for (unsigned i = 0; i < NumElts; ++i) {
6157 SDValue V = Op.getOperand(i);
6158 if (V.getOpcode() == ISD::UNDEF)
6159 continue;
6160 if (i > 0)
6161 isOnlyLowElement = false;
6162 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6163 isConstant = false;
6164
6165 if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
6166 ++NumConstantLanes;
6167 if (!ConstantValue.getNode())
6168 ConstantValue = V;
6169 else if (ConstantValue != V)
6170 usesOnlyOneConstantValue = false;
6171 }
6172
6173 if (!Value.getNode())
6174 Value = V;
6175 else if (V != Value)
6176 usesOnlyOneValue = false;
6177 }
6178
6179 if (!Value.getNode())
6180 return DAG.getUNDEF(VT);
6181
6182 if (isOnlyLowElement)
6183 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
6184
6185 // Use DUP for non-constant splats. For f32 constant splats, reduce to
6186 // i32 and try again.
6187 if (usesOnlyOneValue) {
6188 if (!isConstant) {
6189 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6190 Value.getValueType() != VT)
6191 return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
6192
6193 // This is actually a DUPLANExx operation, which keeps everything vectory.
6194
6195 // DUPLANE works on 128-bit vectors, widen it if necessary.
6196 SDValue Lane = Value.getOperand(1);
6197 Value = Value.getOperand(0);
6198 if (Value.getValueType().getSizeInBits() == 64)
6199 Value = WidenVector(Value, DAG);
6200
6201 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
6202 return DAG.getNode(Opcode, dl, VT, Value, Lane);
6203 }
6204
6205 if (VT.getVectorElementType().isFloatingPoint()) {
6206 SmallVector<SDValue, 8> Ops;
Pirama Arumuga Nainar12aeefc2015-03-17 23:10:29 +00006207 EVT EltTy = VT.getVectorElementType();
6208 assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
6209 "Unsupported floating-point vector type");
6210 MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00006211 for (unsigned i = 0; i < NumElts; ++i)
6212 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
6213 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
6214 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
6215 Val = LowerBUILD_VECTOR(Val, DAG);
6216 if (Val.getNode())
6217 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6218 }
6219 }
6220
6221 // If there was only one constant value used and for more than one lane,
6222 // start by splatting that value, then replace the non-constant lanes. This
6223 // is better than the default, which will perform a separate initialization
6224 // for each lane.
6225 if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
6226 SDValue Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
6227 // Now insert the non-constant lanes.
6228 for (unsigned i = 0; i < NumElts; ++i) {
6229 SDValue V = Op.getOperand(i);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006230 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006231 if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) {
6232 // Note that type legalization likely mucked about with the VT of the
6233 // source operand, so we may have to convert it here before inserting.
6234 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
6235 }
6236 }
6237 return Val;
6238 }
6239
6240 // If all elements are constants and the case above didn't get hit, fall back
6241 // to the default expansion, which will generate a load from the constant
6242 // pool.
6243 if (isConstant)
6244 return SDValue();
6245
6246 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6247 if (NumElts >= 4) {
Ahmed Bougacha239d6352015-08-04 00:48:02 +00006248 if (SDValue shuffle = ReconstructShuffle(Op, DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00006249 return shuffle;
6250 }
6251
6252 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6253 // know the default expansion would otherwise fall back on something even
6254 // worse. For a vector with one or two non-undef values, that's
6255 // scalar_to_vector for the elements followed by a shuffle (provided the
6256 // shuffle is valid for the target) and materialization element by element
6257 // on the stack followed by a load for everything else.
6258 if (!isConstant && !usesOnlyOneValue) {
6259 SDValue Vec = DAG.getUNDEF(VT);
6260 SDValue Op0 = Op.getOperand(0);
6261 unsigned ElemSize = VT.getVectorElementType().getSizeInBits();
6262 unsigned i = 0;
6263 // For 32 and 64 bit types, use INSERT_SUBREG for lane zero to
6264 // a) Avoid a RMW dependency on the full vector register, and
6265 // b) Allow the register coalescer to fold away the copy if the
6266 // value is already in an S or D register.
6267 if (Op0.getOpcode() != ISD::UNDEF && (ElemSize == 32 || ElemSize == 64)) {
6268 unsigned SubIdx = ElemSize == 32 ? AArch64::ssub : AArch64::dsub;
6269 MachineSDNode *N =
6270 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl, VT, Vec, Op0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006271 DAG.getTargetConstant(SubIdx, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006272 Vec = SDValue(N, 0);
6273 ++i;
6274 }
6275 for (; i < NumElts; ++i) {
6276 SDValue V = Op.getOperand(i);
6277 if (V.getOpcode() == ISD::UNDEF)
6278 continue;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006279 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006280 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6281 }
6282 return Vec;
6283 }
6284
6285 // Just use the default expansion. We failed to find a better alternative.
6286 return SDValue();
6287}
6288
6289SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
6290 SelectionDAG &DAG) const {
6291 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
6292
Tim Northovere4b8e132014-07-15 10:00:26 +00006293 // Check for non-constant or out of range lane.
6294 EVT VT = Op.getOperand(0).getValueType();
6295 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
6296 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
Tim Northover3b0846e2014-05-24 12:50:23 +00006297 return SDValue();
6298
Tim Northover3b0846e2014-05-24 12:50:23 +00006299
6300 // Insertion/extraction are legal for V128 types.
6301 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
Oliver Stannard89d15422014-08-27 16:16:04 +00006302 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6303 VT == MVT::v8f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006304 return Op;
6305
6306 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
Oliver Stannard89d15422014-08-27 16:16:04 +00006307 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006308 return SDValue();
6309
6310 // For V64 types, we perform insertion by expanding the value
6311 // to a V128 type and perform the insertion on that.
6312 SDLoc DL(Op);
6313 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6314 EVT WideTy = WideVec.getValueType();
6315
6316 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
6317 Op.getOperand(1), Op.getOperand(2));
6318 // Re-narrow the resultant vector.
6319 return NarrowVector(Node, DAG);
6320}
6321
6322SDValue
6323AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6324 SelectionDAG &DAG) const {
6325 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
6326
Tim Northovere4b8e132014-07-15 10:00:26 +00006327 // Check for non-constant or out of range lane.
6328 EVT VT = Op.getOperand(0).getValueType();
6329 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6330 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
Tim Northover3b0846e2014-05-24 12:50:23 +00006331 return SDValue();
6332
Tim Northover3b0846e2014-05-24 12:50:23 +00006333
6334 // Insertion/extraction are legal for V128 types.
6335 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
Oliver Stannard89d15422014-08-27 16:16:04 +00006336 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6337 VT == MVT::v8f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006338 return Op;
6339
6340 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
Oliver Stannard89d15422014-08-27 16:16:04 +00006341 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006342 return SDValue();
6343
6344 // For V64 types, we perform extraction by expanding the value
6345 // to a V128 type and perform the extraction on that.
6346 SDLoc DL(Op);
6347 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6348 EVT WideTy = WideVec.getValueType();
6349
6350 EVT ExtrTy = WideTy.getVectorElementType();
6351 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
6352 ExtrTy = MVT::i32;
6353
6354 // For extractions, we just return the result directly.
6355 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
6356 Op.getOperand(1));
6357}
6358
6359SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
6360 SelectionDAG &DAG) const {
6361 EVT VT = Op.getOperand(0).getValueType();
6362 SDLoc dl(Op);
6363 // Just in case...
6364 if (!VT.isVector())
6365 return SDValue();
6366
6367 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6368 if (!Cst)
6369 return SDValue();
6370 unsigned Val = Cst->getZExtValue();
6371
6372 unsigned Size = Op.getValueType().getSizeInBits();
6373 if (Val == 0) {
6374 switch (Size) {
6375 case 8:
6376 return DAG.getTargetExtractSubreg(AArch64::bsub, dl, Op.getValueType(),
6377 Op.getOperand(0));
6378 case 16:
6379 return DAG.getTargetExtractSubreg(AArch64::hsub, dl, Op.getValueType(),
6380 Op.getOperand(0));
6381 case 32:
6382 return DAG.getTargetExtractSubreg(AArch64::ssub, dl, Op.getValueType(),
6383 Op.getOperand(0));
6384 case 64:
6385 return DAG.getTargetExtractSubreg(AArch64::dsub, dl, Op.getValueType(),
6386 Op.getOperand(0));
6387 default:
6388 llvm_unreachable("Unexpected vector type in extract_subvector!");
6389 }
6390 }
6391 // If this is extracting the upper 64-bits of a 128-bit vector, we match
6392 // that directly.
6393 if (Size == 64 && Val * VT.getVectorElementType().getSizeInBits() == 64)
6394 return Op;
6395
6396 return SDValue();
6397}
6398
6399bool AArch64TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
6400 EVT VT) const {
6401 if (VT.getVectorNumElements() == 4 &&
6402 (VT.is128BitVector() || VT.is64BitVector())) {
6403 unsigned PFIndexes[4];
6404 for (unsigned i = 0; i != 4; ++i) {
6405 if (M[i] < 0)
6406 PFIndexes[i] = 8;
6407 else
6408 PFIndexes[i] = M[i];
6409 }
6410
6411 // Compute the index in the perfect shuffle table.
6412 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6413 PFIndexes[2] * 9 + PFIndexes[3];
6414 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6415 unsigned Cost = (PFEntry >> 30);
6416
6417 if (Cost <= 4)
6418 return true;
6419 }
6420
6421 bool DummyBool;
6422 int DummyInt;
6423 unsigned DummyUnsigned;
6424
6425 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
6426 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
6427 isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
6428 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
6429 isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
6430 isZIPMask(M, VT, DummyUnsigned) ||
6431 isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
6432 isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
6433 isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
6434 isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
6435 isConcatMask(M, VT, VT.getSizeInBits() == 128));
6436}
6437
6438/// getVShiftImm - Check if this is a valid build_vector for the immediate
6439/// operand of a vector shift operation, where all the elements of the
6440/// build_vector must have the same constant integer value.
6441static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
6442 // Ignore bit_converts.
6443 while (Op.getOpcode() == ISD::BITCAST)
6444 Op = Op.getOperand(0);
6445 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6446 APInt SplatBits, SplatUndef;
6447 unsigned SplatBitSize;
6448 bool HasAnyUndefs;
6449 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
6450 HasAnyUndefs, ElementBits) ||
6451 SplatBitSize > ElementBits)
6452 return false;
6453 Cnt = SplatBits.getSExtValue();
6454 return true;
6455}
6456
6457/// isVShiftLImm - Check if this is a valid build_vector for the immediate
6458/// operand of a vector shift left operation. That value must be in the range:
6459/// 0 <= Value < ElementBits for a left shift; or
6460/// 0 <= Value <= ElementBits for a long left shift.
6461static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
6462 assert(VT.isVector() && "vector shift count is not a vector type");
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00006463 int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00006464 if (!getVShiftImm(Op, ElementBits, Cnt))
6465 return false;
6466 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
6467}
6468
6469/// isVShiftRImm - Check if this is a valid build_vector for the immediate
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00006470/// operand of a vector shift right operation. The value must be in the range:
6471/// 1 <= Value <= ElementBits for a right shift; or
6472static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006473 assert(VT.isVector() && "vector shift count is not a vector type");
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00006474 int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00006475 if (!getVShiftImm(Op, ElementBits, Cnt))
6476 return false;
Tim Northover3b0846e2014-05-24 12:50:23 +00006477 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
6478}
6479
6480SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
6481 SelectionDAG &DAG) const {
6482 EVT VT = Op.getValueType();
6483 SDLoc DL(Op);
6484 int64_t Cnt;
6485
6486 if (!Op.getOperand(1).getValueType().isVector())
6487 return Op;
6488 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6489
6490 switch (Op.getOpcode()) {
6491 default:
6492 llvm_unreachable("unexpected shift opcode");
6493
6494 case ISD::SHL:
6495 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006496 return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
6497 DAG.getConstant(Cnt, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006498 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006499 DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
6500 MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00006501 Op.getOperand(0), Op.getOperand(1));
6502 case ISD::SRA:
6503 case ISD::SRL:
6504 // Right shift immediate
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00006505 if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006506 unsigned Opc =
6507 (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006508 return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
6509 DAG.getConstant(Cnt, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006510 }
6511
6512 // Right shift register. Note, there is not a shift right register
6513 // instruction, but the shift left register instruction takes a signed
6514 // value, where negative numbers specify a right shift.
6515 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
6516 : Intrinsic::aarch64_neon_ushl;
6517 // negate the shift amount
6518 SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
6519 SDValue NegShiftLeft =
6520 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006521 DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
6522 NegShift);
Tim Northover3b0846e2014-05-24 12:50:23 +00006523 return NegShiftLeft;
6524 }
6525
6526 return SDValue();
6527}
6528
6529static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
6530 AArch64CC::CondCode CC, bool NoNans, EVT VT,
6531 SDLoc dl, SelectionDAG &DAG) {
6532 EVT SrcVT = LHS.getValueType();
Tim Northover45aa89c2015-02-08 00:50:47 +00006533 assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
6534 "function only supposed to emit natural comparisons");
Tim Northover3b0846e2014-05-24 12:50:23 +00006535
6536 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
6537 APInt CnstBits(VT.getSizeInBits(), 0);
6538 APInt UndefBits(VT.getSizeInBits(), 0);
6539 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
6540 bool IsZero = IsCnst && (CnstBits == 0);
6541
6542 if (SrcVT.getVectorElementType().isFloatingPoint()) {
6543 switch (CC) {
6544 default:
6545 return SDValue();
6546 case AArch64CC::NE: {
6547 SDValue Fcmeq;
6548 if (IsZero)
6549 Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6550 else
6551 Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6552 return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
6553 }
6554 case AArch64CC::EQ:
6555 if (IsZero)
6556 return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6557 return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6558 case AArch64CC::GE:
6559 if (IsZero)
6560 return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
6561 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
6562 case AArch64CC::GT:
6563 if (IsZero)
6564 return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
6565 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
6566 case AArch64CC::LS:
6567 if (IsZero)
6568 return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
6569 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
6570 case AArch64CC::LT:
6571 if (!NoNans)
6572 return SDValue();
6573 // If we ignore NaNs then we can use to the MI implementation.
6574 // Fallthrough.
6575 case AArch64CC::MI:
6576 if (IsZero)
6577 return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
6578 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
6579 }
6580 }
6581
6582 switch (CC) {
6583 default:
6584 return SDValue();
6585 case AArch64CC::NE: {
6586 SDValue Cmeq;
6587 if (IsZero)
6588 Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6589 else
6590 Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6591 return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
6592 }
6593 case AArch64CC::EQ:
6594 if (IsZero)
6595 return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6596 return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6597 case AArch64CC::GE:
6598 if (IsZero)
6599 return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
6600 return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
6601 case AArch64CC::GT:
6602 if (IsZero)
6603 return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
6604 return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
6605 case AArch64CC::LE:
6606 if (IsZero)
6607 return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
6608 return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
6609 case AArch64CC::LS:
6610 return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
6611 case AArch64CC::LO:
6612 return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
6613 case AArch64CC::LT:
6614 if (IsZero)
6615 return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
6616 return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
6617 case AArch64CC::HI:
6618 return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
6619 case AArch64CC::HS:
6620 return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
6621 }
6622}
6623
6624SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
6625 SelectionDAG &DAG) const {
6626 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6627 SDValue LHS = Op.getOperand(0);
6628 SDValue RHS = Op.getOperand(1);
Tim Northover45aa89c2015-02-08 00:50:47 +00006629 EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
Tim Northover3b0846e2014-05-24 12:50:23 +00006630 SDLoc dl(Op);
6631
6632 if (LHS.getValueType().getVectorElementType().isInteger()) {
6633 assert(LHS.getValueType() == RHS.getValueType());
6634 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
Tim Northover45aa89c2015-02-08 00:50:47 +00006635 SDValue Cmp =
6636 EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
6637 return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00006638 }
6639
6640 assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
6641 LHS.getValueType().getVectorElementType() == MVT::f64);
6642
6643 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
6644 // clean. Some of them require two branches to implement.
6645 AArch64CC::CondCode CC1, CC2;
6646 bool ShouldInvert;
6647 changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
6648
6649 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
6650 SDValue Cmp =
Tim Northover45aa89c2015-02-08 00:50:47 +00006651 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00006652 if (!Cmp.getNode())
6653 return SDValue();
6654
6655 if (CC2 != AArch64CC::AL) {
6656 SDValue Cmp2 =
Tim Northover45aa89c2015-02-08 00:50:47 +00006657 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00006658 if (!Cmp2.getNode())
6659 return SDValue();
6660
Tim Northover45aa89c2015-02-08 00:50:47 +00006661 Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
Tim Northover3b0846e2014-05-24 12:50:23 +00006662 }
6663
Tim Northover45aa89c2015-02-08 00:50:47 +00006664 Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
6665
Tim Northover3b0846e2014-05-24 12:50:23 +00006666 if (ShouldInvert)
6667 return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
6668
6669 return Cmp;
6670}
6671
6672/// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
6673/// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
6674/// specified in the intrinsic calls.
6675bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
6676 const CallInst &I,
6677 unsigned Intrinsic) const {
Mehdi Aminia749f2a2015-07-09 02:09:52 +00006678 auto &DL = I.getModule()->getDataLayout();
Tim Northover3b0846e2014-05-24 12:50:23 +00006679 switch (Intrinsic) {
6680 case Intrinsic::aarch64_neon_ld2:
6681 case Intrinsic::aarch64_neon_ld3:
6682 case Intrinsic::aarch64_neon_ld4:
6683 case Intrinsic::aarch64_neon_ld1x2:
6684 case Intrinsic::aarch64_neon_ld1x3:
6685 case Intrinsic::aarch64_neon_ld1x4:
6686 case Intrinsic::aarch64_neon_ld2lane:
6687 case Intrinsic::aarch64_neon_ld3lane:
6688 case Intrinsic::aarch64_neon_ld4lane:
6689 case Intrinsic::aarch64_neon_ld2r:
6690 case Intrinsic::aarch64_neon_ld3r:
6691 case Intrinsic::aarch64_neon_ld4r: {
6692 Info.opc = ISD::INTRINSIC_W_CHAIN;
6693 // Conservatively set memVT to the entire set of vectors loaded.
Mehdi Aminia749f2a2015-07-09 02:09:52 +00006694 uint64_t NumElts = DL.getTypeAllocSize(I.getType()) / 8;
Tim Northover3b0846e2014-05-24 12:50:23 +00006695 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6696 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6697 Info.offset = 0;
6698 Info.align = 0;
6699 Info.vol = false; // volatile loads with NEON intrinsics not supported
6700 Info.readMem = true;
6701 Info.writeMem = false;
6702 return true;
6703 }
6704 case Intrinsic::aarch64_neon_st2:
6705 case Intrinsic::aarch64_neon_st3:
6706 case Intrinsic::aarch64_neon_st4:
6707 case Intrinsic::aarch64_neon_st1x2:
6708 case Intrinsic::aarch64_neon_st1x3:
6709 case Intrinsic::aarch64_neon_st1x4:
6710 case Intrinsic::aarch64_neon_st2lane:
6711 case Intrinsic::aarch64_neon_st3lane:
6712 case Intrinsic::aarch64_neon_st4lane: {
6713 Info.opc = ISD::INTRINSIC_VOID;
6714 // Conservatively set memVT to the entire set of vectors stored.
6715 unsigned NumElts = 0;
6716 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
6717 Type *ArgTy = I.getArgOperand(ArgI)->getType();
6718 if (!ArgTy->isVectorTy())
6719 break;
Mehdi Aminia749f2a2015-07-09 02:09:52 +00006720 NumElts += DL.getTypeAllocSize(ArgTy) / 8;
Tim Northover3b0846e2014-05-24 12:50:23 +00006721 }
6722 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6723 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6724 Info.offset = 0;
6725 Info.align = 0;
6726 Info.vol = false; // volatile stores with NEON intrinsics not supported
6727 Info.readMem = false;
6728 Info.writeMem = true;
6729 return true;
6730 }
6731 case Intrinsic::aarch64_ldaxr:
6732 case Intrinsic::aarch64_ldxr: {
6733 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
6734 Info.opc = ISD::INTRINSIC_W_CHAIN;
6735 Info.memVT = MVT::getVT(PtrTy->getElementType());
6736 Info.ptrVal = I.getArgOperand(0);
6737 Info.offset = 0;
Mehdi Aminia749f2a2015-07-09 02:09:52 +00006738 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
Tim Northover3b0846e2014-05-24 12:50:23 +00006739 Info.vol = true;
6740 Info.readMem = true;
6741 Info.writeMem = false;
6742 return true;
6743 }
6744 case Intrinsic::aarch64_stlxr:
6745 case Intrinsic::aarch64_stxr: {
6746 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
6747 Info.opc = ISD::INTRINSIC_W_CHAIN;
6748 Info.memVT = MVT::getVT(PtrTy->getElementType());
6749 Info.ptrVal = I.getArgOperand(1);
6750 Info.offset = 0;
Mehdi Aminia749f2a2015-07-09 02:09:52 +00006751 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
Tim Northover3b0846e2014-05-24 12:50:23 +00006752 Info.vol = true;
6753 Info.readMem = false;
6754 Info.writeMem = true;
6755 return true;
6756 }
6757 case Intrinsic::aarch64_ldaxp:
6758 case Intrinsic::aarch64_ldxp: {
6759 Info.opc = ISD::INTRINSIC_W_CHAIN;
6760 Info.memVT = MVT::i128;
6761 Info.ptrVal = I.getArgOperand(0);
6762 Info.offset = 0;
6763 Info.align = 16;
6764 Info.vol = true;
6765 Info.readMem = true;
6766 Info.writeMem = false;
6767 return true;
6768 }
6769 case Intrinsic::aarch64_stlxp:
6770 case Intrinsic::aarch64_stxp: {
6771 Info.opc = ISD::INTRINSIC_W_CHAIN;
6772 Info.memVT = MVT::i128;
6773 Info.ptrVal = I.getArgOperand(2);
6774 Info.offset = 0;
6775 Info.align = 16;
6776 Info.vol = true;
6777 Info.readMem = false;
6778 Info.writeMem = true;
6779 return true;
6780 }
6781 default:
6782 break;
6783 }
6784
6785 return false;
6786}
6787
6788// Truncations from 64-bit GPR to 32-bit GPR is free.
6789bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
6790 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6791 return false;
6792 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6793 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00006794 return NumBits1 > NumBits2;
Tim Northover3b0846e2014-05-24 12:50:23 +00006795}
6796bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
Hao Liu40914502014-05-29 09:19:07 +00006797 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00006798 return false;
6799 unsigned NumBits1 = VT1.getSizeInBits();
6800 unsigned NumBits2 = VT2.getSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00006801 return NumBits1 > NumBits2;
Tim Northover3b0846e2014-05-24 12:50:23 +00006802}
6803
Chad Rosier54390052015-02-23 19:15:16 +00006804/// Check if it is profitable to hoist instruction in then/else to if.
6805/// Not profitable if I and it's user can form a FMA instruction
6806/// because we prefer FMSUB/FMADD.
6807bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
6808 if (I->getOpcode() != Instruction::FMul)
6809 return true;
6810
6811 if (I->getNumUses() != 1)
6812 return true;
6813
6814 Instruction *User = I->user_back();
6815
6816 if (User &&
6817 !(User->getOpcode() == Instruction::FSub ||
6818 User->getOpcode() == Instruction::FAdd))
6819 return true;
6820
6821 const TargetOptions &Options = getTargetMachine().Options;
Mehdi Amini44ede332015-07-09 02:09:04 +00006822 const DataLayout &DL = I->getModule()->getDataLayout();
6823 EVT VT = getValueType(DL, User->getOperand(0)->getType());
Chad Rosier54390052015-02-23 19:15:16 +00006824
6825 if (isFMAFasterThanFMulAndFAdd(VT) &&
6826 isOperationLegalOrCustom(ISD::FMA, VT) &&
6827 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath))
6828 return false;
6829
6830 return true;
6831}
6832
Tim Northover3b0846e2014-05-24 12:50:23 +00006833// All 32-bit GPR operations implicitly zero the high-half of the corresponding
6834// 64-bit GPR.
6835bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
6836 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6837 return false;
6838 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6839 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00006840 return NumBits1 == 32 && NumBits2 == 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00006841}
6842bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
Hao Liu40914502014-05-29 09:19:07 +00006843 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00006844 return false;
6845 unsigned NumBits1 = VT1.getSizeInBits();
6846 unsigned NumBits2 = VT2.getSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00006847 return NumBits1 == 32 && NumBits2 == 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00006848}
6849
6850bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
6851 EVT VT1 = Val.getValueType();
6852 if (isZExtFree(VT1, VT2)) {
6853 return true;
6854 }
6855
6856 if (Val.getOpcode() != ISD::LOAD)
6857 return false;
6858
6859 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
Hao Liu40914502014-05-29 09:19:07 +00006860 return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
6861 VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
6862 VT1.getSizeInBits() <= 32);
Tim Northover3b0846e2014-05-24 12:50:23 +00006863}
6864
Quentin Colombet6843ac42015-03-31 20:52:32 +00006865bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
6866 if (isa<FPExtInst>(Ext))
6867 return false;
6868
6869 // Vector types are next free.
6870 if (Ext->getType()->isVectorTy())
6871 return false;
6872
6873 for (const Use &U : Ext->uses()) {
6874 // The extension is free if we can fold it with a left shift in an
6875 // addressing mode or an arithmetic operation: add, sub, and cmp.
6876
6877 // Is there a shift?
6878 const Instruction *Instr = cast<Instruction>(U.getUser());
6879
6880 // Is this a constant shift?
6881 switch (Instr->getOpcode()) {
6882 case Instruction::Shl:
6883 if (!isa<ConstantInt>(Instr->getOperand(1)))
6884 return false;
6885 break;
6886 case Instruction::GetElementPtr: {
6887 gep_type_iterator GTI = gep_type_begin(Instr);
Mehdi Aminia749f2a2015-07-09 02:09:52 +00006888 auto &DL = Ext->getModule()->getDataLayout();
Quentin Colombet6843ac42015-03-31 20:52:32 +00006889 std::advance(GTI, U.getOperandNo());
6890 Type *IdxTy = *GTI;
6891 // This extension will end up with a shift because of the scaling factor.
6892 // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
6893 // Get the shift amount based on the scaling factor:
6894 // log2(sizeof(IdxTy)) - log2(8).
6895 uint64_t ShiftAmt =
Mehdi Aminia749f2a2015-07-09 02:09:52 +00006896 countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3;
Quentin Colombet6843ac42015-03-31 20:52:32 +00006897 // Is the constant foldable in the shift of the addressing mode?
6898 // I.e., shift amount is between 1 and 4 inclusive.
6899 if (ShiftAmt == 0 || ShiftAmt > 4)
6900 return false;
6901 break;
6902 }
6903 case Instruction::Trunc:
6904 // Check if this is a noop.
6905 // trunc(sext ty1 to ty2) to ty1.
6906 if (Instr->getType() == Ext->getOperand(0)->getType())
6907 continue;
6908 // FALL THROUGH.
6909 default:
6910 return false;
6911 }
6912
6913 // At this point we can use the bfm family, so this extension is free
6914 // for that use.
6915 }
6916 return true;
6917}
6918
Tim Northover3b0846e2014-05-24 12:50:23 +00006919bool AArch64TargetLowering::hasPairedLoad(Type *LoadedType,
6920 unsigned &RequiredAligment) const {
6921 if (!LoadedType->isIntegerTy() && !LoadedType->isFloatTy())
6922 return false;
6923 // Cyclone supports unaligned accesses.
6924 RequiredAligment = 0;
6925 unsigned NumBits = LoadedType->getPrimitiveSizeInBits();
6926 return NumBits == 32 || NumBits == 64;
6927}
6928
6929bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
6930 unsigned &RequiredAligment) const {
6931 if (!LoadedType.isSimple() ||
6932 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
6933 return false;
6934 // Cyclone supports unaligned accesses.
6935 RequiredAligment = 0;
6936 unsigned NumBits = LoadedType.getSizeInBits();
6937 return NumBits == 32 || NumBits == 64;
6938}
6939
Hao Liu7ec8ee32015-06-26 02:32:07 +00006940/// \brief Lower an interleaved load into a ldN intrinsic.
6941///
6942/// E.g. Lower an interleaved load (Factor = 2):
6943/// %wide.vec = load <8 x i32>, <8 x i32>* %ptr
6944/// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
6945/// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
6946///
6947/// Into:
6948/// %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
6949/// %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
6950/// %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
6951bool AArch64TargetLowering::lowerInterleavedLoad(
6952 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
6953 ArrayRef<unsigned> Indices, unsigned Factor) const {
6954 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
6955 "Invalid interleave factor");
6956 assert(!Shuffles.empty() && "Empty shufflevector input");
6957 assert(Shuffles.size() == Indices.size() &&
6958 "Unmatched number of shufflevectors and indices");
6959
Mehdi Aminia749f2a2015-07-09 02:09:52 +00006960 const DataLayout &DL = LI->getModule()->getDataLayout();
Hao Liu7ec8ee32015-06-26 02:32:07 +00006961
6962 VectorType *VecTy = Shuffles[0]->getType();
Mehdi Aminia749f2a2015-07-09 02:09:52 +00006963 unsigned VecSize = DL.getTypeAllocSizeInBits(VecTy);
Hao Liu7ec8ee32015-06-26 02:32:07 +00006964
6965 // Skip illegal vector types.
6966 if (VecSize != 64 && VecSize != 128)
6967 return false;
6968
6969 // A pointer vector can not be the return type of the ldN intrinsics. Need to
6970 // load integer vectors first and then convert to pointer vectors.
6971 Type *EltTy = VecTy->getVectorElementType();
6972 if (EltTy->isPointerTy())
Mehdi Aminia749f2a2015-07-09 02:09:52 +00006973 VecTy =
6974 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
Hao Liu7ec8ee32015-06-26 02:32:07 +00006975
6976 Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
6977 Type *Tys[2] = {VecTy, PtrTy};
6978 static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
6979 Intrinsic::aarch64_neon_ld3,
6980 Intrinsic::aarch64_neon_ld4};
6981 Function *LdNFunc =
6982 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
6983
6984 IRBuilder<> Builder(LI);
6985 Value *Ptr = Builder.CreateBitCast(LI->getPointerOperand(), PtrTy);
6986
6987 CallInst *LdN = Builder.CreateCall(LdNFunc, Ptr, "ldN");
6988
6989 // Replace uses of each shufflevector with the corresponding vector loaded
6990 // by ldN.
6991 for (unsigned i = 0; i < Shuffles.size(); i++) {
6992 ShuffleVectorInst *SVI = Shuffles[i];
6993 unsigned Index = Indices[i];
6994
6995 Value *SubVec = Builder.CreateExtractValue(LdN, Index);
6996
6997 // Convert the integer vector to pointer vector if the element is pointer.
6998 if (EltTy->isPointerTy())
6999 SubVec = Builder.CreateIntToPtr(SubVec, SVI->getType());
7000
7001 SVI->replaceAllUsesWith(SubVec);
7002 }
7003
7004 return true;
7005}
7006
7007/// \brief Get a mask consisting of sequential integers starting from \p Start.
7008///
7009/// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
7010static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
7011 unsigned NumElts) {
7012 SmallVector<Constant *, 16> Mask;
7013 for (unsigned i = 0; i < NumElts; i++)
7014 Mask.push_back(Builder.getInt32(Start + i));
7015
7016 return ConstantVector::get(Mask);
7017}
7018
7019/// \brief Lower an interleaved store into a stN intrinsic.
7020///
7021/// E.g. Lower an interleaved store (Factor = 3):
7022/// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
7023/// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
7024/// store <12 x i32> %i.vec, <12 x i32>* %ptr
7025///
7026/// Into:
7027/// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
7028/// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
7029/// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
7030/// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
7031///
7032/// Note that the new shufflevectors will be removed and we'll only generate one
7033/// st3 instruction in CodeGen.
7034bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
7035 ShuffleVectorInst *SVI,
7036 unsigned Factor) const {
7037 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7038 "Invalid interleave factor");
7039
7040 VectorType *VecTy = SVI->getType();
7041 assert(VecTy->getVectorNumElements() % Factor == 0 &&
7042 "Invalid interleaved store");
7043
7044 unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
7045 Type *EltTy = VecTy->getVectorElementType();
7046 VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
7047
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007048 const DataLayout &DL = SI->getModule()->getDataLayout();
7049 unsigned SubVecSize = DL.getTypeAllocSizeInBits(SubVecTy);
Hao Liu7ec8ee32015-06-26 02:32:07 +00007050
7051 // Skip illegal vector types.
7052 if (SubVecSize != 64 && SubVecSize != 128)
7053 return false;
7054
7055 Value *Op0 = SVI->getOperand(0);
7056 Value *Op1 = SVI->getOperand(1);
7057 IRBuilder<> Builder(SI);
7058
7059 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
7060 // vectors to integer vectors.
7061 if (EltTy->isPointerTy()) {
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007062 Type *IntTy = DL.getIntPtrType(EltTy);
Hao Liu7ec8ee32015-06-26 02:32:07 +00007063 unsigned NumOpElts =
7064 dyn_cast<VectorType>(Op0->getType())->getVectorNumElements();
7065
7066 // Convert to the corresponding integer vector.
7067 Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
7068 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
7069 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
7070
7071 SubVecTy = VectorType::get(IntTy, NumSubElts);
7072 }
7073
7074 Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
7075 Type *Tys[2] = {SubVecTy, PtrTy};
7076 static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
7077 Intrinsic::aarch64_neon_st3,
7078 Intrinsic::aarch64_neon_st4};
7079 Function *StNFunc =
7080 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
7081
7082 SmallVector<Value *, 5> Ops;
7083
7084 // Split the shufflevector operands into sub vectors for the new stN call.
7085 for (unsigned i = 0; i < Factor; i++)
7086 Ops.push_back(Builder.CreateShuffleVector(
7087 Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
7088
7089 Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), PtrTy));
7090 Builder.CreateCall(StNFunc, Ops);
7091 return true;
7092}
7093
Tim Northover3b0846e2014-05-24 12:50:23 +00007094static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
7095 unsigned AlignCheck) {
7096 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
7097 (DstAlign == 0 || DstAlign % AlignCheck == 0));
7098}
7099
7100EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
7101 unsigned SrcAlign, bool IsMemset,
7102 bool ZeroMemset,
7103 bool MemcpyStrSrc,
7104 MachineFunction &MF) const {
7105 // Don't use AdvSIMD to implement 16-byte memset. It would have taken one
7106 // instruction to materialize the v2i64 zero and one store (with restrictive
7107 // addressing mode). Just do two i64 store of zero-registers.
7108 bool Fast;
7109 const Function *F = MF.getFunction();
7110 if (Subtarget->hasFPARMv8() && !IsMemset && Size >= 16 &&
Duncan P. N. Exon Smith003bb7d2015-02-14 02:09:06 +00007111 !F->hasFnAttribute(Attribute::NoImplicitFloat) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00007112 (memOpAlign(SrcAlign, DstAlign, 16) ||
Matt Arsenault6f2a5262014-07-27 17:46:40 +00007113 (allowsMisalignedMemoryAccesses(MVT::f128, 0, 1, &Fast) && Fast)))
Tim Northover3b0846e2014-05-24 12:50:23 +00007114 return MVT::f128;
7115
Lang Hames90333852015-04-09 03:40:33 +00007116 if (Size >= 8 &&
7117 (memOpAlign(SrcAlign, DstAlign, 8) ||
7118 (allowsMisalignedMemoryAccesses(MVT::i64, 0, 1, &Fast) && Fast)))
7119 return MVT::i64;
7120
7121 if (Size >= 4 &&
7122 (memOpAlign(SrcAlign, DstAlign, 4) ||
7123 (allowsMisalignedMemoryAccesses(MVT::i32, 0, 1, &Fast) && Fast)))
Lang Hames522bf132015-04-09 05:34:57 +00007124 return MVT::i32;
Lang Hames90333852015-04-09 03:40:33 +00007125
7126 return MVT::Other;
Tim Northover3b0846e2014-05-24 12:50:23 +00007127}
7128
7129// 12-bit optionally shifted immediates are legal for adds.
7130bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
7131 if ((Immed >> 12) == 0 || ((Immed & 0xfff) == 0 && Immed >> 24 == 0))
7132 return true;
7133 return false;
7134}
7135
7136// Integer comparisons are implemented with ADDS/SUBS, so the range of valid
7137// immediates is the same as for an add or a sub.
7138bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
7139 if (Immed < 0)
7140 Immed *= -1;
7141 return isLegalAddImmediate(Immed);
7142}
7143
7144/// isLegalAddressingMode - Return true if the addressing mode represented
7145/// by AM is legal for this target, for a load/store of the specified type.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00007146bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
7147 const AddrMode &AM, Type *Ty,
Matt Arsenaultbd7d80a2015-06-01 05:31:59 +00007148 unsigned AS) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00007149 // AArch64 has five basic addressing modes:
7150 // reg
7151 // reg + 9-bit signed offset
7152 // reg + SIZE_IN_BYTES * 12-bit unsigned offset
7153 // reg1 + reg2
7154 // reg + SIZE_IN_BYTES * reg
7155
7156 // No global is ever allowed as a base.
7157 if (AM.BaseGV)
7158 return false;
7159
7160 // No reg+reg+imm addressing.
7161 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
7162 return false;
7163
7164 // check reg + imm case:
7165 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
7166 uint64_t NumBytes = 0;
7167 if (Ty->isSized()) {
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00007168 uint64_t NumBits = DL.getTypeSizeInBits(Ty);
Tim Northover3b0846e2014-05-24 12:50:23 +00007169 NumBytes = NumBits / 8;
7170 if (!isPowerOf2_64(NumBits))
7171 NumBytes = 0;
7172 }
7173
7174 if (!AM.Scale) {
7175 int64_t Offset = AM.BaseOffs;
7176
7177 // 9-bit signed offset
7178 if (Offset >= -(1LL << 9) && Offset <= (1LL << 9) - 1)
7179 return true;
7180
7181 // 12-bit unsigned offset
7182 unsigned shift = Log2_64(NumBytes);
7183 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
7184 // Must be a multiple of NumBytes (NumBytes is a power of 2)
7185 (Offset >> shift) << shift == Offset)
7186 return true;
7187 return false;
7188 }
7189
7190 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
7191
7192 if (!AM.Scale || AM.Scale == 1 ||
7193 (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes))
7194 return true;
7195 return false;
7196}
7197
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00007198int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
7199 const AddrMode &AM, Type *Ty,
Matt Arsenaultbd7d80a2015-06-01 05:31:59 +00007200 unsigned AS) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00007201 // Scaling factors are not free at all.
7202 // Operands | Rt Latency
7203 // -------------------------------------------
7204 // Rt, [Xn, Xm] | 4
7205 // -------------------------------------------
7206 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5
7207 // Rt, [Xn, Wm, <extend> #imm] |
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00007208 if (isLegalAddressingMode(DL, AM, Ty, AS))
Tim Northover3b0846e2014-05-24 12:50:23 +00007209 // Scale represents reg2 * scale, thus account for 1 if
7210 // it is not equal to 0 or 1.
7211 return AM.Scale != 0 && AM.Scale != 1;
7212 return -1;
7213}
7214
7215bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
7216 VT = VT.getScalarType();
7217
7218 if (!VT.isSimple())
7219 return false;
7220
7221 switch (VT.getSimpleVT().SimpleTy) {
7222 case MVT::f32:
7223 case MVT::f64:
7224 return true;
7225 default:
7226 break;
7227 }
7228
7229 return false;
7230}
7231
7232const MCPhysReg *
7233AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
7234 // LR is a callee-save register, but we must treat it as clobbered by any call
7235 // site. Hence we include LR in the scratch registers, which are in turn added
7236 // as implicit-defs for stackmaps and patchpoints.
7237 static const MCPhysReg ScratchRegs[] = {
7238 AArch64::X16, AArch64::X17, AArch64::LR, 0
7239 };
7240 return ScratchRegs;
7241}
7242
7243bool
7244AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N) const {
7245 EVT VT = N->getValueType(0);
7246 // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
7247 // it with shift to let it be lowered to UBFX.
7248 if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
7249 isa<ConstantSDNode>(N->getOperand(1))) {
7250 uint64_t TruncMask = N->getConstantOperandVal(1);
7251 if (isMask_64(TruncMask) &&
7252 N->getOperand(0).getOpcode() == ISD::SRL &&
7253 isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
7254 return false;
7255 }
7256 return true;
7257}
7258
7259bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
7260 Type *Ty) const {
7261 assert(Ty->isIntegerTy());
7262
7263 unsigned BitSize = Ty->getPrimitiveSizeInBits();
7264 if (BitSize == 0)
7265 return false;
7266
7267 int64_t Val = Imm.getSExtValue();
7268 if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
7269 return true;
7270
7271 if ((int64_t)Val < 0)
7272 Val = ~Val;
7273 if (BitSize == 32)
7274 Val &= (1LL << 32) - 1;
7275
7276 unsigned LZ = countLeadingZeros((uint64_t)Val);
7277 unsigned Shift = (63 - LZ) / 16;
7278 // MOVZ is free so return true for one or fewer MOVK.
David Blaikie186d2cb2015-03-24 16:24:01 +00007279 return Shift < 3;
Tim Northover3b0846e2014-05-24 12:50:23 +00007280}
7281
7282// Generate SUBS and CSEL for integer abs.
7283static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
7284 EVT VT = N->getValueType(0);
7285
7286 SDValue N0 = N->getOperand(0);
7287 SDValue N1 = N->getOperand(1);
7288 SDLoc DL(N);
7289
7290 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
7291 // and change it to SUB and CSEL.
7292 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
7293 N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
7294 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
7295 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
7296 if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007297 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
Tim Northover3b0846e2014-05-24 12:50:23 +00007298 N0.getOperand(0));
7299 // Generate SUBS & CSEL.
7300 SDValue Cmp =
7301 DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007302 N0.getOperand(0), DAG.getConstant(0, DL, VT));
Tim Northover3b0846e2014-05-24 12:50:23 +00007303 return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007304 DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00007305 SDValue(Cmp.getNode(), 1));
7306 }
7307 return SDValue();
7308}
7309
7310// performXorCombine - Attempts to handle integer ABS.
7311static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
7312 TargetLowering::DAGCombinerInfo &DCI,
7313 const AArch64Subtarget *Subtarget) {
7314 if (DCI.isBeforeLegalizeOps())
7315 return SDValue();
7316
7317 return performIntegerAbsCombine(N, DAG);
7318}
7319
Chad Rosier17020f92014-07-23 14:57:52 +00007320SDValue
7321AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
7322 SelectionDAG &DAG,
7323 std::vector<SDNode *> *Created) const {
7324 // fold (sdiv X, pow2)
7325 EVT VT = N->getValueType(0);
7326 if ((VT != MVT::i32 && VT != MVT::i64) ||
7327 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
7328 return SDValue();
7329
7330 SDLoc DL(N);
7331 SDValue N0 = N->getOperand(0);
7332 unsigned Lg2 = Divisor.countTrailingZeros();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007333 SDValue Zero = DAG.getConstant(0, DL, VT);
7334 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
Chad Rosier17020f92014-07-23 14:57:52 +00007335
7336 // Add (N0 < 0) ? Pow2 - 1 : 0;
7337 SDValue CCVal;
7338 SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
7339 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
7340 SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
7341
7342 if (Created) {
7343 Created->push_back(Cmp.getNode());
7344 Created->push_back(Add.getNode());
7345 Created->push_back(CSel.getNode());
7346 }
7347
7348 // Divide by pow2.
7349 SDValue SRA =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007350 DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
Chad Rosier17020f92014-07-23 14:57:52 +00007351
7352 // If we're dividing by a positive value, we're done. Otherwise, we must
7353 // negate the result.
7354 if (Divisor.isNonNegative())
7355 return SRA;
7356
7357 if (Created)
7358 Created->push_back(SRA.getNode());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007359 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
Chad Rosier17020f92014-07-23 14:57:52 +00007360}
7361
Tim Northover3b0846e2014-05-24 12:50:23 +00007362static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
7363 TargetLowering::DAGCombinerInfo &DCI,
7364 const AArch64Subtarget *Subtarget) {
7365 if (DCI.isBeforeLegalizeOps())
7366 return SDValue();
7367
7368 // Multiplication of a power of two plus/minus one can be done more
7369 // cheaply as as shift+add/sub. For now, this is true unilaterally. If
7370 // future CPUs have a cheaper MADD instruction, this may need to be
7371 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
7372 // 64-bit is 5 cycles, so this is always a win.
7373 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
7374 APInt Value = C->getAPIntValue();
7375 EVT VT = N->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007376 SDLoc DL(N);
Chad Rosiere6b87612014-06-30 14:51:14 +00007377 if (Value.isNonNegative()) {
7378 // (mul x, 2^N + 1) => (add (shl x, N), x)
7379 APInt VM1 = Value - 1;
7380 if (VM1.isPowerOf2()) {
7381 SDValue ShiftedVal =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007382 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7383 DAG.getConstant(VM1.logBase2(), DL, MVT::i64));
7384 return DAG.getNode(ISD::ADD, DL, VT, ShiftedVal,
Chad Rosiere6b87612014-06-30 14:51:14 +00007385 N->getOperand(0));
7386 }
7387 // (mul x, 2^N - 1) => (sub (shl x, N), x)
7388 APInt VP1 = Value + 1;
7389 if (VP1.isPowerOf2()) {
7390 SDValue ShiftedVal =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007391 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7392 DAG.getConstant(VP1.logBase2(), DL, MVT::i64));
7393 return DAG.getNode(ISD::SUB, DL, VT, ShiftedVal,
Chad Rosiere6b87612014-06-30 14:51:14 +00007394 N->getOperand(0));
7395 }
7396 } else {
Chad Rosier8e38f302015-03-03 17:31:01 +00007397 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7398 APInt VNP1 = -Value + 1;
7399 if (VNP1.isPowerOf2()) {
7400 SDValue ShiftedVal =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007401 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7402 DAG.getConstant(VNP1.logBase2(), DL, MVT::i64));
7403 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0),
Chad Rosier8e38f302015-03-03 17:31:01 +00007404 ShiftedVal);
7405 }
Chad Rosiere6b87612014-06-30 14:51:14 +00007406 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7407 APInt VNM1 = -Value - 1;
7408 if (VNM1.isPowerOf2()) {
7409 SDValue ShiftedVal =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007410 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7411 DAG.getConstant(VNM1.logBase2(), DL, MVT::i64));
Chad Rosiere6b87612014-06-30 14:51:14 +00007412 SDValue Add =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007413 DAG.getNode(ISD::ADD, DL, VT, ShiftedVal, N->getOperand(0));
7414 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Add);
Chad Rosiere6b87612014-06-30 14:51:14 +00007415 }
Chad Rosierd96e9f12014-06-09 01:25:51 +00007416 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007417 }
7418 return SDValue();
7419}
7420
Jim Grosbachf7502c42014-07-18 00:40:52 +00007421static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
7422 SelectionDAG &DAG) {
7423 // Take advantage of vector comparisons producing 0 or -1 in each lane to
7424 // optimize away operation when it's from a constant.
7425 //
7426 // The general transformation is:
7427 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
7428 // AND(VECTOR_CMP(x,y), constant2)
7429 // constant2 = UNARYOP(constant)
7430
Jim Grosbach8f6f0852014-07-23 20:41:38 +00007431 // Early exit if this isn't a vector operation, the operand of the
7432 // unary operation isn't a bitwise AND, or if the sizes of the operations
7433 // aren't the same.
Jim Grosbachf7502c42014-07-18 00:40:52 +00007434 EVT VT = N->getValueType(0);
7435 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
Jim Grosbach8f6f0852014-07-23 20:41:38 +00007436 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
7437 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
Jim Grosbachf7502c42014-07-18 00:40:52 +00007438 return SDValue();
7439
Jim Grosbach724e4382014-07-23 20:41:43 +00007440 // Now check that the other operand of the AND is a constant. We could
Jim Grosbachf7502c42014-07-18 00:40:52 +00007441 // make the transformation for non-constant splats as well, but it's unclear
7442 // that would be a benefit as it would not eliminate any operations, just
7443 // perform one more step in scalar code before moving to the vector unit.
7444 if (BuildVectorSDNode *BV =
7445 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
Jim Grosbach724e4382014-07-23 20:41:43 +00007446 // Bail out if the vector isn't a constant.
7447 if (!BV->isConstant())
Jim Grosbachf7502c42014-07-18 00:40:52 +00007448 return SDValue();
7449
7450 // Everything checks out. Build up the new and improved node.
7451 SDLoc DL(N);
7452 EVT IntVT = BV->getValueType(0);
7453 // Create a new constant of the appropriate type for the transformed
7454 // DAG.
7455 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
7456 // The AND node needs bitcasts to/from an integer vector type around it.
7457 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
7458 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
7459 N->getOperand(0)->getOperand(0), MaskConst);
7460 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
7461 return Res;
7462 }
7463
7464 return SDValue();
7465}
7466
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00007467static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
7468 const AArch64Subtarget *Subtarget) {
Jim Grosbachf7502c42014-07-18 00:40:52 +00007469 // First try to optimize away the conversion when it's conditionally from
7470 // a constant. Vectors only.
Ahmed Bougacha239d6352015-08-04 00:48:02 +00007471 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
Jim Grosbachf7502c42014-07-18 00:40:52 +00007472 return Res;
7473
Tim Northover3b0846e2014-05-24 12:50:23 +00007474 EVT VT = N->getValueType(0);
7475 if (VT != MVT::f32 && VT != MVT::f64)
7476 return SDValue();
Jim Grosbachf7502c42014-07-18 00:40:52 +00007477
Tim Northover3b0846e2014-05-24 12:50:23 +00007478 // Only optimize when the source and destination types have the same width.
7479 if (VT.getSizeInBits() != N->getOperand(0).getValueType().getSizeInBits())
7480 return SDValue();
7481
7482 // If the result of an integer load is only used by an integer-to-float
7483 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
7484 // This eliminates an "integer-to-vector-move UOP and improve throughput.
7485 SDValue N0 = N->getOperand(0);
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00007486 if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Tim Northover3b0846e2014-05-24 12:50:23 +00007487 // Do not change the width of a volatile load.
7488 !cast<LoadSDNode>(N0)->isVolatile()) {
7489 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7490 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
7491 LN0->getPointerInfo(), LN0->isVolatile(),
7492 LN0->isNonTemporal(), LN0->isInvariant(),
7493 LN0->getAlignment());
7494
7495 // Make sure successors of the original load stay after it by updating them
7496 // to use the new Chain.
7497 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
7498
7499 unsigned Opcode =
7500 (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
7501 return DAG.getNode(Opcode, SDLoc(N), VT, Load);
7502 }
7503
7504 return SDValue();
7505}
7506
7507/// An EXTR instruction is made up of two shifts, ORed together. This helper
7508/// searches for and classifies those shifts.
7509static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
7510 bool &FromHi) {
7511 if (N.getOpcode() == ISD::SHL)
7512 FromHi = false;
7513 else if (N.getOpcode() == ISD::SRL)
7514 FromHi = true;
7515 else
7516 return false;
7517
7518 if (!isa<ConstantSDNode>(N.getOperand(1)))
7519 return false;
7520
7521 ShiftAmount = N->getConstantOperandVal(1);
7522 Src = N->getOperand(0);
7523 return true;
7524}
7525
7526/// EXTR instruction extracts a contiguous chunk of bits from two existing
7527/// registers viewed as a high/low pair. This function looks for the pattern:
7528/// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an
7529/// EXTR. Can't quite be done in TableGen because the two immediates aren't
7530/// independent.
7531static SDValue tryCombineToEXTR(SDNode *N,
7532 TargetLowering::DAGCombinerInfo &DCI) {
7533 SelectionDAG &DAG = DCI.DAG;
7534 SDLoc DL(N);
7535 EVT VT = N->getValueType(0);
7536
7537 assert(N->getOpcode() == ISD::OR && "Unexpected root");
7538
7539 if (VT != MVT::i32 && VT != MVT::i64)
7540 return SDValue();
7541
7542 SDValue LHS;
7543 uint32_t ShiftLHS = 0;
7544 bool LHSFromHi = 0;
7545 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
7546 return SDValue();
7547
7548 SDValue RHS;
7549 uint32_t ShiftRHS = 0;
7550 bool RHSFromHi = 0;
7551 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
7552 return SDValue();
7553
7554 // If they're both trying to come from the high part of the register, they're
7555 // not really an EXTR.
7556 if (LHSFromHi == RHSFromHi)
7557 return SDValue();
7558
7559 if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
7560 return SDValue();
7561
7562 if (LHSFromHi) {
7563 std::swap(LHS, RHS);
7564 std::swap(ShiftLHS, ShiftRHS);
7565 }
7566
7567 return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007568 DAG.getConstant(ShiftRHS, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00007569}
7570
7571static SDValue tryCombineToBSL(SDNode *N,
7572 TargetLowering::DAGCombinerInfo &DCI) {
7573 EVT VT = N->getValueType(0);
7574 SelectionDAG &DAG = DCI.DAG;
7575 SDLoc DL(N);
7576
7577 if (!VT.isVector())
7578 return SDValue();
7579
7580 SDValue N0 = N->getOperand(0);
7581 if (N0.getOpcode() != ISD::AND)
7582 return SDValue();
7583
7584 SDValue N1 = N->getOperand(1);
7585 if (N1.getOpcode() != ISD::AND)
7586 return SDValue();
7587
7588 // We only have to look for constant vectors here since the general, variable
7589 // case can be handled in TableGen.
7590 unsigned Bits = VT.getVectorElementType().getSizeInBits();
7591 uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
7592 for (int i = 1; i >= 0; --i)
7593 for (int j = 1; j >= 0; --j) {
7594 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
7595 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
7596 if (!BVN0 || !BVN1)
7597 continue;
7598
7599 bool FoundMatch = true;
7600 for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
7601 ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
7602 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
7603 if (!CN0 || !CN1 ||
7604 CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
7605 FoundMatch = false;
7606 break;
7607 }
7608 }
7609
7610 if (FoundMatch)
7611 return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
7612 N0->getOperand(1 - i), N1->getOperand(1 - j));
7613 }
7614
7615 return SDValue();
7616}
7617
7618static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
7619 const AArch64Subtarget *Subtarget) {
7620 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
7621 if (!EnableAArch64ExtrGeneration)
7622 return SDValue();
7623 SelectionDAG &DAG = DCI.DAG;
7624 EVT VT = N->getValueType(0);
7625
7626 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7627 return SDValue();
7628
7629 SDValue Res = tryCombineToEXTR(N, DCI);
7630 if (Res.getNode())
7631 return Res;
7632
7633 Res = tryCombineToBSL(N, DCI);
7634 if (Res.getNode())
7635 return Res;
7636
7637 return SDValue();
7638}
7639
7640static SDValue performBitcastCombine(SDNode *N,
7641 TargetLowering::DAGCombinerInfo &DCI,
7642 SelectionDAG &DAG) {
7643 // Wait 'til after everything is legalized to try this. That way we have
7644 // legal vector types and such.
7645 if (DCI.isBeforeLegalizeOps())
7646 return SDValue();
7647
7648 // Remove extraneous bitcasts around an extract_subvector.
7649 // For example,
7650 // (v4i16 (bitconvert
7651 // (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
7652 // becomes
7653 // (extract_subvector ((v8i16 ...), (i64 4)))
7654
7655 // Only interested in 64-bit vectors as the ultimate result.
7656 EVT VT = N->getValueType(0);
7657 if (!VT.isVector())
7658 return SDValue();
7659 if (VT.getSimpleVT().getSizeInBits() != 64)
7660 return SDValue();
7661 // Is the operand an extract_subvector starting at the beginning or halfway
7662 // point of the vector? A low half may also come through as an
7663 // EXTRACT_SUBREG, so look for that, too.
7664 SDValue Op0 = N->getOperand(0);
7665 if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
7666 !(Op0->isMachineOpcode() &&
7667 Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
7668 return SDValue();
7669 uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
7670 if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
7671 if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
7672 return SDValue();
7673 } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
7674 if (idx != AArch64::dsub)
7675 return SDValue();
7676 // The dsub reference is equivalent to a lane zero subvector reference.
7677 idx = 0;
7678 }
7679 // Look through the bitcast of the input to the extract.
7680 if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
7681 return SDValue();
7682 SDValue Source = Op0->getOperand(0)->getOperand(0);
7683 // If the source type has twice the number of elements as our destination
7684 // type, we know this is an extract of the high or low half of the vector.
7685 EVT SVT = Source->getValueType(0);
7686 if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
7687 return SDValue();
7688
7689 DEBUG(dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
7690
7691 // Create the simplified form to just extract the low or high half of the
7692 // vector directly rather than bothering with the bitcasts.
7693 SDLoc dl(N);
7694 unsigned NumElements = VT.getVectorNumElements();
7695 if (idx) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007696 SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00007697 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
7698 } else {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007699 SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00007700 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
7701 Source, SubReg),
7702 0);
7703 }
7704}
7705
7706static SDValue performConcatVectorsCombine(SDNode *N,
7707 TargetLowering::DAGCombinerInfo &DCI,
7708 SelectionDAG &DAG) {
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00007709 SDLoc dl(N);
7710 EVT VT = N->getValueType(0);
7711 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
7712
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00007713 // Optimize concat_vectors of truncated vectors, where the intermediate
7714 // type is illegal, to avoid said illegality, e.g.,
7715 // (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
7716 // (v2i16 (truncate (v2i64)))))
7717 // ->
Ahmed Bougachae6bb09a2015-03-21 01:08:39 +00007718 // (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
7719 // (v4i32 (bitcast (v2i64))),
7720 // <0, 2, 4, 6>)))
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00007721 // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
7722 // on both input and result type, so we might generate worse code.
7723 // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
7724 if (N->getNumOperands() == 2 &&
7725 N0->getOpcode() == ISD::TRUNCATE &&
7726 N1->getOpcode() == ISD::TRUNCATE) {
7727 SDValue N00 = N0->getOperand(0);
7728 SDValue N10 = N1->getOperand(0);
7729 EVT N00VT = N00.getValueType();
7730
7731 if (N00VT == N10.getValueType() &&
7732 (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
7733 N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
Ahmed Bougachae6bb09a2015-03-21 01:08:39 +00007734 MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
7735 SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
7736 for (size_t i = 0; i < Mask.size(); ++i)
7737 Mask[i] = i * 2;
7738 return DAG.getNode(ISD::TRUNCATE, dl, VT,
7739 DAG.getVectorShuffle(
7740 MidVT, dl,
7741 DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
7742 DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00007743 }
7744 }
7745
Tim Northover3b0846e2014-05-24 12:50:23 +00007746 // Wait 'til after everything is legalized to try this. That way we have
7747 // legal vector types and such.
7748 if (DCI.isBeforeLegalizeOps())
7749 return SDValue();
7750
Tim Northover3b0846e2014-05-24 12:50:23 +00007751 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
7752 // splat. The indexed instructions are going to be expecting a DUPLANE64, so
7753 // canonicalise to that.
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00007754 if (N0 == N1 && VT.getVectorNumElements() == 2) {
Tim Northover3b0846e2014-05-24 12:50:23 +00007755 assert(VT.getVectorElementType().getSizeInBits() == 64);
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00007756 return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007757 DAG.getConstant(0, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00007758 }
7759
7760 // Canonicalise concat_vectors so that the right-hand vector has as few
7761 // bit-casts as possible before its real operation. The primary matching
7762 // destination for these operations will be the narrowing "2" instructions,
7763 // which depend on the operation being performed on this right-hand vector.
7764 // For example,
7765 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS))))
7766 // becomes
7767 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
7768
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00007769 if (N1->getOpcode() != ISD::BITCAST)
Tim Northover3b0846e2014-05-24 12:50:23 +00007770 return SDValue();
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00007771 SDValue RHS = N1->getOperand(0);
Tim Northover3b0846e2014-05-24 12:50:23 +00007772 MVT RHSTy = RHS.getValueType().getSimpleVT();
7773 // If the RHS is not a vector, this is not the pattern we're looking for.
7774 if (!RHSTy.isVector())
7775 return SDValue();
7776
7777 DEBUG(dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
7778
7779 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
7780 RHSTy.getVectorNumElements() * 2);
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00007781 return DAG.getNode(ISD::BITCAST, dl, VT,
7782 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
7783 DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
7784 RHS));
Tim Northover3b0846e2014-05-24 12:50:23 +00007785}
7786
7787static SDValue tryCombineFixedPointConvert(SDNode *N,
7788 TargetLowering::DAGCombinerInfo &DCI,
7789 SelectionDAG &DAG) {
7790 // Wait 'til after everything is legalized to try this. That way we have
7791 // legal vector types and such.
7792 if (DCI.isBeforeLegalizeOps())
7793 return SDValue();
7794 // Transform a scalar conversion of a value from a lane extract into a
7795 // lane extract of a vector conversion. E.g., from foo1 to foo2:
7796 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
7797 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
7798 //
7799 // The second form interacts better with instruction selection and the
7800 // register allocator to avoid cross-class register copies that aren't
7801 // coalescable due to a lane reference.
7802
7803 // Check the operand and see if it originates from a lane extract.
7804 SDValue Op1 = N->getOperand(1);
7805 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7806 // Yep, no additional predication needed. Perform the transform.
7807 SDValue IID = N->getOperand(0);
7808 SDValue Shift = N->getOperand(2);
7809 SDValue Vec = Op1.getOperand(0);
7810 SDValue Lane = Op1.getOperand(1);
7811 EVT ResTy = N->getValueType(0);
7812 EVT VecResTy;
7813 SDLoc DL(N);
7814
7815 // The vector width should be 128 bits by the time we get here, even
7816 // if it started as 64 bits (the extract_vector handling will have
7817 // done so).
7818 assert(Vec.getValueType().getSizeInBits() == 128 &&
7819 "unexpected vector size on extract_vector_elt!");
7820 if (Vec.getValueType() == MVT::v4i32)
7821 VecResTy = MVT::v4f32;
7822 else if (Vec.getValueType() == MVT::v2i64)
7823 VecResTy = MVT::v2f64;
7824 else
Craig Topper2a30d782014-06-18 05:05:13 +00007825 llvm_unreachable("unexpected vector type!");
Tim Northover3b0846e2014-05-24 12:50:23 +00007826
7827 SDValue Convert =
7828 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
7829 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
7830 }
7831 return SDValue();
7832}
7833
7834// AArch64 high-vector "long" operations are formed by performing the non-high
7835// version on an extract_subvector of each operand which gets the high half:
7836//
7837// (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
7838//
7839// However, there are cases which don't have an extract_high explicitly, but
7840// have another operation that can be made compatible with one for free. For
7841// example:
7842//
7843// (dupv64 scalar) --> (extract_high (dup128 scalar))
7844//
7845// This routine does the actual conversion of such DUPs, once outer routines
7846// have determined that everything else is in order.
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00007847// It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
7848// similarly here.
Tim Northover3b0846e2014-05-24 12:50:23 +00007849static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00007850 switch (N.getOpcode()) {
7851 case AArch64ISD::DUP:
Tim Northover3b0846e2014-05-24 12:50:23 +00007852 case AArch64ISD::DUPLANE8:
7853 case AArch64ISD::DUPLANE16:
7854 case AArch64ISD::DUPLANE32:
7855 case AArch64ISD::DUPLANE64:
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00007856 case AArch64ISD::MOVI:
7857 case AArch64ISD::MOVIshift:
7858 case AArch64ISD::MOVIedit:
7859 case AArch64ISD::MOVImsl:
7860 case AArch64ISD::MVNIshift:
7861 case AArch64ISD::MVNImsl:
Tim Northover3b0846e2014-05-24 12:50:23 +00007862 break;
7863 default:
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00007864 // FMOV could be supported, but isn't very useful, as it would only occur
7865 // if you passed a bitcast' floating point immediate to an eligible long
7866 // integer op (addl, smull, ...).
Tim Northover3b0846e2014-05-24 12:50:23 +00007867 return SDValue();
7868 }
7869
7870 MVT NarrowTy = N.getSimpleValueType();
7871 if (!NarrowTy.is64BitVector())
7872 return SDValue();
7873
7874 MVT ElementTy = NarrowTy.getVectorElementType();
7875 unsigned NumElems = NarrowTy.getVectorNumElements();
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00007876 MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
Tim Northover3b0846e2014-05-24 12:50:23 +00007877
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007878 SDLoc dl(N);
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00007879 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
7880 DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007881 DAG.getConstant(NumElems, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00007882}
7883
7884static bool isEssentiallyExtractSubvector(SDValue N) {
7885 if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
7886 return true;
7887
7888 return N.getOpcode() == ISD::BITCAST &&
7889 N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
7890}
7891
7892/// \brief Helper structure to keep track of ISD::SET_CC operands.
7893struct GenericSetCCInfo {
7894 const SDValue *Opnd0;
7895 const SDValue *Opnd1;
7896 ISD::CondCode CC;
7897};
7898
7899/// \brief Helper structure to keep track of a SET_CC lowered into AArch64 code.
7900struct AArch64SetCCInfo {
7901 const SDValue *Cmp;
7902 AArch64CC::CondCode CC;
7903};
7904
7905/// \brief Helper structure to keep track of SetCC information.
7906union SetCCInfo {
7907 GenericSetCCInfo Generic;
7908 AArch64SetCCInfo AArch64;
7909};
7910
7911/// \brief Helper structure to be able to read SetCC information. If set to
7912/// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
7913/// GenericSetCCInfo.
7914struct SetCCInfoAndKind {
7915 SetCCInfo Info;
7916 bool IsAArch64;
7917};
7918
7919/// \brief Check whether or not \p Op is a SET_CC operation, either a generic or
7920/// an
7921/// AArch64 lowered one.
7922/// \p SetCCInfo is filled accordingly.
7923/// \post SetCCInfo is meanginfull only when this function returns true.
7924/// \return True when Op is a kind of SET_CC operation.
7925static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
7926 // If this is a setcc, this is straight forward.
7927 if (Op.getOpcode() == ISD::SETCC) {
7928 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
7929 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
7930 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7931 SetCCInfo.IsAArch64 = false;
7932 return true;
7933 }
7934 // Otherwise, check if this is a matching csel instruction.
7935 // In other words:
7936 // - csel 1, 0, cc
7937 // - csel 0, 1, !cc
7938 if (Op.getOpcode() != AArch64ISD::CSEL)
7939 return false;
7940 // Set the information about the operands.
7941 // TODO: we want the operands of the Cmp not the csel
7942 SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
7943 SetCCInfo.IsAArch64 = true;
7944 SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
7945 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
7946
7947 // Check that the operands matches the constraints:
7948 // (1) Both operands must be constants.
7949 // (2) One must be 1 and the other must be 0.
7950 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
7951 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7952
7953 // Check (1).
7954 if (!TValue || !FValue)
7955 return false;
7956
7957 // Check (2).
7958 if (!TValue->isOne()) {
7959 // Update the comparison when we are interested in !cc.
7960 std::swap(TValue, FValue);
7961 SetCCInfo.Info.AArch64.CC =
7962 AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
7963 }
7964 return TValue->isOne() && FValue->isNullValue();
7965}
7966
7967// Returns true if Op is setcc or zext of setcc.
7968static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
7969 if (isSetCC(Op, Info))
7970 return true;
7971 return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
7972 isSetCC(Op->getOperand(0), Info));
7973}
7974
7975// The folding we want to perform is:
7976// (add x, [zext] (setcc cc ...) )
7977// -->
7978// (csel x, (add x, 1), !cc ...)
7979//
7980// The latter will get matched to a CSINC instruction.
7981static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
7982 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
7983 SDValue LHS = Op->getOperand(0);
7984 SDValue RHS = Op->getOperand(1);
7985 SetCCInfoAndKind InfoAndKind;
7986
7987 // If neither operand is a SET_CC, give up.
7988 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
7989 std::swap(LHS, RHS);
7990 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
7991 return SDValue();
7992 }
7993
7994 // FIXME: This could be generatized to work for FP comparisons.
7995 EVT CmpVT = InfoAndKind.IsAArch64
7996 ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
7997 : InfoAndKind.Info.Generic.Opnd0->getValueType();
7998 if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
7999 return SDValue();
8000
8001 SDValue CCVal;
8002 SDValue Cmp;
8003 SDLoc dl(Op);
8004 if (InfoAndKind.IsAArch64) {
8005 CCVal = DAG.getConstant(
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008006 AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
8007 MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00008008 Cmp = *InfoAndKind.Info.AArch64.Cmp;
8009 } else
8010 Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
8011 *InfoAndKind.Info.Generic.Opnd1,
8012 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
8013 CCVal, DAG, dl);
8014
8015 EVT VT = Op->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008016 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
Tim Northover3b0846e2014-05-24 12:50:23 +00008017 return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
8018}
8019
8020// The basic add/sub long vector instructions have variants with "2" on the end
8021// which act on the high-half of their inputs. They are normally matched by
8022// patterns like:
8023//
8024// (add (zeroext (extract_high LHS)),
8025// (zeroext (extract_high RHS)))
8026// -> uaddl2 vD, vN, vM
8027//
8028// However, if one of the extracts is something like a duplicate, this
8029// instruction can still be used profitably. This function puts the DAG into a
8030// more appropriate form for those patterns to trigger.
8031static SDValue performAddSubLongCombine(SDNode *N,
8032 TargetLowering::DAGCombinerInfo &DCI,
8033 SelectionDAG &DAG) {
8034 if (DCI.isBeforeLegalizeOps())
8035 return SDValue();
8036
8037 MVT VT = N->getSimpleValueType(0);
8038 if (!VT.is128BitVector()) {
8039 if (N->getOpcode() == ISD::ADD)
8040 return performSetccAddFolding(N, DAG);
8041 return SDValue();
8042 }
8043
8044 // Make sure both branches are extended in the same way.
8045 SDValue LHS = N->getOperand(0);
8046 SDValue RHS = N->getOperand(1);
8047 if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
8048 LHS.getOpcode() != ISD::SIGN_EXTEND) ||
8049 LHS.getOpcode() != RHS.getOpcode())
8050 return SDValue();
8051
8052 unsigned ExtType = LHS.getOpcode();
8053
8054 // It's not worth doing if at least one of the inputs isn't already an
8055 // extract, but we don't know which it'll be so we have to try both.
8056 if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
8057 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
8058 if (!RHS.getNode())
8059 return SDValue();
8060
8061 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
8062 } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
8063 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
8064 if (!LHS.getNode())
8065 return SDValue();
8066
8067 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
8068 }
8069
8070 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
8071}
8072
8073// Massage DAGs which we can use the high-half "long" operations on into
8074// something isel will recognize better. E.g.
8075//
8076// (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
8077// (aarch64_neon_umull (extract_high (v2i64 vec)))
8078// (extract_high (v2i64 (dup128 scalar)))))
8079//
James Molloyfaf4e3c2015-07-17 17:10:45 +00008080static SDValue tryCombineLongOpWithDup(SDNode *N,
Tim Northover3b0846e2014-05-24 12:50:23 +00008081 TargetLowering::DAGCombinerInfo &DCI,
8082 SelectionDAG &DAG) {
8083 if (DCI.isBeforeLegalizeOps())
8084 return SDValue();
8085
James Molloyfaf4e3c2015-07-17 17:10:45 +00008086 bool IsIntrinsic = N->getOpcode() == ISD::INTRINSIC_WO_CHAIN;
8087 SDValue LHS = N->getOperand(IsIntrinsic ? 1 : 0);
8088 SDValue RHS = N->getOperand(IsIntrinsic ? 2 : 1);
Tim Northover3b0846e2014-05-24 12:50:23 +00008089 assert(LHS.getValueType().is64BitVector() &&
8090 RHS.getValueType().is64BitVector() &&
8091 "unexpected shape for long operation");
8092
8093 // Either node could be a DUP, but it's not worth doing both of them (you'd
8094 // just as well use the non-high version) so look for a corresponding extract
8095 // operation on the other "wing".
8096 if (isEssentiallyExtractSubvector(LHS)) {
8097 RHS = tryExtendDUPToExtractHigh(RHS, DAG);
8098 if (!RHS.getNode())
8099 return SDValue();
8100 } else if (isEssentiallyExtractSubvector(RHS)) {
8101 LHS = tryExtendDUPToExtractHigh(LHS, DAG);
8102 if (!LHS.getNode())
8103 return SDValue();
8104 }
8105
James Molloyfaf4e3c2015-07-17 17:10:45 +00008106 // N could either be an intrinsic or a sabsdiff/uabsdiff node.
8107 if (IsIntrinsic)
8108 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
8109 N->getOperand(0), LHS, RHS);
8110 else
8111 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
8112 LHS, RHS);
Tim Northover3b0846e2014-05-24 12:50:23 +00008113}
8114
8115static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
8116 MVT ElemTy = N->getSimpleValueType(0).getScalarType();
8117 unsigned ElemBits = ElemTy.getSizeInBits();
8118
8119 int64_t ShiftAmount;
8120 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
8121 APInt SplatValue, SplatUndef;
8122 unsigned SplatBitSize;
8123 bool HasAnyUndefs;
8124 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
8125 HasAnyUndefs, ElemBits) ||
8126 SplatBitSize != ElemBits)
8127 return SDValue();
8128
8129 ShiftAmount = SplatValue.getSExtValue();
8130 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
8131 ShiftAmount = CVN->getSExtValue();
8132 } else
8133 return SDValue();
8134
8135 unsigned Opcode;
8136 bool IsRightShift;
8137 switch (IID) {
8138 default:
8139 llvm_unreachable("Unknown shift intrinsic");
8140 case Intrinsic::aarch64_neon_sqshl:
8141 Opcode = AArch64ISD::SQSHL_I;
8142 IsRightShift = false;
8143 break;
8144 case Intrinsic::aarch64_neon_uqshl:
8145 Opcode = AArch64ISD::UQSHL_I;
8146 IsRightShift = false;
8147 break;
8148 case Intrinsic::aarch64_neon_srshl:
8149 Opcode = AArch64ISD::SRSHR_I;
8150 IsRightShift = true;
8151 break;
8152 case Intrinsic::aarch64_neon_urshl:
8153 Opcode = AArch64ISD::URSHR_I;
8154 IsRightShift = true;
8155 break;
8156 case Intrinsic::aarch64_neon_sqshlu:
8157 Opcode = AArch64ISD::SQSHLU_I;
8158 IsRightShift = false;
8159 break;
8160 }
8161
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008162 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
8163 SDLoc dl(N);
8164 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8165 DAG.getConstant(-ShiftAmount, dl, MVT::i32));
8166 } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
8167 SDLoc dl(N);
8168 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8169 DAG.getConstant(ShiftAmount, dl, MVT::i32));
8170 }
Tim Northover3b0846e2014-05-24 12:50:23 +00008171
8172 return SDValue();
8173}
8174
8175// The CRC32[BH] instructions ignore the high bits of their data operand. Since
8176// the intrinsics must be legal and take an i32, this means there's almost
8177// certainly going to be a zext in the DAG which we can eliminate.
8178static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
8179 SDValue AndN = N->getOperand(2);
8180 if (AndN.getOpcode() != ISD::AND)
8181 return SDValue();
8182
8183 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
8184 if (!CMask || CMask->getZExtValue() != Mask)
8185 return SDValue();
8186
8187 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
8188 N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
8189}
8190
Ahmed Bougachafab58922015-03-10 20:45:38 +00008191static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
8192 SelectionDAG &DAG) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008193 SDLoc dl(N);
8194 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
8195 DAG.getNode(Opc, dl,
Ahmed Bougachafab58922015-03-10 20:45:38 +00008196 N->getOperand(1).getSimpleValueType(),
8197 N->getOperand(1)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008198 DAG.getConstant(0, dl, MVT::i64));
Ahmed Bougachafab58922015-03-10 20:45:38 +00008199}
8200
Tim Northover3b0846e2014-05-24 12:50:23 +00008201static SDValue performIntrinsicCombine(SDNode *N,
8202 TargetLowering::DAGCombinerInfo &DCI,
8203 const AArch64Subtarget *Subtarget) {
8204 SelectionDAG &DAG = DCI.DAG;
8205 unsigned IID = getIntrinsicID(N);
8206 switch (IID) {
8207 default:
8208 break;
8209 case Intrinsic::aarch64_neon_vcvtfxs2fp:
8210 case Intrinsic::aarch64_neon_vcvtfxu2fp:
8211 return tryCombineFixedPointConvert(N, DCI, DAG);
Ahmed Bougachafab58922015-03-10 20:45:38 +00008212 case Intrinsic::aarch64_neon_saddv:
8213 return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
8214 case Intrinsic::aarch64_neon_uaddv:
8215 return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
8216 case Intrinsic::aarch64_neon_sminv:
8217 return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
8218 case Intrinsic::aarch64_neon_uminv:
8219 return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
8220 case Intrinsic::aarch64_neon_smaxv:
8221 return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
8222 case Intrinsic::aarch64_neon_umaxv:
8223 return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00008224 case Intrinsic::aarch64_neon_fmax:
James Molloyedf38f02015-08-11 12:06:33 +00008225 return DAG.getNode(ISD::FMAXNAN, SDLoc(N), N->getValueType(0),
Tim Northover3b0846e2014-05-24 12:50:23 +00008226 N->getOperand(1), N->getOperand(2));
8227 case Intrinsic::aarch64_neon_fmin:
James Molloyedf38f02015-08-11 12:06:33 +00008228 return DAG.getNode(ISD::FMINNAN, SDLoc(N), N->getValueType(0),
Tim Northover3b0846e2014-05-24 12:50:23 +00008229 N->getOperand(1), N->getOperand(2));
James Molloyfaf4e3c2015-07-17 17:10:45 +00008230 case Intrinsic::aarch64_neon_sabd:
8231 return DAG.getNode(ISD::SABSDIFF, SDLoc(N), N->getValueType(0),
8232 N->getOperand(1), N->getOperand(2));
8233 case Intrinsic::aarch64_neon_uabd:
8234 return DAG.getNode(ISD::UABSDIFF, SDLoc(N), N->getValueType(0),
8235 N->getOperand(1), N->getOperand(2));
James Molloyb7b2a1e2015-08-11 12:06:37 +00008236 case Intrinsic::aarch64_neon_fmaxnm:
8237 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
8238 N->getOperand(1), N->getOperand(2));
8239 case Intrinsic::aarch64_neon_fminnm:
8240 return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
8241 N->getOperand(1), N->getOperand(2));
Tim Northover3b0846e2014-05-24 12:50:23 +00008242 case Intrinsic::aarch64_neon_smull:
8243 case Intrinsic::aarch64_neon_umull:
8244 case Intrinsic::aarch64_neon_pmull:
8245 case Intrinsic::aarch64_neon_sqdmull:
James Molloyfaf4e3c2015-07-17 17:10:45 +00008246 return tryCombineLongOpWithDup(N, DCI, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00008247 case Intrinsic::aarch64_neon_sqshl:
8248 case Intrinsic::aarch64_neon_uqshl:
8249 case Intrinsic::aarch64_neon_sqshlu:
8250 case Intrinsic::aarch64_neon_srshl:
8251 case Intrinsic::aarch64_neon_urshl:
8252 return tryCombineShiftImm(IID, N, DAG);
8253 case Intrinsic::aarch64_crc32b:
8254 case Intrinsic::aarch64_crc32cb:
8255 return tryCombineCRC32(0xff, N, DAG);
8256 case Intrinsic::aarch64_crc32h:
8257 case Intrinsic::aarch64_crc32ch:
8258 return tryCombineCRC32(0xffff, N, DAG);
8259 }
8260 return SDValue();
8261}
8262
8263static SDValue performExtendCombine(SDNode *N,
8264 TargetLowering::DAGCombinerInfo &DCI,
8265 SelectionDAG &DAG) {
8266 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
8267 // we can convert that DUP into another extract_high (of a bigger DUP), which
8268 // helps the backend to decide that an sabdl2 would be useful, saving a real
8269 // extract_high operation.
8270 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
James Molloyfaf4e3c2015-07-17 17:10:45 +00008271 (N->getOperand(0).getOpcode() == ISD::SABSDIFF ||
8272 N->getOperand(0).getOpcode() == ISD::UABSDIFF)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00008273 SDNode *ABDNode = N->getOperand(0).getNode();
James Molloyfaf4e3c2015-07-17 17:10:45 +00008274 SDValue NewABD = tryCombineLongOpWithDup(ABDNode, DCI, DAG);
8275 if (!NewABD.getNode())
8276 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00008277
James Molloyfaf4e3c2015-07-17 17:10:45 +00008278 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
8279 NewABD);
Tim Northover3b0846e2014-05-24 12:50:23 +00008280 }
8281
8282 // This is effectively a custom type legalization for AArch64.
8283 //
8284 // Type legalization will split an extend of a small, legal, type to a larger
8285 // illegal type by first splitting the destination type, often creating
8286 // illegal source types, which then get legalized in isel-confusing ways,
8287 // leading to really terrible codegen. E.g.,
8288 // %result = v8i32 sext v8i8 %value
8289 // becomes
8290 // %losrc = extract_subreg %value, ...
8291 // %hisrc = extract_subreg %value, ...
8292 // %lo = v4i32 sext v4i8 %losrc
8293 // %hi = v4i32 sext v4i8 %hisrc
8294 // Things go rapidly downhill from there.
8295 //
8296 // For AArch64, the [sz]ext vector instructions can only go up one element
8297 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
8298 // take two instructions.
8299 //
8300 // This implies that the most efficient way to do the extend from v8i8
8301 // to two v4i32 values is to first extend the v8i8 to v8i16, then do
8302 // the normal splitting to happen for the v8i16->v8i32.
8303
8304 // This is pre-legalization to catch some cases where the default
8305 // type legalization will create ill-tempered code.
8306 if (!DCI.isBeforeLegalizeOps())
8307 return SDValue();
8308
8309 // We're only interested in cleaning things up for non-legal vector types
8310 // here. If both the source and destination are legal, things will just
8311 // work naturally without any fiddling.
8312 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8313 EVT ResVT = N->getValueType(0);
8314 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
8315 return SDValue();
8316 // If the vector type isn't a simple VT, it's beyond the scope of what
8317 // we're worried about here. Let legalization do its thing and hope for
8318 // the best.
Jim Grosbachec2b0d02014-08-28 22:08:28 +00008319 SDValue Src = N->getOperand(0);
8320 EVT SrcVT = Src->getValueType(0);
8321 if (!ResVT.isSimple() || !SrcVT.isSimple())
Tim Northover3b0846e2014-05-24 12:50:23 +00008322 return SDValue();
8323
Tim Northover3b0846e2014-05-24 12:50:23 +00008324 // If the source VT is a 64-bit vector, we can play games and get the
8325 // better results we want.
8326 if (SrcVT.getSizeInBits() != 64)
8327 return SDValue();
8328
8329 unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits();
8330 unsigned ElementCount = SrcVT.getVectorNumElements();
8331 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
8332 SDLoc DL(N);
8333 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
8334
8335 // Now split the rest of the operation into two halves, each with a 64
8336 // bit source.
8337 EVT LoVT, HiVT;
8338 SDValue Lo, Hi;
8339 unsigned NumElements = ResVT.getVectorNumElements();
8340 assert(!(NumElements & 1) && "Splitting vector, but not in half!");
8341 LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
8342 ResVT.getVectorElementType(), NumElements / 2);
8343
8344 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
8345 LoVT.getVectorNumElements());
8346 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008347 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008348 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008349 DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008350 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
8351 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
8352
8353 // Now combine the parts back together so we still have a single result
8354 // like the combiner expects.
8355 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
8356}
8357
8358/// Replace a splat of a scalar to a vector store by scalar stores of the scalar
8359/// value. The load store optimizer pass will merge them to store pair stores.
8360/// This has better performance than a splat of the scalar followed by a split
8361/// vector store. Even if the stores are not merged it is four stores vs a dup,
8362/// followed by an ext.b and two stores.
8363static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode *St) {
8364 SDValue StVal = St->getValue();
8365 EVT VT = StVal.getValueType();
8366
8367 // Don't replace floating point stores, they possibly won't be transformed to
8368 // stp because of the store pair suppress pass.
8369 if (VT.isFloatingPoint())
8370 return SDValue();
8371
8372 // Check for insert vector elements.
8373 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
8374 return SDValue();
8375
8376 // We can express a splat as store pair(s) for 2 or 4 elements.
8377 unsigned NumVecElts = VT.getVectorNumElements();
8378 if (NumVecElts != 4 && NumVecElts != 2)
8379 return SDValue();
8380 SDValue SplatVal = StVal.getOperand(1);
8381 unsigned RemainInsertElts = NumVecElts - 1;
8382
8383 // Check that this is a splat.
8384 while (--RemainInsertElts) {
8385 SDValue NextInsertElt = StVal.getOperand(0);
8386 if (NextInsertElt.getOpcode() != ISD::INSERT_VECTOR_ELT)
8387 return SDValue();
8388 if (NextInsertElt.getOperand(1) != SplatVal)
8389 return SDValue();
8390 StVal = NextInsertElt;
8391 }
8392 unsigned OrigAlignment = St->getAlignment();
8393 unsigned EltOffset = NumVecElts == 4 ? 4 : 8;
8394 unsigned Alignment = std::min(OrigAlignment, EltOffset);
8395
8396 // Create scalar stores. This is at least as good as the code sequence for a
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00008397 // split unaligned store which is a dup.s, ext.b, and two stores.
Tim Northover3b0846e2014-05-24 12:50:23 +00008398 // Most of the time the three stores should be replaced by store pair
8399 // instructions (stp).
8400 SDLoc DL(St);
8401 SDValue BasePtr = St->getBasePtr();
8402 SDValue NewST1 =
8403 DAG.getStore(St->getChain(), DL, SplatVal, BasePtr, St->getPointerInfo(),
8404 St->isVolatile(), St->isNonTemporal(), St->getAlignment());
8405
8406 unsigned Offset = EltOffset;
8407 while (--NumVecElts) {
8408 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008409 DAG.getConstant(Offset, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008410 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
8411 St->getPointerInfo(), St->isVolatile(),
8412 St->isNonTemporal(), Alignment);
8413 Offset += EltOffset;
8414 }
8415 return NewST1;
8416}
8417
8418static SDValue performSTORECombine(SDNode *N,
8419 TargetLowering::DAGCombinerInfo &DCI,
8420 SelectionDAG &DAG,
8421 const AArch64Subtarget *Subtarget) {
8422 if (!DCI.isBeforeLegalize())
8423 return SDValue();
8424
8425 StoreSDNode *S = cast<StoreSDNode>(N);
8426 if (S->isVolatile())
8427 return SDValue();
8428
8429 // Cyclone has bad performance on unaligned 16B stores when crossing line and
Sanjay Patel08efcd92015-01-28 22:37:32 +00008430 // page boundaries. We want to split such stores.
Tim Northover3b0846e2014-05-24 12:50:23 +00008431 if (!Subtarget->isCyclone())
8432 return SDValue();
8433
Sanjay Patel924879a2015-08-04 15:49:57 +00008434 // Don't split at -Oz.
8435 if (DAG.getMachineFunction().getFunction()->optForMinSize())
Tim Northover3b0846e2014-05-24 12:50:23 +00008436 return SDValue();
8437
8438 SDValue StVal = S->getValue();
8439 EVT VT = StVal.getValueType();
8440
8441 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
8442 // those up regresses performance on micro-benchmarks and olden/bh.
8443 if (!VT.isVector() || VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
8444 return SDValue();
8445
8446 // Split unaligned 16B stores. They are terrible for performance.
8447 // Don't split stores with alignment of 1 or 2. Code that uses clang vector
8448 // extensions can use this to mark that it does not want splitting to happen
8449 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
8450 // eliminating alignment hazards is only 1 in 8 for alignment of 2.
8451 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
8452 S->getAlignment() <= 2)
8453 return SDValue();
8454
8455 // If we get a splat of a scalar convert this vector store to a store of
8456 // scalars. They will be merged into store pairs thereby removing two
8457 // instructions.
Ahmed Bougacha239d6352015-08-04 00:48:02 +00008458 if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, S))
Tim Northover3b0846e2014-05-24 12:50:23 +00008459 return ReplacedSplat;
8460
8461 SDLoc DL(S);
8462 unsigned NumElts = VT.getVectorNumElements() / 2;
8463 // Split VT into two.
8464 EVT HalfVT =
8465 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
8466 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008467 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008468 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008469 DAG.getConstant(NumElts, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008470 SDValue BasePtr = S->getBasePtr();
8471 SDValue NewST1 =
8472 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
8473 S->isVolatile(), S->isNonTemporal(), S->getAlignment());
8474 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008475 DAG.getConstant(8, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008476 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
8477 S->getPointerInfo(), S->isVolatile(), S->isNonTemporal(),
8478 S->getAlignment());
8479}
8480
8481/// Target-specific DAG combine function for post-increment LD1 (lane) and
8482/// post-increment LD1R.
8483static SDValue performPostLD1Combine(SDNode *N,
8484 TargetLowering::DAGCombinerInfo &DCI,
8485 bool IsLaneOp) {
8486 if (DCI.isBeforeLegalizeOps())
8487 return SDValue();
8488
8489 SelectionDAG &DAG = DCI.DAG;
8490 EVT VT = N->getValueType(0);
8491
8492 unsigned LoadIdx = IsLaneOp ? 1 : 0;
8493 SDNode *LD = N->getOperand(LoadIdx).getNode();
8494 // If it is not LOAD, can not do such combine.
8495 if (LD->getOpcode() != ISD::LOAD)
8496 return SDValue();
8497
8498 LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
8499 EVT MemVT = LoadSDN->getMemoryVT();
8500 // Check if memory operand is the same type as the vector element.
8501 if (MemVT != VT.getVectorElementType())
8502 return SDValue();
8503
8504 // Check if there are other uses. If so, do not combine as it will introduce
8505 // an extra load.
8506 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
8507 ++UI) {
8508 if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
8509 continue;
8510 if (*UI != N)
8511 return SDValue();
8512 }
8513
8514 SDValue Addr = LD->getOperand(1);
8515 SDValue Vector = N->getOperand(0);
8516 // Search for a use of the address operand that is an increment.
8517 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
8518 Addr.getNode()->use_end(); UI != UE; ++UI) {
8519 SDNode *User = *UI;
8520 if (User->getOpcode() != ISD::ADD
8521 || UI.getUse().getResNo() != Addr.getResNo())
8522 continue;
8523
8524 // Check that the add is independent of the load. Otherwise, folding it
8525 // would create a cycle.
8526 if (User->isPredecessorOf(LD) || LD->isPredecessorOf(User))
8527 continue;
8528 // Also check that add is not used in the vector operand. This would also
8529 // create a cycle.
8530 if (User->isPredecessorOf(Vector.getNode()))
8531 continue;
8532
8533 // If the increment is a constant, it must match the memory ref size.
8534 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8535 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8536 uint32_t IncVal = CInc->getZExtValue();
8537 unsigned NumBytes = VT.getScalarSizeInBits() / 8;
8538 if (IncVal != NumBytes)
8539 continue;
8540 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
8541 }
8542
Ahmed Bougacha2448ef52015-04-17 21:02:30 +00008543 // Finally, check that the vector doesn't depend on the load.
8544 // Again, this would create a cycle.
8545 // The load depending on the vector is fine, as that's the case for the
8546 // LD1*post we'll eventually generate anyway.
8547 if (LoadSDN->isPredecessorOf(Vector.getNode()))
8548 continue;
8549
Tim Northover3b0846e2014-05-24 12:50:23 +00008550 SmallVector<SDValue, 8> Ops;
8551 Ops.push_back(LD->getOperand(0)); // Chain
8552 if (IsLaneOp) {
8553 Ops.push_back(Vector); // The vector to be inserted
8554 Ops.push_back(N->getOperand(2)); // The lane to be inserted in the vector
8555 }
8556 Ops.push_back(Addr);
8557 Ops.push_back(Inc);
8558
8559 EVT Tys[3] = { VT, MVT::i64, MVT::Other };
Craig Toppere1d12942014-08-27 05:25:25 +00008560 SDVTList SDTys = DAG.getVTList(Tys);
Tim Northover3b0846e2014-05-24 12:50:23 +00008561 unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
8562 SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
8563 MemVT,
8564 LoadSDN->getMemOperand());
8565
8566 // Update the uses.
Ahmed Bougacha4c2b0782015-02-19 23:13:10 +00008567 SmallVector<SDValue, 2> NewResults;
Tim Northover3b0846e2014-05-24 12:50:23 +00008568 NewResults.push_back(SDValue(LD, 0)); // The result of load
8569 NewResults.push_back(SDValue(UpdN.getNode(), 2)); // Chain
8570 DCI.CombineTo(LD, NewResults);
8571 DCI.CombineTo(N, SDValue(UpdN.getNode(), 0)); // Dup/Inserted Result
8572 DCI.CombineTo(User, SDValue(UpdN.getNode(), 1)); // Write back register
8573
8574 break;
8575 }
8576 return SDValue();
8577}
8578
8579/// Target-specific DAG combine function for NEON load/store intrinsics
8580/// to merge base address updates.
8581static SDValue performNEONPostLDSTCombine(SDNode *N,
8582 TargetLowering::DAGCombinerInfo &DCI,
8583 SelectionDAG &DAG) {
8584 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8585 return SDValue();
8586
8587 unsigned AddrOpIdx = N->getNumOperands() - 1;
8588 SDValue Addr = N->getOperand(AddrOpIdx);
8589
8590 // Search for a use of the address operand that is an increment.
8591 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8592 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8593 SDNode *User = *UI;
8594 if (User->getOpcode() != ISD::ADD ||
8595 UI.getUse().getResNo() != Addr.getResNo())
8596 continue;
8597
8598 // Check that the add is independent of the load/store. Otherwise, folding
8599 // it would create a cycle.
8600 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8601 continue;
8602
8603 // Find the new opcode for the updating load/store.
8604 bool IsStore = false;
8605 bool IsLaneOp = false;
8606 bool IsDupOp = false;
8607 unsigned NewOpc = 0;
8608 unsigned NumVecs = 0;
8609 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8610 switch (IntNo) {
8611 default: llvm_unreachable("unexpected intrinsic for Neon base update");
8612 case Intrinsic::aarch64_neon_ld2: NewOpc = AArch64ISD::LD2post;
8613 NumVecs = 2; break;
8614 case Intrinsic::aarch64_neon_ld3: NewOpc = AArch64ISD::LD3post;
8615 NumVecs = 3; break;
8616 case Intrinsic::aarch64_neon_ld4: NewOpc = AArch64ISD::LD4post;
8617 NumVecs = 4; break;
8618 case Intrinsic::aarch64_neon_st2: NewOpc = AArch64ISD::ST2post;
8619 NumVecs = 2; IsStore = true; break;
8620 case Intrinsic::aarch64_neon_st3: NewOpc = AArch64ISD::ST3post;
8621 NumVecs = 3; IsStore = true; break;
8622 case Intrinsic::aarch64_neon_st4: NewOpc = AArch64ISD::ST4post;
8623 NumVecs = 4; IsStore = true; break;
8624 case Intrinsic::aarch64_neon_ld1x2: NewOpc = AArch64ISD::LD1x2post;
8625 NumVecs = 2; break;
8626 case Intrinsic::aarch64_neon_ld1x3: NewOpc = AArch64ISD::LD1x3post;
8627 NumVecs = 3; break;
8628 case Intrinsic::aarch64_neon_ld1x4: NewOpc = AArch64ISD::LD1x4post;
8629 NumVecs = 4; break;
8630 case Intrinsic::aarch64_neon_st1x2: NewOpc = AArch64ISD::ST1x2post;
8631 NumVecs = 2; IsStore = true; break;
8632 case Intrinsic::aarch64_neon_st1x3: NewOpc = AArch64ISD::ST1x3post;
8633 NumVecs = 3; IsStore = true; break;
8634 case Intrinsic::aarch64_neon_st1x4: NewOpc = AArch64ISD::ST1x4post;
8635 NumVecs = 4; IsStore = true; break;
8636 case Intrinsic::aarch64_neon_ld2r: NewOpc = AArch64ISD::LD2DUPpost;
8637 NumVecs = 2; IsDupOp = true; break;
8638 case Intrinsic::aarch64_neon_ld3r: NewOpc = AArch64ISD::LD3DUPpost;
8639 NumVecs = 3; IsDupOp = true; break;
8640 case Intrinsic::aarch64_neon_ld4r: NewOpc = AArch64ISD::LD4DUPpost;
8641 NumVecs = 4; IsDupOp = true; break;
8642 case Intrinsic::aarch64_neon_ld2lane: NewOpc = AArch64ISD::LD2LANEpost;
8643 NumVecs = 2; IsLaneOp = true; break;
8644 case Intrinsic::aarch64_neon_ld3lane: NewOpc = AArch64ISD::LD3LANEpost;
8645 NumVecs = 3; IsLaneOp = true; break;
8646 case Intrinsic::aarch64_neon_ld4lane: NewOpc = AArch64ISD::LD4LANEpost;
8647 NumVecs = 4; IsLaneOp = true; break;
8648 case Intrinsic::aarch64_neon_st2lane: NewOpc = AArch64ISD::ST2LANEpost;
8649 NumVecs = 2; IsStore = true; IsLaneOp = true; break;
8650 case Intrinsic::aarch64_neon_st3lane: NewOpc = AArch64ISD::ST3LANEpost;
8651 NumVecs = 3; IsStore = true; IsLaneOp = true; break;
8652 case Intrinsic::aarch64_neon_st4lane: NewOpc = AArch64ISD::ST4LANEpost;
8653 NumVecs = 4; IsStore = true; IsLaneOp = true; break;
8654 }
8655
8656 EVT VecTy;
8657 if (IsStore)
8658 VecTy = N->getOperand(2).getValueType();
8659 else
8660 VecTy = N->getValueType(0);
8661
8662 // If the increment is a constant, it must match the memory ref size.
8663 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8664 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8665 uint32_t IncVal = CInc->getZExtValue();
8666 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8667 if (IsLaneOp || IsDupOp)
8668 NumBytes /= VecTy.getVectorNumElements();
8669 if (IncVal != NumBytes)
8670 continue;
8671 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
8672 }
8673 SmallVector<SDValue, 8> Ops;
8674 Ops.push_back(N->getOperand(0)); // Incoming chain
8675 // Load lane and store have vector list as input.
8676 if (IsLaneOp || IsStore)
8677 for (unsigned i = 2; i < AddrOpIdx; ++i)
8678 Ops.push_back(N->getOperand(i));
8679 Ops.push_back(Addr); // Base register
8680 Ops.push_back(Inc);
8681
8682 // Return Types.
8683 EVT Tys[6];
8684 unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
8685 unsigned n;
8686 for (n = 0; n < NumResultVecs; ++n)
8687 Tys[n] = VecTy;
8688 Tys[n++] = MVT::i64; // Type of write back register
8689 Tys[n] = MVT::Other; // Type of the chain
Craig Toppere1d12942014-08-27 05:25:25 +00008690 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
Tim Northover3b0846e2014-05-24 12:50:23 +00008691
8692 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8693 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
8694 MemInt->getMemoryVT(),
8695 MemInt->getMemOperand());
8696
8697 // Update the uses.
8698 std::vector<SDValue> NewResults;
8699 for (unsigned i = 0; i < NumResultVecs; ++i) {
8700 NewResults.push_back(SDValue(UpdN.getNode(), i));
8701 }
8702 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
8703 DCI.CombineTo(N, NewResults);
8704 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8705
8706 break;
8707 }
8708 return SDValue();
8709}
8710
Louis Gerbarg03c627e2014-08-29 21:00:22 +00008711// Checks to see if the value is the prescribed width and returns information
8712// about its extension mode.
8713static
8714bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
8715 ExtType = ISD::NON_EXTLOAD;
8716 switch(V.getNode()->getOpcode()) {
8717 default:
8718 return false;
8719 case ISD::LOAD: {
8720 LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
8721 if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
8722 || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
8723 ExtType = LoadNode->getExtensionType();
8724 return true;
8725 }
8726 return false;
8727 }
8728 case ISD::AssertSext: {
8729 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
8730 if ((TypeNode->getVT() == MVT::i8 && width == 8)
8731 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
8732 ExtType = ISD::SEXTLOAD;
8733 return true;
8734 }
8735 return false;
8736 }
8737 case ISD::AssertZext: {
8738 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
8739 if ((TypeNode->getVT() == MVT::i8 && width == 8)
8740 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
8741 ExtType = ISD::ZEXTLOAD;
8742 return true;
8743 }
8744 return false;
8745 }
8746 case ISD::Constant:
8747 case ISD::TargetConstant: {
Reid Kleckner39ad7c92014-08-29 22:14:26 +00008748 if (std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
Aaron Ballman8ca53882014-09-02 12:19:02 +00008749 1LL << (width - 1))
Louis Gerbarg03c627e2014-08-29 21:00:22 +00008750 return true;
8751 return false;
8752 }
8753 }
8754
8755 return true;
8756}
8757
8758// This function does a whole lot of voodoo to determine if the tests are
8759// equivalent without and with a mask. Essentially what happens is that given a
8760// DAG resembling:
8761//
8762// +-------------+ +-------------+ +-------------+ +-------------+
8763// | Input | | AddConstant | | CompConstant| | CC |
8764// +-------------+ +-------------+ +-------------+ +-------------+
8765// | | | |
8766// V V | +----------+
8767// +-------------+ +----+ | |
8768// | ADD | |0xff| | |
8769// +-------------+ +----+ | |
8770// | | | |
8771// V V | |
8772// +-------------+ | |
8773// | AND | | |
8774// +-------------+ | |
8775// | | |
8776// +-----+ | |
8777// | | |
8778// V V V
8779// +-------------+
8780// | CMP |
8781// +-------------+
8782//
8783// The AND node may be safely removed for some combinations of inputs. In
8784// particular we need to take into account the extension type of the Input,
8785// the exact values of AddConstant, CompConstant, and CC, along with the nominal
8786// width of the input (this can work for any width inputs, the above graph is
8787// specific to 8 bits.
8788//
8789// The specific equations were worked out by generating output tables for each
8790// AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
8791// problem was simplified by working with 4 bit inputs, which means we only
8792// needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
8793// extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
8794// patterns present in both extensions (0,7). For every distinct set of
8795// AddConstant and CompConstants bit patterns we can consider the masked and
8796// unmasked versions to be equivalent if the result of this function is true for
8797// all 16 distinct bit patterns of for the current extension type of Input (w0).
8798//
8799// sub w8, w0, w1
8800// and w10, w8, #0x0f
8801// cmp w8, w2
8802// cset w9, AArch64CC
8803// cmp w10, w2
8804// cset w11, AArch64CC
8805// cmp w9, w11
8806// cset w0, eq
8807// ret
8808//
8809// Since the above function shows when the outputs are equivalent it defines
8810// when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
8811// would be expensive to run during compiles. The equations below were written
8812// in a test harness that confirmed they gave equivalent outputs to the above
8813// for all inputs function, so they can be used determine if the removal is
8814// legal instead.
8815//
8816// isEquivalentMaskless() is the code for testing if the AND can be removed
8817// factored out of the DAG recognition as the DAG can take several forms.
8818
8819static
8820bool isEquivalentMaskless(unsigned CC, unsigned width,
8821 ISD::LoadExtType ExtType, signed AddConstant,
8822 signed CompConstant) {
8823 // By being careful about our equations and only writing the in term
8824 // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
8825 // make them generally applicable to all bit widths.
8826 signed MaxUInt = (1 << width);
8827
8828 // For the purposes of these comparisons sign extending the type is
8829 // equivalent to zero extending the add and displacing it by half the integer
8830 // width. Provided we are careful and make sure our equations are valid over
8831 // the whole range we can just adjust the input and avoid writing equations
8832 // for sign extended inputs.
8833 if (ExtType == ISD::SEXTLOAD)
8834 AddConstant -= (1 << (width-1));
8835
8836 switch(CC) {
8837 case AArch64CC::LE:
8838 case AArch64CC::GT: {
8839 if ((AddConstant == 0) ||
8840 (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
8841 (AddConstant >= 0 && CompConstant < 0) ||
8842 (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
8843 return true;
8844 } break;
8845 case AArch64CC::LT:
8846 case AArch64CC::GE: {
8847 if ((AddConstant == 0) ||
8848 (AddConstant >= 0 && CompConstant <= 0) ||
8849 (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
8850 return true;
8851 } break;
8852 case AArch64CC::HI:
8853 case AArch64CC::LS: {
8854 if ((AddConstant >= 0 && CompConstant < 0) ||
8855 (AddConstant <= 0 && CompConstant >= -1 &&
8856 CompConstant < AddConstant + MaxUInt))
8857 return true;
8858 } break;
8859 case AArch64CC::PL:
8860 case AArch64CC::MI: {
8861 if ((AddConstant == 0) ||
8862 (AddConstant > 0 && CompConstant <= 0) ||
8863 (AddConstant < 0 && CompConstant <= AddConstant))
8864 return true;
8865 } break;
8866 case AArch64CC::LO:
8867 case AArch64CC::HS: {
8868 if ((AddConstant >= 0 && CompConstant <= 0) ||
8869 (AddConstant <= 0 && CompConstant >= 0 &&
8870 CompConstant <= AddConstant + MaxUInt))
8871 return true;
8872 } break;
8873 case AArch64CC::EQ:
8874 case AArch64CC::NE: {
8875 if ((AddConstant > 0 && CompConstant < 0) ||
8876 (AddConstant < 0 && CompConstant >= 0 &&
8877 CompConstant < AddConstant + MaxUInt) ||
8878 (AddConstant >= 0 && CompConstant >= 0 &&
8879 CompConstant >= AddConstant) ||
8880 (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
8881
8882 return true;
8883 } break;
8884 case AArch64CC::VS:
8885 case AArch64CC::VC:
8886 case AArch64CC::AL:
8887 case AArch64CC::NV:
8888 return true;
8889 case AArch64CC::Invalid:
8890 break;
8891 }
8892
8893 return false;
8894}
8895
8896static
8897SDValue performCONDCombine(SDNode *N,
8898 TargetLowering::DAGCombinerInfo &DCI,
8899 SelectionDAG &DAG, unsigned CCIndex,
8900 unsigned CmpIndex) {
8901 unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
8902 SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
8903 unsigned CondOpcode = SubsNode->getOpcode();
8904
8905 if (CondOpcode != AArch64ISD::SUBS)
8906 return SDValue();
8907
8908 // There is a SUBS feeding this condition. Is it fed by a mask we can
8909 // use?
8910
8911 SDNode *AndNode = SubsNode->getOperand(0).getNode();
8912 unsigned MaskBits = 0;
8913
8914 if (AndNode->getOpcode() != ISD::AND)
8915 return SDValue();
8916
8917 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
8918 uint32_t CNV = CN->getZExtValue();
8919 if (CNV == 255)
8920 MaskBits = 8;
8921 else if (CNV == 65535)
8922 MaskBits = 16;
8923 }
8924
8925 if (!MaskBits)
8926 return SDValue();
8927
8928 SDValue AddValue = AndNode->getOperand(0);
8929
8930 if (AddValue.getOpcode() != ISD::ADD)
8931 return SDValue();
8932
8933 // The basic dag structure is correct, grab the inputs and validate them.
8934
8935 SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
8936 SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
8937 SDValue SubsInputValue = SubsNode->getOperand(1);
8938
8939 // The mask is present and the provenance of all the values is a smaller type,
8940 // lets see if the mask is superfluous.
8941
8942 if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
8943 !isa<ConstantSDNode>(SubsInputValue.getNode()))
8944 return SDValue();
8945
8946 ISD::LoadExtType ExtType;
8947
8948 if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
8949 !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
8950 !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
8951 return SDValue();
8952
8953 if(!isEquivalentMaskless(CC, MaskBits, ExtType,
8954 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
8955 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
8956 return SDValue();
8957
8958 // The AND is not necessary, remove it.
8959
8960 SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
8961 SubsNode->getValueType(1));
8962 SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
8963
8964 SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
8965 DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
8966
8967 return SDValue(N, 0);
8968}
8969
Tim Northover3b0846e2014-05-24 12:50:23 +00008970// Optimize compare with zero and branch.
8971static SDValue performBRCONDCombine(SDNode *N,
8972 TargetLowering::DAGCombinerInfo &DCI,
8973 SelectionDAG &DAG) {
Louis Gerbarg03c627e2014-08-29 21:00:22 +00008974 SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3);
8975 if (NV.getNode())
8976 N = NV.getNode();
Tim Northover3b0846e2014-05-24 12:50:23 +00008977 SDValue Chain = N->getOperand(0);
8978 SDValue Dest = N->getOperand(1);
8979 SDValue CCVal = N->getOperand(2);
8980 SDValue Cmp = N->getOperand(3);
8981
8982 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
8983 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
8984 if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
8985 return SDValue();
8986
8987 unsigned CmpOpc = Cmp.getOpcode();
8988 if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
8989 return SDValue();
8990
8991 // Only attempt folding if there is only one use of the flag and no use of the
8992 // value.
8993 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
8994 return SDValue();
8995
8996 SDValue LHS = Cmp.getOperand(0);
8997 SDValue RHS = Cmp.getOperand(1);
8998
8999 assert(LHS.getValueType() == RHS.getValueType() &&
9000 "Expected the value type to be the same for both operands!");
9001 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
9002 return SDValue();
9003
9004 if (isa<ConstantSDNode>(LHS) && cast<ConstantSDNode>(LHS)->isNullValue())
9005 std::swap(LHS, RHS);
9006
9007 if (!isa<ConstantSDNode>(RHS) || !cast<ConstantSDNode>(RHS)->isNullValue())
9008 return SDValue();
9009
9010 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
9011 LHS.getOpcode() == ISD::SRL)
9012 return SDValue();
9013
9014 // Fold the compare into the branch instruction.
9015 SDValue BR;
9016 if (CC == AArch64CC::EQ)
9017 BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9018 else
9019 BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9020
9021 // Do not add new nodes to DAG combiner worklist.
9022 DCI.CombineTo(N, BR, false);
9023
9024 return SDValue();
9025}
9026
9027// vselect (v1i1 setcc) ->
9028// vselect (v1iXX setcc) (XX is the size of the compared operand type)
9029// FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
9030// condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
9031// such VSELECT.
9032static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
9033 SDValue N0 = N->getOperand(0);
9034 EVT CCVT = N0.getValueType();
9035
9036 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
9037 CCVT.getVectorElementType() != MVT::i1)
9038 return SDValue();
9039
9040 EVT ResVT = N->getValueType(0);
9041 EVT CmpVT = N0.getOperand(0).getValueType();
9042 // Only combine when the result type is of the same size as the compared
9043 // operands.
9044 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
9045 return SDValue();
9046
9047 SDValue IfTrue = N->getOperand(1);
9048 SDValue IfFalse = N->getOperand(2);
9049 SDValue SetCC =
9050 DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
9051 N0.getOperand(0), N0.getOperand(1),
9052 cast<CondCodeSDNode>(N0.getOperand(2))->get());
9053 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
9054 IfTrue, IfFalse);
9055}
9056
9057/// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
9058/// the compare-mask instructions rather than going via NZCV, even if LHS and
9059/// RHS are really scalar. This replaces any scalar setcc in the above pattern
9060/// with a vector one followed by a DUP shuffle on the result.
Ahmed Bougachac004c602015-04-27 21:43:12 +00009061static SDValue performSelectCombine(SDNode *N,
9062 TargetLowering::DAGCombinerInfo &DCI) {
9063 SelectionDAG &DAG = DCI.DAG;
Tim Northover3b0846e2014-05-24 12:50:23 +00009064 SDValue N0 = N->getOperand(0);
9065 EVT ResVT = N->getValueType(0);
Tim Northover3c0915e2014-08-29 15:34:58 +00009066
Ahmed Bougachac004c602015-04-27 21:43:12 +00009067 if (N0.getOpcode() != ISD::SETCC)
Tim Northover3c0915e2014-08-29 15:34:58 +00009068 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00009069
Ahmed Bougachac004c602015-04-27 21:43:12 +00009070 // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
9071 // scalar SetCCResultType. We also don't expect vectors, because we assume
9072 // that selects fed by vector SETCCs are canonicalized to VSELECT.
9073 assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
9074 "Scalar-SETCC feeding SELECT has unexpected result type!");
9075
Tim Northoverc1c05ae2014-08-29 13:05:18 +00009076 // If NumMaskElts == 0, the comparison is larger than select result. The
9077 // largest real NEON comparison is 64-bits per lane, which means the result is
9078 // at most 32-bits and an illegal vector. Just bail out for now.
Tim Northover3c0915e2014-08-29 15:34:58 +00009079 EVT SrcVT = N0.getOperand(0).getValueType();
Ahmed Bougachad0ce0582014-12-01 20:59:00 +00009080
9081 // Don't try to do this optimization when the setcc itself has i1 operands.
9082 // There are no legal vectors of i1, so this would be pointless.
9083 if (SrcVT == MVT::i1)
9084 return SDValue();
9085
Tim Northover3c0915e2014-08-29 15:34:58 +00009086 int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
Tim Northoverc1c05ae2014-08-29 13:05:18 +00009087 if (!ResVT.isVector() || NumMaskElts == 0)
Tim Northover3b0846e2014-05-24 12:50:23 +00009088 return SDValue();
9089
Tim Northoverc1c05ae2014-08-29 13:05:18 +00009090 SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
Tim Northover3b0846e2014-05-24 12:50:23 +00009091 EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
9092
Ahmed Bougacha89bba612015-04-27 21:01:20 +00009093 // Also bail out if the vector CCVT isn't the same size as ResVT.
9094 // This can happen if the SETCC operand size doesn't divide the ResVT size
9095 // (e.g., f64 vs v3f32).
9096 if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
9097 return SDValue();
9098
Ahmed Bougachac004c602015-04-27 21:43:12 +00009099 // Make sure we didn't create illegal types, if we're not supposed to.
9100 assert(DCI.isBeforeLegalize() ||
9101 DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
9102
Tim Northover3b0846e2014-05-24 12:50:23 +00009103 // First perform a vector comparison, where lane 0 is the one we're interested
9104 // in.
Tim Northoverc1c05ae2014-08-29 13:05:18 +00009105 SDLoc DL(N0);
Tim Northover3b0846e2014-05-24 12:50:23 +00009106 SDValue LHS =
9107 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
9108 SDValue RHS =
9109 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
9110 SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
9111
9112 // Now duplicate the comparison mask we want across all other lanes.
9113 SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
9114 SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask.data());
Tim Northoverc1c05ae2014-08-29 13:05:18 +00009115 Mask = DAG.getNode(ISD::BITCAST, DL,
9116 ResVT.changeVectorElementTypeToInteger(), Mask);
Tim Northover3b0846e2014-05-24 12:50:23 +00009117
9118 return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
9119}
9120
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009121/// Get rid of unnecessary NVCASTs (that don't change the type).
9122static SDValue performNVCASTCombine(SDNode *N) {
9123 if (N->getValueType(0) == N->getOperand(0).getValueType())
9124 return N->getOperand(0);
9125
9126 return SDValue();
9127}
9128
Tim Northover3b0846e2014-05-24 12:50:23 +00009129SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
9130 DAGCombinerInfo &DCI) const {
9131 SelectionDAG &DAG = DCI.DAG;
9132 switch (N->getOpcode()) {
9133 default:
9134 break;
9135 case ISD::ADD:
9136 case ISD::SUB:
9137 return performAddSubLongCombine(N, DCI, DAG);
9138 case ISD::XOR:
9139 return performXorCombine(N, DAG, DCI, Subtarget);
9140 case ISD::MUL:
9141 return performMulCombine(N, DAG, DCI, Subtarget);
9142 case ISD::SINT_TO_FP:
9143 case ISD::UINT_TO_FP:
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00009144 return performIntToFpCombine(N, DAG, Subtarget);
Tim Northover3b0846e2014-05-24 12:50:23 +00009145 case ISD::OR:
9146 return performORCombine(N, DCI, Subtarget);
9147 case ISD::INTRINSIC_WO_CHAIN:
9148 return performIntrinsicCombine(N, DCI, Subtarget);
9149 case ISD::ANY_EXTEND:
9150 case ISD::ZERO_EXTEND:
9151 case ISD::SIGN_EXTEND:
9152 return performExtendCombine(N, DCI, DAG);
9153 case ISD::BITCAST:
9154 return performBitcastCombine(N, DCI, DAG);
9155 case ISD::CONCAT_VECTORS:
9156 return performConcatVectorsCombine(N, DCI, DAG);
9157 case ISD::SELECT:
Ahmed Bougachac004c602015-04-27 21:43:12 +00009158 return performSelectCombine(N, DCI);
Tim Northover3b0846e2014-05-24 12:50:23 +00009159 case ISD::VSELECT:
9160 return performVSelectCombine(N, DCI.DAG);
9161 case ISD::STORE:
9162 return performSTORECombine(N, DCI, DAG, Subtarget);
9163 case AArch64ISD::BRCOND:
9164 return performBRCONDCombine(N, DCI, DAG);
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009165 case AArch64ISD::CSEL:
9166 return performCONDCombine(N, DCI, DAG, 2, 3);
Tim Northover3b0846e2014-05-24 12:50:23 +00009167 case AArch64ISD::DUP:
9168 return performPostLD1Combine(N, DCI, false);
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009169 case AArch64ISD::NVCAST:
9170 return performNVCASTCombine(N);
Tim Northover3b0846e2014-05-24 12:50:23 +00009171 case ISD::INSERT_VECTOR_ELT:
9172 return performPostLD1Combine(N, DCI, true);
9173 case ISD::INTRINSIC_VOID:
9174 case ISD::INTRINSIC_W_CHAIN:
9175 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9176 case Intrinsic::aarch64_neon_ld2:
9177 case Intrinsic::aarch64_neon_ld3:
9178 case Intrinsic::aarch64_neon_ld4:
9179 case Intrinsic::aarch64_neon_ld1x2:
9180 case Intrinsic::aarch64_neon_ld1x3:
9181 case Intrinsic::aarch64_neon_ld1x4:
9182 case Intrinsic::aarch64_neon_ld2lane:
9183 case Intrinsic::aarch64_neon_ld3lane:
9184 case Intrinsic::aarch64_neon_ld4lane:
9185 case Intrinsic::aarch64_neon_ld2r:
9186 case Intrinsic::aarch64_neon_ld3r:
9187 case Intrinsic::aarch64_neon_ld4r:
9188 case Intrinsic::aarch64_neon_st2:
9189 case Intrinsic::aarch64_neon_st3:
9190 case Intrinsic::aarch64_neon_st4:
9191 case Intrinsic::aarch64_neon_st1x2:
9192 case Intrinsic::aarch64_neon_st1x3:
9193 case Intrinsic::aarch64_neon_st1x4:
9194 case Intrinsic::aarch64_neon_st2lane:
9195 case Intrinsic::aarch64_neon_st3lane:
9196 case Intrinsic::aarch64_neon_st4lane:
9197 return performNEONPostLDSTCombine(N, DCI, DAG);
9198 default:
9199 break;
9200 }
9201 }
9202 return SDValue();
9203}
9204
9205// Check if the return value is used as only a return value, as otherwise
9206// we can't perform a tail-call. In particular, we need to check for
9207// target ISD nodes that are returns and any other "odd" constructs
9208// that the generic analysis code won't necessarily catch.
9209bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
9210 SDValue &Chain) const {
9211 if (N->getNumValues() != 1)
9212 return false;
9213 if (!N->hasNUsesOfValue(1, 0))
9214 return false;
9215
9216 SDValue TCChain = Chain;
9217 SDNode *Copy = *N->use_begin();
9218 if (Copy->getOpcode() == ISD::CopyToReg) {
9219 // If the copy has a glue operand, we conservatively assume it isn't safe to
9220 // perform a tail call.
9221 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
9222 MVT::Glue)
9223 return false;
9224 TCChain = Copy->getOperand(0);
9225 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
9226 return false;
9227
9228 bool HasRet = false;
9229 for (SDNode *Node : Copy->uses()) {
9230 if (Node->getOpcode() != AArch64ISD::RET_FLAG)
9231 return false;
9232 HasRet = true;
9233 }
9234
9235 if (!HasRet)
9236 return false;
9237
9238 Chain = TCChain;
9239 return true;
9240}
9241
9242// Return whether the an instruction can potentially be optimized to a tail
9243// call. This will cause the optimizers to attempt to move, or duplicate,
9244// return instructions to help enable tail call optimizations for this
9245// instruction.
9246bool AArch64TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
9247 if (!CI->isTailCall())
9248 return false;
9249
9250 return true;
9251}
9252
9253bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
9254 SDValue &Offset,
9255 ISD::MemIndexedMode &AM,
9256 bool &IsInc,
9257 SelectionDAG &DAG) const {
9258 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
9259 return false;
9260
9261 Base = Op->getOperand(0);
9262 // All of the indexed addressing mode instructions take a signed
9263 // 9 bit immediate offset.
9264 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
9265 int64_t RHSC = (int64_t)RHS->getZExtValue();
9266 if (RHSC >= 256 || RHSC <= -256)
9267 return false;
9268 IsInc = (Op->getOpcode() == ISD::ADD);
9269 Offset = Op->getOperand(1);
9270 return true;
9271 }
9272 return false;
9273}
9274
9275bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
9276 SDValue &Offset,
9277 ISD::MemIndexedMode &AM,
9278 SelectionDAG &DAG) const {
9279 EVT VT;
9280 SDValue Ptr;
9281 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9282 VT = LD->getMemoryVT();
9283 Ptr = LD->getBasePtr();
9284 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9285 VT = ST->getMemoryVT();
9286 Ptr = ST->getBasePtr();
9287 } else
9288 return false;
9289
9290 bool IsInc;
9291 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
9292 return false;
9293 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
9294 return true;
9295}
9296
9297bool AArch64TargetLowering::getPostIndexedAddressParts(
9298 SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
9299 ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
9300 EVT VT;
9301 SDValue Ptr;
9302 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9303 VT = LD->getMemoryVT();
9304 Ptr = LD->getBasePtr();
9305 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9306 VT = ST->getMemoryVT();
9307 Ptr = ST->getBasePtr();
9308 } else
9309 return false;
9310
9311 bool IsInc;
9312 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
9313 return false;
9314 // Post-indexing updates the base, so it's not a valid transform
9315 // if that's not the same as the load's pointer.
9316 if (Ptr != Base)
9317 return false;
9318 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
9319 return true;
9320}
9321
Tim Northoverf8bfe212014-07-18 13:07:05 +00009322static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
9323 SelectionDAG &DAG) {
Tim Northoverf8bfe212014-07-18 13:07:05 +00009324 SDLoc DL(N);
9325 SDValue Op = N->getOperand(0);
Ahmed Bougacha87946322014-12-01 20:52:32 +00009326
9327 if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
9328 return;
9329
Tim Northoverf8bfe212014-07-18 13:07:05 +00009330 Op = SDValue(
9331 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
9332 DAG.getUNDEF(MVT::i32), Op,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009333 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
Tim Northoverf8bfe212014-07-18 13:07:05 +00009334 0);
9335 Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
9336 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
9337}
9338
Tim Northover3b0846e2014-05-24 12:50:23 +00009339void AArch64TargetLowering::ReplaceNodeResults(
9340 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
9341 switch (N->getOpcode()) {
9342 default:
9343 llvm_unreachable("Don't know how to custom expand this");
Tim Northoverf8bfe212014-07-18 13:07:05 +00009344 case ISD::BITCAST:
9345 ReplaceBITCASTResults(N, Results, DAG);
9346 return;
Tim Northover3b0846e2014-05-24 12:50:23 +00009347 case ISD::FP_TO_UINT:
9348 case ISD::FP_TO_SINT:
9349 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
9350 // Let normal code take care of it by not adding anything to Results.
9351 return;
9352 }
9353}
9354
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +00009355bool AArch64TargetLowering::useLoadStackGuardNode() const {
9356 return true;
9357}
9358
Sanjay Patel1dd15592015-07-28 23:05:48 +00009359unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
Hao Liu44e5d7a2014-11-21 06:39:58 +00009360 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
9361 // reciprocal if there are three or more FDIVs.
Sanjay Patel1dd15592015-07-28 23:05:48 +00009362 return 3;
Hao Liu44e5d7a2014-11-21 06:39:58 +00009363}
9364
Chandler Carruth9d010ff2014-07-03 00:23:43 +00009365TargetLoweringBase::LegalizeTypeAction
9366AArch64TargetLowering::getPreferredVectorAction(EVT VT) const {
9367 MVT SVT = VT.getSimpleVT();
9368 // During type legalization, we prefer to widen v1i8, v1i16, v1i32 to v8i8,
9369 // v4i16, v2i32 instead of to promote.
9370 if (SVT == MVT::v1i8 || SVT == MVT::v1i16 || SVT == MVT::v1i32
9371 || SVT == MVT::v1f32)
9372 return TypeWidenVector;
9373
9374 return TargetLoweringBase::getPreferredVectorAction(VT);
9375}
9376
Robin Morisseted3d48f2014-09-03 21:29:59 +00009377// Loads and stores less than 128-bits are already atomic; ones above that
9378// are doomed anyway, so defer to the default libcall and blame the OS when
9379// things go wrong.
9380bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
9381 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
9382 return Size == 128;
9383}
9384
9385// Loads and stores less than 128-bits are already atomic; ones above that
9386// are doomed anyway, so defer to the default libcall and blame the OS when
9387// things go wrong.
9388bool AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
9389 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
9390 return Size == 128;
9391}
9392
9393// For the real atomic operations, we have ldxr/stxr up to 128 bits,
JF Bastienf14889e2015-03-04 15:47:57 +00009394TargetLoweringBase::AtomicRMWExpansionKind
9395AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
Robin Morisseted3d48f2014-09-03 21:29:59 +00009396 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
JF Bastienf14889e2015-03-04 15:47:57 +00009397 return Size <= 128 ? AtomicRMWExpansionKind::LLSC
9398 : AtomicRMWExpansionKind::None;
Robin Morisseted3d48f2014-09-03 21:29:59 +00009399}
9400
Robin Morisset25c8e312014-09-17 00:06:58 +00009401bool AArch64TargetLowering::hasLoadLinkedStoreConditional() const {
9402 return true;
9403}
9404
Tim Northover3b0846e2014-05-24 12:50:23 +00009405Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
9406 AtomicOrdering Ord) const {
9407 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
9408 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
Robin Morissetb155f522014-08-18 16:48:58 +00009409 bool IsAcquire = isAtLeastAcquire(Ord);
Tim Northover3b0846e2014-05-24 12:50:23 +00009410
9411 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
9412 // intrinsic must return {i64, i64} and we have to recombine them into a
9413 // single i128 here.
9414 if (ValTy->getPrimitiveSizeInBits() == 128) {
9415 Intrinsic::ID Int =
9416 IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
9417 Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int);
9418
9419 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
9420 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
9421
9422 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
9423 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
9424 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
9425 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
9426 return Builder.CreateOr(
9427 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
9428 }
9429
9430 Type *Tys[] = { Addr->getType() };
9431 Intrinsic::ID Int =
9432 IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
9433 Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int, Tys);
9434
9435 return Builder.CreateTruncOrBitCast(
9436 Builder.CreateCall(Ldxr, Addr),
9437 cast<PointerType>(Addr->getType())->getElementType());
9438}
9439
9440Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
9441 Value *Val, Value *Addr,
9442 AtomicOrdering Ord) const {
9443 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
Robin Morissetb155f522014-08-18 16:48:58 +00009444 bool IsRelease = isAtLeastRelease(Ord);
Tim Northover3b0846e2014-05-24 12:50:23 +00009445
9446 // Since the intrinsics must have legal type, the i128 intrinsics take two
9447 // parameters: "i64, i64". We must marshal Val into the appropriate form
9448 // before the call.
9449 if (Val->getType()->getPrimitiveSizeInBits() == 128) {
9450 Intrinsic::ID Int =
9451 IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
9452 Function *Stxr = Intrinsic::getDeclaration(M, Int);
9453 Type *Int64Ty = Type::getInt64Ty(M->getContext());
9454
9455 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
9456 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
9457 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
David Blaikieff6409d2015-05-18 22:13:54 +00009458 return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
Tim Northover3b0846e2014-05-24 12:50:23 +00009459 }
9460
9461 Intrinsic::ID Int =
9462 IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
9463 Type *Tys[] = { Addr->getType() };
9464 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
9465
David Blaikieff6409d2015-05-18 22:13:54 +00009466 return Builder.CreateCall(Stxr,
9467 {Builder.CreateZExtOrBitCast(
9468 Val, Stxr->getFunctionType()->getParamType(0)),
9469 Addr});
Tim Northover3b0846e2014-05-24 12:50:23 +00009470}
Tim Northover3c55cca2014-11-27 21:02:42 +00009471
9472bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
9473 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
9474 return Ty->isArrayTy();
9475}
Matthias Braunaf7d7702015-07-16 20:02:37 +00009476
9477bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
9478 EVT) const {
9479 return false;
9480}