blob: f607e2ea653184c79bee5911dbc2505c281ff133 [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 +000043static cl::opt<bool>
44EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden,
Kristof Beylsaea84612015-03-04 09:12:08 +000045 cl::desc("Allow AArch64 SLI/SRI formation"),
46 cl::init(false));
47
48// FIXME: The necessary dtprel relocations don't seem to be supported
49// well in the GNU bfd and gold linkers at the moment. Therefore, by
50// default, for now, fall back to GeneralDynamic code generation.
51cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration(
52 "aarch64-elf-ldtls-generation", cl::Hidden,
53 cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
54 cl::init(false));
Tim Northover3b0846e2014-05-24 12:50:23 +000055
Matthias Braunaf7d7702015-07-16 20:02:37 +000056/// Value type used for condition codes.
57static const MVT MVT_CC = MVT::i32;
58
Eric Christopher905f12d2015-01-29 00:19:42 +000059AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
60 const AArch64Subtarget &STI)
61 : TargetLowering(TM), Subtarget(&STI) {
Tim Northover3b0846e2014-05-24 12:50:23 +000062
63 // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
64 // we have to make something up. Arbitrarily, choose ZeroOrOne.
65 setBooleanContents(ZeroOrOneBooleanContent);
66 // When comparing vectors the result sets the different elements in the
67 // vector to all-one or all-zero.
68 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
69
70 // Set up the register classes.
71 addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
72 addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
73
74 if (Subtarget->hasFPARMv8()) {
75 addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
76 addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
77 addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
78 addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
79 }
80
81 if (Subtarget->hasNEON()) {
82 addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
83 addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
84 // Someone set us up the NEON.
85 addDRTypeForNEON(MVT::v2f32);
86 addDRTypeForNEON(MVT::v8i8);
87 addDRTypeForNEON(MVT::v4i16);
88 addDRTypeForNEON(MVT::v2i32);
89 addDRTypeForNEON(MVT::v1i64);
90 addDRTypeForNEON(MVT::v1f64);
Oliver Stannard89d15422014-08-27 16:16:04 +000091 addDRTypeForNEON(MVT::v4f16);
Tim Northover3b0846e2014-05-24 12:50:23 +000092
93 addQRTypeForNEON(MVT::v4f32);
94 addQRTypeForNEON(MVT::v2f64);
95 addQRTypeForNEON(MVT::v16i8);
96 addQRTypeForNEON(MVT::v8i16);
97 addQRTypeForNEON(MVT::v4i32);
98 addQRTypeForNEON(MVT::v2i64);
Oliver Stannard89d15422014-08-27 16:16:04 +000099 addQRTypeForNEON(MVT::v8f16);
Tim Northover3b0846e2014-05-24 12:50:23 +0000100 }
101
102 // Compute derived properties from the register classes
Eric Christopher23a3a7c2015-02-26 00:00:24 +0000103 computeRegisterProperties(Subtarget->getRegisterInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +0000104
105 // Provide all sorts of operation actions
106 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
107 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
108 setOperationAction(ISD::SETCC, MVT::i32, Custom);
109 setOperationAction(ISD::SETCC, MVT::i64, Custom);
110 setOperationAction(ISD::SETCC, MVT::f32, Custom);
111 setOperationAction(ISD::SETCC, MVT::f64, Custom);
112 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
113 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
114 setOperationAction(ISD::BR_CC, MVT::i64, Custom);
115 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
116 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
117 setOperationAction(ISD::SELECT, MVT::i32, Custom);
118 setOperationAction(ISD::SELECT, MVT::i64, Custom);
119 setOperationAction(ISD::SELECT, MVT::f32, Custom);
120 setOperationAction(ISD::SELECT, MVT::f64, Custom);
121 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
122 setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
123 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
124 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
125 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
126 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
127
128 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
129 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
130 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
131
132 setOperationAction(ISD::FREM, MVT::f32, Expand);
133 setOperationAction(ISD::FREM, MVT::f64, Expand);
134 setOperationAction(ISD::FREM, MVT::f80, Expand);
135
136 // Custom lowering hooks are needed for XOR
137 // to fold it into CSINC/CSINV.
138 setOperationAction(ISD::XOR, MVT::i32, Custom);
139 setOperationAction(ISD::XOR, MVT::i64, Custom);
140
Balaram Makam92431702016-02-01 19:13:07 +0000141 // Custom lowering hooks are needed for OR
142 // to fold it into CCMP.
143 setOperationAction(ISD::OR, MVT::i32, Custom);
144 setOperationAction(ISD::OR, MVT::i64, Custom);
145
146 // Custom lowering hooks are needed for AND
147 // to fold it into CCMP.
148 setOperationAction(ISD::AND, MVT::i32, Custom);
149 setOperationAction(ISD::AND, MVT::i64, Custom);
150
Tim Northover3b0846e2014-05-24 12:50:23 +0000151 // Virtually no operation on f128 is legal, but LLVM can't expand them when
152 // there's a valid register class, so we need custom operations in most cases.
153 setOperationAction(ISD::FABS, MVT::f128, Expand);
154 setOperationAction(ISD::FADD, MVT::f128, Custom);
155 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
156 setOperationAction(ISD::FCOS, MVT::f128, Expand);
157 setOperationAction(ISD::FDIV, MVT::f128, Custom);
158 setOperationAction(ISD::FMA, MVT::f128, Expand);
159 setOperationAction(ISD::FMUL, MVT::f128, Custom);
160 setOperationAction(ISD::FNEG, MVT::f128, Expand);
161 setOperationAction(ISD::FPOW, MVT::f128, Expand);
162 setOperationAction(ISD::FREM, MVT::f128, Expand);
163 setOperationAction(ISD::FRINT, MVT::f128, Expand);
164 setOperationAction(ISD::FSIN, MVT::f128, Expand);
165 setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
166 setOperationAction(ISD::FSQRT, MVT::f128, Expand);
167 setOperationAction(ISD::FSUB, MVT::f128, Custom);
168 setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
169 setOperationAction(ISD::SETCC, MVT::f128, Custom);
170 setOperationAction(ISD::BR_CC, MVT::f128, Custom);
171 setOperationAction(ISD::SELECT, MVT::f128, Custom);
172 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
173 setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
174
175 // Lowering for many of the conversions is actually specified by the non-f128
176 // type. The LowerXXX function will be trivial when f128 isn't involved.
177 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
178 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
179 setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
180 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
181 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
182 setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
183 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
184 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
185 setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
186 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
187 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
188 setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
189 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
190 setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
191
192 // Variable arguments.
193 setOperationAction(ISD::VASTART, MVT::Other, Custom);
194 setOperationAction(ISD::VAARG, MVT::Other, Custom);
195 setOperationAction(ISD::VACOPY, MVT::Other, Custom);
196 setOperationAction(ISD::VAEND, MVT::Other, Expand);
197
198 // Variable-sized objects.
199 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
200 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
201 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
202
Tim Northover3b0846e2014-05-24 12:50:23 +0000203 // Constant pool entries
204 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
205
206 // BlockAddress
207 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
208
209 // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
210 setOperationAction(ISD::ADDC, MVT::i32, Custom);
211 setOperationAction(ISD::ADDE, MVT::i32, Custom);
212 setOperationAction(ISD::SUBC, MVT::i32, Custom);
213 setOperationAction(ISD::SUBE, MVT::i32, Custom);
214 setOperationAction(ISD::ADDC, MVT::i64, Custom);
215 setOperationAction(ISD::ADDE, MVT::i64, Custom);
216 setOperationAction(ISD::SUBC, MVT::i64, Custom);
217 setOperationAction(ISD::SUBE, MVT::i64, Custom);
218
219 // AArch64 lacks both left-rotate and popcount instructions.
220 setOperationAction(ISD::ROTL, MVT::i32, Expand);
221 setOperationAction(ISD::ROTL, MVT::i64, Expand);
Charlie Turner458e79b2015-10-27 10:25:20 +0000222 for (MVT VT : MVT::vector_valuetypes()) {
223 setOperationAction(ISD::ROTL, VT, Expand);
224 setOperationAction(ISD::ROTR, VT, Expand);
225 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000226
227 // AArch64 doesn't have {U|S}MUL_LOHI.
228 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
229 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
230
231
Tim Northover3b0846e2014-05-24 12:50:23 +0000232 setOperationAction(ISD::CTPOP, MVT::i32, Custom);
233 setOperationAction(ISD::CTPOP, MVT::i64, Custom);
234
235 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
236 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
Chad Rosierf3491492015-12-04 21:38:44 +0000237 for (MVT VT : MVT::vector_valuetypes()) {
238 setOperationAction(ISD::SDIVREM, VT, Expand);
239 setOperationAction(ISD::UDIVREM, VT, Expand);
240 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000241 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
Tim Northovercdf15292016-04-14 17:03:29 +0000402 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
403
Ahmed Bougachab0ff6432015-09-01 16:23:45 +0000404 // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
405 // This requires the Performance Monitors extension.
406 if (Subtarget->hasPerfMon())
407 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
408
Tim Northover3b0846e2014-05-24 12:50:23 +0000409 if (Subtarget->isTargetMachO()) {
410 // For iOS, we don't want to the normal expansion of a libcall to
411 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
412 // traffic.
413 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
414 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
415 } else {
416 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
417 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
418 }
419
Juergen Ributzka23266502014-12-10 19:43:32 +0000420 // Make floating-point constants legal for the large code model, so they don't
421 // become loads from the constant pool.
422 if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
423 setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
424 setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
425 }
426
Tim Northover3b0846e2014-05-24 12:50:23 +0000427 // AArch64 does not have floating-point extending loads, i1 sign-extending
428 // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000429 for (MVT VT : MVT::fp_valuetypes()) {
430 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
431 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
432 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
433 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
434 }
435 for (MVT VT : MVT::integer_valuetypes())
436 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
437
Tim Northover3b0846e2014-05-24 12:50:23 +0000438 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
439 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
440 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
441 setTruncStoreAction(MVT::f128, MVT::f80, Expand);
442 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
443 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
444 setTruncStoreAction(MVT::f128, MVT::f16, Expand);
Tim Northoverf8bfe212014-07-18 13:07:05 +0000445
446 setOperationAction(ISD::BITCAST, MVT::i16, Custom);
447 setOperationAction(ISD::BITCAST, MVT::f16, Custom);
448
Tim Northover3b0846e2014-05-24 12:50:23 +0000449 // Indexed loads and stores are supported.
450 for (unsigned im = (unsigned)ISD::PRE_INC;
451 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
452 setIndexedLoadAction(im, MVT::i8, Legal);
453 setIndexedLoadAction(im, MVT::i16, Legal);
454 setIndexedLoadAction(im, MVT::i32, Legal);
455 setIndexedLoadAction(im, MVT::i64, Legal);
456 setIndexedLoadAction(im, MVT::f64, Legal);
457 setIndexedLoadAction(im, MVT::f32, Legal);
Ahmed Bougachae0e12db2015-08-04 01:29:38 +0000458 setIndexedLoadAction(im, MVT::f16, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000459 setIndexedStoreAction(im, MVT::i8, Legal);
460 setIndexedStoreAction(im, MVT::i16, Legal);
461 setIndexedStoreAction(im, MVT::i32, Legal);
462 setIndexedStoreAction(im, MVT::i64, Legal);
463 setIndexedStoreAction(im, MVT::f64, Legal);
464 setIndexedStoreAction(im, MVT::f32, Legal);
Ahmed Bougachae0e12db2015-08-04 01:29:38 +0000465 setIndexedStoreAction(im, MVT::f16, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000466 }
467
468 // Trap.
469 setOperationAction(ISD::TRAP, MVT::Other, Legal);
470
471 // We combine OR nodes for bitfield operations.
472 setTargetDAGCombine(ISD::OR);
473
474 // Vector add and sub nodes may conceal a high-half opportunity.
475 // Also, try to fold ADD into CSINC/CSINV..
476 setTargetDAGCombine(ISD::ADD);
477 setTargetDAGCombine(ISD::SUB);
Chad Rosier14aa2ad2016-05-26 19:41:33 +0000478 setTargetDAGCombine(ISD::SRL);
Tim Northover3b0846e2014-05-24 12:50:23 +0000479 setTargetDAGCombine(ISD::XOR);
480 setTargetDAGCombine(ISD::SINT_TO_FP);
481 setTargetDAGCombine(ISD::UINT_TO_FP);
482
Chad Rosierfa30c9b2015-10-07 17:39:18 +0000483 setTargetDAGCombine(ISD::FP_TO_SINT);
484 setTargetDAGCombine(ISD::FP_TO_UINT);
Chad Rosier7c6ac2b2015-10-07 17:51:37 +0000485 setTargetDAGCombine(ISD::FDIV);
Chad Rosierfa30c9b2015-10-07 17:39:18 +0000486
Tim Northover3b0846e2014-05-24 12:50:23 +0000487 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
488
489 setTargetDAGCombine(ISD::ANY_EXTEND);
490 setTargetDAGCombine(ISD::ZERO_EXTEND);
491 setTargetDAGCombine(ISD::SIGN_EXTEND);
492 setTargetDAGCombine(ISD::BITCAST);
493 setTargetDAGCombine(ISD::CONCAT_VECTORS);
494 setTargetDAGCombine(ISD::STORE);
Tim Northover339c83e2015-11-10 00:44:23 +0000495 if (Subtarget->supportsAddressTopByteIgnored())
496 setTargetDAGCombine(ISD::LOAD);
Tim Northover3b0846e2014-05-24 12:50:23 +0000497
498 setTargetDAGCombine(ISD::MUL);
499
500 setTargetDAGCombine(ISD::SELECT);
501 setTargetDAGCombine(ISD::VSELECT);
502
503 setTargetDAGCombine(ISD::INTRINSIC_VOID);
504 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
505 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
Chad Rosier6c36eff2015-09-03 18:13:57 +0000506 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
Tim Northover3b0846e2014-05-24 12:50:23 +0000507
508 MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 8;
509 MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 4;
510 MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = 4;
511
512 setStackPointerRegisterToSaveRestore(AArch64::SP);
513
514 setSchedulingPreference(Sched::Hybrid);
515
516 // Enable TBZ/TBNZ
517 MaskAndBranchFoldingIsLegal = true;
Quentin Colombet6843ac42015-03-31 20:52:32 +0000518 EnableExtLdPromotion = true;
Tim Northover3b0846e2014-05-24 12:50:23 +0000519
Evandro Menezesa3a0a602016-06-10 16:00:18 +0000520 // Set required alignment.
Tim Northover3b0846e2014-05-24 12:50:23 +0000521 setMinFunctionAlignment(2);
Evandro Menezesa3a0a602016-06-10 16:00:18 +0000522 // Set preferred alignments.
523 setPrefFunctionAlignment(STI.getPrefFunctionAlignment());
524 setPrefLoopAlignment(STI.getPrefLoopAlignment());
Tim Northover3b0846e2014-05-24 12:50:23 +0000525
Tim Northover3b0846e2014-05-24 12:50:23 +0000526 setHasExtractBitsInsn(true);
527
Adhemerval Zanella7bc33192015-07-28 13:03:31 +0000528 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
529
Tim Northover3b0846e2014-05-24 12:50:23 +0000530 if (Subtarget->hasNEON()) {
531 // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
532 // silliness like this:
533 setOperationAction(ISD::FABS, MVT::v1f64, Expand);
534 setOperationAction(ISD::FADD, MVT::v1f64, Expand);
535 setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
536 setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
537 setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
538 setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
539 setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
540 setOperationAction(ISD::FMA, MVT::v1f64, Expand);
541 setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
542 setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
543 setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
544 setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
545 setOperationAction(ISD::FREM, MVT::v1f64, Expand);
546 setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
547 setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
548 setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
549 setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
550 setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
551 setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
552 setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
553 setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
554 setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
555 setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
556 setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
557 setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
558
559 setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
560 setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
561 setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
562 setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
563 setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
564
565 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
566
567 // AArch64 doesn't have a direct vector ->f32 conversion instructions for
568 // elements smaller than i32, so promote the input to i32 first.
569 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Promote);
570 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Promote);
571 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Promote);
572 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Promote);
Pirama Arumuga Nainarb1881532015-04-23 17:16:27 +0000573 // i8 and i16 vector elements also need promotion to i32 for v8i8 or v8i16
574 // -> v8f16 conversions.
575 setOperationAction(ISD::SINT_TO_FP, MVT::v8i8, Promote);
576 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Promote);
577 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
578 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Promote);
Tim Northover3b0846e2014-05-24 12:50:23 +0000579 // Similarly, there is no direct i32 -> f64 vector conversion instruction.
580 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
581 setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
582 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
583 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
Pirama Arumuga Nainarb1881532015-04-23 17:16:27 +0000584 // Or, direct i32 -> f16 vector conversion. Set it so custom, so the
585 // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
586 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
587 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000588
Craig Topperc5551bf2016-04-26 05:26:51 +0000589 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand);
590 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand);
591
Craig Topper3b4842b2016-04-28 01:58:21 +0000592 setOperationAction(ISD::CTTZ, MVT::v2i8, Expand);
593 setOperationAction(ISD::CTTZ, MVT::v4i16, Expand);
594 setOperationAction(ISD::CTTZ, MVT::v2i32, Expand);
595 setOperationAction(ISD::CTTZ, MVT::v1i64, Expand);
596 setOperationAction(ISD::CTTZ, MVT::v16i8, Expand);
597 setOperationAction(ISD::CTTZ, MVT::v8i16, Expand);
598 setOperationAction(ISD::CTTZ, MVT::v4i32, Expand);
599 setOperationAction(ISD::CTTZ, MVT::v2i64, Expand);
600
Tim Northover3b0846e2014-05-24 12:50:23 +0000601 // AArch64 doesn't have MUL.2d:
602 setOperationAction(ISD::MUL, MVT::v2i64, Expand);
Chad Rosierd9d0f862014-10-08 02:31:24 +0000603 // Custom handling for some quad-vector types to detect MULL.
604 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
605 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
606 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
607
Tim Northover3b0846e2014-05-24 12:50:23 +0000608 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
609 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
610 // Likewise, narrowing and extending vector loads/stores aren't handled
611 // directly.
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000612 for (MVT VT : MVT::vector_valuetypes()) {
613 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000614
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000615 setOperationAction(ISD::MULHS, VT, Expand);
616 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
617 setOperationAction(ISD::MULHU, VT, Expand);
618 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000619
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000620 setOperationAction(ISD::BSWAP, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000621
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000622 for (MVT InnerVT : MVT::vector_valuetypes()) {
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000623 setTruncStoreAction(VT, InnerVT, Expand);
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000624 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
625 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
626 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
627 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000628 }
629
630 // AArch64 has implementations of a lot of rounding-like FP operations.
Benjamin Kramer57a3d082015-03-08 16:07:39 +0000631 for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000632 setOperationAction(ISD::FFLOOR, Ty, Legal);
633 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
634 setOperationAction(ISD::FCEIL, Ty, Legal);
635 setOperationAction(ISD::FRINT, Ty, Legal);
636 setOperationAction(ISD::FTRUNC, Ty, Legal);
637 setOperationAction(ISD::FROUND, Ty, Legal);
638 }
639 }
James Molloyf089ab72014-08-06 10:42:18 +0000640
Matthias Braun651cff42016-06-02 18:03:53 +0000641 PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive();
Tim Northover3b0846e2014-05-24 12:50:23 +0000642}
643
Craig Topper18e69f42016-04-15 06:20:21 +0000644void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) {
Jiangning Liu08f4cda2014-08-29 01:31:42 +0000645 if (VT == MVT::v2f32 || VT == MVT::v4f16) {
Craig Topper18e69f42016-04-15 06:20:21 +0000646 setOperationAction(ISD::LOAD, VT, Promote);
647 AddPromotedToType(ISD::LOAD, VT, MVT::v2i32);
Tim Northover3b0846e2014-05-24 12:50:23 +0000648
Craig Topper18e69f42016-04-15 06:20:21 +0000649 setOperationAction(ISD::STORE, VT, Promote);
650 AddPromotedToType(ISD::STORE, VT, MVT::v2i32);
Jiangning Liu08f4cda2014-08-29 01:31:42 +0000651 } else if (VT == MVT::v2f64 || VT == MVT::v4f32 || VT == MVT::v8f16) {
Craig Topper18e69f42016-04-15 06:20:21 +0000652 setOperationAction(ISD::LOAD, VT, Promote);
653 AddPromotedToType(ISD::LOAD, VT, MVT::v2i64);
Tim Northover3b0846e2014-05-24 12:50:23 +0000654
Craig Topper18e69f42016-04-15 06:20:21 +0000655 setOperationAction(ISD::STORE, VT, Promote);
656 AddPromotedToType(ISD::STORE, VT, MVT::v2i64);
Tim Northover3b0846e2014-05-24 12:50:23 +0000657 }
658
659 // Mark vector float intrinsics as expand.
660 if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
Craig Topper18e69f42016-04-15 06:20:21 +0000661 setOperationAction(ISD::FSIN, VT, Expand);
662 setOperationAction(ISD::FCOS, VT, Expand);
663 setOperationAction(ISD::FPOWI, VT, Expand);
664 setOperationAction(ISD::FPOW, VT, Expand);
665 setOperationAction(ISD::FLOG, VT, Expand);
666 setOperationAction(ISD::FLOG2, VT, Expand);
667 setOperationAction(ISD::FLOG10, VT, Expand);
668 setOperationAction(ISD::FEXP, VT, Expand);
669 setOperationAction(ISD::FEXP2, VT, Expand);
Ahmed Bougachab0ae36f2015-08-04 00:42:34 +0000670
671 // But we do support custom-lowering for FCOPYSIGN.
Craig Topper18e69f42016-04-15 06:20:21 +0000672 setOperationAction(ISD::FCOPYSIGN, VT, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000673 }
674
Craig Topper18e69f42016-04-15 06:20:21 +0000675 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
676 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
677 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
678 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
679 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
680 setOperationAction(ISD::SRA, VT, Custom);
681 setOperationAction(ISD::SRL, VT, Custom);
682 setOperationAction(ISD::SHL, VT, Custom);
683 setOperationAction(ISD::AND, VT, Custom);
684 setOperationAction(ISD::OR, VT, Custom);
685 setOperationAction(ISD::SETCC, VT, Custom);
686 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000687
Craig Topper18e69f42016-04-15 06:20:21 +0000688 setOperationAction(ISD::SELECT, VT, Expand);
689 setOperationAction(ISD::SELECT_CC, VT, Expand);
690 setOperationAction(ISD::VSELECT, VT, Expand);
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000691 for (MVT InnerVT : MVT::all_valuetypes())
Craig Topper18e69f42016-04-15 06:20:21 +0000692 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000693
694 // CNT supports only B element sizes.
695 if (VT != MVT::v8i8 && VT != MVT::v16i8)
Craig Topper18e69f42016-04-15 06:20:21 +0000696 setOperationAction(ISD::CTPOP, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000697
Craig Topper18e69f42016-04-15 06:20:21 +0000698 setOperationAction(ISD::UDIV, VT, Expand);
699 setOperationAction(ISD::SDIV, VT, Expand);
700 setOperationAction(ISD::UREM, VT, Expand);
701 setOperationAction(ISD::SREM, VT, Expand);
702 setOperationAction(ISD::FREM, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000703
Craig Topper18e69f42016-04-15 06:20:21 +0000704 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
705 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000706
Hal Finkelcd8664c2015-12-11 23:11:52 +0000707 // [SU][MIN|MAX] are available for all NEON types apart from i64.
Craig Topper18e69f42016-04-15 06:20:21 +0000708 if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64)
Hal Finkelcd8664c2015-12-11 23:11:52 +0000709 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
Craig Topper18e69f42016-04-15 06:20:21 +0000710 setOperationAction(Opcode, VT, Legal);
James Molloycfb04432015-05-15 16:15:57 +0000711
James Molloy63be1982015-08-14 09:08:50 +0000712 // F[MIN|MAX][NUM|NAN] are available for all FP NEON types (not f16 though!).
713 if (VT.isFloatingPoint() && VT.getVectorElementType() != MVT::f16)
James Molloyb7b2a1e2015-08-11 12:06:37 +0000714 for (unsigned Opcode : {ISD::FMINNAN, ISD::FMAXNAN,
715 ISD::FMINNUM, ISD::FMAXNUM})
Craig Topper18e69f42016-04-15 06:20:21 +0000716 setOperationAction(Opcode, VT, Legal);
James Molloyedf38f02015-08-11 12:06:33 +0000717
Tim Northover3b0846e2014-05-24 12:50:23 +0000718 if (Subtarget->isLittleEndian()) {
719 for (unsigned im = (unsigned)ISD::PRE_INC;
720 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
Craig Topper18e69f42016-04-15 06:20:21 +0000721 setIndexedLoadAction(im, VT, Legal);
722 setIndexedStoreAction(im, VT, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000723 }
724 }
725}
726
727void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
728 addRegisterClass(VT, &AArch64::FPR64RegClass);
729 addTypeForNEON(VT, MVT::v2i32);
730}
731
732void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
733 addRegisterClass(VT, &AArch64::FPR128RegClass);
734 addTypeForNEON(VT, MVT::v4i32);
735}
736
Mehdi Amini44ede332015-07-09 02:09:04 +0000737EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
738 EVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +0000739 if (!VT.isVector())
740 return MVT::i32;
741 return VT.changeVectorElementTypeToInteger();
742}
743
744/// computeKnownBitsForTargetNode - Determine which of the bits specified in
745/// Mask are known to be either zero or one and return them in the
746/// KnownZero/KnownOne bitsets.
747void AArch64TargetLowering::computeKnownBitsForTargetNode(
748 const SDValue Op, APInt &KnownZero, APInt &KnownOne,
749 const SelectionDAG &DAG, unsigned Depth) const {
750 switch (Op.getOpcode()) {
751 default:
752 break;
753 case AArch64ISD::CSEL: {
754 APInt KnownZero2, KnownOne2;
755 DAG.computeKnownBits(Op->getOperand(0), KnownZero, KnownOne, Depth + 1);
756 DAG.computeKnownBits(Op->getOperand(1), KnownZero2, KnownOne2, Depth + 1);
757 KnownZero &= KnownZero2;
758 KnownOne &= KnownOne2;
759 break;
760 }
761 case ISD::INTRINSIC_W_CHAIN: {
Jun Bum Lim4d3c5982015-09-08 16:11:22 +0000762 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +0000763 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
764 switch (IntID) {
765 default: return;
766 case Intrinsic::aarch64_ldaxr:
767 case Intrinsic::aarch64_ldxr: {
768 unsigned BitWidth = KnownOne.getBitWidth();
769 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
770 unsigned MemBits = VT.getScalarType().getSizeInBits();
771 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
772 return;
773 }
774 }
775 break;
776 }
777 case ISD::INTRINSIC_WO_CHAIN:
778 case ISD::INTRINSIC_VOID: {
779 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
780 switch (IntNo) {
781 default:
782 break;
783 case Intrinsic::aarch64_neon_umaxv:
784 case Intrinsic::aarch64_neon_uminv: {
785 // Figure out the datatype of the vector operand. The UMINV instruction
786 // will zero extend the result, so we can mark as known zero all the
787 // bits larger than the element datatype. 32-bit or larget doesn't need
788 // this as those are legal types and will be handled by isel directly.
789 MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
790 unsigned BitWidth = KnownZero.getBitWidth();
791 if (VT == MVT::v8i8 || VT == MVT::v16i8) {
792 assert(BitWidth >= 8 && "Unexpected width!");
793 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
794 KnownZero |= Mask;
795 } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
796 assert(BitWidth >= 16 && "Unexpected width!");
797 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
798 KnownZero |= Mask;
799 }
800 break;
801 } break;
802 }
803 }
804 }
805}
806
Mehdi Aminieaabc512015-07-09 15:12:23 +0000807MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
808 EVT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +0000809 return MVT::i64;
810}
811
Akira Hatanakaf53b0402015-07-29 14:17:26 +0000812bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
813 unsigned AddrSpace,
814 unsigned Align,
815 bool *Fast) const {
816 if (Subtarget->requiresStrictAlign())
817 return false;
Sanjay Patelbbbf9a12015-09-25 21:49:48 +0000818
Sanjay Patelbbbf9a12015-09-25 21:49:48 +0000819 if (Fast) {
Matthias Braun651cff42016-06-02 18:03:53 +0000820 // Some CPUs are fine with unaligned stores except for 128-bit ones.
821 *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 ||
Sanjay Patelbbbf9a12015-09-25 21:49:48 +0000822 // See comments in performSTORECombine() for more details about
823 // these conditions.
824
825 // Code that uses clang vector extensions can mark that it
826 // wants unaligned accesses to be treated as fast by
827 // underspecifying alignment to be 1 or 2.
828 Align <= 2 ||
829
830 // Disregard v2i64. Memcpy lowering produces those and splitting
831 // them regresses performance on micro-benchmarks and olden/bh.
832 VT == MVT::v2i64;
833 }
Akira Hatanakaf53b0402015-07-29 14:17:26 +0000834 return true;
835}
836
Tim Northover3b0846e2014-05-24 12:50:23 +0000837FastISel *
838AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
839 const TargetLibraryInfo *libInfo) const {
840 return AArch64::createFastISel(funcInfo, libInfo);
841}
842
843const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
Matthias Braund04893f2015-05-07 21:33:59 +0000844 switch ((AArch64ISD::NodeType)Opcode) {
845 case AArch64ISD::FIRST_NUMBER: break;
Tim Northover3b0846e2014-05-24 12:50:23 +0000846 case AArch64ISD::CALL: return "AArch64ISD::CALL";
847 case AArch64ISD::ADRP: return "AArch64ISD::ADRP";
848 case AArch64ISD::ADDlow: return "AArch64ISD::ADDlow";
849 case AArch64ISD::LOADgot: return "AArch64ISD::LOADgot";
850 case AArch64ISD::RET_FLAG: return "AArch64ISD::RET_FLAG";
851 case AArch64ISD::BRCOND: return "AArch64ISD::BRCOND";
852 case AArch64ISD::CSEL: return "AArch64ISD::CSEL";
853 case AArch64ISD::FCSEL: return "AArch64ISD::FCSEL";
854 case AArch64ISD::CSINV: return "AArch64ISD::CSINV";
855 case AArch64ISD::CSNEG: return "AArch64ISD::CSNEG";
856 case AArch64ISD::CSINC: return "AArch64ISD::CSINC";
857 case AArch64ISD::THREAD_POINTER: return "AArch64ISD::THREAD_POINTER";
Kristof Beylsaea84612015-03-04 09:12:08 +0000858 case AArch64ISD::TLSDESC_CALLSEQ: return "AArch64ISD::TLSDESC_CALLSEQ";
Tim Northover3b0846e2014-05-24 12:50:23 +0000859 case AArch64ISD::ADC: return "AArch64ISD::ADC";
860 case AArch64ISD::SBC: return "AArch64ISD::SBC";
861 case AArch64ISD::ADDS: return "AArch64ISD::ADDS";
862 case AArch64ISD::SUBS: return "AArch64ISD::SUBS";
863 case AArch64ISD::ADCS: return "AArch64ISD::ADCS";
864 case AArch64ISD::SBCS: return "AArch64ISD::SBCS";
865 case AArch64ISD::ANDS: return "AArch64ISD::ANDS";
Matthias Braunaf7d7702015-07-16 20:02:37 +0000866 case AArch64ISD::CCMP: return "AArch64ISD::CCMP";
867 case AArch64ISD::CCMN: return "AArch64ISD::CCMN";
868 case AArch64ISD::FCCMP: return "AArch64ISD::FCCMP";
Tim Northover3b0846e2014-05-24 12:50:23 +0000869 case AArch64ISD::FCMP: return "AArch64ISD::FCMP";
Tim Northover3b0846e2014-05-24 12:50:23 +0000870 case AArch64ISD::DUP: return "AArch64ISD::DUP";
871 case AArch64ISD::DUPLANE8: return "AArch64ISD::DUPLANE8";
872 case AArch64ISD::DUPLANE16: return "AArch64ISD::DUPLANE16";
873 case AArch64ISD::DUPLANE32: return "AArch64ISD::DUPLANE32";
874 case AArch64ISD::DUPLANE64: return "AArch64ISD::DUPLANE64";
875 case AArch64ISD::MOVI: return "AArch64ISD::MOVI";
876 case AArch64ISD::MOVIshift: return "AArch64ISD::MOVIshift";
877 case AArch64ISD::MOVIedit: return "AArch64ISD::MOVIedit";
878 case AArch64ISD::MOVImsl: return "AArch64ISD::MOVImsl";
879 case AArch64ISD::FMOV: return "AArch64ISD::FMOV";
880 case AArch64ISD::MVNIshift: return "AArch64ISD::MVNIshift";
881 case AArch64ISD::MVNImsl: return "AArch64ISD::MVNImsl";
882 case AArch64ISD::BICi: return "AArch64ISD::BICi";
883 case AArch64ISD::ORRi: return "AArch64ISD::ORRi";
884 case AArch64ISD::BSL: return "AArch64ISD::BSL";
885 case AArch64ISD::NEG: return "AArch64ISD::NEG";
886 case AArch64ISD::EXTR: return "AArch64ISD::EXTR";
887 case AArch64ISD::ZIP1: return "AArch64ISD::ZIP1";
888 case AArch64ISD::ZIP2: return "AArch64ISD::ZIP2";
889 case AArch64ISD::UZP1: return "AArch64ISD::UZP1";
890 case AArch64ISD::UZP2: return "AArch64ISD::UZP2";
891 case AArch64ISD::TRN1: return "AArch64ISD::TRN1";
892 case AArch64ISD::TRN2: return "AArch64ISD::TRN2";
893 case AArch64ISD::REV16: return "AArch64ISD::REV16";
894 case AArch64ISD::REV32: return "AArch64ISD::REV32";
895 case AArch64ISD::REV64: return "AArch64ISD::REV64";
896 case AArch64ISD::EXT: return "AArch64ISD::EXT";
897 case AArch64ISD::VSHL: return "AArch64ISD::VSHL";
898 case AArch64ISD::VLSHR: return "AArch64ISD::VLSHR";
899 case AArch64ISD::VASHR: return "AArch64ISD::VASHR";
900 case AArch64ISD::CMEQ: return "AArch64ISD::CMEQ";
901 case AArch64ISD::CMGE: return "AArch64ISD::CMGE";
902 case AArch64ISD::CMGT: return "AArch64ISD::CMGT";
903 case AArch64ISD::CMHI: return "AArch64ISD::CMHI";
904 case AArch64ISD::CMHS: return "AArch64ISD::CMHS";
905 case AArch64ISD::FCMEQ: return "AArch64ISD::FCMEQ";
906 case AArch64ISD::FCMGE: return "AArch64ISD::FCMGE";
907 case AArch64ISD::FCMGT: return "AArch64ISD::FCMGT";
908 case AArch64ISD::CMEQz: return "AArch64ISD::CMEQz";
909 case AArch64ISD::CMGEz: return "AArch64ISD::CMGEz";
910 case AArch64ISD::CMGTz: return "AArch64ISD::CMGTz";
911 case AArch64ISD::CMLEz: return "AArch64ISD::CMLEz";
912 case AArch64ISD::CMLTz: return "AArch64ISD::CMLTz";
913 case AArch64ISD::FCMEQz: return "AArch64ISD::FCMEQz";
914 case AArch64ISD::FCMGEz: return "AArch64ISD::FCMGEz";
915 case AArch64ISD::FCMGTz: return "AArch64ISD::FCMGTz";
916 case AArch64ISD::FCMLEz: return "AArch64ISD::FCMLEz";
917 case AArch64ISD::FCMLTz: return "AArch64ISD::FCMLTz";
Ahmed Bougachafab58922015-03-10 20:45:38 +0000918 case AArch64ISD::SADDV: return "AArch64ISD::SADDV";
919 case AArch64ISD::UADDV: return "AArch64ISD::UADDV";
920 case AArch64ISD::SMINV: return "AArch64ISD::SMINV";
921 case AArch64ISD::UMINV: return "AArch64ISD::UMINV";
922 case AArch64ISD::SMAXV: return "AArch64ISD::SMAXV";
923 case AArch64ISD::UMAXV: return "AArch64ISD::UMAXV";
Tim Northover3b0846e2014-05-24 12:50:23 +0000924 case AArch64ISD::NOT: return "AArch64ISD::NOT";
925 case AArch64ISD::BIT: return "AArch64ISD::BIT";
926 case AArch64ISD::CBZ: return "AArch64ISD::CBZ";
927 case AArch64ISD::CBNZ: return "AArch64ISD::CBNZ";
928 case AArch64ISD::TBZ: return "AArch64ISD::TBZ";
929 case AArch64ISD::TBNZ: return "AArch64ISD::TBNZ";
930 case AArch64ISD::TC_RETURN: return "AArch64ISD::TC_RETURN";
Matthias Braund04893f2015-05-07 21:33:59 +0000931 case AArch64ISD::PREFETCH: return "AArch64ISD::PREFETCH";
Tim Northover3b0846e2014-05-24 12:50:23 +0000932 case AArch64ISD::SITOF: return "AArch64ISD::SITOF";
933 case AArch64ISD::UITOF: return "AArch64ISD::UITOF";
Asiri Rathnayake530b3ed2014-10-01 09:59:45 +0000934 case AArch64ISD::NVCAST: return "AArch64ISD::NVCAST";
Tim Northover3b0846e2014-05-24 12:50:23 +0000935 case AArch64ISD::SQSHL_I: return "AArch64ISD::SQSHL_I";
936 case AArch64ISD::UQSHL_I: return "AArch64ISD::UQSHL_I";
937 case AArch64ISD::SRSHR_I: return "AArch64ISD::SRSHR_I";
938 case AArch64ISD::URSHR_I: return "AArch64ISD::URSHR_I";
939 case AArch64ISD::SQSHLU_I: return "AArch64ISD::SQSHLU_I";
940 case AArch64ISD::WrapperLarge: return "AArch64ISD::WrapperLarge";
941 case AArch64ISD::LD2post: return "AArch64ISD::LD2post";
942 case AArch64ISD::LD3post: return "AArch64ISD::LD3post";
943 case AArch64ISD::LD4post: return "AArch64ISD::LD4post";
944 case AArch64ISD::ST2post: return "AArch64ISD::ST2post";
945 case AArch64ISD::ST3post: return "AArch64ISD::ST3post";
946 case AArch64ISD::ST4post: return "AArch64ISD::ST4post";
947 case AArch64ISD::LD1x2post: return "AArch64ISD::LD1x2post";
948 case AArch64ISD::LD1x3post: return "AArch64ISD::LD1x3post";
949 case AArch64ISD::LD1x4post: return "AArch64ISD::LD1x4post";
950 case AArch64ISD::ST1x2post: return "AArch64ISD::ST1x2post";
951 case AArch64ISD::ST1x3post: return "AArch64ISD::ST1x3post";
952 case AArch64ISD::ST1x4post: return "AArch64ISD::ST1x4post";
953 case AArch64ISD::LD1DUPpost: return "AArch64ISD::LD1DUPpost";
954 case AArch64ISD::LD2DUPpost: return "AArch64ISD::LD2DUPpost";
955 case AArch64ISD::LD3DUPpost: return "AArch64ISD::LD3DUPpost";
956 case AArch64ISD::LD4DUPpost: return "AArch64ISD::LD4DUPpost";
957 case AArch64ISD::LD1LANEpost: return "AArch64ISD::LD1LANEpost";
958 case AArch64ISD::LD2LANEpost: return "AArch64ISD::LD2LANEpost";
959 case AArch64ISD::LD3LANEpost: return "AArch64ISD::LD3LANEpost";
960 case AArch64ISD::LD4LANEpost: return "AArch64ISD::LD4LANEpost";
961 case AArch64ISD::ST2LANEpost: return "AArch64ISD::ST2LANEpost";
962 case AArch64ISD::ST3LANEpost: return "AArch64ISD::ST3LANEpost";
963 case AArch64ISD::ST4LANEpost: return "AArch64ISD::ST4LANEpost";
Chad Rosierd9d0f862014-10-08 02:31:24 +0000964 case AArch64ISD::SMULL: return "AArch64ISD::SMULL";
965 case AArch64ISD::UMULL: return "AArch64ISD::UMULL";
Evandro Menezesbcb95cd2016-05-04 20:18:27 +0000966 case AArch64ISD::FRSQRTE: return "AArch64ISD::FRSQRTE";
967 case AArch64ISD::FRECPE: return "AArch64ISD::FRECPE";
Tim Northover3b0846e2014-05-24 12:50:23 +0000968 }
Matthias Braund04893f2015-05-07 21:33:59 +0000969 return nullptr;
Tim Northover3b0846e2014-05-24 12:50:23 +0000970}
971
972MachineBasicBlock *
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +0000973AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI,
Tim Northover3b0846e2014-05-24 12:50:23 +0000974 MachineBasicBlock *MBB) const {
975 // We materialise the F128CSEL pseudo-instruction as some control flow and a
976 // phi node:
977
978 // OrigBB:
979 // [... previous instrs leading to comparison ...]
980 // b.ne TrueBB
981 // b EndBB
982 // TrueBB:
983 // ; Fallthrough
984 // EndBB:
985 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
986
Tim Northover3b0846e2014-05-24 12:50:23 +0000987 MachineFunction *MF = MBB->getParent();
Eric Christopher905f12d2015-01-29 00:19:42 +0000988 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +0000989 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +0000990 DebugLoc DL = MI.getDebugLoc();
Duncan P. N. Exon Smithd3b9df02015-10-13 20:02:15 +0000991 MachineFunction::iterator It = ++MBB->getIterator();
Tim Northover3b0846e2014-05-24 12:50:23 +0000992
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +0000993 unsigned DestReg = MI.getOperand(0).getReg();
994 unsigned IfTrueReg = MI.getOperand(1).getReg();
995 unsigned IfFalseReg = MI.getOperand(2).getReg();
996 unsigned CondCode = MI.getOperand(3).getImm();
997 bool NZCVKilled = MI.getOperand(4).isKill();
Tim Northover3b0846e2014-05-24 12:50:23 +0000998
999 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
1000 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
1001 MF->insert(It, TrueBB);
1002 MF->insert(It, EndBB);
1003
1004 // Transfer rest of current basic-block to EndBB
1005 EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
1006 MBB->end());
1007 EndBB->transferSuccessorsAndUpdatePHIs(MBB);
1008
1009 BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
1010 BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
1011 MBB->addSuccessor(TrueBB);
1012 MBB->addSuccessor(EndBB);
1013
1014 // TrueBB falls through to the end.
1015 TrueBB->addSuccessor(EndBB);
1016
1017 if (!NZCVKilled) {
1018 TrueBB->addLiveIn(AArch64::NZCV);
1019 EndBB->addLiveIn(AArch64::NZCV);
1020 }
1021
1022 BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
1023 .addReg(IfTrueReg)
1024 .addMBB(TrueBB)
1025 .addReg(IfFalseReg)
1026 .addMBB(MBB);
1027
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001028 MI.eraseFromParent();
Tim Northover3b0846e2014-05-24 12:50:23 +00001029 return EndBB;
1030}
1031
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001032MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter(
1033 MachineInstr &MI, MachineBasicBlock *BB) const {
1034 switch (MI.getOpcode()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001035 default:
1036#ifndef NDEBUG
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001037 MI.dump();
Tim Northover3b0846e2014-05-24 12:50:23 +00001038#endif
Craig Topper35b2f752014-06-19 06:10:58 +00001039 llvm_unreachable("Unexpected instruction for custom inserter!");
Tim Northover3b0846e2014-05-24 12:50:23 +00001040
1041 case AArch64::F128CSEL:
1042 return EmitF128CSEL(MI, BB);
1043
1044 case TargetOpcode::STACKMAP:
1045 case TargetOpcode::PATCHPOINT:
1046 return emitPatchPoint(MI, BB);
1047 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001048}
1049
1050//===----------------------------------------------------------------------===//
1051// AArch64 Lowering private implementation.
1052//===----------------------------------------------------------------------===//
1053
1054//===----------------------------------------------------------------------===//
1055// Lowering Code
1056//===----------------------------------------------------------------------===//
1057
1058/// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1059/// CC
1060static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1061 switch (CC) {
1062 default:
1063 llvm_unreachable("Unknown condition code!");
1064 case ISD::SETNE:
1065 return AArch64CC::NE;
1066 case ISD::SETEQ:
1067 return AArch64CC::EQ;
1068 case ISD::SETGT:
1069 return AArch64CC::GT;
1070 case ISD::SETGE:
1071 return AArch64CC::GE;
1072 case ISD::SETLT:
1073 return AArch64CC::LT;
1074 case ISD::SETLE:
1075 return AArch64CC::LE;
1076 case ISD::SETUGT:
1077 return AArch64CC::HI;
1078 case ISD::SETUGE:
1079 return AArch64CC::HS;
1080 case ISD::SETULT:
1081 return AArch64CC::LO;
1082 case ISD::SETULE:
1083 return AArch64CC::LS;
1084 }
1085}
1086
1087/// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1088static void changeFPCCToAArch64CC(ISD::CondCode CC,
1089 AArch64CC::CondCode &CondCode,
1090 AArch64CC::CondCode &CondCode2) {
1091 CondCode2 = AArch64CC::AL;
1092 switch (CC) {
1093 default:
1094 llvm_unreachable("Unknown FP condition!");
1095 case ISD::SETEQ:
1096 case ISD::SETOEQ:
1097 CondCode = AArch64CC::EQ;
1098 break;
1099 case ISD::SETGT:
1100 case ISD::SETOGT:
1101 CondCode = AArch64CC::GT;
1102 break;
1103 case ISD::SETGE:
1104 case ISD::SETOGE:
1105 CondCode = AArch64CC::GE;
1106 break;
1107 case ISD::SETOLT:
1108 CondCode = AArch64CC::MI;
1109 break;
1110 case ISD::SETOLE:
1111 CondCode = AArch64CC::LS;
1112 break;
1113 case ISD::SETONE:
1114 CondCode = AArch64CC::MI;
1115 CondCode2 = AArch64CC::GT;
1116 break;
1117 case ISD::SETO:
1118 CondCode = AArch64CC::VC;
1119 break;
1120 case ISD::SETUO:
1121 CondCode = AArch64CC::VS;
1122 break;
1123 case ISD::SETUEQ:
1124 CondCode = AArch64CC::EQ;
1125 CondCode2 = AArch64CC::VS;
1126 break;
1127 case ISD::SETUGT:
1128 CondCode = AArch64CC::HI;
1129 break;
1130 case ISD::SETUGE:
1131 CondCode = AArch64CC::PL;
1132 break;
1133 case ISD::SETLT:
1134 case ISD::SETULT:
1135 CondCode = AArch64CC::LT;
1136 break;
1137 case ISD::SETLE:
1138 case ISD::SETULE:
1139 CondCode = AArch64CC::LE;
1140 break;
1141 case ISD::SETNE:
1142 case ISD::SETUNE:
1143 CondCode = AArch64CC::NE;
1144 break;
1145 }
1146}
1147
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001148/// Convert a DAG fp condition code to an AArch64 CC.
1149/// This differs from changeFPCCToAArch64CC in that it returns cond codes that
1150/// should be AND'ed instead of OR'ed.
1151static void changeFPCCToANDAArch64CC(ISD::CondCode CC,
1152 AArch64CC::CondCode &CondCode,
1153 AArch64CC::CondCode &CondCode2) {
1154 CondCode2 = AArch64CC::AL;
1155 switch (CC) {
1156 default:
1157 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1158 assert(CondCode2 == AArch64CC::AL);
1159 break;
1160 case ISD::SETONE:
1161 // (a one b)
1162 // == ((a olt b) || (a ogt b))
1163 // == ((a ord b) && (a une b))
1164 CondCode = AArch64CC::VC;
1165 CondCode2 = AArch64CC::NE;
1166 break;
1167 case ISD::SETUEQ:
1168 // (a ueq b)
1169 // == ((a uno b) || (a oeq b))
1170 // == ((a ule b) && (a uge b))
1171 CondCode = AArch64CC::PL;
1172 CondCode2 = AArch64CC::LE;
1173 break;
1174 }
1175}
1176
Tim Northover3b0846e2014-05-24 12:50:23 +00001177/// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1178/// CC usable with the vector instructions. Fewer operations are available
1179/// without a real NZCV register, so we have to use less efficient combinations
1180/// to get the same effect.
1181static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1182 AArch64CC::CondCode &CondCode,
1183 AArch64CC::CondCode &CondCode2,
1184 bool &Invert) {
1185 Invert = false;
1186 switch (CC) {
1187 default:
1188 // Mostly the scalar mappings work fine.
1189 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1190 break;
1191 case ISD::SETUO:
1192 Invert = true; // Fallthrough
1193 case ISD::SETO:
1194 CondCode = AArch64CC::MI;
1195 CondCode2 = AArch64CC::GE;
1196 break;
1197 case ISD::SETUEQ:
1198 case ISD::SETULT:
1199 case ISD::SETULE:
1200 case ISD::SETUGT:
1201 case ISD::SETUGE:
1202 // All of the compare-mask comparisons are ordered, but we can switch
1203 // between the two by a double inversion. E.g. ULE == !OGT.
1204 Invert = true;
1205 changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1206 break;
1207 }
1208}
1209
1210static bool isLegalArithImmed(uint64_t C) {
1211 // Matches AArch64DAGToDAGISel::SelectArithImmed().
1212 return (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1213}
1214
1215static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00001216 const SDLoc &dl, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001217 EVT VT = LHS.getValueType();
1218
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001219 if (VT.isFloatingPoint()) {
1220 assert(VT != MVT::f128);
1221 if (VT == MVT::f16) {
1222 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
1223 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
Weiming Zhao095c2712016-05-11 01:26:32 +00001224 VT = MVT::f32;
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001225 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001226 return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001227 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001228
1229 // The CMP instruction is just an alias for SUBS, and representing it as
1230 // SUBS means that it's possible to get CSE with subtract operations.
1231 // A later phase can perform the optimization of setting the destination
1232 // register to WZR/XZR if it ends up being unused.
1233 unsigned Opcode = AArch64ISD::SUBS;
1234
Artyom Skrobov314ee042015-11-25 19:41:11 +00001235 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001236 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1237 // We'd like to combine a (CMP op1, (sub 0, op2) into a CMN instruction on
1238 // the grounds that "op1 - (-op2) == op1 + op2". However, the C and V flags
1239 // can be set differently by this operation. It comes down to whether
1240 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1241 // everything is fine. If not then the optimization is wrong. Thus general
1242 // comparisons are only valid if op2 != 0.
1243
1244 // So, finally, the only LLVM-native comparisons that don't mention C and V
1245 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1246 // the absence of information about op2.
1247 Opcode = AArch64ISD::ADDS;
1248 RHS = RHS.getOperand(1);
Artyom Skrobov314ee042015-11-25 19:41:11 +00001249 } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001250 !isUnsignedIntSetCC(CC)) {
1251 // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1252 // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1253 // of the signed comparisons.
1254 Opcode = AArch64ISD::ANDS;
1255 RHS = LHS.getOperand(1);
1256 LHS = LHS.getOperand(0);
1257 }
1258
Matthias Braunaf7d7702015-07-16 20:02:37 +00001259 return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
Tim Northover3b0846e2014-05-24 12:50:23 +00001260 .getValue(1);
1261}
1262
Matthias Braunaf7d7702015-07-16 20:02:37 +00001263/// \defgroup AArch64CCMP CMP;CCMP matching
1264///
1265/// These functions deal with the formation of CMP;CCMP;... sequences.
1266/// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1267/// a comparison. They set the NZCV flags to a predefined value if their
1268/// predicate is false. This allows to express arbitrary conjunctions, for
1269/// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B))))"
1270/// expressed as:
1271/// cmp A
1272/// ccmp B, inv(CB), CA
1273/// check for CB flags
1274///
1275/// In general we can create code for arbitrary "... (and (and A B) C)"
1276/// sequences. We can also implement some "or" expressions, because "(or A B)"
1277/// is equivalent to "not (and (not A) (not B))" and we can implement some
1278/// negation operations:
1279/// We can negate the results of a single comparison by inverting the flags
1280/// used when the predicate fails and inverting the flags tested in the next
1281/// instruction; We can also negate the results of the whole previous
1282/// conditional compare sequence by inverting the flags tested in the next
1283/// instruction. However there is no way to negate the result of a partial
1284/// sequence.
1285///
1286/// Therefore on encountering an "or" expression we can negate the subtree on
1287/// one side and have to be able to push the negate to the leafs of the subtree
1288/// on the other side (see also the comments in code). As complete example:
1289/// "or (or (setCA (cmp A)) (setCB (cmp B)))
1290/// (and (setCC (cmp C)) (setCD (cmp D)))"
1291/// is transformed to
1292/// "not (and (not (and (setCC (cmp C)) (setCC (cmp D))))
1293/// (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1294/// and implemented as:
1295/// cmp C
1296/// ccmp D, inv(CD), CC
1297/// ccmp A, CA, inv(CD)
1298/// ccmp B, CB, inv(CA)
1299/// check for CB flags
1300/// A counterexample is "or (and A B) (and C D)" which cannot be implemented
1301/// by conditional compare sequences.
1302/// @{
1303
Geoff Berrye41c2df2015-07-20 22:03:52 +00001304/// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001305static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1306 ISD::CondCode CC, SDValue CCOp,
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001307 AArch64CC::CondCode Predicate,
1308 AArch64CC::CondCode OutCC,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00001309 const SDLoc &DL, SelectionDAG &DAG) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001310 unsigned Opcode = 0;
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001311 if (LHS.getValueType().isFloatingPoint()) {
1312 assert(LHS.getValueType() != MVT::f128);
1313 if (LHS.getValueType() == MVT::f16) {
1314 LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS);
1315 RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS);
1316 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001317 Opcode = AArch64ISD::FCCMP;
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001318 } else if (RHS.getOpcode() == ISD::SUB) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001319 SDValue SubOp0 = RHS.getOperand(0);
Artyom Skrobov314ee042015-11-25 19:41:11 +00001320 if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
Matthias Braunfd13c142016-01-23 04:05:16 +00001321 // See emitComparison() on why we can only do this for SETEQ and SETNE.
1322 Opcode = AArch64ISD::CCMN;
1323 RHS = RHS.getOperand(1);
1324 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001325 }
1326 if (Opcode == 0)
1327 Opcode = AArch64ISD::CCMP;
1328
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001329 SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC);
1330 AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1331 unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001332 SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1333 return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1334}
1335
1336/// Returns true if @p Val is a tree of AND/OR/SETCC operations.
1337/// CanPushNegate is set to true if we can push a negate operation through
1338/// the tree in a was that we are left with AND operations and negate operations
1339/// at the leafs only. i.e. "not (or (or x y) z)" can be changed to
1340/// "and (and (not x) (not y)) (not z)"; "not (or (and x y) z)" cannot be
1341/// brought into such a form.
Matthias Braunfdef49b2016-01-23 04:05:22 +00001342static bool isConjunctionDisjunctionTree(const SDValue Val, bool &CanNegate,
Matthias Braunaf7d7702015-07-16 20:02:37 +00001343 unsigned Depth = 0) {
1344 if (!Val.hasOneUse())
1345 return false;
1346 unsigned Opcode = Val->getOpcode();
1347 if (Opcode == ISD::SETCC) {
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001348 if (Val->getOperand(0).getValueType() == MVT::f128)
1349 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001350 CanNegate = true;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001351 return true;
1352 }
Matthias Braun985bdf92016-01-23 04:05:18 +00001353 // Protect against exponential runtime and stack overflow.
1354 if (Depth > 6)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001355 return false;
1356 if (Opcode == ISD::AND || Opcode == ISD::OR) {
1357 SDValue O0 = Val->getOperand(0);
1358 SDValue O1 = Val->getOperand(1);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001359 bool CanNegateL;
1360 if (!isConjunctionDisjunctionTree(O0, CanNegateL, Depth+1))
Matthias Braunaf7d7702015-07-16 20:02:37 +00001361 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001362 bool CanNegateR;
1363 if (!isConjunctionDisjunctionTree(O1, CanNegateR, Depth+1))
Matthias Braunaf7d7702015-07-16 20:02:37 +00001364 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001365
1366 if (Opcode == ISD::OR) {
1367 // For an OR expression we need to be able to negate at least one side or
1368 // we cannot do the transformation at all.
1369 if (!CanNegateL && !CanNegateR)
1370 return false;
1371 // We can however change a (not (or x y)) to (and (not x) (not y)) if we
1372 // can negate the x and y subtrees.
1373 CanNegate = CanNegateL && CanNegateR;
1374 } else {
1375 // If the operands are OR expressions then we finally need to negate their
1376 // outputs, we can only do that for the operand with emitted last by
1377 // negating OutCC, not for both operands.
1378 bool NeedsNegOutL = O0->getOpcode() == ISD::OR;
1379 bool NeedsNegOutR = O1->getOpcode() == ISD::OR;
1380 if (NeedsNegOutL && NeedsNegOutR)
1381 return false;
1382 // We cannot negate an AND operation (it would become an OR),
1383 CanNegate = false;
1384 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001385 return true;
1386 }
1387 return false;
1388}
1389
1390/// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1391/// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1392/// Tries to transform the given i1 producing node @p Val to a series compare
1393/// and conditional compare operations. @returns an NZCV flags producing node
1394/// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1395/// transformation was not possible.
1396/// On recursive invocations @p PushNegate may be set to true to have negation
1397/// effects pushed to the tree leafs; @p Predicate is an NZCV flag predicate
1398/// for the comparisons in the current subtree; @p Depth limits the search
1399/// depth to avoid stack overflow.
Matthias Braunfdef49b2016-01-23 04:05:22 +00001400static SDValue emitConjunctionDisjunctionTreeRec(SelectionDAG &DAG, SDValue Val,
1401 AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp,
1402 AArch64CC::CondCode Predicate) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001403 // We're at a tree leaf, produce a conditional comparison operation.
1404 unsigned Opcode = Val->getOpcode();
1405 if (Opcode == ISD::SETCC) {
1406 SDValue LHS = Val->getOperand(0);
1407 SDValue RHS = Val->getOperand(1);
1408 ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1409 bool isInteger = LHS.getValueType().isInteger();
Matthias Braunfdef49b2016-01-23 04:05:22 +00001410 if (Negate)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001411 CC = getSetCCInverse(CC, isInteger);
1412 SDLoc DL(Val);
1413 // Determine OutCC and handle FP special case.
1414 if (isInteger) {
1415 OutCC = changeIntCCToAArch64CC(CC);
1416 } else {
1417 assert(LHS.getValueType().isFloatingPoint());
1418 AArch64CC::CondCode ExtraCC;
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001419 changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
1420 // Some floating point conditions can't be tested with a single condition
1421 // code. Construct an additional comparison in this case.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001422 if (ExtraCC != AArch64CC::AL) {
1423 SDValue ExtraCmp;
1424 if (!CCOp.getNode())
1425 ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001426 else
1427 ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate,
1428 ExtraCC, DL, DAG);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001429 CCOp = ExtraCmp;
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001430 Predicate = ExtraCC;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001431 }
1432 }
1433
1434 // Produce a normal comparison if we are first in the chain
Matthias Braunfdef49b2016-01-23 04:05:22 +00001435 if (!CCOp)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001436 return emitComparison(LHS, RHS, CC, DL, DAG);
1437 // Otherwise produce a ccmp.
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001438 return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL,
Matthias Braunaf7d7702015-07-16 20:02:37 +00001439 DAG);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001440 }
Junmo Park3ca3e192016-01-25 10:17:17 +00001441 assert((Opcode == ISD::AND || (Opcode == ISD::OR && Val->hasOneUse())) &&
1442 "Valid conjunction/disjunction tree");
Matthias Braunaf7d7702015-07-16 20:02:37 +00001443
1444 // Check if both sides can be transformed.
1445 SDValue LHS = Val->getOperand(0);
1446 SDValue RHS = Val->getOperand(1);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001447
Matthias Braunfdef49b2016-01-23 04:05:22 +00001448 // In case of an OR we need to negate our operands and the result.
1449 // (A v B) <=> not(not(A) ^ not(B))
1450 bool NegateOpsAndResult = Opcode == ISD::OR;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001451 // We can negate the results of all previous operations by inverting the
Matthias Braunfdef49b2016-01-23 04:05:22 +00001452 // predicate flags giving us a free negation for one side. The other side
1453 // must be negatable by itself.
1454 if (NegateOpsAndResult) {
1455 // See which side we can negate.
1456 bool CanNegateL;
1457 bool isValidL = isConjunctionDisjunctionTree(LHS, CanNegateL);
1458 assert(isValidL && "Valid conjunction/disjunction tree");
1459 (void)isValidL;
1460
1461#ifndef NDEBUG
1462 bool CanNegateR;
1463 bool isValidR = isConjunctionDisjunctionTree(RHS, CanNegateR);
1464 assert(isValidR && "Valid conjunction/disjunction tree");
1465 assert((CanNegateL || CanNegateR) && "Valid conjunction/disjunction tree");
1466#endif
1467
1468 // Order the side which we cannot negate to RHS so we can emit it first.
1469 if (!CanNegateL)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001470 std::swap(LHS, RHS);
Matthias Braun46e56392015-08-20 23:33:34 +00001471 } else {
1472 bool NeedsNegOutL = LHS->getOpcode() == ISD::OR;
Matthias Braun327bca72016-01-23 06:49:29 +00001473 assert((!NeedsNegOutL || RHS->getOpcode() != ISD::OR) &&
Matthias Braunfdef49b2016-01-23 04:05:22 +00001474 "Valid conjunction/disjunction tree");
Matthias Braun46e56392015-08-20 23:33:34 +00001475 // Order the side where we need to negate the output flags to RHS so it
1476 // gets emitted first.
1477 if (NeedsNegOutL)
1478 std::swap(LHS, RHS);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001479 }
1480
1481 // Emit RHS. If we want to negate the tree we only need to push a negate
1482 // through if we are already in a PushNegate case, otherwise we can negate
1483 // the "flags to test" afterwards.
1484 AArch64CC::CondCode RHSCC;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001485 SDValue CmpR = emitConjunctionDisjunctionTreeRec(DAG, RHS, RHSCC, Negate,
1486 CCOp, Predicate);
1487 if (NegateOpsAndResult && !Negate)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001488 RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001489 // Emit LHS. We may need to negate it.
1490 SDValue CmpL = emitConjunctionDisjunctionTreeRec(DAG, LHS, OutCC,
1491 NegateOpsAndResult, CmpR,
1492 RHSCC);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001493 // If we transformed an OR to and AND then we have to negate the result
Matthias Braunfdef49b2016-01-23 04:05:22 +00001494 // (or absorb the Negate parameter).
1495 if (NegateOpsAndResult && !Negate)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001496 OutCC = AArch64CC::getInvertedCondCode(OutCC);
1497 return CmpL;
1498}
1499
Matthias Braunfdef49b2016-01-23 04:05:22 +00001500/// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1501/// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1502/// \see emitConjunctionDisjunctionTreeRec().
1503static SDValue emitConjunctionDisjunctionTree(SelectionDAG &DAG, SDValue Val,
1504 AArch64CC::CondCode &OutCC) {
1505 bool CanNegate;
1506 if (!isConjunctionDisjunctionTree(Val, CanNegate))
1507 return SDValue();
1508
1509 return emitConjunctionDisjunctionTreeRec(DAG, Val, OutCC, false, SDValue(),
1510 AArch64CC::AL);
1511}
1512
Matthias Braunaf7d7702015-07-16 20:02:37 +00001513/// @}
1514
Tim Northover3b0846e2014-05-24 12:50:23 +00001515static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00001516 SDValue &AArch64cc, SelectionDAG &DAG,
1517 const SDLoc &dl) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001518 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1519 EVT VT = RHS.getValueType();
1520 uint64_t C = RHSC->getZExtValue();
1521 if (!isLegalArithImmed(C)) {
1522 // Constant does not fit, try adjusting it by one?
1523 switch (CC) {
1524 default:
1525 break;
1526 case ISD::SETLT:
1527 case ISD::SETGE:
1528 if ((VT == MVT::i32 && C != 0x80000000 &&
1529 isLegalArithImmed((uint32_t)(C - 1))) ||
1530 (VT == MVT::i64 && C != 0x80000000ULL &&
1531 isLegalArithImmed(C - 1ULL))) {
1532 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1533 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001534 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001535 }
1536 break;
1537 case ISD::SETULT:
1538 case ISD::SETUGE:
1539 if ((VT == MVT::i32 && C != 0 &&
1540 isLegalArithImmed((uint32_t)(C - 1))) ||
1541 (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1542 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1543 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001544 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001545 }
1546 break;
1547 case ISD::SETLE:
1548 case ISD::SETGT:
Oliver Stannard269a275c2014-11-03 15:28:40 +00001549 if ((VT == MVT::i32 && C != INT32_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001550 isLegalArithImmed((uint32_t)(C + 1))) ||
Oliver Stannard269a275c2014-11-03 15:28:40 +00001551 (VT == MVT::i64 && C != INT64_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001552 isLegalArithImmed(C + 1ULL))) {
1553 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1554 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001555 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001556 }
1557 break;
1558 case ISD::SETULE:
1559 case ISD::SETUGT:
Oliver Stannard269a275c2014-11-03 15:28:40 +00001560 if ((VT == MVT::i32 && C != UINT32_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001561 isLegalArithImmed((uint32_t)(C + 1))) ||
Oliver Stannard269a275c2014-11-03 15:28:40 +00001562 (VT == MVT::i64 && C != UINT64_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001563 isLegalArithImmed(C + 1ULL))) {
1564 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1565 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001566 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001567 }
1568 break;
1569 }
1570 }
1571 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001572 SDValue Cmp;
1573 AArch64CC::CondCode AArch64CC;
David Xuee978202014-08-28 04:59:53 +00001574 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001575 const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
1576
1577 // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
1578 // For the i8 operand, the largest immediate is 255, so this can be easily
1579 // encoded in the compare instruction. For the i16 operand, however, the
1580 // largest immediate cannot be encoded in the compare.
1581 // Therefore, use a sign extending load and cmn to avoid materializing the
1582 // -1 constant. For example,
1583 // movz w1, #65535
1584 // ldrh w0, [x0, #0]
1585 // cmp w0, w1
1586 // >
1587 // ldrsh w0, [x0, #0]
1588 // cmn w0, #1
1589 // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
1590 // if and only if (sext LHS) == (sext RHS). The checks are in place to
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001591 // ensure both the LHS and RHS are truly zero extended and to make sure the
Matthias Braunaf7d7702015-07-16 20:02:37 +00001592 // transformation is profitable.
1593 if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
1594 cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
1595 cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
1596 LHS.getNode()->hasNUsesOfValue(1, 0)) {
1597 int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
1598 if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
1599 SDValue SExt =
1600 DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
1601 DAG.getValueType(MVT::i16));
1602 Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
1603 RHS.getValueType()),
1604 CC, dl, DAG);
1605 AArch64CC = changeIntCCToAArch64CC(CC);
1606 }
1607 }
1608
1609 if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
1610 if ((Cmp = emitConjunctionDisjunctionTree(DAG, LHS, AArch64CC))) {
1611 if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
1612 AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
David Xuee978202014-08-28 04:59:53 +00001613 }
1614 }
1615 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001616
1617 if (!Cmp) {
1618 Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
1619 AArch64CC = changeIntCCToAArch64CC(CC);
1620 }
1621 AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
Tim Northover3b0846e2014-05-24 12:50:23 +00001622 return Cmp;
1623}
1624
Balaram Makam92431702016-02-01 19:13:07 +00001625// Attempt to form conditional compare sequences for and/or trees
1626// with setcc leafs.
1627static SDValue tryLowerToAArch64Cmp(SDValue Op, SelectionDAG &DAG) {
1628 SDValue LHS = Op.getOperand(0);
1629 SDValue RHS = Op.getOperand(1);
1630 if ((LHS.getOpcode() != ISD::SETCC) || (RHS.getOpcode() != ISD::SETCC))
1631 return Op;
1632
1633 bool CanNegate;
1634 if (!isConjunctionDisjunctionTree(Op, CanNegate))
1635 return SDValue();
1636
1637 EVT VT = Op.getValueType();
1638 SDLoc DL(Op);
1639 SDValue TVal = DAG.getConstant(1, DL, VT);
1640 SDValue FVal = DAG.getConstant(0, DL, VT);
1641 SDValue CCVal;
1642 SDValue Cmp = getAArch64Cmp(Op, FVal, ISD::SETEQ, CCVal, DAG, DL);
1643 return DAG.getNode(AArch64ISD::CSEL, DL, VT, FVal, TVal, CCVal, Cmp);
1644}
1645
Tim Northover3b0846e2014-05-24 12:50:23 +00001646static std::pair<SDValue, SDValue>
1647getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
1648 assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
1649 "Unsupported value type");
1650 SDValue Value, Overflow;
1651 SDLoc DL(Op);
1652 SDValue LHS = Op.getOperand(0);
1653 SDValue RHS = Op.getOperand(1);
1654 unsigned Opc = 0;
1655 switch (Op.getOpcode()) {
1656 default:
1657 llvm_unreachable("Unknown overflow instruction!");
1658 case ISD::SADDO:
1659 Opc = AArch64ISD::ADDS;
1660 CC = AArch64CC::VS;
1661 break;
1662 case ISD::UADDO:
1663 Opc = AArch64ISD::ADDS;
1664 CC = AArch64CC::HS;
1665 break;
1666 case ISD::SSUBO:
1667 Opc = AArch64ISD::SUBS;
1668 CC = AArch64CC::VS;
1669 break;
1670 case ISD::USUBO:
1671 Opc = AArch64ISD::SUBS;
1672 CC = AArch64CC::LO;
1673 break;
1674 // Multiply needs a little bit extra work.
1675 case ISD::SMULO:
1676 case ISD::UMULO: {
1677 CC = AArch64CC::NE;
David Blaikie186d2cb2015-03-24 16:24:01 +00001678 bool IsSigned = Op.getOpcode() == ISD::SMULO;
Tim Northover3b0846e2014-05-24 12:50:23 +00001679 if (Op.getValueType() == MVT::i32) {
1680 unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1681 // For a 32 bit multiply with overflow check we want the instruction
1682 // selector to generate a widening multiply (SMADDL/UMADDL). For that we
1683 // need to generate the following pattern:
1684 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
1685 LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
1686 RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
1687 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1688 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001689 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001690 // On AArch64 the upper 32 bits are always zero extended for a 32 bit
1691 // operation. We need to clear out the upper 32 bits, because we used a
1692 // widening multiply that wrote all 64 bits. In the end this should be a
1693 // noop.
1694 Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
1695 if (IsSigned) {
1696 // The signed overflow check requires more than just a simple check for
1697 // any bit set in the upper 32 bits of the result. These bits could be
1698 // just the sign bits of a negative number. To perform the overflow
1699 // check we have to arithmetic shift right the 32nd bit of the result by
1700 // 31 bits. Then we compare the result to the upper 32 bits.
1701 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001702 DAG.getConstant(32, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001703 UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
1704 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001705 DAG.getConstant(31, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001706 // It is important that LowerBits is last, otherwise the arithmetic
1707 // shift will not be folded into the compare (SUBS).
1708 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
1709 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1710 .getValue(1);
1711 } else {
1712 // The overflow check for unsigned multiply is easy. We only need to
1713 // check if any of the upper 32 bits are set. This can be done with a
1714 // CMP (shifted register). For that we need to generate the following
1715 // pattern:
1716 // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
1717 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001718 DAG.getConstant(32, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001719 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1720 Overflow =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001721 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1722 DAG.getConstant(0, DL, MVT::i64),
Tim Northover3b0846e2014-05-24 12:50:23 +00001723 UpperBits).getValue(1);
1724 }
1725 break;
1726 }
1727 assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
1728 // For the 64 bit multiply
1729 Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1730 if (IsSigned) {
1731 SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
1732 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001733 DAG.getConstant(63, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001734 // It is important that LowerBits is last, otherwise the arithmetic
1735 // shift will not be folded into the compare (SUBS).
1736 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1737 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1738 .getValue(1);
1739 } else {
1740 SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
1741 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1742 Overflow =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001743 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1744 DAG.getConstant(0, DL, MVT::i64),
Tim Northover3b0846e2014-05-24 12:50:23 +00001745 UpperBits).getValue(1);
1746 }
1747 break;
1748 }
1749 } // switch (...)
1750
1751 if (Opc) {
1752 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
1753
1754 // Emit the AArch64 operation with overflow check.
1755 Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
1756 Overflow = Value.getValue(1);
1757 }
1758 return std::make_pair(Value, Overflow);
1759}
1760
1761SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
1762 RTLIB::Libcall Call) const {
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00001763 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
Craig Topper8fe40e02015-10-22 17:05:00 +00001764 return makeLibCall(DAG, Call, MVT::f128, Ops, false, SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00001765}
1766
Balaram Makam92431702016-02-01 19:13:07 +00001767SDValue AArch64TargetLowering::LowerAND(SDValue Op, SelectionDAG &DAG) const {
1768 if (Op.getValueType().isVector())
1769 return LowerVectorAND(Op, DAG);
1770 return tryLowerToAArch64Cmp(Op, DAG);
1771}
1772
1773SDValue AArch64TargetLowering::LowerOR(SDValue Op, SelectionDAG &DAG) const {
1774 if (Op.getValueType().isVector())
1775 return LowerVectorOR(Op, DAG);
1776 return tryLowerToAArch64Cmp(Op, DAG);
1777}
1778
Tim Northover3b0846e2014-05-24 12:50:23 +00001779static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
1780 SDValue Sel = Op.getOperand(0);
1781 SDValue Other = Op.getOperand(1);
1782
1783 // If neither operand is a SELECT_CC, give up.
1784 if (Sel.getOpcode() != ISD::SELECT_CC)
1785 std::swap(Sel, Other);
1786 if (Sel.getOpcode() != ISD::SELECT_CC)
1787 return Op;
1788
1789 // The folding we want to perform is:
1790 // (xor x, (select_cc a, b, cc, 0, -1) )
1791 // -->
1792 // (csel x, (xor x, -1), cc ...)
1793 //
1794 // The latter will get matched to a CSINV instruction.
1795
1796 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
1797 SDValue LHS = Sel.getOperand(0);
1798 SDValue RHS = Sel.getOperand(1);
1799 SDValue TVal = Sel.getOperand(2);
1800 SDValue FVal = Sel.getOperand(3);
1801 SDLoc dl(Sel);
1802
1803 // FIXME: This could be generalized to non-integer comparisons.
1804 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
1805 return Op;
1806
1807 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
1808 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
1809
Eric Christopher572e03a2015-06-19 01:53:21 +00001810 // The values aren't constants, this isn't the pattern we're looking for.
Tim Northover3b0846e2014-05-24 12:50:23 +00001811 if (!CFVal || !CTVal)
1812 return Op;
1813
1814 // We can commute the SELECT_CC by inverting the condition. This
1815 // might be needed to make this fit into a CSINV pattern.
1816 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
1817 std::swap(TVal, FVal);
1818 std::swap(CTVal, CFVal);
1819 CC = ISD::getSetCCInverse(CC, true);
1820 }
1821
1822 // If the constants line up, perform the transform!
1823 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
1824 SDValue CCVal;
1825 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
1826
1827 FVal = Other;
1828 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001829 DAG.getConstant(-1ULL, dl, Other.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00001830
1831 return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
1832 CCVal, Cmp);
1833 }
1834
1835 return Op;
1836}
1837
1838static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
1839 EVT VT = Op.getValueType();
1840
1841 // Let legalize expand this if it isn't a legal type yet.
1842 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
1843 return SDValue();
1844
1845 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
1846
1847 unsigned Opc;
1848 bool ExtraOp = false;
1849 switch (Op.getOpcode()) {
1850 default:
Craig Topper2a30d782014-06-18 05:05:13 +00001851 llvm_unreachable("Invalid code");
Tim Northover3b0846e2014-05-24 12:50:23 +00001852 case ISD::ADDC:
1853 Opc = AArch64ISD::ADDS;
1854 break;
1855 case ISD::SUBC:
1856 Opc = AArch64ISD::SUBS;
1857 break;
1858 case ISD::ADDE:
1859 Opc = AArch64ISD::ADCS;
1860 ExtraOp = true;
1861 break;
1862 case ISD::SUBE:
1863 Opc = AArch64ISD::SBCS;
1864 ExtraOp = true;
1865 break;
1866 }
1867
1868 if (!ExtraOp)
1869 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
1870 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
1871 Op.getOperand(2));
1872}
1873
1874static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
1875 // Let legalize expand this if it isn't a legal type yet.
1876 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
1877 return SDValue();
1878
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001879 SDLoc dl(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00001880 AArch64CC::CondCode CC;
1881 // The actual operation that sets the overflow or carry flag.
1882 SDValue Value, Overflow;
1883 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
1884
1885 // We use 0 and 1 as false and true values.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001886 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
1887 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00001888
1889 // We use an inverted condition, because the conditional select is inverted
1890 // too. This will allow it to be selected to a single instruction:
1891 // CSINC Wd, WZR, WZR, invert(cond).
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001892 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
1893 Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
Tim Northover3b0846e2014-05-24 12:50:23 +00001894 CCVal, Overflow);
1895
1896 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001897 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
Tim Northover3b0846e2014-05-24 12:50:23 +00001898}
1899
1900// Prefetch operands are:
1901// 1: Address to prefetch
1902// 2: bool isWrite
1903// 3: int locality (0 = no locality ... 3 = extreme locality)
1904// 4: bool isDataCache
1905static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
1906 SDLoc DL(Op);
1907 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
1908 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
Yi Konge56de692014-08-05 12:46:47 +00001909 unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00001910
1911 bool IsStream = !Locality;
1912 // When the locality number is set
1913 if (Locality) {
1914 // The front-end should have filtered out the out-of-range values
1915 assert(Locality <= 3 && "Prefetch locality out-of-range");
1916 // The locality degree is the opposite of the cache speed.
1917 // Put the number the other way around.
1918 // The encoding starts at 0 for level 1
1919 Locality = 3 - Locality;
1920 }
1921
1922 // built the mask value encoding the expected behavior.
1923 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit
Yi Konge56de692014-08-05 12:46:47 +00001924 (!IsData << 3) | // IsDataCache bit
Tim Northover3b0846e2014-05-24 12:50:23 +00001925 (Locality << 1) | // Cache level bits
1926 (unsigned)IsStream; // Stream bit
1927 return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001928 DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00001929}
1930
1931SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
1932 SelectionDAG &DAG) const {
1933 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
1934
1935 RTLIB::Libcall LC;
1936 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
1937
1938 return LowerF128Call(Op, DAG, LC);
1939}
1940
1941SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
1942 SelectionDAG &DAG) const {
1943 if (Op.getOperand(0).getValueType() != MVT::f128) {
1944 // It's legal except when f128 is involved
1945 return Op;
1946 }
1947
1948 RTLIB::Libcall LC;
1949 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
1950
1951 // FP_ROUND node has a second operand indicating whether it is known to be
1952 // precise. That doesn't take part in the LibCall so we can't directly use
1953 // LowerF128Call.
1954 SDValue SrcVal = Op.getOperand(0);
Craig Topper8fe40e02015-10-22 17:05:00 +00001955 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
1956 SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00001957}
1958
1959static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
1960 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1961 // Any additional optimization in this function should be recorded
1962 // in the cost tables.
1963 EVT InVT = Op.getOperand(0).getValueType();
1964 EVT VT = Op.getValueType();
Pirama Arumuga Nainar1317d5f2015-12-10 17:16:49 +00001965 unsigned NumElts = InVT.getVectorNumElements();
1966
1967 // f16 vectors are promoted to f32 before a conversion.
1968 if (InVT.getVectorElementType() == MVT::f16) {
1969 MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
1970 SDLoc dl(Op);
1971 return DAG.getNode(
1972 Op.getOpcode(), dl, Op.getValueType(),
1973 DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
1974 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001975
Tim Northoverdbecc3b2014-06-15 09:27:15 +00001976 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001977 SDLoc dl(Op);
1978 SDValue Cv =
1979 DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
1980 Op.getOperand(0));
1981 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
Tim Northoverdbecc3b2014-06-15 09:27:15 +00001982 }
1983
1984 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001985 SDLoc dl(Op);
Oliver Stannard89d15422014-08-27 16:16:04 +00001986 MVT ExtVT =
1987 MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
1988 VT.getVectorNumElements());
1989 SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
Tim Northover3b0846e2014-05-24 12:50:23 +00001990 return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
1991 }
1992
1993 // Type changing conversions are illegal.
Tim Northoverdbecc3b2014-06-15 09:27:15 +00001994 return Op;
Tim Northover3b0846e2014-05-24 12:50:23 +00001995}
1996
1997SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
1998 SelectionDAG &DAG) const {
1999 if (Op.getOperand(0).getValueType().isVector())
2000 return LowerVectorFP_TO_INT(Op, DAG);
2001
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00002002 // f16 conversions are promoted to f32.
2003 if (Op.getOperand(0).getValueType() == MVT::f16) {
2004 SDLoc dl(Op);
2005 return DAG.getNode(
2006 Op.getOpcode(), dl, Op.getValueType(),
2007 DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
2008 }
2009
Tim Northover3b0846e2014-05-24 12:50:23 +00002010 if (Op.getOperand(0).getValueType() != MVT::f128) {
2011 // It's legal except when f128 is involved
2012 return Op;
2013 }
2014
2015 RTLIB::Libcall LC;
2016 if (Op.getOpcode() == ISD::FP_TO_SINT)
2017 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
2018 else
2019 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
2020
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002021 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
Craig Topper8fe40e02015-10-22 17:05:00 +00002022 return makeLibCall(DAG, LC, Op.getValueType(), Ops, false, SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00002023}
2024
2025static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
2026 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2027 // Any additional optimization in this function should be recorded
2028 // in the cost tables.
2029 EVT VT = Op.getValueType();
2030 SDLoc dl(Op);
2031 SDValue In = Op.getOperand(0);
2032 EVT InVT = In.getValueType();
2033
Tim Northoveref0d7602014-06-15 09:27:06 +00002034 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2035 MVT CastVT =
2036 MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
2037 InVT.getVectorNumElements());
2038 In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002039 return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
Tim Northover3b0846e2014-05-24 12:50:23 +00002040 }
2041
Tim Northoveref0d7602014-06-15 09:27:06 +00002042 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2043 unsigned CastOpc =
2044 Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2045 EVT CastVT = VT.changeVectorElementTypeToInteger();
2046 In = DAG.getNode(CastOpc, dl, CastVT, In);
2047 return DAG.getNode(Op.getOpcode(), dl, VT, In);
Tim Northover3b0846e2014-05-24 12:50:23 +00002048 }
2049
Tim Northoveref0d7602014-06-15 09:27:06 +00002050 return Op;
Tim Northover3b0846e2014-05-24 12:50:23 +00002051}
2052
2053SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
2054 SelectionDAG &DAG) const {
2055 if (Op.getValueType().isVector())
2056 return LowerVectorINT_TO_FP(Op, DAG);
2057
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00002058 // f16 conversions are promoted to f32.
2059 if (Op.getValueType() == MVT::f16) {
2060 SDLoc dl(Op);
2061 return DAG.getNode(
2062 ISD::FP_ROUND, dl, MVT::f16,
2063 DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002064 DAG.getIntPtrConstant(0, dl));
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00002065 }
2066
Tim Northover3b0846e2014-05-24 12:50:23 +00002067 // i128 conversions are libcalls.
2068 if (Op.getOperand(0).getValueType() == MVT::i128)
2069 return SDValue();
2070
2071 // Other conversions are legal, unless it's to the completely software-based
2072 // fp128.
2073 if (Op.getValueType() != MVT::f128)
2074 return Op;
2075
2076 RTLIB::Libcall LC;
2077 if (Op.getOpcode() == ISD::SINT_TO_FP)
2078 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2079 else
2080 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2081
2082 return LowerF128Call(Op, DAG, LC);
2083}
2084
2085SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
2086 SelectionDAG &DAG) const {
2087 // For iOS, we want to call an alternative entry point: __sincos_stret,
2088 // which returns the values in two S / D registers.
2089 SDLoc dl(Op);
2090 SDValue Arg = Op.getOperand(0);
2091 EVT ArgVT = Arg.getValueType();
2092 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2093
2094 ArgListTy Args;
2095 ArgListEntry Entry;
2096
2097 Entry.Node = Arg;
2098 Entry.Ty = ArgTy;
2099 Entry.isSExt = false;
2100 Entry.isZExt = false;
2101 Args.push_back(Entry);
2102
2103 const char *LibcallName =
2104 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
Mehdi Amini44ede332015-07-09 02:09:04 +00002105 SDValue Callee =
2106 DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00002107
Reid Kleckner343c3952014-11-20 23:51:47 +00002108 StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
Tim Northover3b0846e2014-05-24 12:50:23 +00002109 TargetLowering::CallLoweringInfo CLI(DAG);
2110 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
Krzysztof Parzyszeke116d5002016-06-22 12:54:25 +00002111 .setCallee(CallingConv::Fast, RetTy, Callee, std::move(Args));
Tim Northover3b0846e2014-05-24 12:50:23 +00002112
2113 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2114 return CallResult.first;
2115}
2116
Tim Northoverf8bfe212014-07-18 13:07:05 +00002117static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
2118 if (Op.getValueType() != MVT::f16)
2119 return SDValue();
2120
2121 assert(Op.getOperand(0).getValueType() == MVT::i16);
2122 SDLoc DL(Op);
2123
2124 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
2125 Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
2126 return SDValue(
2127 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002128 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
Tim Northoverf8bfe212014-07-18 13:07:05 +00002129 0);
2130}
2131
Chad Rosierd9d0f862014-10-08 02:31:24 +00002132static EVT getExtensionTo64Bits(const EVT &OrigVT) {
2133 if (OrigVT.getSizeInBits() >= 64)
2134 return OrigVT;
2135
2136 assert(OrigVT.isSimple() && "Expecting a simple value type");
2137
2138 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
2139 switch (OrigSimpleTy) {
2140 default: llvm_unreachable("Unexpected Vector Type");
2141 case MVT::v2i8:
2142 case MVT::v2i16:
2143 return MVT::v2i32;
2144 case MVT::v4i8:
2145 return MVT::v4i16;
2146 }
2147}
2148
2149static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2150 const EVT &OrigTy,
2151 const EVT &ExtTy,
2152 unsigned ExtOpcode) {
2153 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2154 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2155 // 64-bits we need to insert a new extension so that it will be 64-bits.
2156 assert(ExtTy.is128BitVector() && "Unexpected extension size");
2157 if (OrigTy.getSizeInBits() >= 64)
2158 return N;
2159
2160 // Must extend size to at least 64 bits to be used as an operand for VMULL.
2161 EVT NewVT = getExtensionTo64Bits(OrigTy);
2162
2163 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2164}
2165
2166static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2167 bool isSigned) {
2168 EVT VT = N->getValueType(0);
2169
2170 if (N->getOpcode() != ISD::BUILD_VECTOR)
2171 return false;
2172
Pete Cooper3af9a252015-06-26 18:17:36 +00002173 for (const SDValue &Elt : N->op_values()) {
Chad Rosierd9d0f862014-10-08 02:31:24 +00002174 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
2175 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
2176 unsigned HalfSize = EltSize / 2;
2177 if (isSigned) {
2178 if (!isIntN(HalfSize, C->getSExtValue()))
2179 return false;
2180 } else {
2181 if (!isUIntN(HalfSize, C->getZExtValue()))
2182 return false;
2183 }
2184 continue;
2185 }
2186 return false;
2187 }
2188
2189 return true;
2190}
2191
2192static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2193 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2194 return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2195 N->getOperand(0)->getValueType(0),
2196 N->getValueType(0),
2197 N->getOpcode());
2198
2199 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2200 EVT VT = N->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002201 SDLoc dl(N);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002202 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
2203 unsigned NumElts = VT.getVectorNumElements();
2204 MVT TruncVT = MVT::getIntegerVT(EltSize);
2205 SmallVector<SDValue, 8> Ops;
2206 for (unsigned i = 0; i != NumElts; ++i) {
2207 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2208 const APInt &CInt = C->getAPIntValue();
2209 // Element types smaller than 32 bits are not legal, so use i32 elements.
2210 // The values are implicitly truncated so sext vs. zext doesn't matter.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002211 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
Chad Rosierd9d0f862014-10-08 02:31:24 +00002212 }
Ahmed Bougacha128f8732016-04-26 21:15:30 +00002213 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002214}
2215
2216static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
2217 if (N->getOpcode() == ISD::SIGN_EXTEND)
2218 return true;
2219 if (isExtendedBUILD_VECTOR(N, DAG, true))
2220 return true;
2221 return false;
2222}
2223
2224static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
2225 if (N->getOpcode() == ISD::ZERO_EXTEND)
2226 return true;
2227 if (isExtendedBUILD_VECTOR(N, DAG, false))
2228 return true;
2229 return false;
2230}
2231
2232static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2233 unsigned Opcode = N->getOpcode();
2234 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2235 SDNode *N0 = N->getOperand(0).getNode();
2236 SDNode *N1 = N->getOperand(1).getNode();
2237 return N0->hasOneUse() && N1->hasOneUse() &&
2238 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2239 }
2240 return false;
2241}
2242
2243static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2244 unsigned Opcode = N->getOpcode();
2245 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2246 SDNode *N0 = N->getOperand(0).getNode();
2247 SDNode *N1 = N->getOperand(1).getNode();
2248 return N0->hasOneUse() && N1->hasOneUse() &&
2249 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2250 }
2251 return false;
2252}
2253
2254static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2255 // Multiplications are only custom-lowered for 128-bit vectors so that
2256 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
2257 EVT VT = Op.getValueType();
2258 assert(VT.is128BitVector() && VT.isInteger() &&
2259 "unexpected type for custom-lowering ISD::MUL");
2260 SDNode *N0 = Op.getOperand(0).getNode();
2261 SDNode *N1 = Op.getOperand(1).getNode();
2262 unsigned NewOpc = 0;
2263 bool isMLA = false;
2264 bool isN0SExt = isSignExtended(N0, DAG);
2265 bool isN1SExt = isSignExtended(N1, DAG);
2266 if (isN0SExt && isN1SExt)
2267 NewOpc = AArch64ISD::SMULL;
2268 else {
2269 bool isN0ZExt = isZeroExtended(N0, DAG);
2270 bool isN1ZExt = isZeroExtended(N1, DAG);
2271 if (isN0ZExt && isN1ZExt)
2272 NewOpc = AArch64ISD::UMULL;
2273 else if (isN1SExt || isN1ZExt) {
2274 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2275 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2276 if (isN1SExt && isAddSubSExt(N0, DAG)) {
2277 NewOpc = AArch64ISD::SMULL;
2278 isMLA = true;
2279 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2280 NewOpc = AArch64ISD::UMULL;
2281 isMLA = true;
2282 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2283 std::swap(N0, N1);
2284 NewOpc = AArch64ISD::UMULL;
2285 isMLA = true;
2286 }
2287 }
2288
2289 if (!NewOpc) {
2290 if (VT == MVT::v2i64)
2291 // Fall through to expand this. It is not legal.
2292 return SDValue();
2293 else
2294 // Other vector multiplications are legal.
2295 return Op;
2296 }
2297 }
2298
2299 // Legalize to a S/UMULL instruction
2300 SDLoc DL(Op);
2301 SDValue Op0;
2302 SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2303 if (!isMLA) {
2304 Op0 = skipExtensionForVectorMULL(N0, DAG);
2305 assert(Op0.getValueType().is64BitVector() &&
2306 Op1.getValueType().is64BitVector() &&
2307 "unexpected types for extended operands to VMULL");
2308 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2309 }
2310 // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2311 // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2312 // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2313 SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2314 SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2315 EVT Op1VT = Op1.getValueType();
2316 return DAG.getNode(N0->getOpcode(), DL, VT,
2317 DAG.getNode(NewOpc, DL, VT,
2318 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2319 DAG.getNode(NewOpc, DL, VT,
2320 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2321}
Tim Northoverf8bfe212014-07-18 13:07:05 +00002322
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002323SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2324 SelectionDAG &DAG) const {
2325 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2326 SDLoc dl(Op);
2327 switch (IntNo) {
2328 default: return SDValue(); // Don't custom lower most intrinsics.
Marcin Koscielnicki3fdc2572016-04-19 20:51:05 +00002329 case Intrinsic::thread_pointer: {
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002330 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2331 return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
2332 }
Silviu Barangadb1ddb32015-08-26 11:11:14 +00002333 case Intrinsic::aarch64_neon_smax:
2334 return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
2335 Op.getOperand(1), Op.getOperand(2));
2336 case Intrinsic::aarch64_neon_umax:
2337 return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
2338 Op.getOperand(1), Op.getOperand(2));
2339 case Intrinsic::aarch64_neon_smin:
2340 return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
2341 Op.getOperand(1), Op.getOperand(2));
2342 case Intrinsic::aarch64_neon_umin:
2343 return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
2344 Op.getOperand(1), Op.getOperand(2));
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002345 }
2346}
2347
Tim Northover3b0846e2014-05-24 12:50:23 +00002348SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
2349 SelectionDAG &DAG) const {
2350 switch (Op.getOpcode()) {
2351 default:
2352 llvm_unreachable("unimplemented operand");
2353 return SDValue();
Tim Northoverf8bfe212014-07-18 13:07:05 +00002354 case ISD::BITCAST:
2355 return LowerBITCAST(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002356 case ISD::GlobalAddress:
2357 return LowerGlobalAddress(Op, DAG);
2358 case ISD::GlobalTLSAddress:
2359 return LowerGlobalTLSAddress(Op, DAG);
2360 case ISD::SETCC:
2361 return LowerSETCC(Op, DAG);
2362 case ISD::BR_CC:
2363 return LowerBR_CC(Op, DAG);
2364 case ISD::SELECT:
2365 return LowerSELECT(Op, DAG);
2366 case ISD::SELECT_CC:
2367 return LowerSELECT_CC(Op, DAG);
2368 case ISD::JumpTable:
2369 return LowerJumpTable(Op, DAG);
2370 case ISD::ConstantPool:
2371 return LowerConstantPool(Op, DAG);
2372 case ISD::BlockAddress:
2373 return LowerBlockAddress(Op, DAG);
2374 case ISD::VASTART:
2375 return LowerVASTART(Op, DAG);
2376 case ISD::VACOPY:
2377 return LowerVACOPY(Op, DAG);
2378 case ISD::VAARG:
2379 return LowerVAARG(Op, DAG);
2380 case ISD::ADDC:
2381 case ISD::ADDE:
2382 case ISD::SUBC:
2383 case ISD::SUBE:
2384 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
2385 case ISD::SADDO:
2386 case ISD::UADDO:
2387 case ISD::SSUBO:
2388 case ISD::USUBO:
2389 case ISD::SMULO:
2390 case ISD::UMULO:
2391 return LowerXALUO(Op, DAG);
2392 case ISD::FADD:
2393 return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
2394 case ISD::FSUB:
2395 return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
2396 case ISD::FMUL:
2397 return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
2398 case ISD::FDIV:
2399 return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
2400 case ISD::FP_ROUND:
2401 return LowerFP_ROUND(Op, DAG);
2402 case ISD::FP_EXTEND:
2403 return LowerFP_EXTEND(Op, DAG);
2404 case ISD::FRAMEADDR:
2405 return LowerFRAMEADDR(Op, DAG);
2406 case ISD::RETURNADDR:
2407 return LowerRETURNADDR(Op, DAG);
2408 case ISD::INSERT_VECTOR_ELT:
2409 return LowerINSERT_VECTOR_ELT(Op, DAG);
2410 case ISD::EXTRACT_VECTOR_ELT:
2411 return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2412 case ISD::BUILD_VECTOR:
2413 return LowerBUILD_VECTOR(Op, DAG);
2414 case ISD::VECTOR_SHUFFLE:
2415 return LowerVECTOR_SHUFFLE(Op, DAG);
2416 case ISD::EXTRACT_SUBVECTOR:
2417 return LowerEXTRACT_SUBVECTOR(Op, DAG);
2418 case ISD::SRA:
2419 case ISD::SRL:
2420 case ISD::SHL:
2421 return LowerVectorSRA_SRL_SHL(Op, DAG);
2422 case ISD::SHL_PARTS:
2423 return LowerShiftLeftParts(Op, DAG);
2424 case ISD::SRL_PARTS:
2425 case ISD::SRA_PARTS:
2426 return LowerShiftRightParts(Op, DAG);
2427 case ISD::CTPOP:
2428 return LowerCTPOP(Op, DAG);
2429 case ISD::FCOPYSIGN:
2430 return LowerFCOPYSIGN(Op, DAG);
2431 case ISD::AND:
Balaram Makam92431702016-02-01 19:13:07 +00002432 return LowerAND(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002433 case ISD::OR:
Balaram Makam92431702016-02-01 19:13:07 +00002434 return LowerOR(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002435 case ISD::XOR:
2436 return LowerXOR(Op, DAG);
2437 case ISD::PREFETCH:
2438 return LowerPREFETCH(Op, DAG);
2439 case ISD::SINT_TO_FP:
2440 case ISD::UINT_TO_FP:
2441 return LowerINT_TO_FP(Op, DAG);
2442 case ISD::FP_TO_SINT:
2443 case ISD::FP_TO_UINT:
2444 return LowerFP_TO_INT(Op, DAG);
2445 case ISD::FSINCOS:
2446 return LowerFSINCOS(Op, DAG);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002447 case ISD::MUL:
2448 return LowerMUL(Op, DAG);
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002449 case ISD::INTRINSIC_WO_CHAIN:
2450 return LowerINTRINSIC_WO_CHAIN(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002451 }
2452}
2453
Tim Northover3b0846e2014-05-24 12:50:23 +00002454//===----------------------------------------------------------------------===//
2455// Calling Convention Implementation
2456//===----------------------------------------------------------------------===//
2457
2458#include "AArch64GenCallingConv.inc"
2459
Robin Morisset039781e2014-08-29 21:53:01 +00002460/// Selects the correct CCAssignFn for a given CallingConvention value.
Tim Northover3b0846e2014-05-24 12:50:23 +00002461CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2462 bool IsVarArg) const {
2463 switch (CC) {
2464 default:
2465 llvm_unreachable("Unsupported calling convention.");
2466 case CallingConv::WebKit_JS:
2467 return CC_AArch64_WebKit_JS;
Greg Fitzgeraldfa78d082015-01-19 17:40:05 +00002468 case CallingConv::GHC:
2469 return CC_AArch64_GHC;
Tim Northover3b0846e2014-05-24 12:50:23 +00002470 case CallingConv::C:
2471 case CallingConv::Fast:
Roman Levenstein2792b3f2016-03-10 04:35:09 +00002472 case CallingConv::PreserveMost:
Manman Ren2828c572016-03-18 23:38:49 +00002473 case CallingConv::CXX_FAST_TLS:
Tim Northover3b0846e2014-05-24 12:50:23 +00002474 if (!Subtarget->isTargetDarwin())
2475 return CC_AArch64_AAPCS;
2476 return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
2477 }
2478}
2479
2480SDValue AArch64TargetLowering::LowerFormalArguments(
2481 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00002482 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2483 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00002484 MachineFunction &MF = DAG.getMachineFunction();
2485 MachineFrameInfo *MFI = MF.getFrameInfo();
2486
2487 // Assign locations to all of the incoming arguments.
2488 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002489 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2490 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002491
2492 // At this point, Ins[].VT may already be promoted to i32. To correctly
2493 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2494 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2495 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
2496 // we use a special version of AnalyzeFormalArguments to pass in ValVT and
2497 // LocVT.
2498 unsigned NumArgs = Ins.size();
2499 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2500 unsigned CurArgIdx = 0;
2501 for (unsigned i = 0; i != NumArgs; ++i) {
2502 MVT ValVT = Ins[i].VT;
Andrew Trick05938a52015-02-16 18:10:47 +00002503 if (Ins[i].isOrigArg()) {
2504 std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
2505 CurArgIdx = Ins[i].getOrigArgIndex();
Tim Northover3b0846e2014-05-24 12:50:23 +00002506
Andrew Trick05938a52015-02-16 18:10:47 +00002507 // Get type of the original argument.
Mehdi Amini44ede332015-07-09 02:09:04 +00002508 EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
2509 /*AllowUnknown*/ true);
Andrew Trick05938a52015-02-16 18:10:47 +00002510 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
2511 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2512 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2513 ValVT = MVT::i8;
2514 else if (ActualMVT == MVT::i16)
2515 ValVT = MVT::i16;
2516 }
Tim Northover3b0846e2014-05-24 12:50:23 +00002517 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2518 bool Res =
Tim Northover47e003c2014-05-26 17:21:53 +00002519 AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00002520 assert(!Res && "Call operand has unhandled type");
2521 (void)Res;
2522 }
2523 assert(ArgLocs.size() == Ins.size());
2524 SmallVector<SDValue, 16> ArgValues;
2525 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2526 CCValAssign &VA = ArgLocs[i];
2527
2528 if (Ins[i].Flags.isByVal()) {
2529 // Byval is used for HFAs in the PCS, but the system should work in a
2530 // non-compliant manner for larger structs.
Mehdi Amini44ede332015-07-09 02:09:04 +00002531 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00002532 int Size = Ins[i].Flags.getByValSize();
2533 unsigned NumRegs = (Size + 7) / 8;
2534
2535 // FIXME: This works on big-endian for composite byvals, which are the common
2536 // case. It should also work for fundamental types too.
2537 unsigned FrameIdx =
2538 MFI->CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
Mehdi Amini44ede332015-07-09 02:09:04 +00002539 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00002540 InVals.push_back(FrameIdxN);
2541
2542 continue;
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002543 }
Junmo Park3b8c7152016-01-05 09:36:47 +00002544
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002545 if (VA.isRegLoc()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00002546 // Arguments stored in registers.
2547 EVT RegVT = VA.getLocVT();
2548
2549 SDValue ArgValue;
2550 const TargetRegisterClass *RC;
2551
2552 if (RegVT == MVT::i32)
2553 RC = &AArch64::GPR32RegClass;
2554 else if (RegVT == MVT::i64)
2555 RC = &AArch64::GPR64RegClass;
Oliver Stannard6eda6ff2014-07-11 13:33:46 +00002556 else if (RegVT == MVT::f16)
2557 RC = &AArch64::FPR16RegClass;
Tim Northover3b0846e2014-05-24 12:50:23 +00002558 else if (RegVT == MVT::f32)
2559 RC = &AArch64::FPR32RegClass;
2560 else if (RegVT == MVT::f64 || RegVT.is64BitVector())
2561 RC = &AArch64::FPR64RegClass;
2562 else if (RegVT == MVT::f128 || RegVT.is128BitVector())
2563 RC = &AArch64::FPR128RegClass;
2564 else
2565 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2566
2567 // Transform the arguments in physical registers into virtual ones.
2568 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2569 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2570
2571 // If this is an 8, 16 or 32-bit value, it is really passed promoted
2572 // to 64 bits. Insert an assert[sz]ext to capture this, then
2573 // truncate to the right size.
2574 switch (VA.getLocInfo()) {
2575 default:
2576 llvm_unreachable("Unknown loc info!");
2577 case CCValAssign::Full:
2578 break;
2579 case CCValAssign::BCvt:
2580 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
2581 break;
Tim Northover47e003c2014-05-26 17:21:53 +00002582 case CCValAssign::AExt:
Tim Northover3b0846e2014-05-24 12:50:23 +00002583 case CCValAssign::SExt:
Tim Northover3b0846e2014-05-24 12:50:23 +00002584 case CCValAssign::ZExt:
Tim Northover47e003c2014-05-26 17:21:53 +00002585 // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
2586 // nodes after our lowering.
2587 assert(RegVT == Ins[i].VT && "incorrect register location selected");
Tim Northover3b0846e2014-05-24 12:50:23 +00002588 break;
2589 }
2590
2591 InVals.push_back(ArgValue);
2592
2593 } else { // VA.isRegLoc()
2594 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
2595 unsigned ArgOffset = VA.getLocMemOffset();
Amara Emerson82da7d02014-08-15 14:29:57 +00002596 unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
Tim Northover3b0846e2014-05-24 12:50:23 +00002597
2598 uint32_t BEAlign = 0;
Tim Northover293d4142014-12-03 17:49:26 +00002599 if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
2600 !Ins[i].Flags.isInConsecutiveRegs())
Tim Northover3b0846e2014-05-24 12:50:23 +00002601 BEAlign = 8 - ArgSize;
2602
2603 int FI = MFI->CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
2604
2605 // Create load nodes to retrieve arguments from the stack.
Mehdi Amini44ede332015-07-09 02:09:04 +00002606 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00002607 SDValue ArgValue;
2608
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002609 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
Tim Northover47e003c2014-05-26 17:21:53 +00002610 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002611 MVT MemVT = VA.getValVT();
2612
Tim Northover47e003c2014-05-26 17:21:53 +00002613 switch (VA.getLocInfo()) {
2614 default:
2615 break;
Tim Northover6890add2014-06-03 13:54:53 +00002616 case CCValAssign::BCvt:
2617 MemVT = VA.getLocVT();
2618 break;
Tim Northover47e003c2014-05-26 17:21:53 +00002619 case CCValAssign::SExt:
2620 ExtType = ISD::SEXTLOAD;
2621 break;
2622 case CCValAssign::ZExt:
2623 ExtType = ISD::ZEXTLOAD;
2624 break;
2625 case CCValAssign::AExt:
2626 ExtType = ISD::EXTLOAD;
2627 break;
Tim Northover3b0846e2014-05-24 12:50:23 +00002628 }
2629
Alex Lorenze40c8a22015-08-11 23:09:45 +00002630 ArgValue = DAG.getExtLoad(
2631 ExtType, DL, VA.getLocVT(), Chain, FIN,
2632 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
2633 MemVT, false, false, false, 0);
Tim Northover47e003c2014-05-26 17:21:53 +00002634
Tim Northover3b0846e2014-05-24 12:50:23 +00002635 InVals.push_back(ArgValue);
2636 }
2637 }
2638
2639 // varargs
Matthias Braundff243e2016-04-12 02:16:13 +00002640 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Tim Northover3b0846e2014-05-24 12:50:23 +00002641 if (isVarArg) {
2642 if (!Subtarget->isTargetDarwin()) {
2643 // The AAPCS variadic function ABI is identical to the non-variadic
2644 // one. As a result there may be more arguments in registers and we should
2645 // save them for future reference.
2646 saveVarArgRegisters(CCInfo, DAG, DL, Chain);
2647 }
2648
Tim Northover3b0846e2014-05-24 12:50:23 +00002649 // This will point to the next argument passed via stack.
2650 unsigned StackOffset = CCInfo.getNextStackOffset();
2651 // We currently pass all varargs at 8-byte alignment.
2652 StackOffset = ((StackOffset + 7) & ~7);
Matthias Braundff243e2016-04-12 02:16:13 +00002653 FuncInfo->setVarArgsStackIndex(MFI->CreateFixedObject(4, StackOffset, true));
Tim Northover3b0846e2014-05-24 12:50:23 +00002654 }
2655
Tim Northover3b0846e2014-05-24 12:50:23 +00002656 unsigned StackArgSize = CCInfo.getNextStackOffset();
2657 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2658 if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
2659 // This is a non-standard ABI so by fiat I say we're allowed to make full
2660 // use of the stack area to be popped, which must be aligned to 16 bytes in
2661 // any case:
Rui Ueyamada00f2f2016-01-14 21:06:47 +00002662 StackArgSize = alignTo(StackArgSize, 16);
Tim Northover3b0846e2014-05-24 12:50:23 +00002663
2664 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
2665 // a multiple of 16.
2666 FuncInfo->setArgumentStackToRestore(StackArgSize);
2667
2668 // This realignment carries over to the available bytes below. Our own
2669 // callers will guarantee the space is free by giving an aligned value to
2670 // CALLSEQ_START.
2671 }
2672 // Even if we're not expected to free up the space, it's useful to know how
2673 // much is there while considering tail calls (because we can reuse it).
2674 FuncInfo->setBytesInStackArgArea(StackArgSize);
2675
2676 return Chain;
2677}
2678
2679void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00002680 SelectionDAG &DAG,
2681 const SDLoc &DL,
Tim Northover3b0846e2014-05-24 12:50:23 +00002682 SDValue &Chain) const {
2683 MachineFunction &MF = DAG.getMachineFunction();
2684 MachineFrameInfo *MFI = MF.getFrameInfo();
2685 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Mehdi Amini44ede332015-07-09 02:09:04 +00002686 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00002687
2688 SmallVector<SDValue, 8> MemOps;
2689
2690 static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
2691 AArch64::X3, AArch64::X4, AArch64::X5,
2692 AArch64::X6, AArch64::X7 };
2693 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
Tim Northover3b6b7ca2015-02-21 02:11:17 +00002694 unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
Tim Northover3b0846e2014-05-24 12:50:23 +00002695
2696 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
2697 int GPRIdx = 0;
2698 if (GPRSaveSize != 0) {
2699 GPRIdx = MFI->CreateStackObject(GPRSaveSize, 8, false);
2700
Mehdi Amini44ede332015-07-09 02:09:04 +00002701 SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00002702
2703 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
2704 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
2705 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
Alex Lorenze40c8a22015-08-11 23:09:45 +00002706 SDValue Store = DAG.getStore(
2707 Val.getValue(1), DL, Val, FIN,
2708 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8), false,
2709 false, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00002710 MemOps.push_back(Store);
Mehdi Amini44ede332015-07-09 02:09:04 +00002711 FIN =
2712 DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00002713 }
2714 }
2715 FuncInfo->setVarArgsGPRIndex(GPRIdx);
2716 FuncInfo->setVarArgsGPRSize(GPRSaveSize);
2717
2718 if (Subtarget->hasFPARMv8()) {
2719 static const MCPhysReg FPRArgRegs[] = {
2720 AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
2721 AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
2722 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
Tim Northover3b6b7ca2015-02-21 02:11:17 +00002723 unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
Tim Northover3b0846e2014-05-24 12:50:23 +00002724
2725 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
2726 int FPRIdx = 0;
2727 if (FPRSaveSize != 0) {
2728 FPRIdx = MFI->CreateStackObject(FPRSaveSize, 16, false);
2729
Mehdi Amini44ede332015-07-09 02:09:04 +00002730 SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00002731
2732 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
2733 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
2734 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
2735
Alex Lorenze40c8a22015-08-11 23:09:45 +00002736 SDValue Store = DAG.getStore(
2737 Val.getValue(1), DL, Val, FIN,
2738 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16),
2739 false, false, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00002740 MemOps.push_back(Store);
Mehdi Amini44ede332015-07-09 02:09:04 +00002741 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
2742 DAG.getConstant(16, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00002743 }
2744 }
2745 FuncInfo->setVarArgsFPRIndex(FPRIdx);
2746 FuncInfo->setVarArgsFPRSize(FPRSaveSize);
2747 }
2748
2749 if (!MemOps.empty()) {
2750 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
2751 }
2752}
2753
2754/// LowerCallResult - Lower the result values of a call into the
2755/// appropriate copies out of appropriate physical registers.
2756SDValue AArch64TargetLowering::LowerCallResult(
2757 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00002758 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2759 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
Tim Northover3b0846e2014-05-24 12:50:23 +00002760 SDValue ThisVal) const {
2761 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
2762 ? RetCC_AArch64_WebKit_JS
2763 : RetCC_AArch64_AAPCS;
2764 // Assign locations to each value returned by this call.
2765 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002766 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2767 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002768 CCInfo.AnalyzeCallResult(Ins, RetCC);
2769
2770 // Copy all of the result registers out of their specified physreg.
2771 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2772 CCValAssign VA = RVLocs[i];
2773
2774 // Pass 'this' value directly from the argument to return value, to avoid
2775 // reg unit interference
2776 if (i == 0 && isThisReturn) {
2777 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
2778 "unexpected return calling convention register assignment");
2779 InVals.push_back(ThisVal);
2780 continue;
2781 }
2782
2783 SDValue Val =
2784 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2785 Chain = Val.getValue(1);
2786 InFlag = Val.getValue(2);
2787
2788 switch (VA.getLocInfo()) {
2789 default:
2790 llvm_unreachable("Unknown loc info!");
2791 case CCValAssign::Full:
2792 break;
2793 case CCValAssign::BCvt:
2794 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2795 break;
2796 }
2797
2798 InVals.push_back(Val);
2799 }
2800
2801 return Chain;
2802}
2803
2804bool AArch64TargetLowering::isEligibleForTailCallOptimization(
2805 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
Tim Northover3b0846e2014-05-24 12:50:23 +00002806 const SmallVectorImpl<ISD::OutputArg> &Outs,
2807 const SmallVectorImpl<SDValue> &OutVals,
2808 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2809 // For CallingConv::C this function knows whether the ABI needs
2810 // changing. That's not true for other conventions so they will have to opt in
2811 // manually.
2812 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
2813 return false;
2814
Matthias Braun8d414362016-03-30 22:46:04 +00002815 MachineFunction &MF = DAG.getMachineFunction();
Tim Northover3b0846e2014-05-24 12:50:23 +00002816 const Function *CallerF = MF.getFunction();
2817 CallingConv::ID CallerCC = CallerF->getCallingConv();
2818 bool CCMatch = CallerCC == CalleeCC;
2819
2820 // Byval parameters hand the function a pointer directly into the stack area
2821 // we want to reuse during a tail call. Working around this *is* possible (see
2822 // X86) but less efficient and uglier in LowerCall.
2823 for (Function::const_arg_iterator i = CallerF->arg_begin(),
2824 e = CallerF->arg_end();
2825 i != e; ++i)
2826 if (i->hasByValAttr())
2827 return false;
2828
2829 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
Eric Christopher114fa1c2016-02-29 22:50:49 +00002830 return IsTailCallConvention(CalleeCC) && CCMatch;
Tim Northover3b0846e2014-05-24 12:50:23 +00002831 }
2832
Oliver Stannard12993dd2014-08-18 12:42:15 +00002833 // Externally-defined functions with weak linkage should not be
2834 // tail-called on AArch64 when the OS does not support dynamic
2835 // pre-emption of symbols, as the AAELF spec requires normal calls
2836 // to undefined weak functions to be replaced with a NOP or jump to the
2837 // next instruction. The behaviour of branch instructions in this
2838 // situation (as used for tail calls) is implementation-defined, so we
2839 // cannot rely on the linker replacing the tail call with a return.
2840 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2841 const GlobalValue *GV = G->getGlobal();
Daniel Sandersc81f4502015-06-16 15:44:21 +00002842 const Triple &TT = getTargetMachine().getTargetTriple();
Saleem Abdulrasool67f72992015-01-03 21:35:00 +00002843 if (GV->hasExternalWeakLinkage() &&
2844 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
Oliver Stannard12993dd2014-08-18 12:42:15 +00002845 return false;
2846 }
2847
Tim Northover3b0846e2014-05-24 12:50:23 +00002848 // Now we search for cases where we can use a tail call without changing the
2849 // ABI. Sibcall is used in some places (particularly gcc) to refer to this
2850 // concept.
2851
2852 // I want anyone implementing a new calling convention to think long and hard
2853 // about this assert.
2854 assert((!isVarArg || CalleeCC == CallingConv::C) &&
2855 "Unexpected variadic calling convention");
2856
Matthias Braun8d414362016-03-30 22:46:04 +00002857 LLVMContext &C = *DAG.getContext();
Tim Northover3b0846e2014-05-24 12:50:23 +00002858 if (isVarArg && !Outs.empty()) {
2859 // At least two cases here: if caller is fastcc then we can't have any
2860 // memory arguments (we'd be expected to clean up the stack afterwards). If
2861 // caller is C then we could potentially use its argument area.
2862
2863 // FIXME: for now we take the most conservative of these in both cases:
2864 // disallow all variadic memory operands.
2865 SmallVector<CCValAssign, 16> ArgLocs;
Matthias Braun8d414362016-03-30 22:46:04 +00002866 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
Tim Northover3b0846e2014-05-24 12:50:23 +00002867
2868 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
Pete Cooper7be8f8f2015-08-03 19:04:32 +00002869 for (const CCValAssign &ArgLoc : ArgLocs)
2870 if (!ArgLoc.isRegLoc())
Tim Northover3b0846e2014-05-24 12:50:23 +00002871 return false;
2872 }
2873
Matthias Braun8d414362016-03-30 22:46:04 +00002874 // Check that the call results are passed in the same way.
2875 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
2876 CCAssignFnForCall(CalleeCC, isVarArg),
2877 CCAssignFnForCall(CallerCC, isVarArg)))
2878 return false;
Matthias Braun870c34f2016-04-04 18:56:13 +00002879 // The callee has to preserve all registers the caller needs to preserve.
Matthias Braun74a0bd32016-04-13 21:43:16 +00002880 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
2881 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
Matthias Braun870c34f2016-04-04 18:56:13 +00002882 if (!CCMatch) {
Matthias Braun74a0bd32016-04-13 21:43:16 +00002883 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2884 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
Matthias Braun870c34f2016-04-04 18:56:13 +00002885 return false;
2886 }
Tim Northover3b0846e2014-05-24 12:50:23 +00002887
2888 // Nothing more to check if the callee is taking no arguments
2889 if (Outs.empty())
2890 return true;
2891
2892 SmallVector<CCValAssign, 16> ArgLocs;
Matthias Braun8d414362016-03-30 22:46:04 +00002893 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
Tim Northover3b0846e2014-05-24 12:50:23 +00002894
2895 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2896
2897 const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2898
Matthias Braun74a0bd32016-04-13 21:43:16 +00002899 // If the stack arguments for this call do not fit into our own save area then
2900 // the call cannot be made tail.
2901 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2902 return false;
2903
Matthias Braun46b0f032016-04-14 01:10:42 +00002904 const MachineRegisterInfo &MRI = MF.getRegInfo();
2905 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
2906 return false;
Matthias Braun74a0bd32016-04-13 21:43:16 +00002907
2908 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +00002909}
2910
2911SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
2912 SelectionDAG &DAG,
2913 MachineFrameInfo *MFI,
2914 int ClobberedFI) const {
2915 SmallVector<SDValue, 8> ArgChains;
2916 int64_t FirstByte = MFI->getObjectOffset(ClobberedFI);
2917 int64_t LastByte = FirstByte + MFI->getObjectSize(ClobberedFI) - 1;
2918
2919 // Include the original chain at the beginning of the list. When this is
2920 // used by target LowerCall hooks, this helps legalize find the
2921 // CALLSEQ_BEGIN node.
2922 ArgChains.push_back(Chain);
2923
2924 // Add a chain value for each stack argument corresponding
2925 for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
2926 UE = DAG.getEntryNode().getNode()->use_end();
2927 U != UE; ++U)
2928 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
2929 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
2930 if (FI->getIndex() < 0) {
2931 int64_t InFirstByte = MFI->getObjectOffset(FI->getIndex());
2932 int64_t InLastByte = InFirstByte;
2933 InLastByte += MFI->getObjectSize(FI->getIndex()) - 1;
2934
2935 if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
2936 (FirstByte <= InFirstByte && InFirstByte <= LastByte))
2937 ArgChains.push_back(SDValue(L, 1));
2938 }
2939
2940 // Build a tokenfactor for all the chains.
2941 return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
2942}
2943
2944bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
2945 bool TailCallOpt) const {
2946 return CallCC == CallingConv::Fast && TailCallOpt;
2947}
2948
2949bool AArch64TargetLowering::IsTailCallConvention(CallingConv::ID CallCC) const {
Roman Levenstein2792b3f2016-03-10 04:35:09 +00002950 return CallCC == CallingConv::Fast ||
2951 CallCC == CallingConv::PreserveMost;
Tim Northover3b0846e2014-05-24 12:50:23 +00002952}
2953
2954/// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
2955/// and add input and output parameter nodes.
2956SDValue
2957AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
2958 SmallVectorImpl<SDValue> &InVals) const {
2959 SelectionDAG &DAG = CLI.DAG;
2960 SDLoc &DL = CLI.DL;
2961 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2962 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2963 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2964 SDValue Chain = CLI.Chain;
2965 SDValue Callee = CLI.Callee;
2966 bool &IsTailCall = CLI.IsTailCall;
2967 CallingConv::ID CallConv = CLI.CallConv;
2968 bool IsVarArg = CLI.IsVarArg;
2969
2970 MachineFunction &MF = DAG.getMachineFunction();
Tim Northover3b0846e2014-05-24 12:50:23 +00002971 bool IsThisReturn = false;
2972
2973 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2974 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2975 bool IsSibCall = false;
2976
2977 if (IsTailCall) {
2978 // Check if it's really possible to do a tail call.
2979 IsTailCall = isEligibleForTailCallOptimization(
Matthias Brauncc7fba42016-04-01 02:49:17 +00002980 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002981 if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
2982 report_fatal_error("failed to perform tail call elimination on a call "
2983 "site marked musttail");
2984
2985 // A sibling call is one where we're under the usual C ABI and not planning
2986 // to change that but can still do a tail call:
2987 if (!TailCallOpt && IsTailCall)
2988 IsSibCall = true;
2989
2990 if (IsTailCall)
2991 ++NumTailCalls;
2992 }
2993
2994 // Analyze operands of the call, assigning locations to each operand.
2995 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002996 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
2997 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002998
2999 if (IsVarArg) {
3000 // Handle fixed and variable vector arguments differently.
3001 // Variable vector arguments always go into memory.
3002 unsigned NumArgs = Outs.size();
3003
3004 for (unsigned i = 0; i != NumArgs; ++i) {
3005 MVT ArgVT = Outs[i].VT;
3006 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3007 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
3008 /*IsVarArg=*/ !Outs[i].IsFixed);
3009 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3010 assert(!Res && "Call operand has unhandled type");
3011 (void)Res;
3012 }
3013 } else {
3014 // At this point, Outs[].VT may already be promoted to i32. To correctly
3015 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
3016 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
3017 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
3018 // we use a special version of AnalyzeCallOperands to pass in ValVT and
3019 // LocVT.
3020 unsigned NumArgs = Outs.size();
3021 for (unsigned i = 0; i != NumArgs; ++i) {
3022 MVT ValVT = Outs[i].VT;
3023 // Get type of the original argument.
Mehdi Amini44ede332015-07-09 02:09:04 +00003024 EVT ActualVT = getValueType(DAG.getDataLayout(),
3025 CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
Tim Northover3b0846e2014-05-24 12:50:23 +00003026 /*AllowUnknown*/ true);
3027 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
3028 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3029 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
Tim Northover3b0846e2014-05-24 12:50:23 +00003030 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
Tim Northover47e003c2014-05-26 17:21:53 +00003031 ValVT = MVT::i8;
Tim Northover3b0846e2014-05-24 12:50:23 +00003032 else if (ActualMVT == MVT::i16)
Tim Northover47e003c2014-05-26 17:21:53 +00003033 ValVT = MVT::i16;
Tim Northover3b0846e2014-05-24 12:50:23 +00003034
3035 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
Tim Northover47e003c2014-05-26 17:21:53 +00003036 bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00003037 assert(!Res && "Call operand has unhandled type");
3038 (void)Res;
3039 }
3040 }
3041
3042 // Get a count of how many bytes are to be pushed on the stack.
3043 unsigned NumBytes = CCInfo.getNextStackOffset();
3044
3045 if (IsSibCall) {
3046 // Since we're not changing the ABI to make this a tail call, the memory
3047 // operands are already available in the caller's incoming argument space.
3048 NumBytes = 0;
3049 }
3050
3051 // FPDiff is the byte offset of the call's argument area from the callee's.
3052 // Stores to callee stack arguments will be placed in FixedStackSlots offset
3053 // by this amount for a tail call. In a sibling call it must be 0 because the
3054 // caller will deallocate the entire stack and the callee still expects its
3055 // arguments to begin at SP+0. Completely unused for non-tail calls.
3056 int FPDiff = 0;
3057
3058 if (IsTailCall && !IsSibCall) {
3059 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
3060
3061 // Since callee will pop argument stack as a tail call, we must keep the
3062 // popped size 16-byte aligned.
Rui Ueyamada00f2f2016-01-14 21:06:47 +00003063 NumBytes = alignTo(NumBytes, 16);
Tim Northover3b0846e2014-05-24 12:50:23 +00003064
3065 // FPDiff will be negative if this tail call requires more space than we
3066 // would automatically have in our incoming argument space. Positive if we
3067 // can actually shrink the stack.
3068 FPDiff = NumReusableBytes - NumBytes;
3069
3070 // The stack pointer must be 16-byte aligned at all times it's used for a
3071 // memory operation, which in practice means at *all* times and in
3072 // particular across call boundaries. Therefore our own arguments started at
3073 // a 16-byte aligned SP and the delta applied for the tail call should
3074 // satisfy the same constraint.
3075 assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
3076 }
3077
3078 // Adjust the stack pointer for the new arguments...
3079 // These operations are automatically eliminated by the prolog/epilog pass
3080 if (!IsSibCall)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003081 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, DL,
3082 true),
3083 DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003084
Mehdi Amini44ede332015-07-09 02:09:04 +00003085 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
3086 getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00003087
3088 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3089 SmallVector<SDValue, 8> MemOpChains;
Mehdi Amini44ede332015-07-09 02:09:04 +00003090 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003091
3092 // Walk the register/memloc assignments, inserting copies/loads.
3093 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
3094 ++i, ++realArgIdx) {
3095 CCValAssign &VA = ArgLocs[i];
3096 SDValue Arg = OutVals[realArgIdx];
3097 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
3098
3099 // Promote the value if needed.
3100 switch (VA.getLocInfo()) {
3101 default:
3102 llvm_unreachable("Unknown loc info!");
3103 case CCValAssign::Full:
3104 break;
3105 case CCValAssign::SExt:
3106 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3107 break;
3108 case CCValAssign::ZExt:
3109 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3110 break;
3111 case CCValAssign::AExt:
Tim Northover68ae5032014-05-26 17:22:07 +00003112 if (Outs[realArgIdx].ArgVT == MVT::i1) {
3113 // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
3114 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3115 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
3116 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003117 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3118 break;
3119 case CCValAssign::BCvt:
3120 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3121 break;
3122 case CCValAssign::FPExt:
3123 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3124 break;
3125 }
3126
3127 if (VA.isRegLoc()) {
3128 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i64) {
3129 assert(VA.getLocVT() == MVT::i64 &&
3130 "unexpected calling convention register assignment");
3131 assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
3132 "unexpected use of 'returned'");
3133 IsThisReturn = true;
3134 }
3135 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3136 } else {
3137 assert(VA.isMemLoc());
3138
3139 SDValue DstAddr;
3140 MachinePointerInfo DstInfo;
3141
3142 // FIXME: This works on big-endian for composite byvals, which are the
3143 // common case. It should also work for fundamental types too.
3144 uint32_t BEAlign = 0;
3145 unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
Amara Emerson82da7d02014-08-15 14:29:57 +00003146 : VA.getValVT().getSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00003147 OpSize = (OpSize + 7) / 8;
Tim Northover293d4142014-12-03 17:49:26 +00003148 if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
3149 !Flags.isInConsecutiveRegs()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003150 if (OpSize < 8)
3151 BEAlign = 8 - OpSize;
3152 }
3153 unsigned LocMemOffset = VA.getLocMemOffset();
3154 int32_t Offset = LocMemOffset + BEAlign;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003155 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
Mehdi Amini44ede332015-07-09 02:09:04 +00003156 PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
Tim Northover3b0846e2014-05-24 12:50:23 +00003157
3158 if (IsTailCall) {
3159 Offset = Offset + FPDiff;
3160 int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3161
Mehdi Amini44ede332015-07-09 02:09:04 +00003162 DstAddr = DAG.getFrameIndex(FI, PtrVT);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003163 DstInfo =
3164 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
Tim Northover3b0846e2014-05-24 12:50:23 +00003165
3166 // Make sure any stack arguments overlapping with where we're storing
3167 // are loaded before this eventual operation. Otherwise they'll be
3168 // clobbered.
3169 Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
3170 } else {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003171 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003172
Mehdi Amini44ede332015-07-09 02:09:04 +00003173 DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003174 DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
3175 LocMemOffset);
Tim Northover3b0846e2014-05-24 12:50:23 +00003176 }
3177
3178 if (Outs[i].Flags.isByVal()) {
3179 SDValue SizeNode =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003180 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00003181 SDValue Cpy = DAG.getMemcpy(
3182 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
Krzysztof Parzyszeka46c36b2015-04-13 17:16:45 +00003183 /*isVol = */ false, /*AlwaysInline = */ false,
3184 /*isTailCall = */ false,
3185 DstInfo, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00003186
3187 MemOpChains.push_back(Cpy);
3188 } else {
3189 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
3190 // promoted to a legal register type i32, we should truncate Arg back to
3191 // i1/i8/i16.
Tim Northover6890add2014-06-03 13:54:53 +00003192 if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
3193 VA.getValVT() == MVT::i16)
3194 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
Tim Northover3b0846e2014-05-24 12:50:23 +00003195
3196 SDValue Store =
3197 DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, false, false, 0);
3198 MemOpChains.push_back(Store);
3199 }
3200 }
3201 }
3202
3203 if (!MemOpChains.empty())
3204 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3205
3206 // Build a sequence of copy-to-reg nodes chained together with token chain
3207 // and flag operands which copy the outgoing args into the appropriate regs.
3208 SDValue InFlag;
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003209 for (auto &RegToPass : RegsToPass) {
3210 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3211 RegToPass.second, InFlag);
Tim Northover3b0846e2014-05-24 12:50:23 +00003212 InFlag = Chain.getValue(1);
3213 }
3214
3215 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3216 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3217 // node so that legalize doesn't hack it.
3218 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3219 Subtarget->isTargetMachO()) {
3220 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3221 const GlobalValue *GV = G->getGlobal();
3222 bool InternalLinkage = GV->hasInternalLinkage();
3223 if (InternalLinkage)
Mehdi Amini44ede332015-07-09 02:09:04 +00003224 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00003225 else {
Mehdi Amini44ede332015-07-09 02:09:04 +00003226 Callee =
3227 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT);
3228 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
Tim Northover3b0846e2014-05-24 12:50:23 +00003229 }
3230 } else if (ExternalSymbolSDNode *S =
3231 dyn_cast<ExternalSymbolSDNode>(Callee)) {
3232 const char *Sym = S->getSymbol();
Mehdi Amini44ede332015-07-09 02:09:04 +00003233 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
3234 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
Tim Northover3b0846e2014-05-24 12:50:23 +00003235 }
3236 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3237 const GlobalValue *GV = G->getGlobal();
Mehdi Amini44ede332015-07-09 02:09:04 +00003238 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00003239 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3240 const char *Sym = S->getSymbol();
Mehdi Amini44ede332015-07-09 02:09:04 +00003241 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00003242 }
3243
3244 // We don't usually want to end the call-sequence here because we would tidy
3245 // the frame up *after* the call, however in the ABI-changing tail-call case
3246 // we've carefully laid out the parameters so that when sp is reset they'll be
3247 // in the correct location.
3248 if (IsTailCall && !IsSibCall) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003249 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3250 DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003251 InFlag = Chain.getValue(1);
3252 }
3253
3254 std::vector<SDValue> Ops;
3255 Ops.push_back(Chain);
3256 Ops.push_back(Callee);
3257
3258 if (IsTailCall) {
3259 // Each tail call may have to adjust the stack by a different amount, so
3260 // this information must travel along with the operation for eventual
3261 // consumption by emitEpilogue.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003262 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00003263 }
3264
3265 // Add argument registers to the end of the list so that they are known live
3266 // into the call.
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003267 for (auto &RegToPass : RegsToPass)
3268 Ops.push_back(DAG.getRegister(RegToPass.first,
3269 RegToPass.second.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00003270
3271 // Add a register mask operand representing the call-preserved registers.
3272 const uint32_t *Mask;
Eric Christopher905f12d2015-01-29 00:19:42 +00003273 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00003274 if (IsThisReturn) {
3275 // For 'this' returns, use the X0-preserving mask if applicable
Eric Christopher9deb75d2015-03-11 22:42:13 +00003276 Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003277 if (!Mask) {
3278 IsThisReturn = false;
Eric Christopher9deb75d2015-03-11 22:42:13 +00003279 Mask = TRI->getCallPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003280 }
3281 } else
Eric Christopher9deb75d2015-03-11 22:42:13 +00003282 Mask = TRI->getCallPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003283
3284 assert(Mask && "Missing call preserved mask for calling convention");
3285 Ops.push_back(DAG.getRegisterMask(Mask));
3286
3287 if (InFlag.getNode())
3288 Ops.push_back(InFlag);
3289
3290 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3291
3292 // If we're doing a tall call, use a TC_RETURN here rather than an
3293 // actual call instruction.
Arnold Schwaighoferf54b73d2015-05-08 23:52:00 +00003294 if (IsTailCall) {
3295 MF.getFrameInfo()->setHasTailCall();
Tim Northover3b0846e2014-05-24 12:50:23 +00003296 return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
Arnold Schwaighoferf54b73d2015-05-08 23:52:00 +00003297 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003298
3299 // Returns a chain and a flag for retval copy to use.
3300 Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
3301 InFlag = Chain.getValue(1);
3302
Rui Ueyamada00f2f2016-01-14 21:06:47 +00003303 uint64_t CalleePopBytes =
3304 DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00003305
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003306 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3307 DAG.getIntPtrConstant(CalleePopBytes, DL, true),
Tim Northover3b0846e2014-05-24 12:50:23 +00003308 InFlag, DL);
3309 if (!Ins.empty())
3310 InFlag = Chain.getValue(1);
3311
3312 // Handle result values, copying them out of physregs into vregs that we
3313 // return.
3314 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3315 InVals, IsThisReturn,
3316 IsThisReturn ? OutVals[0] : SDValue());
3317}
3318
3319bool AArch64TargetLowering::CanLowerReturn(
3320 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
3321 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
3322 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3323 ? RetCC_AArch64_WebKit_JS
3324 : RetCC_AArch64_AAPCS;
3325 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003326 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
Tim Northover3b0846e2014-05-24 12:50:23 +00003327 return CCInfo.CheckReturn(Outs, RetCC);
3328}
3329
3330SDValue
3331AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3332 bool isVarArg,
3333 const SmallVectorImpl<ISD::OutputArg> &Outs,
3334 const SmallVectorImpl<SDValue> &OutVals,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003335 const SDLoc &DL, SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00003336 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3337 ? RetCC_AArch64_WebKit_JS
3338 : RetCC_AArch64_AAPCS;
3339 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003340 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3341 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00003342 CCInfo.AnalyzeReturn(Outs, RetCC);
3343
3344 // Copy the result values into the output registers.
3345 SDValue Flag;
3346 SmallVector<SDValue, 4> RetOps(1, Chain);
3347 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
3348 ++i, ++realRVLocIdx) {
3349 CCValAssign &VA = RVLocs[i];
3350 assert(VA.isRegLoc() && "Can only return in registers!");
3351 SDValue Arg = OutVals[realRVLocIdx];
3352
3353 switch (VA.getLocInfo()) {
3354 default:
3355 llvm_unreachable("Unknown loc info!");
3356 case CCValAssign::Full:
Tim Northover68ae5032014-05-26 17:22:07 +00003357 if (Outs[i].ArgVT == MVT::i1) {
3358 // AAPCS requires i1 to be zero-extended to i8 by the producer of the
3359 // value. This is strictly redundant on Darwin (which uses "zeroext
3360 // i1"), but will be optimised out before ISel.
3361 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3362 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3363 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003364 break;
3365 case CCValAssign::BCvt:
3366 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3367 break;
3368 }
3369
3370 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
3371 Flag = Chain.getValue(1);
3372 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3373 }
Manman Rencbe4f942015-12-16 21:04:19 +00003374 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3375 const MCPhysReg *I =
3376 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
3377 if (I) {
3378 for (; *I; ++I) {
3379 if (AArch64::GPR64RegClass.contains(*I))
3380 RetOps.push_back(DAG.getRegister(*I, MVT::i64));
3381 else if (AArch64::FPR64RegClass.contains(*I))
3382 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
3383 else
3384 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
3385 }
3386 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003387
3388 RetOps[0] = Chain; // Update chain.
3389
3390 // Add the flag if we have it.
3391 if (Flag.getNode())
3392 RetOps.push_back(Flag);
3393
3394 return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
3395}
3396
3397//===----------------------------------------------------------------------===//
3398// Other Lowering Code
3399//===----------------------------------------------------------------------===//
3400
3401SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
3402 SelectionDAG &DAG) const {
Mehdi Amini44ede332015-07-09 02:09:04 +00003403 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003404 SDLoc DL(Op);
Asiri Rathnayake369c0302014-09-10 13:54:38 +00003405 const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
3406 const GlobalValue *GV = GN->getGlobal();
Tim Northover3b0846e2014-05-24 12:50:23 +00003407 unsigned char OpFlags =
3408 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
3409
3410 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
3411 "unexpected offset in global node");
3412
3413 // This also catched the large code model case for Darwin.
3414 if ((OpFlags & AArch64II::MO_GOT) != 0) {
3415 SDValue GotAddr = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
3416 // FIXME: Once remat is capable of dealing with instructions with register
3417 // operands, expand this into two nodes instead of using a wrapper node.
3418 return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
3419 }
3420
3421 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
3422 const unsigned char MO_NC = AArch64II::MO_NC;
3423 return DAG.getNode(
3424 AArch64ISD::WrapperLarge, DL, PtrVT,
3425 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G3),
3426 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
3427 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
3428 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
3429 } else {
3430 // Use ADRP/ADD or ADRP/LDR for everything else: the small model on ELF and
3431 // the only correct model on Darwin.
3432 SDValue Hi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
3433 OpFlags | AArch64II::MO_PAGE);
3434 unsigned char LoFlags = OpFlags | AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
3435 SDValue Lo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, LoFlags);
3436
3437 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3438 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3439 }
3440}
3441
3442/// \brief Convert a TLS address reference into the correct sequence of loads
3443/// and calls to compute the variable's address (for Darwin, currently) and
3444/// return an SDValue containing the final node.
3445
3446/// Darwin only has one TLS scheme which must be capable of dealing with the
3447/// fully general situation, in the worst case. This means:
3448/// + "extern __thread" declaration.
3449/// + Defined in a possibly unknown dynamic library.
3450///
3451/// The general system is that each __thread variable has a [3 x i64] descriptor
3452/// which contains information used by the runtime to calculate the address. The
3453/// only part of this the compiler needs to know about is the first xword, which
3454/// contains a function pointer that must be called with the address of the
3455/// entire descriptor in "x0".
3456///
3457/// Since this descriptor may be in a different unit, in general even the
3458/// descriptor must be accessed via an indirect load. The "ideal" code sequence
3459/// is:
3460/// adrp x0, _var@TLVPPAGE
3461/// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor
3462/// ldr x1, [x0] ; x1 contains 1st entry of descriptor,
3463/// ; the function pointer
3464/// blr x1 ; Uses descriptor address in x0
3465/// ; Address of _var is now in x0.
3466///
3467/// If the address of _var's descriptor *is* known to the linker, then it can
3468/// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
3469/// a slight efficiency gain.
3470SDValue
3471AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
3472 SelectionDAG &DAG) const {
3473 assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
3474
3475 SDLoc DL(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00003476 MVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003477 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3478
3479 SDValue TLVPAddr =
3480 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3481 SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
3482
3483 // The first entry in the descriptor is a function pointer that we must call
3484 // to obtain the address of the variable.
3485 SDValue Chain = DAG.getEntryNode();
3486 SDValue FuncTLVGet =
Alex Lorenze40c8a22015-08-11 23:09:45 +00003487 DAG.getLoad(MVT::i64, DL, Chain, DescAddr,
3488 MachinePointerInfo::getGOT(DAG.getMachineFunction()), false,
3489 true, true, 8);
Tim Northover3b0846e2014-05-24 12:50:23 +00003490 Chain = FuncTLVGet.getValue(1);
3491
3492 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3493 MFI->setAdjustsStack(true);
3494
3495 // TLS calls preserve all registers except those that absolutely must be
3496 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
3497 // silly).
Eric Christopher6c901622015-01-28 03:51:33 +00003498 const uint32_t *Mask =
Eric Christopher905f12d2015-01-29 00:19:42 +00003499 Subtarget->getRegisterInfo()->getTLSCallPreservedMask();
Tim Northover3b0846e2014-05-24 12:50:23 +00003500
3501 // Finally, we can make the call. This is just a degenerate version of a
3502 // normal AArch64 call node: x0 takes the address of the descriptor, and
3503 // returns the address of the variable in this thread.
3504 Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
3505 Chain =
3506 DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3507 Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
3508 DAG.getRegisterMask(Mask), Chain.getValue(1));
3509 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
3510}
3511
3512/// When accessing thread-local variables under either the general-dynamic or
3513/// local-dynamic system, we make a "TLS-descriptor" call. The variable will
3514/// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
Kristof Beylsaea84612015-03-04 09:12:08 +00003515/// is a function pointer to carry out the resolution.
Tim Northover3b0846e2014-05-24 12:50:23 +00003516///
Kristof Beylsaea84612015-03-04 09:12:08 +00003517/// The sequence is:
3518/// adrp x0, :tlsdesc:var
3519/// ldr x1, [x0, #:tlsdesc_lo12:var]
3520/// add x0, x0, #:tlsdesc_lo12:var
3521/// .tlsdesccall var
3522/// blr x1
3523/// (TPIDR_EL0 offset now in x0)
Tim Northover3b0846e2014-05-24 12:50:23 +00003524///
Kristof Beylsaea84612015-03-04 09:12:08 +00003525/// The above sequence must be produced unscheduled, to enable the linker to
3526/// optimize/relax this sequence.
3527/// Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
3528/// above sequence, and expanded really late in the compilation flow, to ensure
3529/// the sequence is produced as per above.
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003530SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr,
3531 const SDLoc &DL,
Kristof Beylsaea84612015-03-04 09:12:08 +00003532 SelectionDAG &DAG) const {
Mehdi Amini44ede332015-07-09 02:09:04 +00003533 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003534
Kristof Beylsaea84612015-03-04 09:12:08 +00003535 SDValue Chain = DAG.getEntryNode();
Tim Northover3b0846e2014-05-24 12:50:23 +00003536 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
Kristof Beylsaea84612015-03-04 09:12:08 +00003537
3538 SmallVector<SDValue, 2> Ops;
3539 Ops.push_back(Chain);
3540 Ops.push_back(SymAddr);
3541
3542 Chain = DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, Ops);
3543 SDValue Glue = Chain.getValue(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00003544
3545 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
3546}
3547
3548SDValue
3549AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
3550 SelectionDAG &DAG) const {
3551 assert(Subtarget->isTargetELF() && "This function expects an ELF target");
3552 assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
3553 "ELF TLS only supported in small memory model");
Kristof Beylsaea84612015-03-04 09:12:08 +00003554 // Different choices can be made for the maximum size of the TLS area for a
3555 // module. For the small address model, the default TLS size is 16MiB and the
3556 // maximum TLS size is 4GiB.
3557 // FIXME: add -mtls-size command line option and make it control the 16MiB
3558 // vs. 4GiB code sequence generation.
Tim Northover3b0846e2014-05-24 12:50:23 +00003559 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3560
3561 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
Chih-Hung Hsieh1e859582015-07-28 16:24:05 +00003562
3563 if (DAG.getTarget().Options.EmulatedTLS)
3564 return LowerToTLSEmulatedModel(GA, DAG);
3565
Kristof Beylsaea84612015-03-04 09:12:08 +00003566 if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
3567 if (Model == TLSModel::LocalDynamic)
3568 Model = TLSModel::GeneralDynamic;
3569 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003570
3571 SDValue TPOff;
Mehdi Amini44ede332015-07-09 02:09:04 +00003572 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003573 SDLoc DL(Op);
3574 const GlobalValue *GV = GA->getGlobal();
3575
3576 SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
3577
3578 if (Model == TLSModel::LocalExec) {
3579 SDValue HiVar = DAG.getTargetGlobalAddress(
Kristof Beylsaea84612015-03-04 09:12:08 +00003580 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
Tim Northover3b0846e2014-05-24 12:50:23 +00003581 SDValue LoVar = DAG.getTargetGlobalAddress(
3582 GV, DL, PtrVT, 0,
Kristof Beylsaea84612015-03-04 09:12:08 +00003583 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
Tim Northover3b0846e2014-05-24 12:50:23 +00003584
Kristof Beylsaea84612015-03-04 09:12:08 +00003585 SDValue TPWithOff_lo =
3586 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003587 HiVar,
3588 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003589 0);
3590 SDValue TPWithOff =
3591 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003592 LoVar,
3593 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003594 0);
3595 return TPWithOff;
Tim Northover3b0846e2014-05-24 12:50:23 +00003596 } else if (Model == TLSModel::InitialExec) {
3597 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3598 TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
3599 } else if (Model == TLSModel::LocalDynamic) {
3600 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
3601 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
3602 // the beginning of the module's TLS region, followed by a DTPREL offset
3603 // calculation.
3604
3605 // These accesses will need deduplicating if there's more than one.
3606 AArch64FunctionInfo *MFI =
3607 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
3608 MFI->incNumLocalDynamicTLSAccesses();
3609
Tim Northover3b0846e2014-05-24 12:50:23 +00003610 // The call needs a relocation too for linker relaxation. It doesn't make
3611 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3612 // the address.
3613 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
3614 AArch64II::MO_TLS);
3615
3616 // Now we can calculate the offset from TPIDR_EL0 to this module's
3617 // thread-local area.
Kristof Beylsaea84612015-03-04 09:12:08 +00003618 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00003619
3620 // Now use :dtprel_whatever: operations to calculate this variable's offset
3621 // in its thread-storage area.
3622 SDValue HiVar = DAG.getTargetGlobalAddress(
Kristof Beylsaea84612015-03-04 09:12:08 +00003623 GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
Tim Northover3b0846e2014-05-24 12:50:23 +00003624 SDValue LoVar = DAG.getTargetGlobalAddress(
3625 GV, DL, MVT::i64, 0,
Tim Northover3b0846e2014-05-24 12:50:23 +00003626 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3627
Kristof Beylsaea84612015-03-04 09:12:08 +00003628 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003629 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003630 0);
3631 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003632 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003633 0);
3634 } else if (Model == TLSModel::GeneralDynamic) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003635 // The call needs a relocation too for linker relaxation. It doesn't make
3636 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3637 // the address.
3638 SDValue SymAddr =
3639 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3640
3641 // Finally we can make a call to calculate the offset from tpidr_el0.
Kristof Beylsaea84612015-03-04 09:12:08 +00003642 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00003643 } else
3644 llvm_unreachable("Unsupported ELF TLS access model");
3645
3646 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
3647}
3648
3649SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
3650 SelectionDAG &DAG) const {
3651 if (Subtarget->isTargetDarwin())
3652 return LowerDarwinGlobalTLSAddress(Op, DAG);
3653 else if (Subtarget->isTargetELF())
3654 return LowerELFGlobalTLSAddress(Op, DAG);
3655
3656 llvm_unreachable("Unexpected platform trying to use TLS");
3657}
3658SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3659 SDValue Chain = Op.getOperand(0);
3660 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3661 SDValue LHS = Op.getOperand(2);
3662 SDValue RHS = Op.getOperand(3);
3663 SDValue Dest = Op.getOperand(4);
3664 SDLoc dl(Op);
3665
3666 // Handle f128 first, since lowering it will result in comparing the return
3667 // value of a libcall against zero, which is just what the rest of LowerBR_CC
3668 // is expecting to deal with.
3669 if (LHS.getValueType() == MVT::f128) {
3670 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3671
3672 // If softenSetCCOperands returned a scalar, we need to compare the result
3673 // against zero to select between true and false values.
3674 if (!RHS.getNode()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003675 RHS = DAG.getConstant(0, dl, LHS.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00003676 CC = ISD::SETNE;
3677 }
3678 }
3679
3680 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
3681 // instruction.
3682 unsigned Opc = LHS.getOpcode();
Artyom Skrobov314ee042015-11-25 19:41:11 +00003683 if (LHS.getResNo() == 1 && isOneConstant(RHS) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00003684 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3685 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
3686 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
3687 "Unexpected condition code.");
3688 // Only lower legal XALUO ops.
3689 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
3690 return SDValue();
3691
3692 // The actual operation with overflow check.
3693 AArch64CC::CondCode OFCC;
3694 SDValue Value, Overflow;
3695 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
3696
3697 if (CC == ISD::SETNE)
3698 OFCC = getInvertedCondCode(OFCC);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003699 SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003700
Ahmed Bougachadf956a22015-02-06 23:15:39 +00003701 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3702 Overflow);
Tim Northover3b0846e2014-05-24 12:50:23 +00003703 }
3704
3705 if (LHS.getValueType().isInteger()) {
3706 assert((LHS.getValueType() == RHS.getValueType()) &&
3707 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3708
3709 // If the RHS of the comparison is zero, we can potentially fold this
3710 // to a specialized branch.
3711 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
3712 if (RHSC && RHSC->getZExtValue() == 0) {
3713 if (CC == ISD::SETEQ) {
3714 // See if we can use a TBZ to fold in an AND as well.
3715 // TBZ has a smaller branch displacement than CBZ. If the offset is
3716 // out of bounds, a late MI-layer pass rewrites branches.
3717 // 403.gcc is an example that hits this case.
3718 if (LHS.getOpcode() == ISD::AND &&
3719 isa<ConstantSDNode>(LHS.getOperand(1)) &&
3720 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3721 SDValue Test = LHS.getOperand(0);
3722 uint64_t Mask = LHS.getConstantOperandVal(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00003723 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003724 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3725 Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00003726 }
3727
3728 return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
3729 } else if (CC == ISD::SETNE) {
3730 // See if we can use a TBZ to fold in an AND as well.
3731 // TBZ has a smaller branch displacement than CBZ. If the offset is
3732 // out of bounds, a late MI-layer pass rewrites branches.
3733 // 403.gcc is an example that hits this case.
3734 if (LHS.getOpcode() == ISD::AND &&
3735 isa<ConstantSDNode>(LHS.getOperand(1)) &&
3736 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3737 SDValue Test = LHS.getOperand(0);
3738 uint64_t Mask = LHS.getConstantOperandVal(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00003739 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003740 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3741 Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00003742 }
3743
3744 return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
Chad Rosier579c02c2014-08-01 14:48:56 +00003745 } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
3746 // Don't combine AND since emitComparison converts the AND to an ANDS
3747 // (a.k.a. TST) and the test in the test bit and branch instruction
3748 // becomes redundant. This would also increase register pressure.
3749 uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
3750 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003751 DAG.getConstant(Mask, dl, MVT::i64), Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00003752 }
3753 }
Chad Rosier579c02c2014-08-01 14:48:56 +00003754 if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
3755 LHS.getOpcode() != ISD::AND) {
3756 // Don't combine AND since emitComparison converts the AND to an ANDS
3757 // (a.k.a. TST) and the test in the test bit and branch instruction
3758 // becomes redundant. This would also increase register pressure.
3759 uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
3760 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003761 DAG.getConstant(Mask, dl, MVT::i64), Dest);
Chad Rosier579c02c2014-08-01 14:48:56 +00003762 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003763
3764 SDValue CCVal;
3765 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3766 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3767 Cmp);
3768 }
3769
3770 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3771
3772 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
3773 // clean. Some of them require two branches to implement.
3774 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3775 AArch64CC::CondCode CC1, CC2;
3776 changeFPCCToAArch64CC(CC, CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003777 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003778 SDValue BR1 =
3779 DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
3780 if (CC2 != AArch64CC::AL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003781 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003782 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
3783 Cmp);
3784 }
3785
3786 return BR1;
3787}
3788
3789SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
3790 SelectionDAG &DAG) const {
3791 EVT VT = Op.getValueType();
3792 SDLoc DL(Op);
3793
3794 SDValue In1 = Op.getOperand(0);
3795 SDValue In2 = Op.getOperand(1);
3796 EVT SrcVT = In2.getValueType();
Ahmed Bougacha2a97b1b2015-08-13 01:13:56 +00003797
3798 if (SrcVT.bitsLT(VT))
3799 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
3800 else if (SrcVT.bitsGT(VT))
3801 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
Tim Northover3b0846e2014-05-24 12:50:23 +00003802
3803 EVT VecVT;
3804 EVT EltVT;
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00003805 uint64_t EltMask;
3806 SDValue VecVal1, VecVal2;
Tim Northover3b0846e2014-05-24 12:50:23 +00003807 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
3808 EltVT = MVT::i32;
Ahmed Bougachab0ae36f2015-08-04 00:42:34 +00003809 VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00003810 EltMask = 0x80000000ULL;
Tim Northover3b0846e2014-05-24 12:50:23 +00003811
3812 if (!VT.isVector()) {
3813 VecVal1 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3814 DAG.getUNDEF(VecVT), In1);
3815 VecVal2 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3816 DAG.getUNDEF(VecVT), In2);
3817 } else {
3818 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3819 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3820 }
3821 } else if (VT == MVT::f64 || VT == MVT::v2f64) {
3822 EltVT = MVT::i64;
3823 VecVT = MVT::v2i64;
3824
Eric Christopher572e03a2015-06-19 01:53:21 +00003825 // We want to materialize a mask with the high bit set, but the AdvSIMD
Tim Northover3b0846e2014-05-24 12:50:23 +00003826 // immediate moves cannot materialize that in a single instruction for
3827 // 64-bit elements. Instead, materialize zero and then negate it.
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00003828 EltMask = 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00003829
3830 if (!VT.isVector()) {
3831 VecVal1 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3832 DAG.getUNDEF(VecVT), In1);
3833 VecVal2 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3834 DAG.getUNDEF(VecVT), In2);
3835 } else {
3836 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3837 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3838 }
3839 } else {
3840 llvm_unreachable("Invalid type for copysign!");
3841 }
3842
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003843 SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00003844
3845 // If we couldn't materialize the mask above, then the mask vector will be
3846 // the zero vector, and we need to negate it here.
3847 if (VT == MVT::f64 || VT == MVT::v2f64) {
3848 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
3849 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
3850 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
3851 }
3852
3853 SDValue Sel =
3854 DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
3855
3856 if (VT == MVT::f32)
3857 return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
3858 else if (VT == MVT::f64)
3859 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
3860 else
3861 return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
3862}
3863
3864SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
Duncan P. N. Exon Smith003bb7d2015-02-14 02:09:06 +00003865 if (DAG.getMachineFunction().getFunction()->hasFnAttribute(
3866 Attribute::NoImplicitFloat))
Tim Northover3b0846e2014-05-24 12:50:23 +00003867 return SDValue();
3868
Weiming Zhao7a2d1562014-11-19 00:29:14 +00003869 if (!Subtarget->hasNEON())
3870 return SDValue();
3871
Tim Northover3b0846e2014-05-24 12:50:23 +00003872 // While there is no integer popcount instruction, it can
3873 // be more efficiently lowered to the following sequence that uses
3874 // AdvSIMD registers/instructions as long as the copies to/from
3875 // the AdvSIMD registers are cheap.
3876 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd
3877 // CNT V0.8B, V0.8B // 8xbyte pop-counts
3878 // ADDV B0, V0.8B // sum 8xbyte pop-counts
3879 // UMOV X0, V0.B[0] // copy byte result back to integer reg
3880 SDValue Val = Op.getOperand(0);
3881 SDLoc DL(Op);
3882 EVT VT = Op.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00003883
Hao Liue0335d72015-01-30 02:13:53 +00003884 if (VT == MVT::i32)
3885 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
3886 Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
Tim Northover3b0846e2014-05-24 12:50:23 +00003887
Hao Liue0335d72015-01-30 02:13:53 +00003888 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
Tim Northover3b0846e2014-05-24 12:50:23 +00003889 SDValue UaddLV = DAG.getNode(
3890 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003891 DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
Tim Northover3b0846e2014-05-24 12:50:23 +00003892
3893 if (VT == MVT::i64)
3894 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
3895 return UaddLV;
3896}
3897
3898SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3899
3900 if (Op.getValueType().isVector())
3901 return LowerVSETCC(Op, DAG);
3902
3903 SDValue LHS = Op.getOperand(0);
3904 SDValue RHS = Op.getOperand(1);
3905 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3906 SDLoc dl(Op);
3907
3908 // We chose ZeroOrOneBooleanContents, so use zero and one.
3909 EVT VT = Op.getValueType();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003910 SDValue TVal = DAG.getConstant(1, dl, VT);
3911 SDValue FVal = DAG.getConstant(0, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00003912
3913 // Handle f128 first, since one possible outcome is a normal integer
3914 // comparison which gets picked up by the next if statement.
3915 if (LHS.getValueType() == MVT::f128) {
3916 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3917
3918 // If softenSetCCOperands returned a scalar, use it.
3919 if (!RHS.getNode()) {
3920 assert(LHS.getValueType() == Op.getValueType() &&
3921 "Unexpected setcc expansion!");
3922 return LHS;
3923 }
3924 }
3925
3926 if (LHS.getValueType().isInteger()) {
3927 SDValue CCVal;
3928 SDValue Cmp =
3929 getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
3930
3931 // Note that we inverted the condition above, so we reverse the order of
3932 // the true and false operands here. This will allow the setcc to be
3933 // matched to a single CSINC instruction.
3934 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
3935 }
3936
3937 // Now we know we're dealing with FP values.
3938 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3939
3940 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
3941 // and do the comparison.
3942 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3943
3944 AArch64CC::CondCode CC1, CC2;
3945 changeFPCCToAArch64CC(CC, CC1, CC2);
3946 if (CC2 == AArch64CC::AL) {
3947 changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003948 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003949
3950 // Note that we inverted the condition above, so we reverse the order of
3951 // the true and false operands here. This will allow the setcc to be
3952 // matched to a single CSINC instruction.
3953 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
3954 } else {
3955 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
3956 // totally clean. Some of them require two CSELs to implement. As is in
3957 // this case, we emit the first CSEL and then emit a second using the output
3958 // of the first as the RHS. We're effectively OR'ing the two CC's together.
3959
3960 // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003961 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003962 SDValue CS1 =
3963 DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3964
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003965 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003966 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3967 }
3968}
3969
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00003970SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
3971 SDValue RHS, SDValue TVal,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003972 SDValue FVal, const SDLoc &dl,
Tim Northover3b0846e2014-05-24 12:50:23 +00003973 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00003974 // Handle f128 first, because it will result in a comparison of some RTLIB
3975 // call result against zero.
3976 if (LHS.getValueType() == MVT::f128) {
3977 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3978
3979 // If softenSetCCOperands returned a scalar, we need to compare the result
3980 // against zero to select between true and false values.
3981 if (!RHS.getNode()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003982 RHS = DAG.getConstant(0, dl, LHS.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00003983 CC = ISD::SETNE;
3984 }
3985 }
3986
Ahmed Bougacha88ddeae2015-11-17 16:45:40 +00003987 // Also handle f16, for which we need to do a f32 comparison.
3988 if (LHS.getValueType() == MVT::f16) {
3989 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
3990 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
3991 }
3992
3993 // Next, handle integers.
Tim Northover3b0846e2014-05-24 12:50:23 +00003994 if (LHS.getValueType().isInteger()) {
3995 assert((LHS.getValueType() == RHS.getValueType()) &&
3996 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3997
3998 unsigned Opcode = AArch64ISD::CSEL;
3999
4000 // If both the TVal and the FVal are constants, see if we can swap them in
4001 // order to for a CSINV or CSINC out of them.
4002 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
4003 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
4004
4005 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
4006 std::swap(TVal, FVal);
4007 std::swap(CTVal, CFVal);
4008 CC = ISD::getSetCCInverse(CC, true);
4009 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
4010 std::swap(TVal, FVal);
4011 std::swap(CTVal, CFVal);
4012 CC = ISD::getSetCCInverse(CC, true);
4013 } else if (TVal.getOpcode() == ISD::XOR) {
4014 // If TVal is a NOT we want to swap TVal and FVal so that we can match
4015 // with a CSINV rather than a CSEL.
Artyom Skrobov314ee042015-11-25 19:41:11 +00004016 if (isAllOnesConstant(TVal.getOperand(1))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004017 std::swap(TVal, FVal);
4018 std::swap(CTVal, CFVal);
4019 CC = ISD::getSetCCInverse(CC, true);
4020 }
4021 } else if (TVal.getOpcode() == ISD::SUB) {
4022 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
4023 // that we can match with a CSNEG rather than a CSEL.
Artyom Skrobov314ee042015-11-25 19:41:11 +00004024 if (isNullConstant(TVal.getOperand(0))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004025 std::swap(TVal, FVal);
4026 std::swap(CTVal, CFVal);
4027 CC = ISD::getSetCCInverse(CC, true);
4028 }
4029 } else if (CTVal && CFVal) {
4030 const int64_t TrueVal = CTVal->getSExtValue();
4031 const int64_t FalseVal = CFVal->getSExtValue();
4032 bool Swap = false;
4033
4034 // If both TVal and FVal are constants, see if FVal is the
4035 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
4036 // instead of a CSEL in that case.
4037 if (TrueVal == ~FalseVal) {
4038 Opcode = AArch64ISD::CSINV;
4039 } else if (TrueVal == -FalseVal) {
4040 Opcode = AArch64ISD::CSNEG;
4041 } else if (TVal.getValueType() == MVT::i32) {
4042 // If our operands are only 32-bit wide, make sure we use 32-bit
4043 // arithmetic for the check whether we can use CSINC. This ensures that
4044 // the addition in the check will wrap around properly in case there is
4045 // an overflow (which would not be the case if we do the check with
4046 // 64-bit arithmetic).
4047 const uint32_t TrueVal32 = CTVal->getZExtValue();
4048 const uint32_t FalseVal32 = CFVal->getZExtValue();
4049
4050 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
4051 Opcode = AArch64ISD::CSINC;
4052
4053 if (TrueVal32 > FalseVal32) {
4054 Swap = true;
4055 }
4056 }
4057 // 64-bit check whether we can use CSINC.
4058 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
4059 Opcode = AArch64ISD::CSINC;
4060
4061 if (TrueVal > FalseVal) {
4062 Swap = true;
4063 }
4064 }
4065
4066 // Swap TVal and FVal if necessary.
4067 if (Swap) {
4068 std::swap(TVal, FVal);
4069 std::swap(CTVal, CFVal);
4070 CC = ISD::getSetCCInverse(CC, true);
4071 }
4072
4073 if (Opcode != AArch64ISD::CSEL) {
4074 // Drop FVal since we can get its value by simply inverting/negating
4075 // TVal.
4076 FVal = TVal;
4077 }
4078 }
4079
4080 SDValue CCVal;
4081 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
4082
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004083 EVT VT = TVal.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00004084 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
4085 }
4086
4087 // Now we know we're dealing with FP values.
4088 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
4089 assert(LHS.getValueType() == RHS.getValueType());
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004090 EVT VT = TVal.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00004091 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
4092
4093 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4094 // clean. Some of them require two CSELs to implement.
4095 AArch64CC::CondCode CC1, CC2;
4096 changeFPCCToAArch64CC(CC, CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004097 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004098 SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4099
4100 // If we need a second CSEL, emit it, using the output of the first as the
4101 // RHS. We're effectively OR'ing the two CC's together.
4102 if (CC2 != AArch64CC::AL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004103 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004104 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4105 }
4106
4107 // Otherwise, return the output of the first CSEL.
4108 return CS1;
4109}
4110
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004111SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
4112 SelectionDAG &DAG) const {
4113 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4114 SDValue LHS = Op.getOperand(0);
4115 SDValue RHS = Op.getOperand(1);
4116 SDValue TVal = Op.getOperand(2);
4117 SDValue FVal = Op.getOperand(3);
4118 SDLoc DL(Op);
4119 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4120}
4121
4122SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
4123 SelectionDAG &DAG) const {
4124 SDValue CCVal = Op->getOperand(0);
4125 SDValue TVal = Op->getOperand(1);
4126 SDValue FVal = Op->getOperand(2);
4127 SDLoc DL(Op);
4128
4129 unsigned Opc = CCVal.getOpcode();
4130 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
4131 // instruction.
4132 if (CCVal.getResNo() == 1 &&
4133 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4134 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
4135 // Only lower legal XALUO ops.
4136 if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
4137 return SDValue();
4138
4139 AArch64CC::CondCode OFCC;
4140 SDValue Value, Overflow;
4141 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004142 SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004143
4144 return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
4145 CCVal, Overflow);
4146 }
4147
4148 // Lower it the same way as we would lower a SELECT_CC node.
4149 ISD::CondCode CC;
4150 SDValue LHS, RHS;
4151 if (CCVal.getOpcode() == ISD::SETCC) {
4152 LHS = CCVal.getOperand(0);
4153 RHS = CCVal.getOperand(1);
4154 CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
4155 } else {
4156 LHS = CCVal;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004157 RHS = DAG.getConstant(0, DL, CCVal.getValueType());
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004158 CC = ISD::SETNE;
4159 }
4160 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4161}
4162
Tim Northover3b0846e2014-05-24 12:50:23 +00004163SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
4164 SelectionDAG &DAG) const {
4165 // Jump table entries as PC relative offsets. No additional tweaking
4166 // is necessary here. Just get the address of the jump table.
4167 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00004168 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004169 SDLoc DL(Op);
4170
4171 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4172 !Subtarget->isTargetMachO()) {
4173 const unsigned char MO_NC = AArch64II::MO_NC;
4174 return DAG.getNode(
4175 AArch64ISD::WrapperLarge, DL, PtrVT,
4176 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G3),
4177 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G2 | MO_NC),
4178 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G1 | MO_NC),
4179 DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4180 AArch64II::MO_G0 | MO_NC));
4181 }
4182
4183 SDValue Hi =
4184 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_PAGE);
4185 SDValue Lo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4186 AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4187 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4188 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4189}
4190
4191SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
4192 SelectionDAG &DAG) const {
4193 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00004194 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004195 SDLoc DL(Op);
4196
4197 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4198 // Use the GOT for the large code model on iOS.
4199 if (Subtarget->isTargetMachO()) {
4200 SDValue GotAddr = DAG.getTargetConstantPool(
4201 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4202 AArch64II::MO_GOT);
4203 return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
4204 }
4205
4206 const unsigned char MO_NC = AArch64II::MO_NC;
4207 return DAG.getNode(
4208 AArch64ISD::WrapperLarge, DL, PtrVT,
4209 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4210 CP->getOffset(), AArch64II::MO_G3),
4211 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4212 CP->getOffset(), AArch64II::MO_G2 | MO_NC),
4213 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4214 CP->getOffset(), AArch64II::MO_G1 | MO_NC),
4215 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4216 CP->getOffset(), AArch64II::MO_G0 | MO_NC));
4217 } else {
4218 // Use ADRP/ADD or ADRP/LDR for everything else: the small memory model on
4219 // ELF, the only valid one on Darwin.
4220 SDValue Hi =
4221 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4222 CP->getOffset(), AArch64II::MO_PAGE);
4223 SDValue Lo = DAG.getTargetConstantPool(
4224 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4225 AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4226
4227 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4228 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4229 }
4230}
4231
4232SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
4233 SelectionDAG &DAG) const {
4234 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
Mehdi Amini44ede332015-07-09 02:09:04 +00004235 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004236 SDLoc DL(Op);
4237 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4238 !Subtarget->isTargetMachO()) {
4239 const unsigned char MO_NC = AArch64II::MO_NC;
4240 return DAG.getNode(
4241 AArch64ISD::WrapperLarge, DL, PtrVT,
4242 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G3),
4243 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
4244 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
4245 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
4246 } else {
4247 SDValue Hi = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGE);
4248 SDValue Lo = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGEOFF |
4249 AArch64II::MO_NC);
4250 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4251 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4252 }
4253}
4254
4255SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
4256 SelectionDAG &DAG) const {
4257 AArch64FunctionInfo *FuncInfo =
4258 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4259
4260 SDLoc DL(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00004261 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
4262 getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00004263 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4264 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
4265 MachinePointerInfo(SV), false, false, 0);
4266}
4267
4268SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
4269 SelectionDAG &DAG) const {
4270 // The layout of the va_list struct is specified in the AArch64 Procedure Call
4271 // Standard, section B.3.
4272 MachineFunction &MF = DAG.getMachineFunction();
4273 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Mehdi Amini44ede332015-07-09 02:09:04 +00004274 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004275 SDLoc DL(Op);
4276
4277 SDValue Chain = Op.getOperand(0);
4278 SDValue VAList = Op.getOperand(1);
4279 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4280 SmallVector<SDValue, 4> MemOps;
4281
4282 // void *__stack at offset 0
Mehdi Amini44ede332015-07-09 02:09:04 +00004283 SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004284 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
4285 MachinePointerInfo(SV), false, false, 8));
4286
4287 // void *__gr_top at offset 8
4288 int GPRSize = FuncInfo->getVarArgsGPRSize();
4289 if (GPRSize > 0) {
4290 SDValue GRTop, GRTopAddr;
4291
Mehdi Amini44ede332015-07-09 02:09:04 +00004292 GRTopAddr =
4293 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004294
Mehdi Amini44ede332015-07-09 02:09:04 +00004295 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
4296 GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
4297 DAG.getConstant(GPRSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004298
4299 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
4300 MachinePointerInfo(SV, 8), false, false, 8));
4301 }
4302
4303 // void *__vr_top at offset 16
4304 int FPRSize = FuncInfo->getVarArgsFPRSize();
4305 if (FPRSize > 0) {
4306 SDValue VRTop, VRTopAddr;
Mehdi Amini44ede332015-07-09 02:09:04 +00004307 VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4308 DAG.getConstant(16, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004309
Mehdi Amini44ede332015-07-09 02:09:04 +00004310 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
4311 VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
4312 DAG.getConstant(FPRSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004313
4314 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
4315 MachinePointerInfo(SV, 16), false, false, 8));
4316 }
4317
4318 // int __gr_offs at offset 24
Mehdi Amini44ede332015-07-09 02:09:04 +00004319 SDValue GROffsAddr =
4320 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004321 MemOps.push_back(DAG.getStore(Chain, DL,
4322 DAG.getConstant(-GPRSize, DL, MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00004323 GROffsAddr, MachinePointerInfo(SV, 24), false,
4324 false, 4));
4325
4326 // int __vr_offs at offset 28
Mehdi Amini44ede332015-07-09 02:09:04 +00004327 SDValue VROffsAddr =
4328 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004329 MemOps.push_back(DAG.getStore(Chain, DL,
4330 DAG.getConstant(-FPRSize, DL, MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00004331 VROffsAddr, MachinePointerInfo(SV, 28), false,
4332 false, 4));
4333
4334 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
4335}
4336
4337SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
4338 SelectionDAG &DAG) const {
4339 return Subtarget->isTargetDarwin() ? LowerDarwin_VASTART(Op, DAG)
4340 : LowerAAPCS_VASTART(Op, DAG);
4341}
4342
4343SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
4344 SelectionDAG &DAG) const {
4345 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
4346 // pointer.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004347 SDLoc DL(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00004348 unsigned VaListSize = Subtarget->isTargetDarwin() ? 8 : 32;
4349 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4350 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4351
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004352 return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1),
4353 Op.getOperand(2),
4354 DAG.getConstant(VaListSize, DL, MVT::i32),
Krzysztof Parzyszeka46c36b2015-04-13 17:16:45 +00004355 8, false, false, false, MachinePointerInfo(DestSV),
Tim Northover3b0846e2014-05-24 12:50:23 +00004356 MachinePointerInfo(SrcSV));
4357}
4358
4359SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
4360 assert(Subtarget->isTargetDarwin() &&
4361 "automatic va_arg instruction only works on Darwin");
4362
4363 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4364 EVT VT = Op.getValueType();
4365 SDLoc DL(Op);
4366 SDValue Chain = Op.getOperand(0);
4367 SDValue Addr = Op.getOperand(1);
4368 unsigned Align = Op.getConstantOperandVal(3);
Mehdi Amini44ede332015-07-09 02:09:04 +00004369 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004370
Mehdi Amini44ede332015-07-09 02:09:04 +00004371 SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V),
4372 false, false, false, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00004373 Chain = VAList.getValue(1);
4374
4375 if (Align > 8) {
4376 assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
Mehdi Amini44ede332015-07-09 02:09:04 +00004377 VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4378 DAG.getConstant(Align - 1, DL, PtrVT));
4379 VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
4380 DAG.getConstant(-(int64_t)Align, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004381 }
4382
4383 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
Mehdi Amini44ede332015-07-09 02:09:04 +00004384 uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
Tim Northover3b0846e2014-05-24 12:50:23 +00004385
4386 // Scalar integer and FP values smaller than 64 bits are implicitly extended
4387 // up to 64 bits. At the very least, we have to increase the striding of the
4388 // vaargs list to match this, and for FP values we need to introduce
4389 // FP_ROUND nodes as well.
4390 if (VT.isInteger() && !VT.isVector())
4391 ArgSize = 8;
4392 bool NeedFPTrunc = false;
4393 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
4394 ArgSize = 8;
4395 NeedFPTrunc = true;
4396 }
4397
4398 // Increment the pointer, VAList, to the next vaarg
Mehdi Amini44ede332015-07-09 02:09:04 +00004399 SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4400 DAG.getConstant(ArgSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004401 // Store the incremented VAList to the legalized pointer
4402 SDValue APStore = DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V),
4403 false, false, 0);
4404
4405 // Load the actual argument out of the pointer VAList
4406 if (NeedFPTrunc) {
4407 // Load the value as an f64.
4408 SDValue WideFP = DAG.getLoad(MVT::f64, DL, APStore, VAList,
4409 MachinePointerInfo(), false, false, false, 0);
4410 // Round the value down to an f32.
4411 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004412 DAG.getIntPtrConstant(1, DL));
Tim Northover3b0846e2014-05-24 12:50:23 +00004413 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
4414 // Merge the rounded value with the chain output of the load.
4415 return DAG.getMergeValues(Ops, DL);
4416 }
4417
4418 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo(), false,
4419 false, false, 0);
4420}
4421
4422SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
4423 SelectionDAG &DAG) const {
4424 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4425 MFI->setFrameAddressIsTaken(true);
4426
4427 EVT VT = Op.getValueType();
4428 SDLoc DL(Op);
4429 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4430 SDValue FrameAddr =
4431 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
4432 while (Depth--)
4433 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
4434 MachinePointerInfo(), false, false, false, 0);
4435 return FrameAddr;
4436}
4437
4438// FIXME? Maybe this could be a TableGen attribute on some registers and
4439// this table could be generated automatically from RegInfo.
Pat Gavlina717f252015-07-09 17:40:29 +00004440unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT,
4441 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004442 unsigned Reg = StringSwitch<unsigned>(RegName)
4443 .Case("sp", AArch64::SP)
4444 .Default(0);
4445 if (Reg)
4446 return Reg;
Luke Cheeseman85fd06d2015-06-01 12:02:47 +00004447 report_fatal_error(Twine("Invalid register name \""
4448 + StringRef(RegName) + "\"."));
Tim Northover3b0846e2014-05-24 12:50:23 +00004449}
4450
4451SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
4452 SelectionDAG &DAG) const {
4453 MachineFunction &MF = DAG.getMachineFunction();
4454 MachineFrameInfo *MFI = MF.getFrameInfo();
4455 MFI->setReturnAddressIsTaken(true);
4456
4457 EVT VT = Op.getValueType();
4458 SDLoc DL(Op);
4459 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4460 if (Depth) {
4461 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
Mehdi Amini44ede332015-07-09 02:09:04 +00004462 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00004463 return DAG.getLoad(VT, DL, DAG.getEntryNode(),
4464 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
4465 MachinePointerInfo(), false, false, false, 0);
4466 }
4467
4468 // Return LR, which contains the return address. Mark it an implicit live-in.
4469 unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
4470 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4471}
4472
4473/// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4474/// i64 values and take a 2 x i64 value to shift plus a shift amount.
4475SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
4476 SelectionDAG &DAG) const {
4477 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4478 EVT VT = Op.getValueType();
4479 unsigned VTBits = VT.getSizeInBits();
4480 SDLoc dl(Op);
4481 SDValue ShOpLo = Op.getOperand(0);
4482 SDValue ShOpHi = Op.getOperand(1);
4483 SDValue ShAmt = Op.getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00004484 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4485
4486 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4487
4488 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004489 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
Tim Northoverf3be9d52015-12-02 00:33:54 +00004490 SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4491
4492 // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
4493 // is "undef". We wanted 0, so CSEL it directly.
4494 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
4495 ISD::SETEQ, dl, DAG);
4496 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
4497 HiBitsForLo =
4498 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
4499 HiBitsForLo, CCVal, Cmp);
4500
Tim Northover3b0846e2014-05-24 12:50:23 +00004501 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004502 DAG.getConstant(VTBits, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00004503
Tim Northoverf3be9d52015-12-02 00:33:54 +00004504 SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4505 SDValue LoForNormalShift =
4506 DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
Tim Northover3b0846e2014-05-24 12:50:23 +00004507
Tim Northoverf3be9d52015-12-02 00:33:54 +00004508 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
4509 dl, DAG);
4510 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4511 SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4512 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
4513 LoForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00004514
4515 // AArch64 shifts larger than the register width are wrapped rather than
4516 // clamped, so we can't just emit "hi >> x".
Tim Northoverf3be9d52015-12-02 00:33:54 +00004517 SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4518 SDValue HiForBigShift =
4519 Opc == ISD::SRA
4520 ? DAG.getNode(Opc, dl, VT, ShOpHi,
4521 DAG.getConstant(VTBits - 1, dl, MVT::i64))
4522 : DAG.getConstant(0, dl, VT);
4523 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
4524 HiForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00004525
4526 SDValue Ops[2] = { Lo, Hi };
4527 return DAG.getMergeValues(Ops, dl);
4528}
4529
Tim Northoverf3be9d52015-12-02 00:33:54 +00004530
Tim Northover3b0846e2014-05-24 12:50:23 +00004531/// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4532/// i64 values and take a 2 x i64 value to shift plus a shift amount.
4533SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
Tim Northoverf3be9d52015-12-02 00:33:54 +00004534 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004535 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4536 EVT VT = Op.getValueType();
4537 unsigned VTBits = VT.getSizeInBits();
4538 SDLoc dl(Op);
4539 SDValue ShOpLo = Op.getOperand(0);
4540 SDValue ShOpHi = Op.getOperand(1);
4541 SDValue ShAmt = Op.getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00004542
4543 assert(Op.getOpcode() == ISD::SHL_PARTS);
4544 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004545 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
Tim Northoverf3be9d52015-12-02 00:33:54 +00004546 SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4547
4548 // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
4549 // is "undef". We wanted 0, so CSEL it directly.
4550 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
4551 ISD::SETEQ, dl, DAG);
4552 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
4553 LoBitsForHi =
4554 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
4555 LoBitsForHi, CCVal, Cmp);
4556
Tim Northover3b0846e2014-05-24 12:50:23 +00004557 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004558 DAG.getConstant(VTBits, dl, MVT::i64));
Tim Northoverf3be9d52015-12-02 00:33:54 +00004559 SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4560 SDValue HiForNormalShift =
4561 DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
Tim Northover3b0846e2014-05-24 12:50:23 +00004562
Tim Northoverf3be9d52015-12-02 00:33:54 +00004563 SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
Tim Northover3b0846e2014-05-24 12:50:23 +00004564
Tim Northoverf3be9d52015-12-02 00:33:54 +00004565 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
4566 dl, DAG);
4567 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4568 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
4569 HiForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00004570
4571 // AArch64 shifts of larger than register sizes are wrapped rather than
4572 // clamped, so we can't just emit "lo << a" if a is too big.
Tim Northoverf3be9d52015-12-02 00:33:54 +00004573 SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
4574 SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4575 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
4576 LoForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00004577
4578 SDValue Ops[2] = { Lo, Hi };
4579 return DAG.getMergeValues(Ops, dl);
4580}
4581
4582bool AArch64TargetLowering::isOffsetFoldingLegal(
4583 const GlobalAddressSDNode *GA) const {
4584 // The AArch64 target doesn't support folding offsets into global addresses.
4585 return false;
4586}
4587
4588bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4589 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
4590 // FIXME: We should be able to handle f128 as well with a clever lowering.
4591 if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32))
4592 return true;
4593
4594 if (VT == MVT::f64)
4595 return AArch64_AM::getFP64Imm(Imm) != -1;
4596 else if (VT == MVT::f32)
4597 return AArch64_AM::getFP32Imm(Imm) != -1;
4598 return false;
4599}
4600
4601//===----------------------------------------------------------------------===//
4602// AArch64 Optimization Hooks
4603//===----------------------------------------------------------------------===//
4604
Evandro Menezesbcb95cd2016-05-04 20:18:27 +00004605/// getEstimate - Return the appropriate estimate DAG for either the reciprocal
4606/// or the reciprocal square root.
4607static SDValue getEstimate(const AArch64Subtarget &ST,
4608 const AArch64TargetLowering::DAGCombinerInfo &DCI, unsigned Opcode,
4609 const SDValue &Operand, unsigned &ExtraSteps) {
4610 if (!ST.hasNEON())
4611 return SDValue();
4612
4613 EVT VT = Operand.getValueType();
4614
4615 std::string RecipOp;
4616 RecipOp = Opcode == (AArch64ISD::FRECPE) ? "div": "sqrt";
4617 RecipOp = ((VT.isVector()) ? "vec-": "") + RecipOp;
4618 RecipOp += (VT.getScalarType() == MVT::f64) ? "d": "f";
4619
4620 TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
4621 if (!Recips.isEnabled(RecipOp))
4622 return SDValue();
4623
4624 ExtraSteps = Recips.getRefinementSteps(RecipOp);
4625 return DCI.DAG.getNode(Opcode, SDLoc(Operand), VT, Operand);
4626}
4627
4628SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand,
4629 DAGCombinerInfo &DCI, unsigned &ExtraSteps) const {
4630 return getEstimate(*Subtarget, DCI, AArch64ISD::FRECPE, Operand, ExtraSteps);
4631}
4632
4633SDValue AArch64TargetLowering::getRsqrtEstimate(SDValue Operand,
4634 DAGCombinerInfo &DCI, unsigned &ExtraSteps, bool &UseOneConst) const {
4635 UseOneConst = true;
4636 return getEstimate(*Subtarget, DCI, AArch64ISD::FRSQRTE, Operand, ExtraSteps);
4637}
4638
Tim Northover3b0846e2014-05-24 12:50:23 +00004639//===----------------------------------------------------------------------===//
4640// AArch64 Inline Assembly Support
4641//===----------------------------------------------------------------------===//
4642
4643// Table of Constraints
4644// TODO: This is the current set of constraints supported by ARM for the
4645// compiler, not all of them may make sense, e.g. S may be difficult to support.
4646//
4647// r - A general register
4648// w - An FP/SIMD register of some size in the range v0-v31
4649// x - An FP/SIMD register of some size in the range v0-v15
4650// I - Constant that can be used with an ADD instruction
4651// J - Constant that can be used with a SUB instruction
4652// K - Constant that can be used with a 32-bit logical instruction
4653// L - Constant that can be used with a 64-bit logical instruction
4654// M - Constant that can be used as a 32-bit MOV immediate
4655// N - Constant that can be used as a 64-bit MOV immediate
4656// Q - A memory reference with base register and no offset
4657// S - A symbolic address
4658// Y - Floating point constant zero
4659// Z - Integer constant zero
4660//
4661// Note that general register operands will be output using their 64-bit x
4662// register name, whatever the size of the variable, unless the asm operand
4663// is prefixed by the %w modifier. Floating-point and SIMD register operands
4664// will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
4665// %q modifier.
Silviu Barangaf60be282016-05-09 11:10:44 +00004666const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
4667 // At this point, we have to lower this constraint to something else, so we
4668 // lower it to an "r" or "w". However, by doing this we will force the result
4669 // to be in register, while the X constraint is much more permissive.
4670 //
4671 // Although we are correct (we are free to emit anything, without
4672 // constraints), we might break use cases that would expect us to be more
4673 // efficient and emit something else.
4674 if (!Subtarget->hasFPARMv8())
4675 return "r";
4676
4677 if (ConstraintVT.isFloatingPoint())
4678 return "w";
4679
4680 if (ConstraintVT.isVector() &&
4681 (ConstraintVT.getSizeInBits() == 64 ||
4682 ConstraintVT.getSizeInBits() == 128))
4683 return "w";
4684
4685 return "r";
4686}
Tim Northover3b0846e2014-05-24 12:50:23 +00004687
4688/// getConstraintType - Given a constraint letter, return the type of
4689/// constraint it is for this target.
4690AArch64TargetLowering::ConstraintType
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00004691AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004692 if (Constraint.size() == 1) {
4693 switch (Constraint[0]) {
4694 default:
4695 break;
4696 case 'z':
4697 return C_Other;
4698 case 'x':
4699 case 'w':
4700 return C_RegisterClass;
4701 // An address with a single base register. Due to the way we
4702 // currently handle addresses it is the same as 'r'.
4703 case 'Q':
4704 return C_Memory;
4705 }
4706 }
4707 return TargetLowering::getConstraintType(Constraint);
4708}
4709
4710/// Examine constraint type and operand type and determine a weight value.
4711/// This object must already have been set up with the operand type
4712/// and the current alternative constraint selected.
4713TargetLowering::ConstraintWeight
4714AArch64TargetLowering::getSingleConstraintMatchWeight(
4715 AsmOperandInfo &info, const char *constraint) const {
4716 ConstraintWeight weight = CW_Invalid;
4717 Value *CallOperandVal = info.CallOperandVal;
4718 // If we don't have a value, we can't do a match,
4719 // but allow it at the lowest weight.
4720 if (!CallOperandVal)
4721 return CW_Default;
4722 Type *type = CallOperandVal->getType();
4723 // Look at the constraint type.
4724 switch (*constraint) {
4725 default:
4726 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
4727 break;
4728 case 'x':
4729 case 'w':
4730 if (type->isFloatingPointTy() || type->isVectorTy())
4731 weight = CW_Register;
4732 break;
4733 case 'z':
4734 weight = CW_Constant;
4735 break;
4736 }
4737 return weight;
4738}
4739
4740std::pair<unsigned, const TargetRegisterClass *>
4741AArch64TargetLowering::getRegForInlineAsmConstraint(
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00004742 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004743 if (Constraint.size() == 1) {
4744 switch (Constraint[0]) {
4745 case 'r':
4746 if (VT.getSizeInBits() == 64)
4747 return std::make_pair(0U, &AArch64::GPR64commonRegClass);
4748 return std::make_pair(0U, &AArch64::GPR32commonRegClass);
4749 case 'w':
4750 if (VT == MVT::f32)
4751 return std::make_pair(0U, &AArch64::FPR32RegClass);
4752 if (VT.getSizeInBits() == 64)
4753 return std::make_pair(0U, &AArch64::FPR64RegClass);
4754 if (VT.getSizeInBits() == 128)
4755 return std::make_pair(0U, &AArch64::FPR128RegClass);
4756 break;
4757 // The instructions that this constraint is designed for can
4758 // only take 128-bit registers so just use that regclass.
4759 case 'x':
4760 if (VT.getSizeInBits() == 128)
4761 return std::make_pair(0U, &AArch64::FPR128_loRegClass);
4762 break;
4763 }
4764 }
4765 if (StringRef("{cc}").equals_lower(Constraint))
4766 return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
4767
4768 // Use the default implementation in TargetLowering to convert the register
4769 // constraint into a member of a register class.
4770 std::pair<unsigned, const TargetRegisterClass *> Res;
Eric Christopher11e4df72015-02-26 22:38:43 +00004771 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004772
4773 // Not found as a standard register?
4774 if (!Res.second) {
4775 unsigned Size = Constraint.size();
4776 if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
4777 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00004778 int RegNo;
4779 bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
4780 if (!Failed && RegNo >= 0 && RegNo <= 31) {
Tim Northover9508a702016-05-10 22:26:45 +00004781 // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size.
Tim Northover3b0846e2014-05-24 12:50:23 +00004782 // By default we'll emit v0-v31 for this unless there's a modifier where
4783 // we'll emit the correct register as well.
Tim Northover9508a702016-05-10 22:26:45 +00004784 if (VT != MVT::Other && VT.getSizeInBits() == 64) {
4785 Res.first = AArch64::FPR64RegClass.getRegister(RegNo);
4786 Res.second = &AArch64::FPR64RegClass;
4787 } else {
4788 Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
4789 Res.second = &AArch64::FPR128RegClass;
4790 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004791 }
4792 }
4793 }
4794
4795 return Res;
4796}
4797
4798/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
4799/// vector. If it is invalid, don't add anything to Ops.
4800void AArch64TargetLowering::LowerAsmOperandForConstraint(
4801 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
4802 SelectionDAG &DAG) const {
4803 SDValue Result;
4804
4805 // Currently only support length 1 constraints.
4806 if (Constraint.length() != 1)
4807 return;
4808
4809 char ConstraintLetter = Constraint[0];
4810 switch (ConstraintLetter) {
4811 default:
4812 break;
4813
4814 // This set of constraints deal with valid constants for various instructions.
4815 // Validate and return a target constant for them if we can.
4816 case 'z': {
4817 // 'z' maps to xzr or wzr so it needs an input of 0.
Artyom Skrobov314ee042015-11-25 19:41:11 +00004818 if (!isNullConstant(Op))
Tim Northover3b0846e2014-05-24 12:50:23 +00004819 return;
4820
4821 if (Op.getValueType() == MVT::i64)
4822 Result = DAG.getRegister(AArch64::XZR, MVT::i64);
4823 else
4824 Result = DAG.getRegister(AArch64::WZR, MVT::i32);
4825 break;
4826 }
4827
4828 case 'I':
4829 case 'J':
4830 case 'K':
4831 case 'L':
4832 case 'M':
4833 case 'N':
4834 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4835 if (!C)
4836 return;
4837
4838 // Grab the value and do some validation.
4839 uint64_t CVal = C->getZExtValue();
4840 switch (ConstraintLetter) {
4841 // The I constraint applies only to simple ADD or SUB immediate operands:
4842 // i.e. 0 to 4095 with optional shift by 12
4843 // The J constraint applies only to ADD or SUB immediates that would be
4844 // valid when negated, i.e. if [an add pattern] were to be output as a SUB
4845 // instruction [or vice versa], in other words -1 to -4095 with optional
4846 // left shift by 12.
4847 case 'I':
4848 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
4849 break;
4850 return;
4851 case 'J': {
4852 uint64_t NVal = -C->getSExtValue();
Tim Northover2c46beb2014-07-27 07:10:29 +00004853 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
4854 CVal = C->getSExtValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00004855 break;
Tim Northover2c46beb2014-07-27 07:10:29 +00004856 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004857 return;
4858 }
4859 // The K and L constraints apply *only* to logical immediates, including
4860 // what used to be the MOVI alias for ORR (though the MOVI alias has now
4861 // been removed and MOV should be used). So these constraints have to
4862 // distinguish between bit patterns that are valid 32-bit or 64-bit
4863 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
4864 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
4865 // versa.
4866 case 'K':
4867 if (AArch64_AM::isLogicalImmediate(CVal, 32))
4868 break;
4869 return;
4870 case 'L':
4871 if (AArch64_AM::isLogicalImmediate(CVal, 64))
4872 break;
4873 return;
4874 // The M and N constraints are a superset of K and L respectively, for use
4875 // with the MOV (immediate) alias. As well as the logical immediates they
4876 // also match 32 or 64-bit immediates that can be loaded either using a
4877 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
4878 // (M) or 64-bit 0x1234000000000000 (N) etc.
4879 // As a note some of this code is liberally stolen from the asm parser.
4880 case 'M': {
4881 if (!isUInt<32>(CVal))
4882 return;
4883 if (AArch64_AM::isLogicalImmediate(CVal, 32))
4884 break;
4885 if ((CVal & 0xFFFF) == CVal)
4886 break;
4887 if ((CVal & 0xFFFF0000ULL) == CVal)
4888 break;
4889 uint64_t NCVal = ~(uint32_t)CVal;
4890 if ((NCVal & 0xFFFFULL) == NCVal)
4891 break;
4892 if ((NCVal & 0xFFFF0000ULL) == NCVal)
4893 break;
4894 return;
4895 }
4896 case 'N': {
4897 if (AArch64_AM::isLogicalImmediate(CVal, 64))
4898 break;
4899 if ((CVal & 0xFFFFULL) == CVal)
4900 break;
4901 if ((CVal & 0xFFFF0000ULL) == CVal)
4902 break;
4903 if ((CVal & 0xFFFF00000000ULL) == CVal)
4904 break;
4905 if ((CVal & 0xFFFF000000000000ULL) == CVal)
4906 break;
4907 uint64_t NCVal = ~CVal;
4908 if ((NCVal & 0xFFFFULL) == NCVal)
4909 break;
4910 if ((NCVal & 0xFFFF0000ULL) == NCVal)
4911 break;
4912 if ((NCVal & 0xFFFF00000000ULL) == NCVal)
4913 break;
4914 if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
4915 break;
4916 return;
4917 }
4918 default:
4919 return;
4920 }
4921
4922 // All assembler immediates are 64-bit integers.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004923 Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00004924 break;
4925 }
4926
4927 if (Result.getNode()) {
4928 Ops.push_back(Result);
4929 return;
4930 }
4931
4932 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
4933}
4934
4935//===----------------------------------------------------------------------===//
4936// AArch64 Advanced SIMD Support
4937//===----------------------------------------------------------------------===//
4938
4939/// WidenVector - Given a value in the V64 register class, produce the
4940/// equivalent value in the V128 register class.
4941static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
4942 EVT VT = V64Reg.getValueType();
4943 unsigned NarrowSize = VT.getVectorNumElements();
4944 MVT EltTy = VT.getVectorElementType().getSimpleVT();
4945 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
4946 SDLoc DL(V64Reg);
4947
4948 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004949 V64Reg, DAG.getConstant(0, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00004950}
4951
4952/// getExtFactor - Determine the adjustment factor for the position when
4953/// generating an "extract from vector registers" instruction.
4954static unsigned getExtFactor(SDValue &V) {
4955 EVT EltType = V.getValueType().getVectorElementType();
4956 return EltType.getSizeInBits() / 8;
4957}
4958
4959/// NarrowVector - Given a value in the V128 register class, produce the
4960/// equivalent value in the V64 register class.
4961static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
4962 EVT VT = V128Reg.getValueType();
4963 unsigned WideSize = VT.getVectorNumElements();
4964 MVT EltTy = VT.getVectorElementType().getSimpleVT();
4965 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
4966 SDLoc DL(V128Reg);
4967
4968 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
4969}
4970
4971// Gather data to see if the operation can be modelled as a
4972// shuffle in combination with VEXTs.
4973SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
4974 SelectionDAG &DAG) const {
Kevin Qinf0ec9af2014-06-18 05:54:42 +00004975 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
Tim Northover3b0846e2014-05-24 12:50:23 +00004976 SDLoc dl(Op);
4977 EVT VT = Op.getValueType();
4978 unsigned NumElts = VT.getVectorNumElements();
4979
Tim Northover7324e842014-07-24 15:39:55 +00004980 struct ShuffleSourceInfo {
4981 SDValue Vec;
4982 unsigned MinElt;
4983 unsigned MaxElt;
Tim Northover3b0846e2014-05-24 12:50:23 +00004984
Tim Northover7324e842014-07-24 15:39:55 +00004985 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
4986 // be compatible with the shuffle we intend to construct. As a result
4987 // ShuffleVec will be some sliding window into the original Vec.
4988 SDValue ShuffleVec;
4989
4990 // Code should guarantee that element i in Vec starts at element "WindowBase
4991 // + i * WindowScale in ShuffleVec".
4992 int WindowBase;
4993 int WindowScale;
4994
4995 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
4996 ShuffleSourceInfo(SDValue Vec)
4997 : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
4998 WindowScale(1) {}
4999 };
5000
5001 // First gather all vectors used as an immediate source for this BUILD_VECTOR
5002 // node.
5003 SmallVector<ShuffleSourceInfo, 2> Sources;
Tim Northover3b0846e2014-05-24 12:50:23 +00005004 for (unsigned i = 0; i < NumElts; ++i) {
5005 SDValue V = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00005006 if (V.isUndef())
Tim Northover3b0846e2014-05-24 12:50:23 +00005007 continue;
Ahmed Bougachadfc77352016-01-14 02:12:30 +00005008 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5009 !isa<ConstantSDNode>(V.getOperand(1))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005010 // A shuffle can only come from building a vector from various
Ahmed Bougachadfc77352016-01-14 02:12:30 +00005011 // elements of other vectors, provided their indices are constant.
Tim Northover3b0846e2014-05-24 12:50:23 +00005012 return SDValue();
5013 }
5014
Tim Northover7324e842014-07-24 15:39:55 +00005015 // Add this element source to the list if it's not already there.
Tim Northover3b0846e2014-05-24 12:50:23 +00005016 SDValue SourceVec = V.getOperand(0);
Tim Northover7324e842014-07-24 15:39:55 +00005017 auto Source = std::find(Sources.begin(), Sources.end(), SourceVec);
5018 if (Source == Sources.end())
James Molloyf497d552014-10-17 17:06:31 +00005019 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
Tim Northover3b0846e2014-05-24 12:50:23 +00005020
Tim Northover7324e842014-07-24 15:39:55 +00005021 // Update the minimum and maximum lane number seen.
5022 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5023 Source->MinElt = std::min(Source->MinElt, EltNo);
5024 Source->MaxElt = std::max(Source->MaxElt, EltNo);
Tim Northover3b0846e2014-05-24 12:50:23 +00005025 }
5026
5027 // Currently only do something sane when at most two source vectors
Tim Northover7324e842014-07-24 15:39:55 +00005028 // are involved.
5029 if (Sources.size() > 2)
Tim Northover3b0846e2014-05-24 12:50:23 +00005030 return SDValue();
5031
Kevin Qin9a2a2c52014-07-24 02:05:42 +00005032 // Find out the smallest element size among result and two sources, and use
5033 // it as element size to build the shuffle_vector.
5034 EVT SmallestEltTy = VT.getVectorElementType();
Tim Northover7324e842014-07-24 15:39:55 +00005035 for (auto &Source : Sources) {
5036 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00005037 if (SrcEltTy.bitsLT(SmallestEltTy)) {
5038 SmallestEltTy = SrcEltTy;
5039 }
5040 }
5041 unsigned ResMultiplier =
5042 VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00005043 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
5044 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
Tim Northover3b0846e2014-05-24 12:50:23 +00005045
Tim Northover7324e842014-07-24 15:39:55 +00005046 // If the source vector is too wide or too narrow, we may nevertheless be able
5047 // to construct a compatible shuffle either by concatenating it with UNDEF or
5048 // extracting a suitable range of elements.
5049 for (auto &Src : Sources) {
5050 EVT SrcVT = Src.ShuffleVec.getValueType();
Kevin Qinf0ec9af2014-06-18 05:54:42 +00005051
Tim Northover7324e842014-07-24 15:39:55 +00005052 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
Tim Northover3b0846e2014-05-24 12:50:23 +00005053 continue;
Tim Northover7324e842014-07-24 15:39:55 +00005054
5055 // This stage of the search produces a source with the same element type as
5056 // the original, but with a total width matching the BUILD_VECTOR output.
5057 EVT EltVT = SrcVT.getVectorElementType();
James Molloyf497d552014-10-17 17:06:31 +00005058 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
5059 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
Tim Northover7324e842014-07-24 15:39:55 +00005060
5061 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
5062 assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00005063 // We can pad out the smaller vector for free, so if it's part of a
5064 // shuffle...
Tim Northover7324e842014-07-24 15:39:55 +00005065 Src.ShuffleVec =
5066 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
5067 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00005068 continue;
5069 }
5070
Tim Northover7324e842014-07-24 15:39:55 +00005071 assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00005072
James Molloyf497d552014-10-17 17:06:31 +00005073 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005074 // Span too large for a VEXT to cope
5075 return SDValue();
5076 }
5077
James Molloyf497d552014-10-17 17:06:31 +00005078 if (Src.MinElt >= NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005079 // The extraction can just take the second half
Tim Northover7324e842014-07-24 15:39:55 +00005080 Src.ShuffleVec =
5081 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005082 DAG.getConstant(NumSrcElts, dl, MVT::i64));
James Molloyf497d552014-10-17 17:06:31 +00005083 Src.WindowBase = -NumSrcElts;
5084 } else if (Src.MaxElt < NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005085 // The extraction can just take the first half
Tim Northover5e84fe32014-12-06 00:33:37 +00005086 Src.ShuffleVec =
5087 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005088 DAG.getConstant(0, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005089 } else {
5090 // An actual VEXT is needed
Tim Northover5e84fe32014-12-06 00:33:37 +00005091 SDValue VEXTSrc1 =
5092 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005093 DAG.getConstant(0, dl, MVT::i64));
Tim Northover7324e842014-07-24 15:39:55 +00005094 SDValue VEXTSrc2 =
5095 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005096 DAG.getConstant(NumSrcElts, dl, MVT::i64));
Tim Northover7324e842014-07-24 15:39:55 +00005097 unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
5098
5099 Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005100 VEXTSrc2,
5101 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover7324e842014-07-24 15:39:55 +00005102 Src.WindowBase = -Src.MinElt;
Tim Northover3b0846e2014-05-24 12:50:23 +00005103 }
5104 }
5105
Tim Northover7324e842014-07-24 15:39:55 +00005106 // Another possible incompatibility occurs from the vector element types. We
5107 // can fix this by bitcasting the source vectors to the same type we intend
5108 // for the shuffle.
5109 for (auto &Src : Sources) {
5110 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
5111 if (SrcEltTy == SmallestEltTy)
5112 continue;
5113 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
5114 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
5115 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
5116 Src.WindowBase *= Src.WindowScale;
5117 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005118
Tim Northover7324e842014-07-24 15:39:55 +00005119 // Final sanity check before we try to actually produce a shuffle.
5120 DEBUG(
5121 for (auto Src : Sources)
5122 assert(Src.ShuffleVec.getValueType() == ShuffleVT);
5123 );
5124
5125 // The stars all align, our next step is to produce the mask for the shuffle.
5126 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
5127 int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00005128 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005129 SDValue Entry = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00005130 if (Entry.isUndef())
Tim Northover7324e842014-07-24 15:39:55 +00005131 continue;
Tim Northover3b0846e2014-05-24 12:50:23 +00005132
Tim Northover7324e842014-07-24 15:39:55 +00005133 auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0));
5134 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
5135
5136 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
5137 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
5138 // segment.
5139 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
5140 int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
5141 VT.getVectorElementType().getSizeInBits());
5142 int LanesDefined = BitsDefined / BitsPerShuffleLane;
5143
5144 // This source is expected to fill ResMultiplier lanes of the final shuffle,
5145 // starting at the appropriate offset.
5146 int *LaneMask = &Mask[i * ResMultiplier];
5147
5148 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
5149 ExtractBase += NumElts * (Src - Sources.begin());
5150 for (int j = 0; j < LanesDefined; ++j)
5151 LaneMask[j] = ExtractBase + j;
Tim Northover3b0846e2014-05-24 12:50:23 +00005152 }
5153
5154 // Final check before we try to produce nonsense...
Tim Northover7324e842014-07-24 15:39:55 +00005155 if (!isShuffleMaskLegal(Mask, ShuffleVT))
5156 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00005157
Tim Northover7324e842014-07-24 15:39:55 +00005158 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
5159 for (unsigned i = 0; i < Sources.size(); ++i)
5160 ShuffleOps[i] = Sources[i].ShuffleVec;
5161
5162 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
5163 ShuffleOps[1], &Mask[0]);
5164 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
Tim Northover3b0846e2014-05-24 12:50:23 +00005165}
5166
5167// check if an EXT instruction can handle the shuffle mask when the
5168// vector sources of the shuffle are the same.
5169static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
5170 unsigned NumElts = VT.getVectorNumElements();
5171
5172 // Assume that the first shuffle index is not UNDEF. Fail if it is.
5173 if (M[0] < 0)
5174 return false;
5175
5176 Imm = M[0];
5177
5178 // If this is a VEXT shuffle, the immediate value is the index of the first
5179 // element. The other shuffle indices must be the successive elements after
5180 // the first one.
5181 unsigned ExpectedElt = Imm;
5182 for (unsigned i = 1; i < NumElts; ++i) {
5183 // Increment the expected index. If it wraps around, just follow it
5184 // back to index zero and keep going.
5185 ++ExpectedElt;
5186 if (ExpectedElt == NumElts)
5187 ExpectedElt = 0;
5188
5189 if (M[i] < 0)
5190 continue; // ignore UNDEF indices
5191 if (ExpectedElt != static_cast<unsigned>(M[i]))
5192 return false;
5193 }
5194
5195 return true;
5196}
5197
5198// check if an EXT instruction can handle the shuffle mask when the
5199// vector sources of the shuffle are different.
5200static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
5201 unsigned &Imm) {
5202 // Look for the first non-undef element.
5203 const int *FirstRealElt = std::find_if(M.begin(), M.end(),
5204 [](int Elt) {return Elt >= 0;});
5205
5206 // Benefit form APInt to handle overflow when calculating expected element.
5207 unsigned NumElts = VT.getVectorNumElements();
5208 unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
5209 APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
5210 // The following shuffle indices must be the successive elements after the
5211 // first real element.
5212 const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
5213 [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
5214 if (FirstWrongElt != M.end())
5215 return false;
5216
5217 // The index of an EXT is the first element if it is not UNDEF.
5218 // Watch out for the beginning UNDEFs. The EXT index should be the expected
Junmo Park3b8c7152016-01-05 09:36:47 +00005219 // value of the first element. E.g.
Tim Northover3b0846e2014-05-24 12:50:23 +00005220 // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
5221 // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
5222 // ExpectedElt is the last mask index plus 1.
5223 Imm = ExpectedElt.getZExtValue();
5224
5225 // There are two difference cases requiring to reverse input vectors.
5226 // For example, for vector <4 x i32> we have the following cases,
5227 // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
5228 // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
5229 // For both cases, we finally use mask <5, 6, 7, 0>, which requires
5230 // to reverse two input vectors.
5231 if (Imm < NumElts)
5232 ReverseEXT = true;
5233 else
5234 Imm -= NumElts;
5235
5236 return true;
5237}
5238
5239/// isREVMask - Check if a vector shuffle corresponds to a REV
5240/// instruction with the specified blocksize. (The order of the elements
5241/// within each block of the vector is reversed.)
5242static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5243 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
5244 "Only possible block sizes for REV are: 16, 32, 64");
5245
5246 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5247 if (EltSz == 64)
5248 return false;
5249
5250 unsigned NumElts = VT.getVectorNumElements();
5251 unsigned BlockElts = M[0] + 1;
5252 // If the first shuffle index is UNDEF, be optimistic.
5253 if (M[0] < 0)
5254 BlockElts = BlockSize / EltSz;
5255
5256 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5257 return false;
5258
5259 for (unsigned i = 0; i < NumElts; ++i) {
5260 if (M[i] < 0)
5261 continue; // ignore UNDEF indices
5262 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
5263 return false;
5264 }
5265
5266 return true;
5267}
5268
5269static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5270 unsigned NumElts = VT.getVectorNumElements();
5271 WhichResult = (M[0] == 0 ? 0 : 1);
5272 unsigned Idx = WhichResult * NumElts / 2;
5273 for (unsigned i = 0; i != NumElts; i += 2) {
5274 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5275 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
5276 return false;
5277 Idx += 1;
5278 }
5279
5280 return true;
5281}
5282
5283static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5284 unsigned NumElts = VT.getVectorNumElements();
5285 WhichResult = (M[0] == 0 ? 0 : 1);
5286 for (unsigned i = 0; i != NumElts; ++i) {
5287 if (M[i] < 0)
5288 continue; // ignore UNDEF indices
5289 if ((unsigned)M[i] != 2 * i + WhichResult)
5290 return false;
5291 }
5292
5293 return true;
5294}
5295
5296static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5297 unsigned NumElts = VT.getVectorNumElements();
5298 WhichResult = (M[0] == 0 ? 0 : 1);
5299 for (unsigned i = 0; i < NumElts; i += 2) {
5300 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5301 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
5302 return false;
5303 }
5304 return true;
5305}
5306
5307/// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
5308/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5309/// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5310static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5311 unsigned NumElts = VT.getVectorNumElements();
5312 WhichResult = (M[0] == 0 ? 0 : 1);
5313 unsigned Idx = WhichResult * NumElts / 2;
5314 for (unsigned i = 0; i != NumElts; i += 2) {
5315 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5316 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
5317 return false;
5318 Idx += 1;
5319 }
5320
5321 return true;
5322}
5323
5324/// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
5325/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5326/// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5327static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5328 unsigned Half = VT.getVectorNumElements() / 2;
5329 WhichResult = (M[0] == 0 ? 0 : 1);
5330 for (unsigned j = 0; j != 2; ++j) {
5331 unsigned Idx = WhichResult;
5332 for (unsigned i = 0; i != Half; ++i) {
5333 int MIdx = M[i + j * Half];
5334 if (MIdx >= 0 && (unsigned)MIdx != Idx)
5335 return false;
5336 Idx += 2;
5337 }
5338 }
5339
5340 return true;
5341}
5342
5343/// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
5344/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5345/// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5346static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5347 unsigned NumElts = VT.getVectorNumElements();
5348 WhichResult = (M[0] == 0 ? 0 : 1);
5349 for (unsigned i = 0; i < NumElts; i += 2) {
5350 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5351 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
5352 return false;
5353 }
5354 return true;
5355}
5356
5357static bool isINSMask(ArrayRef<int> M, int NumInputElements,
5358 bool &DstIsLeft, int &Anomaly) {
5359 if (M.size() != static_cast<size_t>(NumInputElements))
5360 return false;
5361
5362 int NumLHSMatch = 0, NumRHSMatch = 0;
5363 int LastLHSMismatch = -1, LastRHSMismatch = -1;
5364
5365 for (int i = 0; i < NumInputElements; ++i) {
5366 if (M[i] == -1) {
5367 ++NumLHSMatch;
5368 ++NumRHSMatch;
5369 continue;
5370 }
5371
5372 if (M[i] == i)
5373 ++NumLHSMatch;
5374 else
5375 LastLHSMismatch = i;
5376
5377 if (M[i] == i + NumInputElements)
5378 ++NumRHSMatch;
5379 else
5380 LastRHSMismatch = i;
5381 }
5382
5383 if (NumLHSMatch == NumInputElements - 1) {
5384 DstIsLeft = true;
5385 Anomaly = LastLHSMismatch;
5386 return true;
5387 } else if (NumRHSMatch == NumInputElements - 1) {
5388 DstIsLeft = false;
5389 Anomaly = LastRHSMismatch;
5390 return true;
5391 }
5392
5393 return false;
5394}
5395
5396static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
5397 if (VT.getSizeInBits() != 128)
5398 return false;
5399
5400 unsigned NumElts = VT.getVectorNumElements();
5401
5402 for (int I = 0, E = NumElts / 2; I != E; I++) {
5403 if (Mask[I] != I)
5404 return false;
5405 }
5406
5407 int Offset = NumElts / 2;
5408 for (int I = NumElts / 2, E = NumElts; I != E; I++) {
5409 if (Mask[I] != I + SplitLHS * Offset)
5410 return false;
5411 }
5412
5413 return true;
5414}
5415
5416static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
5417 SDLoc DL(Op);
5418 EVT VT = Op.getValueType();
5419 SDValue V0 = Op.getOperand(0);
5420 SDValue V1 = Op.getOperand(1);
5421 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
5422
5423 if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
5424 VT.getVectorElementType() != V1.getValueType().getVectorElementType())
5425 return SDValue();
5426
5427 bool SplitV0 = V0.getValueType().getSizeInBits() == 128;
5428
5429 if (!isConcatMask(Mask, VT, SplitV0))
5430 return SDValue();
5431
5432 EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
5433 VT.getVectorNumElements() / 2);
5434 if (SplitV0) {
5435 V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005436 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005437 }
5438 if (V1.getValueType().getSizeInBits() == 128) {
5439 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005440 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005441 }
5442 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
5443}
5444
5445/// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5446/// the specified operations to build the shuffle.
5447static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5448 SDValue RHS, SelectionDAG &DAG,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00005449 const SDLoc &dl) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005450 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5451 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
5452 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
5453
5454 enum {
5455 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5456 OP_VREV,
5457 OP_VDUP0,
5458 OP_VDUP1,
5459 OP_VDUP2,
5460 OP_VDUP3,
5461 OP_VEXT1,
5462 OP_VEXT2,
5463 OP_VEXT3,
5464 OP_VUZPL, // VUZP, left result
5465 OP_VUZPR, // VUZP, right result
5466 OP_VZIPL, // VZIP, left result
5467 OP_VZIPR, // VZIP, right result
5468 OP_VTRNL, // VTRN, left result
5469 OP_VTRNR // VTRN, right result
5470 };
5471
5472 if (OpNum == OP_COPY) {
5473 if (LHSID == (1 * 9 + 2) * 9 + 3)
5474 return LHS;
5475 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
5476 return RHS;
5477 }
5478
5479 SDValue OpLHS, OpRHS;
5480 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5481 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5482 EVT VT = OpLHS.getValueType();
5483
5484 switch (OpNum) {
5485 default:
5486 llvm_unreachable("Unknown shuffle opcode!");
5487 case OP_VREV:
5488 // VREV divides the vector in half and swaps within the half.
5489 if (VT.getVectorElementType() == MVT::i32 ||
5490 VT.getVectorElementType() == MVT::f32)
5491 return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
5492 // vrev <4 x i16> -> REV32
Oliver Stannard89d15422014-08-27 16:16:04 +00005493 if (VT.getVectorElementType() == MVT::i16 ||
5494 VT.getVectorElementType() == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00005495 return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
5496 // vrev <4 x i8> -> REV16
5497 assert(VT.getVectorElementType() == MVT::i8);
5498 return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
5499 case OP_VDUP0:
5500 case OP_VDUP1:
5501 case OP_VDUP2:
5502 case OP_VDUP3: {
5503 EVT EltTy = VT.getVectorElementType();
5504 unsigned Opcode;
5505 if (EltTy == MVT::i8)
5506 Opcode = AArch64ISD::DUPLANE8;
Ahmed Bougacha941420d2015-04-16 23:57:07 +00005507 else if (EltTy == MVT::i16 || EltTy == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00005508 Opcode = AArch64ISD::DUPLANE16;
5509 else if (EltTy == MVT::i32 || EltTy == MVT::f32)
5510 Opcode = AArch64ISD::DUPLANE32;
5511 else if (EltTy == MVT::i64 || EltTy == MVT::f64)
5512 Opcode = AArch64ISD::DUPLANE64;
5513 else
5514 llvm_unreachable("Invalid vector element type?");
5515
5516 if (VT.getSizeInBits() == 64)
5517 OpLHS = WidenVector(OpLHS, DAG);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005518 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00005519 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
5520 }
5521 case OP_VEXT1:
5522 case OP_VEXT2:
5523 case OP_VEXT3: {
5524 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
5525 return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005526 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005527 }
5528 case OP_VUZPL:
5529 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
5530 OpRHS);
5531 case OP_VUZPR:
5532 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
5533 OpRHS);
5534 case OP_VZIPL:
5535 return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
5536 OpRHS);
5537 case OP_VZIPR:
5538 return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
5539 OpRHS);
5540 case OP_VTRNL:
5541 return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
5542 OpRHS);
5543 case OP_VTRNR:
5544 return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
5545 OpRHS);
5546 }
5547}
5548
5549static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
5550 SelectionDAG &DAG) {
5551 // Check to see if we can use the TBL instruction.
5552 SDValue V1 = Op.getOperand(0);
5553 SDValue V2 = Op.getOperand(1);
5554 SDLoc DL(Op);
5555
5556 EVT EltVT = Op.getValueType().getVectorElementType();
5557 unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
5558
5559 SmallVector<SDValue, 8> TBLMask;
5560 for (int Val : ShuffleMask) {
5561 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
5562 unsigned Offset = Byte + Val * BytesPerElt;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005563 TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005564 }
5565 }
5566
5567 MVT IndexVT = MVT::v8i8;
5568 unsigned IndexLen = 8;
5569 if (Op.getValueType().getSizeInBits() == 128) {
5570 IndexVT = MVT::v16i8;
5571 IndexLen = 16;
5572 }
5573
5574 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
5575 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
5576
5577 SDValue Shuffle;
Sanjay Patel57195842016-03-14 17:28:46 +00005578 if (V2.getNode()->isUndef()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005579 if (IndexLen == 8)
5580 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
5581 Shuffle = DAG.getNode(
5582 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005583 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00005584 DAG.getBuildVector(IndexVT, DL,
5585 makeArrayRef(TBLMask.data(), IndexLen)));
Tim Northover3b0846e2014-05-24 12:50:23 +00005586 } else {
5587 if (IndexLen == 8) {
5588 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
5589 Shuffle = DAG.getNode(
5590 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005591 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00005592 DAG.getBuildVector(IndexVT, DL,
5593 makeArrayRef(TBLMask.data(), IndexLen)));
Tim Northover3b0846e2014-05-24 12:50:23 +00005594 } else {
5595 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
5596 // cannot currently represent the register constraints on the input
5597 // table registers.
5598 // Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00005599 // DAG.getBuildVector(IndexVT, DL, &TBLMask[0],
5600 // IndexLen));
Tim Northover3b0846e2014-05-24 12:50:23 +00005601 Shuffle = DAG.getNode(
5602 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00005603 DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst,
5604 V2Cst, DAG.getBuildVector(IndexVT, DL,
5605 makeArrayRef(TBLMask.data(), IndexLen)));
Tim Northover3b0846e2014-05-24 12:50:23 +00005606 }
5607 }
5608 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
5609}
5610
5611static unsigned getDUPLANEOp(EVT EltType) {
5612 if (EltType == MVT::i8)
5613 return AArch64ISD::DUPLANE8;
Oliver Stannard89d15422014-08-27 16:16:04 +00005614 if (EltType == MVT::i16 || EltType == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00005615 return AArch64ISD::DUPLANE16;
5616 if (EltType == MVT::i32 || EltType == MVT::f32)
5617 return AArch64ISD::DUPLANE32;
5618 if (EltType == MVT::i64 || EltType == MVT::f64)
5619 return AArch64ISD::DUPLANE64;
5620
5621 llvm_unreachable("Invalid vector element type?");
5622}
5623
5624SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5625 SelectionDAG &DAG) const {
5626 SDLoc dl(Op);
5627 EVT VT = Op.getValueType();
5628
5629 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5630
5631 // Convert shuffles that are directly supported on NEON to target-specific
5632 // DAG nodes, instead of keeping them as shuffles and matching them again
5633 // during code selection. This is more efficient and avoids the possibility
5634 // of inconsistencies between legalization and selection.
5635 ArrayRef<int> ShuffleMask = SVN->getMask();
5636
5637 SDValue V1 = Op.getOperand(0);
5638 SDValue V2 = Op.getOperand(1);
5639
Craig Topperbc56e3b2016-06-30 04:38:51 +00005640 if (SVN->isSplat()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005641 int Lane = SVN->getSplatIndex();
5642 // If this is undef splat, generate it via "just" vdup, if possible.
5643 if (Lane == -1)
5644 Lane = 0;
5645
5646 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
5647 return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
5648 V1.getOperand(0));
5649 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
5650 // constant. If so, we can just reference the lane's definition directly.
5651 if (V1.getOpcode() == ISD::BUILD_VECTOR &&
5652 !isa<ConstantSDNode>(V1.getOperand(Lane)))
5653 return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
5654
5655 // Otherwise, duplicate from the lane of the input vector.
5656 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
5657
5658 // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
5659 // to make a vector of the same size as this SHUFFLE. We can ignore the
5660 // extract entirely, and canonicalise the concat using WidenVector.
5661 if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
5662 Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
5663 V1 = V1.getOperand(0);
5664 } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
5665 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
5666 Lane -= Idx * VT.getVectorNumElements() / 2;
5667 V1 = WidenVector(V1.getOperand(Idx), DAG);
5668 } else if (VT.getSizeInBits() == 64)
5669 V1 = WidenVector(V1, DAG);
5670
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005671 return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005672 }
5673
5674 if (isREVMask(ShuffleMask, VT, 64))
5675 return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
5676 if (isREVMask(ShuffleMask, VT, 32))
5677 return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
5678 if (isREVMask(ShuffleMask, VT, 16))
5679 return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
5680
5681 bool ReverseEXT = false;
5682 unsigned Imm;
5683 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
5684 if (ReverseEXT)
5685 std::swap(V1, V2);
5686 Imm *= getExtFactor(V1);
5687 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005688 DAG.getConstant(Imm, dl, MVT::i32));
Sanjay Patel57195842016-03-14 17:28:46 +00005689 } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005690 Imm *= getExtFactor(V1);
5691 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005692 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005693 }
5694
5695 unsigned WhichResult;
5696 if (isZIPMask(ShuffleMask, VT, WhichResult)) {
5697 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5698 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5699 }
5700 if (isUZPMask(ShuffleMask, VT, WhichResult)) {
5701 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5702 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5703 }
5704 if (isTRNMask(ShuffleMask, VT, WhichResult)) {
5705 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5706 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5707 }
5708
5709 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5710 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5711 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5712 }
5713 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5714 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5715 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5716 }
5717 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5718 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5719 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5720 }
5721
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00005722 if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00005723 return Concat;
5724
5725 bool DstIsLeft;
5726 int Anomaly;
5727 int NumInputElements = V1.getValueType().getVectorNumElements();
5728 if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
5729 SDValue DstVec = DstIsLeft ? V1 : V2;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005730 SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00005731
5732 SDValue SrcVec = V1;
5733 int SrcLane = ShuffleMask[Anomaly];
5734 if (SrcLane >= NumInputElements) {
5735 SrcVec = V2;
5736 SrcLane -= VT.getVectorNumElements();
5737 }
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005738 SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00005739
5740 EVT ScalarVT = VT.getVectorElementType();
Oliver Stannard89d15422014-08-27 16:16:04 +00005741
5742 if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00005743 ScalarVT = MVT::i32;
5744
5745 return DAG.getNode(
5746 ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5747 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
5748 DstLaneV);
5749 }
5750
5751 // If the shuffle is not directly supported and it has 4 elements, use
5752 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5753 unsigned NumElts = VT.getVectorNumElements();
5754 if (NumElts == 4) {
5755 unsigned PFIndexes[4];
5756 for (unsigned i = 0; i != 4; ++i) {
5757 if (ShuffleMask[i] < 0)
5758 PFIndexes[i] = 8;
5759 else
5760 PFIndexes[i] = ShuffleMask[i];
5761 }
5762
5763 // Compute the index in the perfect shuffle table.
5764 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
5765 PFIndexes[2] * 9 + PFIndexes[3];
5766 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5767 unsigned Cost = (PFEntry >> 30);
5768
5769 if (Cost <= 4)
5770 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5771 }
5772
5773 return GenerateTBL(Op, ShuffleMask, DAG);
5774}
5775
5776static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
5777 APInt &UndefBits) {
5778 EVT VT = BVN->getValueType(0);
5779 APInt SplatBits, SplatUndef;
5780 unsigned SplatBitSize;
5781 bool HasAnyUndefs;
5782 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5783 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
5784
5785 for (unsigned i = 0; i < NumSplats; ++i) {
5786 CnstBits <<= SplatBitSize;
5787 UndefBits <<= SplatBitSize;
5788 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
5789 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
5790 }
5791
5792 return true;
5793 }
5794
5795 return false;
5796}
5797
5798SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op,
5799 SelectionDAG &DAG) const {
5800 BuildVectorSDNode *BVN =
5801 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5802 SDValue LHS = Op.getOperand(0);
5803 SDLoc dl(Op);
5804 EVT VT = Op.getValueType();
5805
5806 if (!BVN)
5807 return Op;
5808
5809 APInt CnstBits(VT.getSizeInBits(), 0);
5810 APInt UndefBits(VT.getSizeInBits(), 0);
5811 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5812 // We only have BIC vector immediate instruction, which is and-not.
5813 CnstBits = ~CnstBits;
5814
5815 // We make use of a little bit of goto ickiness in order to avoid having to
5816 // duplicate the immediate matching logic for the undef toggled case.
5817 bool SecondTry = false;
5818 AttemptModImm:
5819
5820 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5821 CnstBits = CnstBits.zextOrTrunc(64);
5822 uint64_t CnstVal = CnstBits.getZExtValue();
5823
5824 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5825 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5826 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5827 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005828 DAG.getConstant(CnstVal, dl, MVT::i32),
5829 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005830 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005831 }
5832
5833 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5834 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5835 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5836 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005837 DAG.getConstant(CnstVal, dl, MVT::i32),
5838 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005839 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005840 }
5841
5842 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5843 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5844 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5845 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005846 DAG.getConstant(CnstVal, dl, MVT::i32),
5847 DAG.getConstant(16, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005848 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005849 }
5850
5851 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5852 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5853 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5854 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005855 DAG.getConstant(CnstVal, dl, MVT::i32),
5856 DAG.getConstant(24, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005857 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005858 }
5859
5860 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5861 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5862 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5863 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005864 DAG.getConstant(CnstVal, dl, MVT::i32),
5865 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005866 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005867 }
5868
5869 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5870 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5871 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5872 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005873 DAG.getConstant(CnstVal, dl, MVT::i32),
5874 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005875 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005876 }
5877 }
5878
5879 if (SecondTry)
5880 goto FailedModImm;
5881 SecondTry = true;
5882 CnstBits = ~UndefBits;
5883 goto AttemptModImm;
5884 }
5885
5886// We can always fall back to a non-immediate AND.
5887FailedModImm:
5888 return Op;
5889}
5890
5891// Specialized code to quickly find if PotentialBVec is a BuildVector that
5892// consists of only the same constant int value, returned in reference arg
5893// ConstVal
5894static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
5895 uint64_t &ConstVal) {
5896 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
5897 if (!Bvec)
5898 return false;
5899 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
5900 if (!FirstElt)
5901 return false;
5902 EVT VT = Bvec->getValueType(0);
5903 unsigned NumElts = VT.getVectorNumElements();
5904 for (unsigned i = 1; i < NumElts; ++i)
5905 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
5906 return false;
5907 ConstVal = FirstElt->getZExtValue();
5908 return true;
5909}
5910
5911static unsigned getIntrinsicID(const SDNode *N) {
5912 unsigned Opcode = N->getOpcode();
5913 switch (Opcode) {
5914 default:
5915 return Intrinsic::not_intrinsic;
5916 case ISD::INTRINSIC_WO_CHAIN: {
5917 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
5918 if (IID < Intrinsic::num_intrinsics)
5919 return IID;
5920 return Intrinsic::not_intrinsic;
5921 }
5922 }
5923}
5924
5925// Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
5926// to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
5927// BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
5928// Also, logical shift right -> sri, with the same structure.
5929static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
5930 EVT VT = N->getValueType(0);
5931
5932 if (!VT.isVector())
5933 return SDValue();
5934
5935 SDLoc DL(N);
5936
5937 // Is the first op an AND?
5938 const SDValue And = N->getOperand(0);
5939 if (And.getOpcode() != ISD::AND)
5940 return SDValue();
5941
5942 // Is the second op an shl or lshr?
5943 SDValue Shift = N->getOperand(1);
5944 // This will have been turned into: AArch64ISD::VSHL vector, #shift
5945 // or AArch64ISD::VLSHR vector, #shift
5946 unsigned ShiftOpc = Shift.getOpcode();
5947 if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
5948 return SDValue();
5949 bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
5950
5951 // Is the shift amount constant?
5952 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
5953 if (!C2node)
5954 return SDValue();
5955
5956 // Is the and mask vector all constant?
5957 uint64_t C1;
5958 if (!isAllConstantBuildVector(And.getOperand(1), C1))
5959 return SDValue();
5960
5961 // Is C1 == ~C2, taking into account how much one can shift elements of a
5962 // particular size?
5963 uint64_t C2 = C2node->getZExtValue();
5964 unsigned ElemSizeInBits = VT.getVectorElementType().getSizeInBits();
5965 if (C2 > ElemSizeInBits)
5966 return SDValue();
5967 unsigned ElemMask = (1 << ElemSizeInBits) - 1;
5968 if ((C1 & ElemMask) != (~C2 & ElemMask))
5969 return SDValue();
5970
5971 SDValue X = And.getOperand(0);
5972 SDValue Y = Shift.getOperand(0);
5973
5974 unsigned Intrin =
5975 IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
5976 SDValue ResultSLI =
5977 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005978 DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
5979 Shift.getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00005980
5981 DEBUG(dbgs() << "aarch64-lower: transformed: \n");
5982 DEBUG(N->dump(&DAG));
5983 DEBUG(dbgs() << "into: \n");
5984 DEBUG(ResultSLI->dump(&DAG));
5985
5986 ++NumShiftInserts;
5987 return ResultSLI;
5988}
5989
5990SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
5991 SelectionDAG &DAG) const {
5992 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
5993 if (EnableAArch64SlrGeneration) {
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00005994 if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00005995 return Res;
5996 }
5997
5998 BuildVectorSDNode *BVN =
5999 dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
6000 SDValue LHS = Op.getOperand(1);
6001 SDLoc dl(Op);
6002 EVT VT = Op.getValueType();
6003
6004 // OR commutes, so try swapping the operands.
6005 if (!BVN) {
6006 LHS = Op.getOperand(0);
6007 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
6008 }
6009 if (!BVN)
6010 return Op;
6011
6012 APInt CnstBits(VT.getSizeInBits(), 0);
6013 APInt UndefBits(VT.getSizeInBits(), 0);
6014 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
6015 // We make use of a little bit of goto ickiness in order to avoid having to
6016 // duplicate the immediate matching logic for the undef toggled case.
6017 bool SecondTry = false;
6018 AttemptModImm:
6019
6020 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
6021 CnstBits = CnstBits.zextOrTrunc(64);
6022 uint64_t CnstVal = CnstBits.getZExtValue();
6023
6024 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6025 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6026 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6027 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006028 DAG.getConstant(CnstVal, dl, MVT::i32),
6029 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00006030 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006031 }
6032
6033 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6034 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6035 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6036 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006037 DAG.getConstant(CnstVal, dl, MVT::i32),
6038 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00006039 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006040 }
6041
6042 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6043 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6044 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6045 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006046 DAG.getConstant(CnstVal, dl, MVT::i32),
6047 DAG.getConstant(16, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00006048 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006049 }
6050
6051 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6052 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6053 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6054 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006055 DAG.getConstant(CnstVal, dl, MVT::i32),
6056 DAG.getConstant(24, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00006057 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006058 }
6059
6060 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6061 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6062 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6063 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006064 DAG.getConstant(CnstVal, dl, MVT::i32),
6065 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00006066 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006067 }
6068
6069 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6070 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6071 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6072 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006073 DAG.getConstant(CnstVal, dl, MVT::i32),
6074 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00006075 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006076 }
6077 }
6078
6079 if (SecondTry)
6080 goto FailedModImm;
6081 SecondTry = true;
6082 CnstBits = UndefBits;
6083 goto AttemptModImm;
6084 }
6085
6086// We can always fall back to a non-immediate OR.
6087FailedModImm:
6088 return Op;
6089}
6090
Kevin Qin4473c192014-07-07 02:45:40 +00006091// Normalize the operands of BUILD_VECTOR. The value of constant operands will
6092// be truncated to fit element width.
6093static SDValue NormalizeBuildVector(SDValue Op,
6094 SelectionDAG &DAG) {
6095 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
Tim Northover3b0846e2014-05-24 12:50:23 +00006096 SDLoc dl(Op);
6097 EVT VT = Op.getValueType();
Kevin Qin4473c192014-07-07 02:45:40 +00006098 EVT EltTy= VT.getVectorElementType();
6099
6100 if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
6101 return Op;
6102
6103 SmallVector<SDValue, 16> Ops;
Pete Cooper7be8f8f2015-08-03 19:04:32 +00006104 for (SDValue Lane : Op->ops()) {
6105 if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
Kevin Qin4473c192014-07-07 02:45:40 +00006106 APInt LowBits(EltTy.getSizeInBits(),
Pete Cooper7be8f8f2015-08-03 19:04:32 +00006107 CstLane->getZExtValue());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006108 Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
Kevin Qin4473c192014-07-07 02:45:40 +00006109 }
6110 Ops.push_back(Lane);
6111 }
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006112 return DAG.getBuildVector(VT, dl, Ops);
Kevin Qin4473c192014-07-07 02:45:40 +00006113}
6114
6115SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
6116 SelectionDAG &DAG) const {
6117 SDLoc dl(Op);
6118 EVT VT = Op.getValueType();
6119 Op = NormalizeBuildVector(Op, DAG);
6120 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
Tim Northover3b0846e2014-05-24 12:50:23 +00006121
6122 APInt CnstBits(VT.getSizeInBits(), 0);
6123 APInt UndefBits(VT.getSizeInBits(), 0);
6124 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
6125 // We make use of a little bit of goto ickiness in order to avoid having to
6126 // duplicate the immediate matching logic for the undef toggled case.
6127 bool SecondTry = false;
6128 AttemptModImm:
6129
6130 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
6131 CnstBits = CnstBits.zextOrTrunc(64);
6132 uint64_t CnstVal = CnstBits.getZExtValue();
6133
6134 // Certain magic vector constants (used to express things like NOT
6135 // and NEG) are passed through unmodified. This allows codegen patterns
6136 // for these operations to match. Special-purpose patterns will lower
6137 // these immediates to MOVIs if it proves necessary.
6138 if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL))
6139 return Op;
6140
6141 // The many faces of MOVI...
6142 if (AArch64_AM::isAdvSIMDModImmType10(CnstVal)) {
6143 CnstVal = AArch64_AM::encodeAdvSIMDModImmType10(CnstVal);
6144 if (VT.getSizeInBits() == 128) {
6145 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::v2i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006146 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006147 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006148 }
6149
6150 // Support the V64 version via subregister insertion.
6151 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::f64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006152 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006153 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006154 }
6155
6156 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6157 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6158 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6159 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006160 DAG.getConstant(CnstVal, dl, MVT::i32),
6161 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006162 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006163 }
6164
6165 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6166 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6167 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6168 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006169 DAG.getConstant(CnstVal, dl, MVT::i32),
6170 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006171 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006172 }
6173
6174 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6175 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6176 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6177 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006178 DAG.getConstant(CnstVal, dl, MVT::i32),
6179 DAG.getConstant(16, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006180 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006181 }
6182
6183 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6184 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6185 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6186 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006187 DAG.getConstant(CnstVal, dl, MVT::i32),
6188 DAG.getConstant(24, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006189 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006190 }
6191
6192 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6193 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6194 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6195 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006196 DAG.getConstant(CnstVal, dl, MVT::i32),
6197 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006198 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006199 }
6200
6201 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6202 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6203 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6204 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006205 DAG.getConstant(CnstVal, dl, MVT::i32),
6206 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006207 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006208 }
6209
6210 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6211 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6212 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6213 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006214 DAG.getConstant(CnstVal, dl, MVT::i32),
6215 DAG.getConstant(264, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006216 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006217 }
6218
6219 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6220 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6221 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6222 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006223 DAG.getConstant(CnstVal, dl, MVT::i32),
6224 DAG.getConstant(272, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006225 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006226 }
6227
6228 if (AArch64_AM::isAdvSIMDModImmType9(CnstVal)) {
6229 CnstVal = AArch64_AM::encodeAdvSIMDModImmType9(CnstVal);
6230 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
6231 SDValue Mov = DAG.getNode(AArch64ISD::MOVI, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006232 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006233 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006234 }
6235
6236 // The few faces of FMOV...
6237 if (AArch64_AM::isAdvSIMDModImmType11(CnstVal)) {
6238 CnstVal = AArch64_AM::encodeAdvSIMDModImmType11(CnstVal);
6239 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32;
6240 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006241 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006242 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006243 }
6244
6245 if (AArch64_AM::isAdvSIMDModImmType12(CnstVal) &&
6246 VT.getSizeInBits() == 128) {
6247 CnstVal = AArch64_AM::encodeAdvSIMDModImmType12(CnstVal);
6248 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MVT::v2f64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006249 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006250 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006251 }
6252
6253 // The many faces of MVNI...
6254 CnstVal = ~CnstVal;
6255 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6256 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6257 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6258 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006259 DAG.getConstant(CnstVal, dl, MVT::i32),
6260 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006261 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006262 }
6263
6264 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6265 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6266 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6267 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006268 DAG.getConstant(CnstVal, dl, MVT::i32),
6269 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006270 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006271 }
6272
6273 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6274 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6275 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6276 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006277 DAG.getConstant(CnstVal, dl, MVT::i32),
6278 DAG.getConstant(16, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006279 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006280 }
6281
6282 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6283 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6284 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6285 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006286 DAG.getConstant(CnstVal, dl, MVT::i32),
6287 DAG.getConstant(24, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006288 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006289 }
6290
6291 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6292 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6293 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6294 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006295 DAG.getConstant(CnstVal, dl, MVT::i32),
6296 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006297 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006298 }
6299
6300 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6301 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6302 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6303 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006304 DAG.getConstant(CnstVal, dl, MVT::i32),
6305 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006306 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006307 }
6308
6309 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6310 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6311 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6312 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006313 DAG.getConstant(CnstVal, dl, MVT::i32),
6314 DAG.getConstant(264, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006315 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006316 }
6317
6318 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6319 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6320 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6321 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006322 DAG.getConstant(CnstVal, dl, MVT::i32),
6323 DAG.getConstant(272, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006324 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006325 }
6326 }
6327
6328 if (SecondTry)
6329 goto FailedModImm;
6330 SecondTry = true;
6331 CnstBits = UndefBits;
6332 goto AttemptModImm;
6333 }
6334FailedModImm:
6335
6336 // Scan through the operands to find some interesting properties we can
6337 // exploit:
6338 // 1) If only one value is used, we can use a DUP, or
6339 // 2) if only the low element is not undef, we can just insert that, or
6340 // 3) if only one constant value is used (w/ some non-constant lanes),
6341 // we can splat the constant value into the whole vector then fill
6342 // in the non-constant lanes.
6343 // 4) FIXME: If different constant values are used, but we can intelligently
6344 // select the values we'll be overwriting for the non-constant
6345 // lanes such that we can directly materialize the vector
6346 // some other way (MOVI, e.g.), we can be sneaky.
6347 unsigned NumElts = VT.getVectorNumElements();
6348 bool isOnlyLowElement = true;
6349 bool usesOnlyOneValue = true;
6350 bool usesOnlyOneConstantValue = true;
6351 bool isConstant = true;
6352 unsigned NumConstantLanes = 0;
6353 SDValue Value;
6354 SDValue ConstantValue;
6355 for (unsigned i = 0; i < NumElts; ++i) {
6356 SDValue V = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00006357 if (V.isUndef())
Tim Northover3b0846e2014-05-24 12:50:23 +00006358 continue;
6359 if (i > 0)
6360 isOnlyLowElement = false;
6361 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6362 isConstant = false;
6363
6364 if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
6365 ++NumConstantLanes;
6366 if (!ConstantValue.getNode())
6367 ConstantValue = V;
6368 else if (ConstantValue != V)
6369 usesOnlyOneConstantValue = false;
6370 }
6371
6372 if (!Value.getNode())
6373 Value = V;
6374 else if (V != Value)
6375 usesOnlyOneValue = false;
6376 }
6377
6378 if (!Value.getNode())
6379 return DAG.getUNDEF(VT);
6380
6381 if (isOnlyLowElement)
6382 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
6383
6384 // Use DUP for non-constant splats. For f32 constant splats, reduce to
6385 // i32 and try again.
6386 if (usesOnlyOneValue) {
6387 if (!isConstant) {
6388 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6389 Value.getValueType() != VT)
6390 return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
6391
6392 // This is actually a DUPLANExx operation, which keeps everything vectory.
6393
6394 // DUPLANE works on 128-bit vectors, widen it if necessary.
6395 SDValue Lane = Value.getOperand(1);
6396 Value = Value.getOperand(0);
6397 if (Value.getValueType().getSizeInBits() == 64)
6398 Value = WidenVector(Value, DAG);
6399
6400 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
6401 return DAG.getNode(Opcode, dl, VT, Value, Lane);
6402 }
6403
6404 if (VT.getVectorElementType().isFloatingPoint()) {
6405 SmallVector<SDValue, 8> Ops;
Pirama Arumuga Nainar12aeefc2015-03-17 23:10:29 +00006406 EVT EltTy = VT.getVectorElementType();
6407 assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
6408 "Unsupported floating-point vector type");
6409 MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00006410 for (unsigned i = 0; i < NumElts; ++i)
6411 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
6412 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006413 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
Tim Northover3b0846e2014-05-24 12:50:23 +00006414 Val = LowerBUILD_VECTOR(Val, DAG);
6415 if (Val.getNode())
6416 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6417 }
6418 }
6419
6420 // If there was only one constant value used and for more than one lane,
6421 // start by splatting that value, then replace the non-constant lanes. This
6422 // is better than the default, which will perform a separate initialization
6423 // for each lane.
6424 if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
6425 SDValue Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
6426 // Now insert the non-constant lanes.
6427 for (unsigned i = 0; i < NumElts; ++i) {
6428 SDValue V = Op.getOperand(i);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006429 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006430 if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) {
6431 // Note that type legalization likely mucked about with the VT of the
6432 // source operand, so we may have to convert it here before inserting.
6433 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
6434 }
6435 }
6436 return Val;
6437 }
6438
6439 // If all elements are constants and the case above didn't get hit, fall back
6440 // to the default expansion, which will generate a load from the constant
6441 // pool.
6442 if (isConstant)
6443 return SDValue();
6444
6445 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6446 if (NumElts >= 4) {
Ahmed Bougacha239d6352015-08-04 00:48:02 +00006447 if (SDValue shuffle = ReconstructShuffle(Op, DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00006448 return shuffle;
6449 }
6450
6451 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6452 // know the default expansion would otherwise fall back on something even
6453 // worse. For a vector with one or two non-undef values, that's
6454 // scalar_to_vector for the elements followed by a shuffle (provided the
6455 // shuffle is valid for the target) and materialization element by element
6456 // on the stack followed by a load for everything else.
6457 if (!isConstant && !usesOnlyOneValue) {
6458 SDValue Vec = DAG.getUNDEF(VT);
6459 SDValue Op0 = Op.getOperand(0);
6460 unsigned ElemSize = VT.getVectorElementType().getSizeInBits();
6461 unsigned i = 0;
6462 // For 32 and 64 bit types, use INSERT_SUBREG for lane zero to
6463 // a) Avoid a RMW dependency on the full vector register, and
6464 // b) Allow the register coalescer to fold away the copy if the
6465 // value is already in an S or D register.
Matthias Braun0acbd082015-08-31 18:25:15 +00006466 // Do not do this for UNDEF/LOAD nodes because we have better patterns
6467 // for those avoiding the SCALAR_TO_VECTOR/BUILD_VECTOR.
Sanjay Patel75068522016-03-14 18:09:43 +00006468 if (!Op0.isUndef() && Op0.getOpcode() != ISD::LOAD &&
Matthias Braun0acbd082015-08-31 18:25:15 +00006469 (ElemSize == 32 || ElemSize == 64)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006470 unsigned SubIdx = ElemSize == 32 ? AArch64::ssub : AArch64::dsub;
6471 MachineSDNode *N =
6472 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl, VT, Vec, Op0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006473 DAG.getTargetConstant(SubIdx, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006474 Vec = SDValue(N, 0);
6475 ++i;
6476 }
6477 for (; i < NumElts; ++i) {
6478 SDValue V = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00006479 if (V.isUndef())
Tim Northover3b0846e2014-05-24 12:50:23 +00006480 continue;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006481 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006482 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6483 }
6484 return Vec;
6485 }
6486
6487 // Just use the default expansion. We failed to find a better alternative.
6488 return SDValue();
6489}
6490
6491SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
6492 SelectionDAG &DAG) const {
6493 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
6494
Tim Northovere4b8e132014-07-15 10:00:26 +00006495 // Check for non-constant or out of range lane.
6496 EVT VT = Op.getOperand(0).getValueType();
6497 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
6498 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
Tim Northover3b0846e2014-05-24 12:50:23 +00006499 return SDValue();
6500
Tim Northover3b0846e2014-05-24 12:50:23 +00006501
6502 // Insertion/extraction are legal for V128 types.
6503 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
Oliver Stannard89d15422014-08-27 16:16:04 +00006504 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6505 VT == MVT::v8f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006506 return Op;
6507
6508 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
Oliver Stannard89d15422014-08-27 16:16:04 +00006509 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006510 return SDValue();
6511
6512 // For V64 types, we perform insertion by expanding the value
6513 // to a V128 type and perform the insertion on that.
6514 SDLoc DL(Op);
6515 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6516 EVT WideTy = WideVec.getValueType();
6517
6518 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
6519 Op.getOperand(1), Op.getOperand(2));
6520 // Re-narrow the resultant vector.
6521 return NarrowVector(Node, DAG);
6522}
6523
6524SDValue
6525AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6526 SelectionDAG &DAG) const {
6527 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
6528
Tim Northovere4b8e132014-07-15 10:00:26 +00006529 // Check for non-constant or out of range lane.
6530 EVT VT = Op.getOperand(0).getValueType();
6531 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6532 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
Tim Northover3b0846e2014-05-24 12:50:23 +00006533 return SDValue();
6534
Tim Northover3b0846e2014-05-24 12:50:23 +00006535
6536 // Insertion/extraction are legal for V128 types.
6537 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
Oliver Stannard89d15422014-08-27 16:16:04 +00006538 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6539 VT == MVT::v8f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006540 return Op;
6541
6542 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
Oliver Stannard89d15422014-08-27 16:16:04 +00006543 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006544 return SDValue();
6545
6546 // For V64 types, we perform extraction by expanding the value
6547 // to a V128 type and perform the extraction on that.
6548 SDLoc DL(Op);
6549 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6550 EVT WideTy = WideVec.getValueType();
6551
6552 EVT ExtrTy = WideTy.getVectorElementType();
6553 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
6554 ExtrTy = MVT::i32;
6555
6556 // For extractions, we just return the result directly.
6557 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
6558 Op.getOperand(1));
6559}
6560
6561SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
6562 SelectionDAG &DAG) const {
6563 EVT VT = Op.getOperand(0).getValueType();
6564 SDLoc dl(Op);
6565 // Just in case...
6566 if (!VT.isVector())
6567 return SDValue();
6568
6569 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6570 if (!Cst)
6571 return SDValue();
6572 unsigned Val = Cst->getZExtValue();
6573
6574 unsigned Size = Op.getValueType().getSizeInBits();
Charlie Turner7b7b06f2015-11-09 12:45:11 +00006575
6576 // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
6577 if (Val == 0)
6578 return Op;
6579
Tim Northover3b0846e2014-05-24 12:50:23 +00006580 // If this is extracting the upper 64-bits of a 128-bit vector, we match
6581 // that directly.
6582 if (Size == 64 && Val * VT.getVectorElementType().getSizeInBits() == 64)
6583 return Op;
6584
6585 return SDValue();
6586}
6587
6588bool AArch64TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
6589 EVT VT) const {
6590 if (VT.getVectorNumElements() == 4 &&
6591 (VT.is128BitVector() || VT.is64BitVector())) {
6592 unsigned PFIndexes[4];
6593 for (unsigned i = 0; i != 4; ++i) {
6594 if (M[i] < 0)
6595 PFIndexes[i] = 8;
6596 else
6597 PFIndexes[i] = M[i];
6598 }
6599
6600 // Compute the index in the perfect shuffle table.
6601 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6602 PFIndexes[2] * 9 + PFIndexes[3];
6603 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6604 unsigned Cost = (PFEntry >> 30);
6605
6606 if (Cost <= 4)
6607 return true;
6608 }
6609
6610 bool DummyBool;
6611 int DummyInt;
6612 unsigned DummyUnsigned;
6613
6614 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
6615 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
6616 isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
6617 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
6618 isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
6619 isZIPMask(M, VT, DummyUnsigned) ||
6620 isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
6621 isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
6622 isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
6623 isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
6624 isConcatMask(M, VT, VT.getSizeInBits() == 128));
6625}
6626
6627/// getVShiftImm - Check if this is a valid build_vector for the immediate
6628/// operand of a vector shift operation, where all the elements of the
6629/// build_vector must have the same constant integer value.
6630static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
6631 // Ignore bit_converts.
6632 while (Op.getOpcode() == ISD::BITCAST)
6633 Op = Op.getOperand(0);
6634 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6635 APInt SplatBits, SplatUndef;
6636 unsigned SplatBitSize;
6637 bool HasAnyUndefs;
6638 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
6639 HasAnyUndefs, ElementBits) ||
6640 SplatBitSize > ElementBits)
6641 return false;
6642 Cnt = SplatBits.getSExtValue();
6643 return true;
6644}
6645
6646/// isVShiftLImm - Check if this is a valid build_vector for the immediate
6647/// operand of a vector shift left operation. That value must be in the range:
6648/// 0 <= Value < ElementBits for a left shift; or
6649/// 0 <= Value <= ElementBits for a long left shift.
6650static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
6651 assert(VT.isVector() && "vector shift count is not a vector type");
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00006652 int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00006653 if (!getVShiftImm(Op, ElementBits, Cnt))
6654 return false;
6655 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
6656}
6657
6658/// isVShiftRImm - Check if this is a valid build_vector for the immediate
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00006659/// operand of a vector shift right operation. The value must be in the range:
6660/// 1 <= Value <= ElementBits for a right shift; or
6661static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006662 assert(VT.isVector() && "vector shift count is not a vector type");
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00006663 int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00006664 if (!getVShiftImm(Op, ElementBits, Cnt))
6665 return false;
Tim Northover3b0846e2014-05-24 12:50:23 +00006666 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
6667}
6668
6669SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
6670 SelectionDAG &DAG) const {
6671 EVT VT = Op.getValueType();
6672 SDLoc DL(Op);
6673 int64_t Cnt;
6674
6675 if (!Op.getOperand(1).getValueType().isVector())
6676 return Op;
6677 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6678
6679 switch (Op.getOpcode()) {
6680 default:
6681 llvm_unreachable("unexpected shift opcode");
6682
6683 case ISD::SHL:
6684 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006685 return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
6686 DAG.getConstant(Cnt, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006687 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006688 DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
6689 MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00006690 Op.getOperand(0), Op.getOperand(1));
6691 case ISD::SRA:
6692 case ISD::SRL:
6693 // Right shift immediate
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00006694 if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006695 unsigned Opc =
6696 (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006697 return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
6698 DAG.getConstant(Cnt, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006699 }
6700
6701 // Right shift register. Note, there is not a shift right register
6702 // instruction, but the shift left register instruction takes a signed
6703 // value, where negative numbers specify a right shift.
6704 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
6705 : Intrinsic::aarch64_neon_ushl;
6706 // negate the shift amount
6707 SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
6708 SDValue NegShiftLeft =
6709 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006710 DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
6711 NegShift);
Tim Northover3b0846e2014-05-24 12:50:23 +00006712 return NegShiftLeft;
6713 }
6714
6715 return SDValue();
6716}
6717
6718static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
6719 AArch64CC::CondCode CC, bool NoNans, EVT VT,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00006720 const SDLoc &dl, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006721 EVT SrcVT = LHS.getValueType();
Tim Northover45aa89c2015-02-08 00:50:47 +00006722 assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
6723 "function only supposed to emit natural comparisons");
Tim Northover3b0846e2014-05-24 12:50:23 +00006724
6725 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
6726 APInt CnstBits(VT.getSizeInBits(), 0);
6727 APInt UndefBits(VT.getSizeInBits(), 0);
6728 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
6729 bool IsZero = IsCnst && (CnstBits == 0);
6730
6731 if (SrcVT.getVectorElementType().isFloatingPoint()) {
6732 switch (CC) {
6733 default:
6734 return SDValue();
6735 case AArch64CC::NE: {
6736 SDValue Fcmeq;
6737 if (IsZero)
6738 Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6739 else
6740 Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6741 return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
6742 }
6743 case AArch64CC::EQ:
6744 if (IsZero)
6745 return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6746 return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6747 case AArch64CC::GE:
6748 if (IsZero)
6749 return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
6750 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
6751 case AArch64CC::GT:
6752 if (IsZero)
6753 return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
6754 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
6755 case AArch64CC::LS:
6756 if (IsZero)
6757 return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
6758 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
6759 case AArch64CC::LT:
6760 if (!NoNans)
6761 return SDValue();
6762 // If we ignore NaNs then we can use to the MI implementation.
6763 // Fallthrough.
6764 case AArch64CC::MI:
6765 if (IsZero)
6766 return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
6767 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
6768 }
6769 }
6770
6771 switch (CC) {
6772 default:
6773 return SDValue();
6774 case AArch64CC::NE: {
6775 SDValue Cmeq;
6776 if (IsZero)
6777 Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6778 else
6779 Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6780 return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
6781 }
6782 case AArch64CC::EQ:
6783 if (IsZero)
6784 return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6785 return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6786 case AArch64CC::GE:
6787 if (IsZero)
6788 return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
6789 return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
6790 case AArch64CC::GT:
6791 if (IsZero)
6792 return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
6793 return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
6794 case AArch64CC::LE:
6795 if (IsZero)
6796 return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
6797 return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
6798 case AArch64CC::LS:
6799 return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
6800 case AArch64CC::LO:
6801 return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
6802 case AArch64CC::LT:
6803 if (IsZero)
6804 return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
6805 return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
6806 case AArch64CC::HI:
6807 return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
6808 case AArch64CC::HS:
6809 return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
6810 }
6811}
6812
6813SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
6814 SelectionDAG &DAG) const {
6815 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6816 SDValue LHS = Op.getOperand(0);
6817 SDValue RHS = Op.getOperand(1);
Tim Northover45aa89c2015-02-08 00:50:47 +00006818 EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
Tim Northover3b0846e2014-05-24 12:50:23 +00006819 SDLoc dl(Op);
6820
6821 if (LHS.getValueType().getVectorElementType().isInteger()) {
6822 assert(LHS.getValueType() == RHS.getValueType());
6823 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
Tim Northover45aa89c2015-02-08 00:50:47 +00006824 SDValue Cmp =
6825 EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
6826 return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00006827 }
6828
Pirama Arumuga Nainar71e9a2a2016-01-22 01:16:57 +00006829 if (LHS.getValueType().getVectorElementType() == MVT::f16)
6830 return SDValue();
6831
Tim Northover3b0846e2014-05-24 12:50:23 +00006832 assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
6833 LHS.getValueType().getVectorElementType() == MVT::f64);
6834
6835 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
6836 // clean. Some of them require two branches to implement.
6837 AArch64CC::CondCode CC1, CC2;
6838 bool ShouldInvert;
6839 changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
6840
6841 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
6842 SDValue Cmp =
Tim Northover45aa89c2015-02-08 00:50:47 +00006843 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00006844 if (!Cmp.getNode())
6845 return SDValue();
6846
6847 if (CC2 != AArch64CC::AL) {
6848 SDValue Cmp2 =
Tim Northover45aa89c2015-02-08 00:50:47 +00006849 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00006850 if (!Cmp2.getNode())
6851 return SDValue();
6852
Tim Northover45aa89c2015-02-08 00:50:47 +00006853 Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
Tim Northover3b0846e2014-05-24 12:50:23 +00006854 }
6855
Tim Northover45aa89c2015-02-08 00:50:47 +00006856 Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
6857
Tim Northover3b0846e2014-05-24 12:50:23 +00006858 if (ShouldInvert)
6859 return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
6860
6861 return Cmp;
6862}
6863
6864/// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
6865/// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
6866/// specified in the intrinsic calls.
6867bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
6868 const CallInst &I,
6869 unsigned Intrinsic) const {
Mehdi Aminia749f2a2015-07-09 02:09:52 +00006870 auto &DL = I.getModule()->getDataLayout();
Tim Northover3b0846e2014-05-24 12:50:23 +00006871 switch (Intrinsic) {
6872 case Intrinsic::aarch64_neon_ld2:
6873 case Intrinsic::aarch64_neon_ld3:
6874 case Intrinsic::aarch64_neon_ld4:
6875 case Intrinsic::aarch64_neon_ld1x2:
6876 case Intrinsic::aarch64_neon_ld1x3:
6877 case Intrinsic::aarch64_neon_ld1x4:
6878 case Intrinsic::aarch64_neon_ld2lane:
6879 case Intrinsic::aarch64_neon_ld3lane:
6880 case Intrinsic::aarch64_neon_ld4lane:
6881 case Intrinsic::aarch64_neon_ld2r:
6882 case Intrinsic::aarch64_neon_ld3r:
6883 case Intrinsic::aarch64_neon_ld4r: {
6884 Info.opc = ISD::INTRINSIC_W_CHAIN;
6885 // Conservatively set memVT to the entire set of vectors loaded.
Ahmed Bougacha97564c32015-12-09 01:19:50 +00006886 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00006887 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6888 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6889 Info.offset = 0;
6890 Info.align = 0;
6891 Info.vol = false; // volatile loads with NEON intrinsics not supported
6892 Info.readMem = true;
6893 Info.writeMem = false;
6894 return true;
6895 }
6896 case Intrinsic::aarch64_neon_st2:
6897 case Intrinsic::aarch64_neon_st3:
6898 case Intrinsic::aarch64_neon_st4:
6899 case Intrinsic::aarch64_neon_st1x2:
6900 case Intrinsic::aarch64_neon_st1x3:
6901 case Intrinsic::aarch64_neon_st1x4:
6902 case Intrinsic::aarch64_neon_st2lane:
6903 case Intrinsic::aarch64_neon_st3lane:
6904 case Intrinsic::aarch64_neon_st4lane: {
6905 Info.opc = ISD::INTRINSIC_VOID;
6906 // Conservatively set memVT to the entire set of vectors stored.
6907 unsigned NumElts = 0;
6908 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
6909 Type *ArgTy = I.getArgOperand(ArgI)->getType();
6910 if (!ArgTy->isVectorTy())
6911 break;
Ahmed Bougacha97564c32015-12-09 01:19:50 +00006912 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00006913 }
6914 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6915 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6916 Info.offset = 0;
6917 Info.align = 0;
6918 Info.vol = false; // volatile stores with NEON intrinsics not supported
6919 Info.readMem = false;
6920 Info.writeMem = true;
6921 return true;
6922 }
6923 case Intrinsic::aarch64_ldaxr:
6924 case Intrinsic::aarch64_ldxr: {
6925 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
6926 Info.opc = ISD::INTRINSIC_W_CHAIN;
6927 Info.memVT = MVT::getVT(PtrTy->getElementType());
6928 Info.ptrVal = I.getArgOperand(0);
6929 Info.offset = 0;
Mehdi Aminia749f2a2015-07-09 02:09:52 +00006930 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
Tim Northover3b0846e2014-05-24 12:50:23 +00006931 Info.vol = true;
6932 Info.readMem = true;
6933 Info.writeMem = false;
6934 return true;
6935 }
6936 case Intrinsic::aarch64_stlxr:
6937 case Intrinsic::aarch64_stxr: {
6938 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
6939 Info.opc = ISD::INTRINSIC_W_CHAIN;
6940 Info.memVT = MVT::getVT(PtrTy->getElementType());
6941 Info.ptrVal = I.getArgOperand(1);
6942 Info.offset = 0;
Mehdi Aminia749f2a2015-07-09 02:09:52 +00006943 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
Tim Northover3b0846e2014-05-24 12:50:23 +00006944 Info.vol = true;
6945 Info.readMem = false;
6946 Info.writeMem = true;
6947 return true;
6948 }
6949 case Intrinsic::aarch64_ldaxp:
6950 case Intrinsic::aarch64_ldxp: {
6951 Info.opc = ISD::INTRINSIC_W_CHAIN;
6952 Info.memVT = MVT::i128;
6953 Info.ptrVal = I.getArgOperand(0);
6954 Info.offset = 0;
6955 Info.align = 16;
6956 Info.vol = true;
6957 Info.readMem = true;
6958 Info.writeMem = false;
6959 return true;
6960 }
6961 case Intrinsic::aarch64_stlxp:
6962 case Intrinsic::aarch64_stxp: {
6963 Info.opc = ISD::INTRINSIC_W_CHAIN;
6964 Info.memVT = MVT::i128;
6965 Info.ptrVal = I.getArgOperand(2);
6966 Info.offset = 0;
6967 Info.align = 16;
6968 Info.vol = true;
6969 Info.readMem = false;
6970 Info.writeMem = true;
6971 return true;
6972 }
6973 default:
6974 break;
6975 }
6976
6977 return false;
6978}
6979
6980// Truncations from 64-bit GPR to 32-bit GPR is free.
6981bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
6982 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6983 return false;
6984 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6985 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00006986 return NumBits1 > NumBits2;
Tim Northover3b0846e2014-05-24 12:50:23 +00006987}
6988bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
Hao Liu40914502014-05-29 09:19:07 +00006989 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00006990 return false;
6991 unsigned NumBits1 = VT1.getSizeInBits();
6992 unsigned NumBits2 = VT2.getSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00006993 return NumBits1 > NumBits2;
Tim Northover3b0846e2014-05-24 12:50:23 +00006994}
6995
Chad Rosier54390052015-02-23 19:15:16 +00006996/// Check if it is profitable to hoist instruction in then/else to if.
6997/// Not profitable if I and it's user can form a FMA instruction
6998/// because we prefer FMSUB/FMADD.
6999bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
7000 if (I->getOpcode() != Instruction::FMul)
7001 return true;
7002
7003 if (I->getNumUses() != 1)
7004 return true;
7005
7006 Instruction *User = I->user_back();
7007
7008 if (User &&
7009 !(User->getOpcode() == Instruction::FSub ||
7010 User->getOpcode() == Instruction::FAdd))
7011 return true;
7012
7013 const TargetOptions &Options = getTargetMachine().Options;
Mehdi Amini44ede332015-07-09 02:09:04 +00007014 const DataLayout &DL = I->getModule()->getDataLayout();
7015 EVT VT = getValueType(DL, User->getOperand(0)->getType());
Chad Rosier54390052015-02-23 19:15:16 +00007016
Eric Christopher114fa1c2016-02-29 22:50:49 +00007017 return !(isFMAFasterThanFMulAndFAdd(VT) &&
7018 isOperationLegalOrCustom(ISD::FMA, VT) &&
7019 (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7020 Options.UnsafeFPMath));
Chad Rosier54390052015-02-23 19:15:16 +00007021}
7022
Tim Northover3b0846e2014-05-24 12:50:23 +00007023// All 32-bit GPR operations implicitly zero the high-half of the corresponding
7024// 64-bit GPR.
7025bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
7026 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
7027 return false;
7028 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7029 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00007030 return NumBits1 == 32 && NumBits2 == 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00007031}
7032bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
Hao Liu40914502014-05-29 09:19:07 +00007033 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00007034 return false;
7035 unsigned NumBits1 = VT1.getSizeInBits();
7036 unsigned NumBits2 = VT2.getSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00007037 return NumBits1 == 32 && NumBits2 == 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00007038}
7039
7040bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
7041 EVT VT1 = Val.getValueType();
7042 if (isZExtFree(VT1, VT2)) {
7043 return true;
7044 }
7045
7046 if (Val.getOpcode() != ISD::LOAD)
7047 return false;
7048
7049 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
Hao Liu40914502014-05-29 09:19:07 +00007050 return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
7051 VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
7052 VT1.getSizeInBits() <= 32);
Tim Northover3b0846e2014-05-24 12:50:23 +00007053}
7054
Quentin Colombet6843ac42015-03-31 20:52:32 +00007055bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
7056 if (isa<FPExtInst>(Ext))
7057 return false;
7058
7059 // Vector types are next free.
7060 if (Ext->getType()->isVectorTy())
7061 return false;
7062
7063 for (const Use &U : Ext->uses()) {
7064 // The extension is free if we can fold it with a left shift in an
7065 // addressing mode or an arithmetic operation: add, sub, and cmp.
7066
7067 // Is there a shift?
7068 const Instruction *Instr = cast<Instruction>(U.getUser());
7069
7070 // Is this a constant shift?
7071 switch (Instr->getOpcode()) {
7072 case Instruction::Shl:
7073 if (!isa<ConstantInt>(Instr->getOperand(1)))
7074 return false;
7075 break;
7076 case Instruction::GetElementPtr: {
7077 gep_type_iterator GTI = gep_type_begin(Instr);
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007078 auto &DL = Ext->getModule()->getDataLayout();
Quentin Colombet6843ac42015-03-31 20:52:32 +00007079 std::advance(GTI, U.getOperandNo());
7080 Type *IdxTy = *GTI;
7081 // This extension will end up with a shift because of the scaling factor.
7082 // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
7083 // Get the shift amount based on the scaling factor:
7084 // log2(sizeof(IdxTy)) - log2(8).
7085 uint64_t ShiftAmt =
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007086 countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3;
Quentin Colombet6843ac42015-03-31 20:52:32 +00007087 // Is the constant foldable in the shift of the addressing mode?
7088 // I.e., shift amount is between 1 and 4 inclusive.
7089 if (ShiftAmt == 0 || ShiftAmt > 4)
7090 return false;
7091 break;
7092 }
7093 case Instruction::Trunc:
7094 // Check if this is a noop.
7095 // trunc(sext ty1 to ty2) to ty1.
7096 if (Instr->getType() == Ext->getOperand(0)->getType())
7097 continue;
7098 // FALL THROUGH.
7099 default:
7100 return false;
7101 }
7102
7103 // At this point we can use the bfm family, so this extension is free
7104 // for that use.
7105 }
7106 return true;
7107}
7108
Tim Northover3b0846e2014-05-24 12:50:23 +00007109bool AArch64TargetLowering::hasPairedLoad(Type *LoadedType,
7110 unsigned &RequiredAligment) const {
7111 if (!LoadedType->isIntegerTy() && !LoadedType->isFloatTy())
7112 return false;
7113 // Cyclone supports unaligned accesses.
7114 RequiredAligment = 0;
7115 unsigned NumBits = LoadedType->getPrimitiveSizeInBits();
7116 return NumBits == 32 || NumBits == 64;
7117}
7118
7119bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
7120 unsigned &RequiredAligment) const {
7121 if (!LoadedType.isSimple() ||
7122 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
7123 return false;
7124 // Cyclone supports unaligned accesses.
7125 RequiredAligment = 0;
7126 unsigned NumBits = LoadedType.getSizeInBits();
7127 return NumBits == 32 || NumBits == 64;
7128}
7129
Hao Liu7ec8ee32015-06-26 02:32:07 +00007130/// \brief Lower an interleaved load into a ldN intrinsic.
7131///
7132/// E.g. Lower an interleaved load (Factor = 2):
7133/// %wide.vec = load <8 x i32>, <8 x i32>* %ptr
7134/// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
7135/// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
7136///
7137/// Into:
7138/// %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
7139/// %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
7140/// %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
7141bool AArch64TargetLowering::lowerInterleavedLoad(
7142 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
7143 ArrayRef<unsigned> Indices, unsigned Factor) const {
7144 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7145 "Invalid interleave factor");
7146 assert(!Shuffles.empty() && "Empty shufflevector input");
7147 assert(Shuffles.size() == Indices.size() &&
7148 "Unmatched number of shufflevectors and indices");
7149
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007150 const DataLayout &DL = LI->getModule()->getDataLayout();
Hao Liu7ec8ee32015-06-26 02:32:07 +00007151
7152 VectorType *VecTy = Shuffles[0]->getType();
Ahmed Bougacha97564c32015-12-09 01:19:50 +00007153 unsigned VecSize = DL.getTypeSizeInBits(VecTy);
Hao Liu7ec8ee32015-06-26 02:32:07 +00007154
Jeroen Ketemaaebca092015-10-07 14:53:29 +00007155 // Skip if we do not have NEON and skip illegal vector types.
7156 if (!Subtarget->hasNEON() || (VecSize != 64 && VecSize != 128))
Hao Liu7ec8ee32015-06-26 02:32:07 +00007157 return false;
7158
7159 // A pointer vector can not be the return type of the ldN intrinsics. Need to
7160 // load integer vectors first and then convert to pointer vectors.
7161 Type *EltTy = VecTy->getVectorElementType();
7162 if (EltTy->isPointerTy())
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007163 VecTy =
7164 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
Hao Liu7ec8ee32015-06-26 02:32:07 +00007165
7166 Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
7167 Type *Tys[2] = {VecTy, PtrTy};
7168 static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
7169 Intrinsic::aarch64_neon_ld3,
7170 Intrinsic::aarch64_neon_ld4};
7171 Function *LdNFunc =
7172 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
7173
7174 IRBuilder<> Builder(LI);
7175 Value *Ptr = Builder.CreateBitCast(LI->getPointerOperand(), PtrTy);
7176
7177 CallInst *LdN = Builder.CreateCall(LdNFunc, Ptr, "ldN");
7178
7179 // Replace uses of each shufflevector with the corresponding vector loaded
7180 // by ldN.
7181 for (unsigned i = 0; i < Shuffles.size(); i++) {
7182 ShuffleVectorInst *SVI = Shuffles[i];
7183 unsigned Index = Indices[i];
7184
7185 Value *SubVec = Builder.CreateExtractValue(LdN, Index);
7186
7187 // Convert the integer vector to pointer vector if the element is pointer.
7188 if (EltTy->isPointerTy())
7189 SubVec = Builder.CreateIntToPtr(SubVec, SVI->getType());
7190
7191 SVI->replaceAllUsesWith(SubVec);
7192 }
7193
7194 return true;
7195}
7196
7197/// \brief Get a mask consisting of sequential integers starting from \p Start.
7198///
7199/// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
7200static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
7201 unsigned NumElts) {
7202 SmallVector<Constant *, 16> Mask;
7203 for (unsigned i = 0; i < NumElts; i++)
7204 Mask.push_back(Builder.getInt32(Start + i));
7205
7206 return ConstantVector::get(Mask);
7207}
7208
7209/// \brief Lower an interleaved store into a stN intrinsic.
7210///
7211/// E.g. Lower an interleaved store (Factor = 3):
7212/// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
7213/// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
7214/// store <12 x i32> %i.vec, <12 x i32>* %ptr
7215///
7216/// Into:
7217/// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
7218/// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
7219/// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
7220/// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
7221///
7222/// Note that the new shufflevectors will be removed and we'll only generate one
7223/// st3 instruction in CodeGen.
7224bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
7225 ShuffleVectorInst *SVI,
7226 unsigned Factor) const {
7227 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7228 "Invalid interleave factor");
7229
7230 VectorType *VecTy = SVI->getType();
7231 assert(VecTy->getVectorNumElements() % Factor == 0 &&
7232 "Invalid interleaved store");
7233
7234 unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
7235 Type *EltTy = VecTy->getVectorElementType();
7236 VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
7237
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007238 const DataLayout &DL = SI->getModule()->getDataLayout();
Ahmed Bougacha97564c32015-12-09 01:19:50 +00007239 unsigned SubVecSize = DL.getTypeSizeInBits(SubVecTy);
Hao Liu7ec8ee32015-06-26 02:32:07 +00007240
Jeroen Ketemaaebca092015-10-07 14:53:29 +00007241 // Skip if we do not have NEON and skip illegal vector types.
7242 if (!Subtarget->hasNEON() || (SubVecSize != 64 && SubVecSize != 128))
Hao Liu7ec8ee32015-06-26 02:32:07 +00007243 return false;
7244
7245 Value *Op0 = SVI->getOperand(0);
7246 Value *Op1 = SVI->getOperand(1);
7247 IRBuilder<> Builder(SI);
7248
7249 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
7250 // vectors to integer vectors.
7251 if (EltTy->isPointerTy()) {
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007252 Type *IntTy = DL.getIntPtrType(EltTy);
Hao Liu7ec8ee32015-06-26 02:32:07 +00007253 unsigned NumOpElts =
7254 dyn_cast<VectorType>(Op0->getType())->getVectorNumElements();
7255
7256 // Convert to the corresponding integer vector.
7257 Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
7258 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
7259 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
7260
7261 SubVecTy = VectorType::get(IntTy, NumSubElts);
7262 }
7263
7264 Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
7265 Type *Tys[2] = {SubVecTy, PtrTy};
7266 static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
7267 Intrinsic::aarch64_neon_st3,
7268 Intrinsic::aarch64_neon_st4};
7269 Function *StNFunc =
7270 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
7271
7272 SmallVector<Value *, 5> Ops;
7273
7274 // Split the shufflevector operands into sub vectors for the new stN call.
7275 for (unsigned i = 0; i < Factor; i++)
7276 Ops.push_back(Builder.CreateShuffleVector(
7277 Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
7278
7279 Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), PtrTy));
7280 Builder.CreateCall(StNFunc, Ops);
7281 return true;
7282}
7283
Tim Northover3b0846e2014-05-24 12:50:23 +00007284static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
7285 unsigned AlignCheck) {
7286 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
7287 (DstAlign == 0 || DstAlign % AlignCheck == 0));
7288}
7289
7290EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
7291 unsigned SrcAlign, bool IsMemset,
7292 bool ZeroMemset,
7293 bool MemcpyStrSrc,
7294 MachineFunction &MF) const {
7295 // Don't use AdvSIMD to implement 16-byte memset. It would have taken one
7296 // instruction to materialize the v2i64 zero and one store (with restrictive
7297 // addressing mode). Just do two i64 store of zero-registers.
7298 bool Fast;
7299 const Function *F = MF.getFunction();
7300 if (Subtarget->hasFPARMv8() && !IsMemset && Size >= 16 &&
Duncan P. N. Exon Smith003bb7d2015-02-14 02:09:06 +00007301 !F->hasFnAttribute(Attribute::NoImplicitFloat) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00007302 (memOpAlign(SrcAlign, DstAlign, 16) ||
Matt Arsenault6f2a5262014-07-27 17:46:40 +00007303 (allowsMisalignedMemoryAccesses(MVT::f128, 0, 1, &Fast) && Fast)))
Tim Northover3b0846e2014-05-24 12:50:23 +00007304 return MVT::f128;
7305
Lang Hames90333852015-04-09 03:40:33 +00007306 if (Size >= 8 &&
7307 (memOpAlign(SrcAlign, DstAlign, 8) ||
7308 (allowsMisalignedMemoryAccesses(MVT::i64, 0, 1, &Fast) && Fast)))
7309 return MVT::i64;
7310
7311 if (Size >= 4 &&
7312 (memOpAlign(SrcAlign, DstAlign, 4) ||
7313 (allowsMisalignedMemoryAccesses(MVT::i32, 0, 1, &Fast) && Fast)))
Lang Hames522bf132015-04-09 05:34:57 +00007314 return MVT::i32;
Lang Hames90333852015-04-09 03:40:33 +00007315
7316 return MVT::Other;
Tim Northover3b0846e2014-05-24 12:50:23 +00007317}
7318
7319// 12-bit optionally shifted immediates are legal for adds.
7320bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
Geoff Berry486f49c2016-06-07 16:48:43 +00007321 // Avoid UB for INT64_MIN.
7322 if (Immed == std::numeric_limits<int64_t>::min())
7323 return false;
7324 // Same encoding for add/sub, just flip the sign.
7325 Immed = std::abs(Immed);
Eric Christopher114fa1c2016-02-29 22:50:49 +00007326 return ((Immed >> 12) == 0 || ((Immed & 0xfff) == 0 && Immed >> 24 == 0));
Tim Northover3b0846e2014-05-24 12:50:23 +00007327}
7328
7329// Integer comparisons are implemented with ADDS/SUBS, so the range of valid
7330// immediates is the same as for an add or a sub.
7331bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00007332 return isLegalAddImmediate(Immed);
7333}
7334
7335/// isLegalAddressingMode - Return true if the addressing mode represented
7336/// by AM is legal for this target, for a load/store of the specified type.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00007337bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
7338 const AddrMode &AM, Type *Ty,
Matt Arsenaultbd7d80a2015-06-01 05:31:59 +00007339 unsigned AS) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00007340 // AArch64 has five basic addressing modes:
7341 // reg
7342 // reg + 9-bit signed offset
7343 // reg + SIZE_IN_BYTES * 12-bit unsigned offset
7344 // reg1 + reg2
7345 // reg + SIZE_IN_BYTES * reg
7346
7347 // No global is ever allowed as a base.
7348 if (AM.BaseGV)
7349 return false;
7350
7351 // No reg+reg+imm addressing.
7352 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
7353 return false;
7354
7355 // check reg + imm case:
7356 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
7357 uint64_t NumBytes = 0;
7358 if (Ty->isSized()) {
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00007359 uint64_t NumBits = DL.getTypeSizeInBits(Ty);
Tim Northover3b0846e2014-05-24 12:50:23 +00007360 NumBytes = NumBits / 8;
7361 if (!isPowerOf2_64(NumBits))
7362 NumBytes = 0;
7363 }
7364
7365 if (!AM.Scale) {
7366 int64_t Offset = AM.BaseOffs;
7367
7368 // 9-bit signed offset
7369 if (Offset >= -(1LL << 9) && Offset <= (1LL << 9) - 1)
7370 return true;
7371
7372 // 12-bit unsigned offset
7373 unsigned shift = Log2_64(NumBytes);
7374 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
7375 // Must be a multiple of NumBytes (NumBytes is a power of 2)
7376 (Offset >> shift) << shift == Offset)
7377 return true;
7378 return false;
7379 }
7380
7381 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
7382
Eric Christopher114fa1c2016-02-29 22:50:49 +00007383 return !AM.Scale || AM.Scale == 1 ||
7384 (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes);
Tim Northover3b0846e2014-05-24 12:50:23 +00007385}
7386
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00007387int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
7388 const AddrMode &AM, Type *Ty,
Matt Arsenaultbd7d80a2015-06-01 05:31:59 +00007389 unsigned AS) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00007390 // Scaling factors are not free at all.
7391 // Operands | Rt Latency
7392 // -------------------------------------------
7393 // Rt, [Xn, Xm] | 4
7394 // -------------------------------------------
7395 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5
7396 // Rt, [Xn, Wm, <extend> #imm] |
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00007397 if (isLegalAddressingMode(DL, AM, Ty, AS))
Tim Northover3b0846e2014-05-24 12:50:23 +00007398 // Scale represents reg2 * scale, thus account for 1 if
7399 // it is not equal to 0 or 1.
7400 return AM.Scale != 0 && AM.Scale != 1;
7401 return -1;
7402}
7403
7404bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
7405 VT = VT.getScalarType();
7406
7407 if (!VT.isSimple())
7408 return false;
7409
7410 switch (VT.getSimpleVT().SimpleTy) {
7411 case MVT::f32:
7412 case MVT::f64:
7413 return true;
7414 default:
7415 break;
7416 }
7417
7418 return false;
7419}
7420
7421const MCPhysReg *
7422AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
7423 // LR is a callee-save register, but we must treat it as clobbered by any call
7424 // site. Hence we include LR in the scratch registers, which are in turn added
7425 // as implicit-defs for stackmaps and patchpoints.
7426 static const MCPhysReg ScratchRegs[] = {
7427 AArch64::X16, AArch64::X17, AArch64::LR, 0
7428 };
7429 return ScratchRegs;
7430}
7431
7432bool
7433AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N) const {
7434 EVT VT = N->getValueType(0);
7435 // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
7436 // it with shift to let it be lowered to UBFX.
7437 if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
7438 isa<ConstantSDNode>(N->getOperand(1))) {
7439 uint64_t TruncMask = N->getConstantOperandVal(1);
7440 if (isMask_64(TruncMask) &&
7441 N->getOperand(0).getOpcode() == ISD::SRL &&
7442 isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
7443 return false;
7444 }
7445 return true;
7446}
7447
7448bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
7449 Type *Ty) const {
7450 assert(Ty->isIntegerTy());
7451
7452 unsigned BitSize = Ty->getPrimitiveSizeInBits();
7453 if (BitSize == 0)
7454 return false;
7455
7456 int64_t Val = Imm.getSExtValue();
7457 if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
7458 return true;
7459
7460 if ((int64_t)Val < 0)
7461 Val = ~Val;
7462 if (BitSize == 32)
7463 Val &= (1LL << 32) - 1;
7464
7465 unsigned LZ = countLeadingZeros((uint64_t)Val);
7466 unsigned Shift = (63 - LZ) / 16;
7467 // MOVZ is free so return true for one or fewer MOVK.
David Blaikie186d2cb2015-03-24 16:24:01 +00007468 return Shift < 3;
Tim Northover3b0846e2014-05-24 12:50:23 +00007469}
7470
Sanjay Pateld6cb4ec2016-03-03 15:56:08 +00007471/// Turn vector tests of the signbit in the form of:
7472/// xor (sra X, elt_size(X)-1), -1
7473/// into:
7474/// cmge X, X, #0
7475static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
7476 const AArch64Subtarget *Subtarget) {
7477 EVT VT = N->getValueType(0);
7478 if (!Subtarget->hasNEON() || !VT.isVector())
7479 return SDValue();
7480
7481 // There must be a shift right algebraic before the xor, and the xor must be a
7482 // 'not' operation.
7483 SDValue Shift = N->getOperand(0);
7484 SDValue Ones = N->getOperand(1);
7485 if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() ||
7486 !ISD::isBuildVectorAllOnes(Ones.getNode()))
7487 return SDValue();
7488
7489 // The shift should be smearing the sign bit across each vector element.
7490 auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
7491 EVT ShiftEltTy = Shift.getValueType().getVectorElementType();
7492 if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1)
7493 return SDValue();
7494
7495 return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0));
7496}
7497
Tim Northover3b0846e2014-05-24 12:50:23 +00007498// Generate SUBS and CSEL for integer abs.
7499static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
7500 EVT VT = N->getValueType(0);
7501
7502 SDValue N0 = N->getOperand(0);
7503 SDValue N1 = N->getOperand(1);
7504 SDLoc DL(N);
7505
7506 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
7507 // and change it to SUB and CSEL.
7508 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
7509 N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
7510 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
7511 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
7512 if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007513 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
Tim Northover3b0846e2014-05-24 12:50:23 +00007514 N0.getOperand(0));
7515 // Generate SUBS & CSEL.
7516 SDValue Cmp =
7517 DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007518 N0.getOperand(0), DAG.getConstant(0, DL, VT));
Tim Northover3b0846e2014-05-24 12:50:23 +00007519 return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007520 DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00007521 SDValue(Cmp.getNode(), 1));
7522 }
7523 return SDValue();
7524}
7525
Tim Northover3b0846e2014-05-24 12:50:23 +00007526static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
7527 TargetLowering::DAGCombinerInfo &DCI,
7528 const AArch64Subtarget *Subtarget) {
7529 if (DCI.isBeforeLegalizeOps())
7530 return SDValue();
7531
Sanjay Pateld6cb4ec2016-03-03 15:56:08 +00007532 if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget))
7533 return Cmp;
7534
Tim Northover3b0846e2014-05-24 12:50:23 +00007535 return performIntegerAbsCombine(N, DAG);
7536}
7537
Chad Rosier17020f92014-07-23 14:57:52 +00007538SDValue
7539AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
7540 SelectionDAG &DAG,
7541 std::vector<SDNode *> *Created) const {
Haicheng Wu6a6bc752016-03-28 18:17:07 +00007542 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
7543 if (isIntDivCheap(N->getValueType(0), Attr))
7544 return SDValue(N,0); // Lower SDIV as SDIV
7545
Chad Rosier17020f92014-07-23 14:57:52 +00007546 // fold (sdiv X, pow2)
7547 EVT VT = N->getValueType(0);
7548 if ((VT != MVT::i32 && VT != MVT::i64) ||
7549 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
7550 return SDValue();
7551
7552 SDLoc DL(N);
7553 SDValue N0 = N->getOperand(0);
7554 unsigned Lg2 = Divisor.countTrailingZeros();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007555 SDValue Zero = DAG.getConstant(0, DL, VT);
7556 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
Chad Rosier17020f92014-07-23 14:57:52 +00007557
7558 // Add (N0 < 0) ? Pow2 - 1 : 0;
7559 SDValue CCVal;
7560 SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
7561 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
7562 SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
7563
7564 if (Created) {
7565 Created->push_back(Cmp.getNode());
7566 Created->push_back(Add.getNode());
7567 Created->push_back(CSel.getNode());
7568 }
7569
7570 // Divide by pow2.
7571 SDValue SRA =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007572 DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
Chad Rosier17020f92014-07-23 14:57:52 +00007573
7574 // If we're dividing by a positive value, we're done. Otherwise, we must
7575 // negate the result.
7576 if (Divisor.isNonNegative())
7577 return SRA;
7578
7579 if (Created)
7580 Created->push_back(SRA.getNode());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007581 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
Chad Rosier17020f92014-07-23 14:57:52 +00007582}
7583
Tim Northover3b0846e2014-05-24 12:50:23 +00007584static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
7585 TargetLowering::DAGCombinerInfo &DCI,
7586 const AArch64Subtarget *Subtarget) {
7587 if (DCI.isBeforeLegalizeOps())
7588 return SDValue();
7589
7590 // Multiplication of a power of two plus/minus one can be done more
7591 // cheaply as as shift+add/sub. For now, this is true unilaterally. If
7592 // future CPUs have a cheaper MADD instruction, this may need to be
7593 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
7594 // 64-bit is 5 cycles, so this is always a win.
7595 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
Benjamin Kramer46e38f32016-06-08 10:01:20 +00007596 const APInt &Value = C->getAPIntValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00007597 EVT VT = N->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007598 SDLoc DL(N);
Chad Rosiere6b87612014-06-30 14:51:14 +00007599 if (Value.isNonNegative()) {
7600 // (mul x, 2^N + 1) => (add (shl x, N), x)
7601 APInt VM1 = Value - 1;
7602 if (VM1.isPowerOf2()) {
7603 SDValue ShiftedVal =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007604 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7605 DAG.getConstant(VM1.logBase2(), DL, MVT::i64));
7606 return DAG.getNode(ISD::ADD, DL, VT, ShiftedVal,
Chad Rosiere6b87612014-06-30 14:51:14 +00007607 N->getOperand(0));
7608 }
7609 // (mul x, 2^N - 1) => (sub (shl x, N), x)
7610 APInt VP1 = Value + 1;
7611 if (VP1.isPowerOf2()) {
7612 SDValue ShiftedVal =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007613 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7614 DAG.getConstant(VP1.logBase2(), DL, MVT::i64));
7615 return DAG.getNode(ISD::SUB, DL, VT, ShiftedVal,
Chad Rosiere6b87612014-06-30 14:51:14 +00007616 N->getOperand(0));
7617 }
7618 } else {
Chad Rosier8e38f302015-03-03 17:31:01 +00007619 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7620 APInt VNP1 = -Value + 1;
7621 if (VNP1.isPowerOf2()) {
7622 SDValue ShiftedVal =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007623 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7624 DAG.getConstant(VNP1.logBase2(), DL, MVT::i64));
7625 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0),
Chad Rosier8e38f302015-03-03 17:31:01 +00007626 ShiftedVal);
7627 }
Chad Rosiere6b87612014-06-30 14:51:14 +00007628 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7629 APInt VNM1 = -Value - 1;
7630 if (VNM1.isPowerOf2()) {
7631 SDValue ShiftedVal =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007632 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7633 DAG.getConstant(VNM1.logBase2(), DL, MVT::i64));
Chad Rosiere6b87612014-06-30 14:51:14 +00007634 SDValue Add =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007635 DAG.getNode(ISD::ADD, DL, VT, ShiftedVal, N->getOperand(0));
7636 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Add);
Chad Rosiere6b87612014-06-30 14:51:14 +00007637 }
Chad Rosierd96e9f12014-06-09 01:25:51 +00007638 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007639 }
7640 return SDValue();
7641}
7642
Jim Grosbachf7502c42014-07-18 00:40:52 +00007643static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
7644 SelectionDAG &DAG) {
7645 // Take advantage of vector comparisons producing 0 or -1 in each lane to
7646 // optimize away operation when it's from a constant.
7647 //
7648 // The general transformation is:
7649 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
7650 // AND(VECTOR_CMP(x,y), constant2)
7651 // constant2 = UNARYOP(constant)
7652
Jim Grosbach8f6f0852014-07-23 20:41:38 +00007653 // Early exit if this isn't a vector operation, the operand of the
7654 // unary operation isn't a bitwise AND, or if the sizes of the operations
7655 // aren't the same.
Jim Grosbachf7502c42014-07-18 00:40:52 +00007656 EVT VT = N->getValueType(0);
7657 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
Jim Grosbach8f6f0852014-07-23 20:41:38 +00007658 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
7659 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
Jim Grosbachf7502c42014-07-18 00:40:52 +00007660 return SDValue();
7661
Jim Grosbach724e4382014-07-23 20:41:43 +00007662 // Now check that the other operand of the AND is a constant. We could
Jim Grosbachf7502c42014-07-18 00:40:52 +00007663 // make the transformation for non-constant splats as well, but it's unclear
7664 // that would be a benefit as it would not eliminate any operations, just
7665 // perform one more step in scalar code before moving to the vector unit.
7666 if (BuildVectorSDNode *BV =
7667 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
Jim Grosbach724e4382014-07-23 20:41:43 +00007668 // Bail out if the vector isn't a constant.
7669 if (!BV->isConstant())
Jim Grosbachf7502c42014-07-18 00:40:52 +00007670 return SDValue();
7671
7672 // Everything checks out. Build up the new and improved node.
7673 SDLoc DL(N);
7674 EVT IntVT = BV->getValueType(0);
7675 // Create a new constant of the appropriate type for the transformed
7676 // DAG.
7677 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
7678 // The AND node needs bitcasts to/from an integer vector type around it.
7679 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
7680 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
7681 N->getOperand(0)->getOperand(0), MaskConst);
7682 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
7683 return Res;
7684 }
7685
7686 return SDValue();
7687}
7688
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00007689static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
7690 const AArch64Subtarget *Subtarget) {
Jim Grosbachf7502c42014-07-18 00:40:52 +00007691 // First try to optimize away the conversion when it's conditionally from
7692 // a constant. Vectors only.
Ahmed Bougacha239d6352015-08-04 00:48:02 +00007693 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
Jim Grosbachf7502c42014-07-18 00:40:52 +00007694 return Res;
7695
Tim Northover3b0846e2014-05-24 12:50:23 +00007696 EVT VT = N->getValueType(0);
7697 if (VT != MVT::f32 && VT != MVT::f64)
7698 return SDValue();
Jim Grosbachf7502c42014-07-18 00:40:52 +00007699
Tim Northover3b0846e2014-05-24 12:50:23 +00007700 // Only optimize when the source and destination types have the same width.
7701 if (VT.getSizeInBits() != N->getOperand(0).getValueType().getSizeInBits())
7702 return SDValue();
7703
7704 // If the result of an integer load is only used by an integer-to-float
7705 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
Chad Rosier1f385612015-10-02 16:42:59 +00007706 // This eliminates an "integer-to-vector-move" UOP and improves throughput.
Tim Northover3b0846e2014-05-24 12:50:23 +00007707 SDValue N0 = N->getOperand(0);
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00007708 if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Tim Northover3b0846e2014-05-24 12:50:23 +00007709 // Do not change the width of a volatile load.
7710 !cast<LoadSDNode>(N0)->isVolatile()) {
7711 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7712 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
7713 LN0->getPointerInfo(), LN0->isVolatile(),
7714 LN0->isNonTemporal(), LN0->isInvariant(),
7715 LN0->getAlignment());
7716
7717 // Make sure successors of the original load stay after it by updating them
7718 // to use the new Chain.
7719 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
7720
7721 unsigned Opcode =
7722 (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
7723 return DAG.getNode(Opcode, SDLoc(N), VT, Load);
7724 }
7725
7726 return SDValue();
7727}
7728
Chad Rosierfa30c9b2015-10-07 17:39:18 +00007729/// Fold a floating-point multiply by power of two into floating-point to
7730/// fixed-point conversion.
7731static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
7732 const AArch64Subtarget *Subtarget) {
7733 if (!Subtarget->hasNEON())
7734 return SDValue();
7735
7736 SDValue Op = N->getOperand(0);
Tim Northover6092de52016-03-10 23:02:21 +00007737 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
7738 Op.getOpcode() != ISD::FMUL)
Chad Rosierfa30c9b2015-10-07 17:39:18 +00007739 return SDValue();
7740
7741 SDValue ConstVec = Op->getOperand(1);
7742 if (!isa<BuildVectorSDNode>(ConstVec))
7743 return SDValue();
7744
7745 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
7746 uint32_t FloatBits = FloatTy.getSizeInBits();
7747 if (FloatBits != 32 && FloatBits != 64)
7748 return SDValue();
7749
7750 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
7751 uint32_t IntBits = IntTy.getSizeInBits();
7752 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
7753 return SDValue();
7754
7755 // Avoid conversions where iN is larger than the float (e.g., float -> i64).
7756 if (IntBits > FloatBits)
7757 return SDValue();
7758
7759 BitVector UndefElements;
7760 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
7761 int32_t Bits = IntBits == 64 ? 64 : 32;
7762 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
7763 if (C == -1 || C == 0 || C > Bits)
7764 return SDValue();
7765
7766 MVT ResTy;
7767 unsigned NumLanes = Op.getValueType().getVectorNumElements();
7768 switch (NumLanes) {
7769 default:
7770 return SDValue();
7771 case 2:
7772 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
7773 break;
7774 case 4:
7775 ResTy = MVT::v4i32;
7776 break;
7777 }
7778
7779 SDLoc DL(N);
7780 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
7781 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
7782 : Intrinsic::aarch64_neon_vcvtfp2fxu;
7783 SDValue FixConv =
7784 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
7785 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
7786 Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
7787 // We can handle smaller integers by generating an extra trunc.
7788 if (IntBits < FloatBits)
7789 FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
7790
7791 return FixConv;
7792}
7793
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00007794/// Fold a floating-point divide by power of two into fixed-point to
7795/// floating-point conversion.
7796static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
7797 const AArch64Subtarget *Subtarget) {
7798 if (!Subtarget->hasNEON())
7799 return SDValue();
7800
7801 SDValue Op = N->getOperand(0);
7802 unsigned Opc = Op->getOpcode();
7803 if (!Op.getValueType().isVector() ||
7804 (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
7805 return SDValue();
7806
7807 SDValue ConstVec = N->getOperand(1);
7808 if (!isa<BuildVectorSDNode>(ConstVec))
7809 return SDValue();
7810
7811 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
7812 int32_t IntBits = IntTy.getSizeInBits();
7813 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
7814 return SDValue();
7815
7816 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
7817 int32_t FloatBits = FloatTy.getSizeInBits();
7818 if (FloatBits != 32 && FloatBits != 64)
7819 return SDValue();
7820
7821 // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
7822 if (IntBits > FloatBits)
7823 return SDValue();
7824
7825 BitVector UndefElements;
7826 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
7827 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
7828 if (C == -1 || C == 0 || C > FloatBits)
7829 return SDValue();
7830
7831 MVT ResTy;
7832 unsigned NumLanes = Op.getValueType().getVectorNumElements();
7833 switch (NumLanes) {
7834 default:
7835 return SDValue();
7836 case 2:
7837 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
7838 break;
7839 case 4:
7840 ResTy = MVT::v4i32;
7841 break;
7842 }
7843
7844 SDLoc DL(N);
7845 SDValue ConvInput = Op.getOperand(0);
7846 bool IsSigned = Opc == ISD::SINT_TO_FP;
7847 if (IntBits < FloatBits)
7848 ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
7849 ResTy, ConvInput);
7850
7851 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
7852 : Intrinsic::aarch64_neon_vcvtfxu2fp;
7853 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
7854 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
7855 DAG.getConstant(C, DL, MVT::i32));
7856}
7857
Tim Northover3b0846e2014-05-24 12:50:23 +00007858/// An EXTR instruction is made up of two shifts, ORed together. This helper
7859/// searches for and classifies those shifts.
7860static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
7861 bool &FromHi) {
7862 if (N.getOpcode() == ISD::SHL)
7863 FromHi = false;
7864 else if (N.getOpcode() == ISD::SRL)
7865 FromHi = true;
7866 else
7867 return false;
7868
7869 if (!isa<ConstantSDNode>(N.getOperand(1)))
7870 return false;
7871
7872 ShiftAmount = N->getConstantOperandVal(1);
7873 Src = N->getOperand(0);
7874 return true;
7875}
7876
7877/// EXTR instruction extracts a contiguous chunk of bits from two existing
7878/// registers viewed as a high/low pair. This function looks for the pattern:
7879/// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an
7880/// EXTR. Can't quite be done in TableGen because the two immediates aren't
7881/// independent.
7882static SDValue tryCombineToEXTR(SDNode *N,
7883 TargetLowering::DAGCombinerInfo &DCI) {
7884 SelectionDAG &DAG = DCI.DAG;
7885 SDLoc DL(N);
7886 EVT VT = N->getValueType(0);
7887
7888 assert(N->getOpcode() == ISD::OR && "Unexpected root");
7889
7890 if (VT != MVT::i32 && VT != MVT::i64)
7891 return SDValue();
7892
7893 SDValue LHS;
7894 uint32_t ShiftLHS = 0;
7895 bool LHSFromHi = 0;
7896 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
7897 return SDValue();
7898
7899 SDValue RHS;
7900 uint32_t ShiftRHS = 0;
7901 bool RHSFromHi = 0;
7902 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
7903 return SDValue();
7904
7905 // If they're both trying to come from the high part of the register, they're
7906 // not really an EXTR.
7907 if (LHSFromHi == RHSFromHi)
7908 return SDValue();
7909
7910 if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
7911 return SDValue();
7912
7913 if (LHSFromHi) {
7914 std::swap(LHS, RHS);
7915 std::swap(ShiftLHS, ShiftRHS);
7916 }
7917
7918 return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007919 DAG.getConstant(ShiftRHS, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00007920}
7921
7922static SDValue tryCombineToBSL(SDNode *N,
7923 TargetLowering::DAGCombinerInfo &DCI) {
7924 EVT VT = N->getValueType(0);
7925 SelectionDAG &DAG = DCI.DAG;
7926 SDLoc DL(N);
7927
7928 if (!VT.isVector())
7929 return SDValue();
7930
7931 SDValue N0 = N->getOperand(0);
7932 if (N0.getOpcode() != ISD::AND)
7933 return SDValue();
7934
7935 SDValue N1 = N->getOperand(1);
7936 if (N1.getOpcode() != ISD::AND)
7937 return SDValue();
7938
7939 // We only have to look for constant vectors here since the general, variable
7940 // case can be handled in TableGen.
7941 unsigned Bits = VT.getVectorElementType().getSizeInBits();
7942 uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
7943 for (int i = 1; i >= 0; --i)
7944 for (int j = 1; j >= 0; --j) {
7945 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
7946 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
7947 if (!BVN0 || !BVN1)
7948 continue;
7949
7950 bool FoundMatch = true;
7951 for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
7952 ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
7953 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
7954 if (!CN0 || !CN1 ||
7955 CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
7956 FoundMatch = false;
7957 break;
7958 }
7959 }
7960
7961 if (FoundMatch)
7962 return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
7963 N0->getOperand(1 - i), N1->getOperand(1 - j));
7964 }
7965
7966 return SDValue();
7967}
7968
7969static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
7970 const AArch64Subtarget *Subtarget) {
7971 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
Tim Northover3b0846e2014-05-24 12:50:23 +00007972 SelectionDAG &DAG = DCI.DAG;
7973 EVT VT = N->getValueType(0);
7974
7975 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7976 return SDValue();
7977
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00007978 if (SDValue Res = tryCombineToEXTR(N, DCI))
Tim Northover3b0846e2014-05-24 12:50:23 +00007979 return Res;
7980
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00007981 if (SDValue Res = tryCombineToBSL(N, DCI))
Tim Northover3b0846e2014-05-24 12:50:23 +00007982 return Res;
7983
7984 return SDValue();
7985}
7986
Chad Rosier14aa2ad2016-05-26 19:41:33 +00007987static SDValue performSRLCombine(SDNode *N,
7988 TargetLowering::DAGCombinerInfo &DCI) {
7989 SelectionDAG &DAG = DCI.DAG;
7990 EVT VT = N->getValueType(0);
7991 if (VT != MVT::i32 && VT != MVT::i64)
7992 return SDValue();
7993
7994 // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the
7995 // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32)
7996 // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero.
7997 SDValue N0 = N->getOperand(0);
7998 if (N0.getOpcode() == ISD::BSWAP) {
7999 SDLoc DL(N);
8000 SDValue N1 = N->getOperand(1);
8001 SDValue N00 = N0.getOperand(0);
8002 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
8003 uint64_t ShiftAmt = C->getZExtValue();
8004 if (VT == MVT::i32 && ShiftAmt == 16 &&
8005 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16)))
8006 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
8007 if (VT == MVT::i64 && ShiftAmt == 32 &&
8008 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32)))
8009 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
8010 }
8011 }
8012 return SDValue();
8013}
8014
Tim Northover3b0846e2014-05-24 12:50:23 +00008015static SDValue performBitcastCombine(SDNode *N,
8016 TargetLowering::DAGCombinerInfo &DCI,
8017 SelectionDAG &DAG) {
8018 // Wait 'til after everything is legalized to try this. That way we have
8019 // legal vector types and such.
8020 if (DCI.isBeforeLegalizeOps())
8021 return SDValue();
8022
8023 // Remove extraneous bitcasts around an extract_subvector.
8024 // For example,
8025 // (v4i16 (bitconvert
8026 // (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
8027 // becomes
8028 // (extract_subvector ((v8i16 ...), (i64 4)))
8029
8030 // Only interested in 64-bit vectors as the ultimate result.
8031 EVT VT = N->getValueType(0);
8032 if (!VT.isVector())
8033 return SDValue();
8034 if (VT.getSimpleVT().getSizeInBits() != 64)
8035 return SDValue();
8036 // Is the operand an extract_subvector starting at the beginning or halfway
8037 // point of the vector? A low half may also come through as an
8038 // EXTRACT_SUBREG, so look for that, too.
8039 SDValue Op0 = N->getOperand(0);
8040 if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
8041 !(Op0->isMachineOpcode() &&
8042 Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
8043 return SDValue();
8044 uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
8045 if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
8046 if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
8047 return SDValue();
8048 } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
8049 if (idx != AArch64::dsub)
8050 return SDValue();
8051 // The dsub reference is equivalent to a lane zero subvector reference.
8052 idx = 0;
8053 }
8054 // Look through the bitcast of the input to the extract.
8055 if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
8056 return SDValue();
8057 SDValue Source = Op0->getOperand(0)->getOperand(0);
8058 // If the source type has twice the number of elements as our destination
8059 // type, we know this is an extract of the high or low half of the vector.
8060 EVT SVT = Source->getValueType(0);
8061 if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
8062 return SDValue();
8063
8064 DEBUG(dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
8065
8066 // Create the simplified form to just extract the low or high half of the
8067 // vector directly rather than bothering with the bitcasts.
8068 SDLoc dl(N);
8069 unsigned NumElements = VT.getVectorNumElements();
8070 if (idx) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008071 SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00008072 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
8073 } else {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008074 SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00008075 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
8076 Source, SubReg),
8077 0);
8078 }
8079}
8080
8081static SDValue performConcatVectorsCombine(SDNode *N,
8082 TargetLowering::DAGCombinerInfo &DCI,
8083 SelectionDAG &DAG) {
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00008084 SDLoc dl(N);
8085 EVT VT = N->getValueType(0);
8086 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
8087
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00008088 // Optimize concat_vectors of truncated vectors, where the intermediate
8089 // type is illegal, to avoid said illegality, e.g.,
8090 // (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
8091 // (v2i16 (truncate (v2i64)))))
8092 // ->
Ahmed Bougachae6bb09a2015-03-21 01:08:39 +00008093 // (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
8094 // (v4i32 (bitcast (v2i64))),
8095 // <0, 2, 4, 6>)))
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00008096 // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
8097 // on both input and result type, so we might generate worse code.
8098 // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
8099 if (N->getNumOperands() == 2 &&
8100 N0->getOpcode() == ISD::TRUNCATE &&
8101 N1->getOpcode() == ISD::TRUNCATE) {
8102 SDValue N00 = N0->getOperand(0);
8103 SDValue N10 = N1->getOperand(0);
8104 EVT N00VT = N00.getValueType();
8105
8106 if (N00VT == N10.getValueType() &&
8107 (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
8108 N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
Ahmed Bougachae6bb09a2015-03-21 01:08:39 +00008109 MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
8110 SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
8111 for (size_t i = 0; i < Mask.size(); ++i)
8112 Mask[i] = i * 2;
8113 return DAG.getNode(ISD::TRUNCATE, dl, VT,
8114 DAG.getVectorShuffle(
8115 MidVT, dl,
8116 DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
8117 DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00008118 }
8119 }
8120
Tim Northover3b0846e2014-05-24 12:50:23 +00008121 // Wait 'til after everything is legalized to try this. That way we have
8122 // legal vector types and such.
8123 if (DCI.isBeforeLegalizeOps())
8124 return SDValue();
8125
Tim Northover3b0846e2014-05-24 12:50:23 +00008126 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
8127 // splat. The indexed instructions are going to be expecting a DUPLANE64, so
8128 // canonicalise to that.
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00008129 if (N0 == N1 && VT.getVectorNumElements() == 2) {
Tim Northover3b0846e2014-05-24 12:50:23 +00008130 assert(VT.getVectorElementType().getSizeInBits() == 64);
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00008131 return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008132 DAG.getConstant(0, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008133 }
8134
8135 // Canonicalise concat_vectors so that the right-hand vector has as few
8136 // bit-casts as possible before its real operation. The primary matching
8137 // destination for these operations will be the narrowing "2" instructions,
8138 // which depend on the operation being performed on this right-hand vector.
8139 // For example,
8140 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS))))
8141 // becomes
8142 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
8143
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00008144 if (N1->getOpcode() != ISD::BITCAST)
Tim Northover3b0846e2014-05-24 12:50:23 +00008145 return SDValue();
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00008146 SDValue RHS = N1->getOperand(0);
Tim Northover3b0846e2014-05-24 12:50:23 +00008147 MVT RHSTy = RHS.getValueType().getSimpleVT();
8148 // If the RHS is not a vector, this is not the pattern we're looking for.
8149 if (!RHSTy.isVector())
8150 return SDValue();
8151
8152 DEBUG(dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
8153
8154 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
8155 RHSTy.getVectorNumElements() * 2);
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00008156 return DAG.getNode(ISD::BITCAST, dl, VT,
8157 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
8158 DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
8159 RHS));
Tim Northover3b0846e2014-05-24 12:50:23 +00008160}
8161
8162static SDValue tryCombineFixedPointConvert(SDNode *N,
8163 TargetLowering::DAGCombinerInfo &DCI,
8164 SelectionDAG &DAG) {
8165 // Wait 'til after everything is legalized to try this. That way we have
8166 // legal vector types and such.
8167 if (DCI.isBeforeLegalizeOps())
8168 return SDValue();
8169 // Transform a scalar conversion of a value from a lane extract into a
8170 // lane extract of a vector conversion. E.g., from foo1 to foo2:
8171 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
8172 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
8173 //
8174 // The second form interacts better with instruction selection and the
8175 // register allocator to avoid cross-class register copies that aren't
8176 // coalescable due to a lane reference.
8177
8178 // Check the operand and see if it originates from a lane extract.
8179 SDValue Op1 = N->getOperand(1);
8180 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8181 // Yep, no additional predication needed. Perform the transform.
8182 SDValue IID = N->getOperand(0);
8183 SDValue Shift = N->getOperand(2);
8184 SDValue Vec = Op1.getOperand(0);
8185 SDValue Lane = Op1.getOperand(1);
8186 EVT ResTy = N->getValueType(0);
8187 EVT VecResTy;
8188 SDLoc DL(N);
8189
8190 // The vector width should be 128 bits by the time we get here, even
8191 // if it started as 64 bits (the extract_vector handling will have
8192 // done so).
8193 assert(Vec.getValueType().getSizeInBits() == 128 &&
8194 "unexpected vector size on extract_vector_elt!");
8195 if (Vec.getValueType() == MVT::v4i32)
8196 VecResTy = MVT::v4f32;
8197 else if (Vec.getValueType() == MVT::v2i64)
8198 VecResTy = MVT::v2f64;
8199 else
Craig Topper2a30d782014-06-18 05:05:13 +00008200 llvm_unreachable("unexpected vector type!");
Tim Northover3b0846e2014-05-24 12:50:23 +00008201
8202 SDValue Convert =
8203 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
8204 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
8205 }
8206 return SDValue();
8207}
8208
8209// AArch64 high-vector "long" operations are formed by performing the non-high
8210// version on an extract_subvector of each operand which gets the high half:
8211//
8212// (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
8213//
8214// However, there are cases which don't have an extract_high explicitly, but
8215// have another operation that can be made compatible with one for free. For
8216// example:
8217//
8218// (dupv64 scalar) --> (extract_high (dup128 scalar))
8219//
8220// This routine does the actual conversion of such DUPs, once outer routines
8221// have determined that everything else is in order.
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008222// It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
8223// similarly here.
Tim Northover3b0846e2014-05-24 12:50:23 +00008224static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00008225 switch (N.getOpcode()) {
8226 case AArch64ISD::DUP:
Tim Northover3b0846e2014-05-24 12:50:23 +00008227 case AArch64ISD::DUPLANE8:
8228 case AArch64ISD::DUPLANE16:
8229 case AArch64ISD::DUPLANE32:
8230 case AArch64ISD::DUPLANE64:
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008231 case AArch64ISD::MOVI:
8232 case AArch64ISD::MOVIshift:
8233 case AArch64ISD::MOVIedit:
8234 case AArch64ISD::MOVImsl:
8235 case AArch64ISD::MVNIshift:
8236 case AArch64ISD::MVNImsl:
Tim Northover3b0846e2014-05-24 12:50:23 +00008237 break;
8238 default:
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008239 // FMOV could be supported, but isn't very useful, as it would only occur
8240 // if you passed a bitcast' floating point immediate to an eligible long
8241 // integer op (addl, smull, ...).
Tim Northover3b0846e2014-05-24 12:50:23 +00008242 return SDValue();
8243 }
8244
8245 MVT NarrowTy = N.getSimpleValueType();
8246 if (!NarrowTy.is64BitVector())
8247 return SDValue();
8248
8249 MVT ElementTy = NarrowTy.getVectorElementType();
8250 unsigned NumElems = NarrowTy.getVectorNumElements();
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008251 MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
Tim Northover3b0846e2014-05-24 12:50:23 +00008252
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008253 SDLoc dl(N);
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008254 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
8255 DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008256 DAG.getConstant(NumElems, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008257}
8258
8259static bool isEssentiallyExtractSubvector(SDValue N) {
8260 if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
8261 return true;
8262
8263 return N.getOpcode() == ISD::BITCAST &&
8264 N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
8265}
8266
8267/// \brief Helper structure to keep track of ISD::SET_CC operands.
8268struct GenericSetCCInfo {
8269 const SDValue *Opnd0;
8270 const SDValue *Opnd1;
8271 ISD::CondCode CC;
8272};
8273
8274/// \brief Helper structure to keep track of a SET_CC lowered into AArch64 code.
8275struct AArch64SetCCInfo {
8276 const SDValue *Cmp;
8277 AArch64CC::CondCode CC;
8278};
8279
8280/// \brief Helper structure to keep track of SetCC information.
8281union SetCCInfo {
8282 GenericSetCCInfo Generic;
8283 AArch64SetCCInfo AArch64;
8284};
8285
8286/// \brief Helper structure to be able to read SetCC information. If set to
8287/// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
8288/// GenericSetCCInfo.
8289struct SetCCInfoAndKind {
8290 SetCCInfo Info;
8291 bool IsAArch64;
8292};
8293
8294/// \brief Check whether or not \p Op is a SET_CC operation, either a generic or
8295/// an
8296/// AArch64 lowered one.
8297/// \p SetCCInfo is filled accordingly.
8298/// \post SetCCInfo is meanginfull only when this function returns true.
8299/// \return True when Op is a kind of SET_CC operation.
8300static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
8301 // If this is a setcc, this is straight forward.
8302 if (Op.getOpcode() == ISD::SETCC) {
8303 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
8304 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
8305 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8306 SetCCInfo.IsAArch64 = false;
8307 return true;
8308 }
8309 // Otherwise, check if this is a matching csel instruction.
8310 // In other words:
8311 // - csel 1, 0, cc
8312 // - csel 0, 1, !cc
8313 if (Op.getOpcode() != AArch64ISD::CSEL)
8314 return false;
8315 // Set the information about the operands.
8316 // TODO: we want the operands of the Cmp not the csel
8317 SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
8318 SetCCInfo.IsAArch64 = true;
8319 SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
8320 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
8321
8322 // Check that the operands matches the constraints:
8323 // (1) Both operands must be constants.
8324 // (2) One must be 1 and the other must be 0.
8325 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
8326 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8327
8328 // Check (1).
8329 if (!TValue || !FValue)
8330 return false;
8331
8332 // Check (2).
8333 if (!TValue->isOne()) {
8334 // Update the comparison when we are interested in !cc.
8335 std::swap(TValue, FValue);
8336 SetCCInfo.Info.AArch64.CC =
8337 AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
8338 }
8339 return TValue->isOne() && FValue->isNullValue();
8340}
8341
8342// Returns true if Op is setcc or zext of setcc.
8343static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
8344 if (isSetCC(Op, Info))
8345 return true;
8346 return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
8347 isSetCC(Op->getOperand(0), Info));
8348}
8349
8350// The folding we want to perform is:
8351// (add x, [zext] (setcc cc ...) )
8352// -->
8353// (csel x, (add x, 1), !cc ...)
8354//
8355// The latter will get matched to a CSINC instruction.
8356static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
8357 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
8358 SDValue LHS = Op->getOperand(0);
8359 SDValue RHS = Op->getOperand(1);
8360 SetCCInfoAndKind InfoAndKind;
8361
8362 // If neither operand is a SET_CC, give up.
8363 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
8364 std::swap(LHS, RHS);
8365 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
8366 return SDValue();
8367 }
8368
8369 // FIXME: This could be generatized to work for FP comparisons.
8370 EVT CmpVT = InfoAndKind.IsAArch64
8371 ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
8372 : InfoAndKind.Info.Generic.Opnd0->getValueType();
8373 if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
8374 return SDValue();
8375
8376 SDValue CCVal;
8377 SDValue Cmp;
8378 SDLoc dl(Op);
8379 if (InfoAndKind.IsAArch64) {
8380 CCVal = DAG.getConstant(
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008381 AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
8382 MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00008383 Cmp = *InfoAndKind.Info.AArch64.Cmp;
8384 } else
8385 Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
8386 *InfoAndKind.Info.Generic.Opnd1,
8387 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
8388 CCVal, DAG, dl);
8389
8390 EVT VT = Op->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008391 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
Tim Northover3b0846e2014-05-24 12:50:23 +00008392 return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
8393}
8394
8395// The basic add/sub long vector instructions have variants with "2" on the end
8396// which act on the high-half of their inputs. They are normally matched by
8397// patterns like:
8398//
8399// (add (zeroext (extract_high LHS)),
8400// (zeroext (extract_high RHS)))
8401// -> uaddl2 vD, vN, vM
8402//
8403// However, if one of the extracts is something like a duplicate, this
8404// instruction can still be used profitably. This function puts the DAG into a
8405// more appropriate form for those patterns to trigger.
8406static SDValue performAddSubLongCombine(SDNode *N,
8407 TargetLowering::DAGCombinerInfo &DCI,
8408 SelectionDAG &DAG) {
8409 if (DCI.isBeforeLegalizeOps())
8410 return SDValue();
8411
8412 MVT VT = N->getSimpleValueType(0);
8413 if (!VT.is128BitVector()) {
8414 if (N->getOpcode() == ISD::ADD)
8415 return performSetccAddFolding(N, DAG);
8416 return SDValue();
8417 }
8418
8419 // Make sure both branches are extended in the same way.
8420 SDValue LHS = N->getOperand(0);
8421 SDValue RHS = N->getOperand(1);
8422 if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
8423 LHS.getOpcode() != ISD::SIGN_EXTEND) ||
8424 LHS.getOpcode() != RHS.getOpcode())
8425 return SDValue();
8426
8427 unsigned ExtType = LHS.getOpcode();
8428
8429 // It's not worth doing if at least one of the inputs isn't already an
8430 // extract, but we don't know which it'll be so we have to try both.
8431 if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
8432 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
8433 if (!RHS.getNode())
8434 return SDValue();
8435
8436 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
8437 } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
8438 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
8439 if (!LHS.getNode())
8440 return SDValue();
8441
8442 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
8443 }
8444
8445 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
8446}
8447
8448// Massage DAGs which we can use the high-half "long" operations on into
8449// something isel will recognize better. E.g.
8450//
8451// (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
8452// (aarch64_neon_umull (extract_high (v2i64 vec)))
8453// (extract_high (v2i64 (dup128 scalar)))))
8454//
Hal Finkelcd8664c2015-12-11 23:11:52 +00008455static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
Tim Northover3b0846e2014-05-24 12:50:23 +00008456 TargetLowering::DAGCombinerInfo &DCI,
8457 SelectionDAG &DAG) {
8458 if (DCI.isBeforeLegalizeOps())
8459 return SDValue();
8460
Hal Finkelcd8664c2015-12-11 23:11:52 +00008461 SDValue LHS = N->getOperand(1);
8462 SDValue RHS = N->getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00008463 assert(LHS.getValueType().is64BitVector() &&
8464 RHS.getValueType().is64BitVector() &&
8465 "unexpected shape for long operation");
8466
8467 // Either node could be a DUP, but it's not worth doing both of them (you'd
8468 // just as well use the non-high version) so look for a corresponding extract
8469 // operation on the other "wing".
8470 if (isEssentiallyExtractSubvector(LHS)) {
8471 RHS = tryExtendDUPToExtractHigh(RHS, DAG);
8472 if (!RHS.getNode())
8473 return SDValue();
8474 } else if (isEssentiallyExtractSubvector(RHS)) {
8475 LHS = tryExtendDUPToExtractHigh(LHS, DAG);
8476 if (!LHS.getNode())
8477 return SDValue();
8478 }
8479
Hal Finkelcd8664c2015-12-11 23:11:52 +00008480 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
8481 N->getOperand(0), LHS, RHS);
Tim Northover3b0846e2014-05-24 12:50:23 +00008482}
8483
8484static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
8485 MVT ElemTy = N->getSimpleValueType(0).getScalarType();
8486 unsigned ElemBits = ElemTy.getSizeInBits();
8487
8488 int64_t ShiftAmount;
8489 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
8490 APInt SplatValue, SplatUndef;
8491 unsigned SplatBitSize;
8492 bool HasAnyUndefs;
8493 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
8494 HasAnyUndefs, ElemBits) ||
8495 SplatBitSize != ElemBits)
8496 return SDValue();
8497
8498 ShiftAmount = SplatValue.getSExtValue();
8499 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
8500 ShiftAmount = CVN->getSExtValue();
8501 } else
8502 return SDValue();
8503
8504 unsigned Opcode;
8505 bool IsRightShift;
8506 switch (IID) {
8507 default:
8508 llvm_unreachable("Unknown shift intrinsic");
8509 case Intrinsic::aarch64_neon_sqshl:
8510 Opcode = AArch64ISD::SQSHL_I;
8511 IsRightShift = false;
8512 break;
8513 case Intrinsic::aarch64_neon_uqshl:
8514 Opcode = AArch64ISD::UQSHL_I;
8515 IsRightShift = false;
8516 break;
8517 case Intrinsic::aarch64_neon_srshl:
8518 Opcode = AArch64ISD::SRSHR_I;
8519 IsRightShift = true;
8520 break;
8521 case Intrinsic::aarch64_neon_urshl:
8522 Opcode = AArch64ISD::URSHR_I;
8523 IsRightShift = true;
8524 break;
8525 case Intrinsic::aarch64_neon_sqshlu:
8526 Opcode = AArch64ISD::SQSHLU_I;
8527 IsRightShift = false;
8528 break;
8529 }
8530
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008531 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
8532 SDLoc dl(N);
8533 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8534 DAG.getConstant(-ShiftAmount, dl, MVT::i32));
8535 } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
8536 SDLoc dl(N);
8537 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8538 DAG.getConstant(ShiftAmount, dl, MVT::i32));
8539 }
Tim Northover3b0846e2014-05-24 12:50:23 +00008540
8541 return SDValue();
8542}
8543
8544// The CRC32[BH] instructions ignore the high bits of their data operand. Since
8545// the intrinsics must be legal and take an i32, this means there's almost
8546// certainly going to be a zext in the DAG which we can eliminate.
8547static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
8548 SDValue AndN = N->getOperand(2);
8549 if (AndN.getOpcode() != ISD::AND)
8550 return SDValue();
8551
8552 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
8553 if (!CMask || CMask->getZExtValue() != Mask)
8554 return SDValue();
8555
8556 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
8557 N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
8558}
8559
Ahmed Bougachafab58922015-03-10 20:45:38 +00008560static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
8561 SelectionDAG &DAG) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008562 SDLoc dl(N);
8563 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
8564 DAG.getNode(Opc, dl,
Ahmed Bougachafab58922015-03-10 20:45:38 +00008565 N->getOperand(1).getSimpleValueType(),
8566 N->getOperand(1)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008567 DAG.getConstant(0, dl, MVT::i64));
Ahmed Bougachafab58922015-03-10 20:45:38 +00008568}
8569
Tim Northover3b0846e2014-05-24 12:50:23 +00008570static SDValue performIntrinsicCombine(SDNode *N,
8571 TargetLowering::DAGCombinerInfo &DCI,
8572 const AArch64Subtarget *Subtarget) {
8573 SelectionDAG &DAG = DCI.DAG;
8574 unsigned IID = getIntrinsicID(N);
8575 switch (IID) {
8576 default:
8577 break;
8578 case Intrinsic::aarch64_neon_vcvtfxs2fp:
8579 case Intrinsic::aarch64_neon_vcvtfxu2fp:
8580 return tryCombineFixedPointConvert(N, DCI, DAG);
Ahmed Bougachafab58922015-03-10 20:45:38 +00008581 case Intrinsic::aarch64_neon_saddv:
8582 return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
8583 case Intrinsic::aarch64_neon_uaddv:
8584 return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
8585 case Intrinsic::aarch64_neon_sminv:
8586 return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
8587 case Intrinsic::aarch64_neon_uminv:
8588 return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
8589 case Intrinsic::aarch64_neon_smaxv:
8590 return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
8591 case Intrinsic::aarch64_neon_umaxv:
8592 return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00008593 case Intrinsic::aarch64_neon_fmax:
James Molloyedf38f02015-08-11 12:06:33 +00008594 return DAG.getNode(ISD::FMAXNAN, SDLoc(N), N->getValueType(0),
Tim Northover3b0846e2014-05-24 12:50:23 +00008595 N->getOperand(1), N->getOperand(2));
8596 case Intrinsic::aarch64_neon_fmin:
James Molloyedf38f02015-08-11 12:06:33 +00008597 return DAG.getNode(ISD::FMINNAN, SDLoc(N), N->getValueType(0),
Tim Northover3b0846e2014-05-24 12:50:23 +00008598 N->getOperand(1), N->getOperand(2));
James Molloyb7b2a1e2015-08-11 12:06:37 +00008599 case Intrinsic::aarch64_neon_fmaxnm:
8600 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
8601 N->getOperand(1), N->getOperand(2));
8602 case Intrinsic::aarch64_neon_fminnm:
8603 return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
8604 N->getOperand(1), N->getOperand(2));
Tim Northover3b0846e2014-05-24 12:50:23 +00008605 case Intrinsic::aarch64_neon_smull:
8606 case Intrinsic::aarch64_neon_umull:
8607 case Intrinsic::aarch64_neon_pmull:
8608 case Intrinsic::aarch64_neon_sqdmull:
Hal Finkelcd8664c2015-12-11 23:11:52 +00008609 return tryCombineLongOpWithDup(IID, N, DCI, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00008610 case Intrinsic::aarch64_neon_sqshl:
8611 case Intrinsic::aarch64_neon_uqshl:
8612 case Intrinsic::aarch64_neon_sqshlu:
8613 case Intrinsic::aarch64_neon_srshl:
8614 case Intrinsic::aarch64_neon_urshl:
8615 return tryCombineShiftImm(IID, N, DAG);
8616 case Intrinsic::aarch64_crc32b:
8617 case Intrinsic::aarch64_crc32cb:
8618 return tryCombineCRC32(0xff, N, DAG);
8619 case Intrinsic::aarch64_crc32h:
8620 case Intrinsic::aarch64_crc32ch:
8621 return tryCombineCRC32(0xffff, N, DAG);
8622 }
8623 return SDValue();
8624}
8625
8626static SDValue performExtendCombine(SDNode *N,
8627 TargetLowering::DAGCombinerInfo &DCI,
8628 SelectionDAG &DAG) {
8629 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
8630 // we can convert that DUP into another extract_high (of a bigger DUP), which
8631 // helps the backend to decide that an sabdl2 would be useful, saving a real
8632 // extract_high operation.
8633 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
Hal Finkelcd8664c2015-12-11 23:11:52 +00008634 N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
Tim Northover3b0846e2014-05-24 12:50:23 +00008635 SDNode *ABDNode = N->getOperand(0).getNode();
Hal Finkelcd8664c2015-12-11 23:11:52 +00008636 unsigned IID = getIntrinsicID(ABDNode);
8637 if (IID == Intrinsic::aarch64_neon_sabd ||
8638 IID == Intrinsic::aarch64_neon_uabd) {
8639 SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
8640 if (!NewABD.getNode())
8641 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00008642
Hal Finkelcd8664c2015-12-11 23:11:52 +00008643 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
8644 NewABD);
8645 }
Tim Northover3b0846e2014-05-24 12:50:23 +00008646 }
8647
8648 // This is effectively a custom type legalization for AArch64.
8649 //
8650 // Type legalization will split an extend of a small, legal, type to a larger
8651 // illegal type by first splitting the destination type, often creating
8652 // illegal source types, which then get legalized in isel-confusing ways,
8653 // leading to really terrible codegen. E.g.,
8654 // %result = v8i32 sext v8i8 %value
8655 // becomes
8656 // %losrc = extract_subreg %value, ...
8657 // %hisrc = extract_subreg %value, ...
8658 // %lo = v4i32 sext v4i8 %losrc
8659 // %hi = v4i32 sext v4i8 %hisrc
8660 // Things go rapidly downhill from there.
8661 //
8662 // For AArch64, the [sz]ext vector instructions can only go up one element
8663 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
8664 // take two instructions.
8665 //
8666 // This implies that the most efficient way to do the extend from v8i8
8667 // to two v4i32 values is to first extend the v8i8 to v8i16, then do
8668 // the normal splitting to happen for the v8i16->v8i32.
8669
8670 // This is pre-legalization to catch some cases where the default
8671 // type legalization will create ill-tempered code.
8672 if (!DCI.isBeforeLegalizeOps())
8673 return SDValue();
8674
8675 // We're only interested in cleaning things up for non-legal vector types
8676 // here. If both the source and destination are legal, things will just
8677 // work naturally without any fiddling.
Matthew Simpson13dddb02015-12-17 21:29:47 +00008678 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00008679 EVT ResVT = N->getValueType(0);
8680 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
8681 return SDValue();
8682 // If the vector type isn't a simple VT, it's beyond the scope of what
8683 // we're worried about here. Let legalization do its thing and hope for
8684 // the best.
Jim Grosbachec2b0d02014-08-28 22:08:28 +00008685 SDValue Src = N->getOperand(0);
8686 EVT SrcVT = Src->getValueType(0);
8687 if (!ResVT.isSimple() || !SrcVT.isSimple())
Tim Northover3b0846e2014-05-24 12:50:23 +00008688 return SDValue();
8689
Tim Northover3b0846e2014-05-24 12:50:23 +00008690 // If the source VT is a 64-bit vector, we can play games and get the
8691 // better results we want.
8692 if (SrcVT.getSizeInBits() != 64)
8693 return SDValue();
8694
8695 unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits();
8696 unsigned ElementCount = SrcVT.getVectorNumElements();
8697 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
8698 SDLoc DL(N);
8699 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
8700
8701 // Now split the rest of the operation into two halves, each with a 64
8702 // bit source.
8703 EVT LoVT, HiVT;
8704 SDValue Lo, Hi;
8705 unsigned NumElements = ResVT.getVectorNumElements();
8706 assert(!(NumElements & 1) && "Splitting vector, but not in half!");
8707 LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
8708 ResVT.getVectorElementType(), NumElements / 2);
8709
8710 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
8711 LoVT.getVectorNumElements());
8712 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008713 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008714 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008715 DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008716 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
8717 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
8718
8719 // Now combine the parts back together so we still have a single result
8720 // like the combiner expects.
8721 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
8722}
8723
8724/// Replace a splat of a scalar to a vector store by scalar stores of the scalar
8725/// value. The load store optimizer pass will merge them to store pair stores.
8726/// This has better performance than a splat of the scalar followed by a split
8727/// vector store. Even if the stores are not merged it is four stores vs a dup,
8728/// followed by an ext.b and two stores.
8729static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode *St) {
8730 SDValue StVal = St->getValue();
8731 EVT VT = StVal.getValueType();
8732
8733 // Don't replace floating point stores, they possibly won't be transformed to
8734 // stp because of the store pair suppress pass.
8735 if (VT.isFloatingPoint())
8736 return SDValue();
8737
8738 // Check for insert vector elements.
8739 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
8740 return SDValue();
8741
8742 // We can express a splat as store pair(s) for 2 or 4 elements.
8743 unsigned NumVecElts = VT.getVectorNumElements();
8744 if (NumVecElts != 4 && NumVecElts != 2)
8745 return SDValue();
8746 SDValue SplatVal = StVal.getOperand(1);
8747 unsigned RemainInsertElts = NumVecElts - 1;
8748
8749 // Check that this is a splat.
8750 while (--RemainInsertElts) {
8751 SDValue NextInsertElt = StVal.getOperand(0);
8752 if (NextInsertElt.getOpcode() != ISD::INSERT_VECTOR_ELT)
8753 return SDValue();
8754 if (NextInsertElt.getOperand(1) != SplatVal)
8755 return SDValue();
8756 StVal = NextInsertElt;
8757 }
8758 unsigned OrigAlignment = St->getAlignment();
8759 unsigned EltOffset = NumVecElts == 4 ? 4 : 8;
8760 unsigned Alignment = std::min(OrigAlignment, EltOffset);
8761
8762 // Create scalar stores. This is at least as good as the code sequence for a
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00008763 // split unaligned store which is a dup.s, ext.b, and two stores.
Tim Northover3b0846e2014-05-24 12:50:23 +00008764 // Most of the time the three stores should be replaced by store pair
8765 // instructions (stp).
8766 SDLoc DL(St);
8767 SDValue BasePtr = St->getBasePtr();
8768 SDValue NewST1 =
8769 DAG.getStore(St->getChain(), DL, SplatVal, BasePtr, St->getPointerInfo(),
8770 St->isVolatile(), St->isNonTemporal(), St->getAlignment());
8771
8772 unsigned Offset = EltOffset;
8773 while (--NumVecElts) {
8774 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008775 DAG.getConstant(Offset, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008776 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
8777 St->getPointerInfo(), St->isVolatile(),
8778 St->isNonTemporal(), Alignment);
8779 Offset += EltOffset;
8780 }
8781 return NewST1;
8782}
8783
Tim Northover339c83e2015-11-10 00:44:23 +00008784static SDValue split16BStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
8785 SelectionDAG &DAG,
8786 const AArch64Subtarget *Subtarget) {
Tim Northover3b0846e2014-05-24 12:50:23 +00008787 if (!DCI.isBeforeLegalize())
8788 return SDValue();
8789
8790 StoreSDNode *S = cast<StoreSDNode>(N);
8791 if (S->isVolatile())
8792 return SDValue();
8793
Sanjay Patelbbbf9a12015-09-25 21:49:48 +00008794 // FIXME: The logic for deciding if an unaligned store should be split should
8795 // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
8796 // a call to that function here.
8797
Matthias Braun651cff42016-06-02 18:03:53 +00008798 if (!Subtarget->isMisaligned128StoreSlow())
Tim Northover3b0846e2014-05-24 12:50:23 +00008799 return SDValue();
8800
Sanjay Patel924879a2015-08-04 15:49:57 +00008801 // Don't split at -Oz.
8802 if (DAG.getMachineFunction().getFunction()->optForMinSize())
Tim Northover3b0846e2014-05-24 12:50:23 +00008803 return SDValue();
8804
8805 SDValue StVal = S->getValue();
8806 EVT VT = StVal.getValueType();
8807
8808 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
8809 // those up regresses performance on micro-benchmarks and olden/bh.
8810 if (!VT.isVector() || VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
8811 return SDValue();
8812
8813 // Split unaligned 16B stores. They are terrible for performance.
8814 // Don't split stores with alignment of 1 or 2. Code that uses clang vector
8815 // extensions can use this to mark that it does not want splitting to happen
8816 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
8817 // eliminating alignment hazards is only 1 in 8 for alignment of 2.
8818 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
8819 S->getAlignment() <= 2)
8820 return SDValue();
8821
8822 // If we get a splat of a scalar convert this vector store to a store of
8823 // scalars. They will be merged into store pairs thereby removing two
8824 // instructions.
Ahmed Bougacha239d6352015-08-04 00:48:02 +00008825 if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, S))
Tim Northover3b0846e2014-05-24 12:50:23 +00008826 return ReplacedSplat;
8827
8828 SDLoc DL(S);
8829 unsigned NumElts = VT.getVectorNumElements() / 2;
8830 // Split VT into two.
8831 EVT HalfVT =
8832 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
8833 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008834 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008835 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008836 DAG.getConstant(NumElts, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008837 SDValue BasePtr = S->getBasePtr();
8838 SDValue NewST1 =
8839 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
8840 S->isVolatile(), S->isNonTemporal(), S->getAlignment());
8841 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008842 DAG.getConstant(8, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008843 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
8844 S->getPointerInfo(), S->isVolatile(), S->isNonTemporal(),
8845 S->getAlignment());
8846}
8847
8848/// Target-specific DAG combine function for post-increment LD1 (lane) and
8849/// post-increment LD1R.
8850static SDValue performPostLD1Combine(SDNode *N,
8851 TargetLowering::DAGCombinerInfo &DCI,
8852 bool IsLaneOp) {
8853 if (DCI.isBeforeLegalizeOps())
8854 return SDValue();
8855
8856 SelectionDAG &DAG = DCI.DAG;
8857 EVT VT = N->getValueType(0);
8858
8859 unsigned LoadIdx = IsLaneOp ? 1 : 0;
8860 SDNode *LD = N->getOperand(LoadIdx).getNode();
8861 // If it is not LOAD, can not do such combine.
8862 if (LD->getOpcode() != ISD::LOAD)
8863 return SDValue();
8864
8865 LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
8866 EVT MemVT = LoadSDN->getMemoryVT();
8867 // Check if memory operand is the same type as the vector element.
8868 if (MemVT != VT.getVectorElementType())
8869 return SDValue();
8870
8871 // Check if there are other uses. If so, do not combine as it will introduce
8872 // an extra load.
8873 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
8874 ++UI) {
8875 if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
8876 continue;
8877 if (*UI != N)
8878 return SDValue();
8879 }
8880
8881 SDValue Addr = LD->getOperand(1);
8882 SDValue Vector = N->getOperand(0);
8883 // Search for a use of the address operand that is an increment.
8884 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
8885 Addr.getNode()->use_end(); UI != UE; ++UI) {
8886 SDNode *User = *UI;
8887 if (User->getOpcode() != ISD::ADD
8888 || UI.getUse().getResNo() != Addr.getResNo())
8889 continue;
8890
8891 // Check that the add is independent of the load. Otherwise, folding it
8892 // would create a cycle.
8893 if (User->isPredecessorOf(LD) || LD->isPredecessorOf(User))
8894 continue;
8895 // Also check that add is not used in the vector operand. This would also
8896 // create a cycle.
8897 if (User->isPredecessorOf(Vector.getNode()))
8898 continue;
8899
8900 // If the increment is a constant, it must match the memory ref size.
8901 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8902 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8903 uint32_t IncVal = CInc->getZExtValue();
8904 unsigned NumBytes = VT.getScalarSizeInBits() / 8;
8905 if (IncVal != NumBytes)
8906 continue;
8907 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
8908 }
8909
Ahmed Bougacha2448ef52015-04-17 21:02:30 +00008910 // Finally, check that the vector doesn't depend on the load.
8911 // Again, this would create a cycle.
8912 // The load depending on the vector is fine, as that's the case for the
8913 // LD1*post we'll eventually generate anyway.
8914 if (LoadSDN->isPredecessorOf(Vector.getNode()))
8915 continue;
8916
Tim Northover3b0846e2014-05-24 12:50:23 +00008917 SmallVector<SDValue, 8> Ops;
8918 Ops.push_back(LD->getOperand(0)); // Chain
8919 if (IsLaneOp) {
8920 Ops.push_back(Vector); // The vector to be inserted
8921 Ops.push_back(N->getOperand(2)); // The lane to be inserted in the vector
8922 }
8923 Ops.push_back(Addr);
8924 Ops.push_back(Inc);
8925
8926 EVT Tys[3] = { VT, MVT::i64, MVT::Other };
Craig Toppere1d12942014-08-27 05:25:25 +00008927 SDVTList SDTys = DAG.getVTList(Tys);
Tim Northover3b0846e2014-05-24 12:50:23 +00008928 unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
8929 SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
8930 MemVT,
8931 LoadSDN->getMemOperand());
8932
8933 // Update the uses.
Ahmed Bougacha4c2b0782015-02-19 23:13:10 +00008934 SmallVector<SDValue, 2> NewResults;
Tim Northover3b0846e2014-05-24 12:50:23 +00008935 NewResults.push_back(SDValue(LD, 0)); // The result of load
8936 NewResults.push_back(SDValue(UpdN.getNode(), 2)); // Chain
8937 DCI.CombineTo(LD, NewResults);
8938 DCI.CombineTo(N, SDValue(UpdN.getNode(), 0)); // Dup/Inserted Result
8939 DCI.CombineTo(User, SDValue(UpdN.getNode(), 1)); // Write back register
8940
8941 break;
8942 }
8943 return SDValue();
8944}
8945
Tim Northover339c83e2015-11-10 00:44:23 +00008946/// Simplify \Addr given that the top byte of it is ignored by HW during
8947/// address translation.
8948static bool performTBISimplification(SDValue Addr,
8949 TargetLowering::DAGCombinerInfo &DCI,
8950 SelectionDAG &DAG) {
8951 APInt DemandedMask = APInt::getLowBitsSet(64, 56);
8952 APInt KnownZero, KnownOne;
8953 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
8954 DCI.isBeforeLegalizeOps());
8955 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8956 if (TLI.SimplifyDemandedBits(Addr, DemandedMask, KnownZero, KnownOne, TLO)) {
8957 DCI.CommitTargetLoweringOpt(TLO);
8958 return true;
8959 }
8960 return false;
8961}
8962
8963static SDValue performSTORECombine(SDNode *N,
8964 TargetLowering::DAGCombinerInfo &DCI,
8965 SelectionDAG &DAG,
8966 const AArch64Subtarget *Subtarget) {
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00008967 if (SDValue Split = split16BStores(N, DCI, DAG, Subtarget))
Tim Northover339c83e2015-11-10 00:44:23 +00008968 return Split;
8969
8970 if (Subtarget->supportsAddressTopByteIgnored() &&
8971 performTBISimplification(N->getOperand(2), DCI, DAG))
8972 return SDValue(N, 0);
8973
8974 return SDValue();
8975}
8976
8977 /// This function handles the log2-shuffle pattern produced by the
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008978/// LoopVectorizer for the across vector reduction. It consists of
8979/// log2(NumVectorElements) steps and, in each step, 2^(s) elements
8980/// are reduced, where s is an induction variable from 0 to
8981/// log2(NumVectorElements).
8982static SDValue tryMatchAcrossLaneShuffleForReduction(SDNode *N, SDValue OpV,
8983 unsigned Op,
8984 SelectionDAG &DAG) {
8985 EVT VTy = OpV->getOperand(0).getValueType();
8986 if (!VTy.isVector())
Chad Rosier6c36eff2015-09-03 18:13:57 +00008987 return SDValue();
8988
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008989 int NumVecElts = VTy.getVectorNumElements();
Jun Bum Lim0aace132015-10-09 14:11:25 +00008990 if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) {
8991 if (NumVecElts != 4)
8992 return SDValue();
8993 } else {
8994 if (NumVecElts != 4 && NumVecElts != 8 && NumVecElts != 16)
8995 return SDValue();
8996 }
Chad Rosier6c36eff2015-09-03 18:13:57 +00008997
8998 int NumExpectedSteps = APInt(8, NumVecElts).logBase2();
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008999 SDValue PreOp = OpV;
Chad Rosier6c36eff2015-09-03 18:13:57 +00009000 // Iterate over each step of the across vector reduction.
9001 for (int CurStep = 0; CurStep != NumExpectedSteps; ++CurStep) {
Chad Rosier6c36eff2015-09-03 18:13:57 +00009002 SDValue CurOp = PreOp.getOperand(0);
9003 SDValue Shuffle = PreOp.getOperand(1);
9004 if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE) {
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009005 // Try to swap the 1st and 2nd operand as add and min/max instructions
9006 // are commutative.
Chad Rosier6c36eff2015-09-03 18:13:57 +00009007 CurOp = PreOp.getOperand(1);
9008 Shuffle = PreOp.getOperand(0);
9009 if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE)
9010 return SDValue();
9011 }
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009012
9013 // Check if the input vector is fed by the operator we want to handle,
9014 // except the last step; the very first input vector is not necessarily
9015 // the same operator we are handling.
9016 if (CurOp.getOpcode() != Op && (CurStep != (NumExpectedSteps - 1)))
9017 return SDValue();
9018
Chad Rosier6c36eff2015-09-03 18:13:57 +00009019 // Check if it forms one step of the across vector reduction.
9020 // E.g.,
9021 // %cur = add %1, %0
9022 // %shuffle = vector_shuffle %cur, <2, 3, u, u>
9023 // %pre = add %cur, %shuffle
9024 if (Shuffle.getOperand(0) != CurOp)
9025 return SDValue();
9026
9027 int NumMaskElts = 1 << CurStep;
9028 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Shuffle)->getMask();
9029 // Check mask values in each step.
9030 // We expect the shuffle mask in each step follows a specific pattern
9031 // denoted here by the <M, U> form, where M is a sequence of integers
9032 // starting from NumMaskElts, increasing by 1, and the number integers
9033 // in M should be NumMaskElts. U is a sequence of UNDEFs and the number
9034 // of undef in U should be NumVecElts - NumMaskElts.
9035 // E.g., for <8 x i16>, mask values in each step should be :
9036 // step 0 : <1,u,u,u,u,u,u,u>
9037 // step 1 : <2,3,u,u,u,u,u,u>
9038 // step 2 : <4,5,6,7,u,u,u,u>
9039 for (int i = 0; i < NumVecElts; ++i)
9040 if ((i < NumMaskElts && Mask[i] != (NumMaskElts + i)) ||
9041 (i >= NumMaskElts && !(Mask[i] < 0)))
9042 return SDValue();
9043
9044 PreOp = CurOp;
9045 }
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009046 unsigned Opcode;
Jun Bum Lim0aace132015-10-09 14:11:25 +00009047 bool IsIntrinsic = false;
9048
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009049 switch (Op) {
9050 default:
9051 llvm_unreachable("Unexpected operator for across vector reduction");
9052 case ISD::ADD:
9053 Opcode = AArch64ISD::UADDV;
9054 break;
9055 case ISD::SMAX:
9056 Opcode = AArch64ISD::SMAXV;
9057 break;
9058 case ISD::UMAX:
9059 Opcode = AArch64ISD::UMAXV;
9060 break;
9061 case ISD::SMIN:
9062 Opcode = AArch64ISD::SMINV;
9063 break;
9064 case ISD::UMIN:
9065 Opcode = AArch64ISD::UMINV;
9066 break;
Jun Bum Lim0aace132015-10-09 14:11:25 +00009067 case ISD::FMAXNUM:
9068 Opcode = Intrinsic::aarch64_neon_fmaxnmv;
9069 IsIntrinsic = true;
9070 break;
9071 case ISD::FMINNUM:
9072 Opcode = Intrinsic::aarch64_neon_fminnmv;
9073 IsIntrinsic = true;
9074 break;
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009075 }
Chad Rosier6c36eff2015-09-03 18:13:57 +00009076 SDLoc DL(N);
Jun Bum Lim0aace132015-10-09 14:11:25 +00009077
9078 return IsIntrinsic
9079 ? DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, N->getValueType(0),
9080 DAG.getConstant(Opcode, DL, MVT::i32), PreOp)
9081 : DAG.getNode(
9082 ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0),
9083 DAG.getNode(Opcode, DL, PreOp.getSimpleValueType(), PreOp),
9084 DAG.getConstant(0, DL, MVT::i64));
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009085}
9086
9087/// Target-specific DAG combine for the across vector min/max reductions.
9088/// This function specifically handles the final clean-up step of the vector
9089/// min/max reductions produced by the LoopVectorizer. It is the log2-shuffle
9090/// pattern, which narrows down and finds the final min/max value from all
9091/// elements of the vector.
9092/// For example, for a <16 x i8> vector :
9093/// svn0 = vector_shuffle %0, undef<8,9,10,11,12,13,14,15,u,u,u,u,u,u,u,u>
9094/// %smax0 = smax %arr, svn0
9095/// %svn1 = vector_shuffle %smax0, undef<4,5,6,7,u,u,u,u,u,u,u,u,u,u,u,u>
9096/// %smax1 = smax %smax0, %svn1
9097/// %svn2 = vector_shuffle %smax1, undef<2,3,u,u,u,u,u,u,u,u,u,u,u,u,u,u>
9098/// %smax2 = smax %smax1, svn2
9099/// %svn3 = vector_shuffle %smax2, undef<1,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u>
9100/// %sc = setcc %smax2, %svn3, gt
9101/// %n0 = extract_vector_elt %sc, #0
9102/// %n1 = extract_vector_elt %smax2, #0
9103/// %n2 = extract_vector_elt $smax2, #1
9104/// %result = select %n0, %n1, n2
9105/// becomes :
9106/// %1 = smaxv %0
9107/// %result = extract_vector_elt %1, 0
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009108static SDValue
9109performAcrossLaneMinMaxReductionCombine(SDNode *N, SelectionDAG &DAG,
9110 const AArch64Subtarget *Subtarget) {
9111 if (!Subtarget->hasNEON())
9112 return SDValue();
9113
9114 SDValue N0 = N->getOperand(0);
9115 SDValue IfTrue = N->getOperand(1);
9116 SDValue IfFalse = N->getOperand(2);
9117
9118 // Check if the SELECT merges up the final result of the min/max
9119 // from a vector.
9120 if (N0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9121 IfTrue.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9122 IfFalse.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9123 return SDValue();
9124
9125 // Expect N0 is fed by SETCC.
9126 SDValue SetCC = N0.getOperand(0);
9127 EVT SetCCVT = SetCC.getValueType();
9128 if (SetCC.getOpcode() != ISD::SETCC || !SetCCVT.isVector() ||
9129 SetCCVT.getVectorElementType() != MVT::i1)
9130 return SDValue();
9131
9132 SDValue VectorOp = SetCC.getOperand(0);
9133 unsigned Op = VectorOp->getOpcode();
9134 // Check if the input vector is fed by the operator we want to handle.
Jun Bum Lim0aace132015-10-09 14:11:25 +00009135 if (Op != ISD::SMAX && Op != ISD::UMAX && Op != ISD::SMIN &&
9136 Op != ISD::UMIN && Op != ISD::FMAXNUM && Op != ISD::FMINNUM)
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009137 return SDValue();
9138
9139 EVT VTy = VectorOp.getValueType();
9140 if (!VTy.isVector())
9141 return SDValue();
9142
Jun Bum Lim0aace132015-10-09 14:11:25 +00009143 if (VTy.getSizeInBits() < 64)
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009144 return SDValue();
9145
Jun Bum Lim0aace132015-10-09 14:11:25 +00009146 EVT EltTy = VTy.getVectorElementType();
9147 if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) {
9148 if (EltTy != MVT::f32)
9149 return SDValue();
9150 } else {
9151 if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8)
9152 return SDValue();
9153 }
9154
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009155 // Check if extracting from the same vector.
9156 // For example,
9157 // %sc = setcc %vector, %svn1, gt
9158 // %n0 = extract_vector_elt %sc, #0
9159 // %n1 = extract_vector_elt %vector, #0
9160 // %n2 = extract_vector_elt $vector, #1
9161 if (!(VectorOp == IfTrue->getOperand(0) &&
9162 VectorOp == IfFalse->getOperand(0)))
9163 return SDValue();
9164
9165 // Check if the condition code is matched with the operator type.
9166 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get();
9167 if ((Op == ISD::SMAX && CC != ISD::SETGT && CC != ISD::SETGE) ||
9168 (Op == ISD::UMAX && CC != ISD::SETUGT && CC != ISD::SETUGE) ||
9169 (Op == ISD::SMIN && CC != ISD::SETLT && CC != ISD::SETLE) ||
Jun Bum Lim0aace132015-10-09 14:11:25 +00009170 (Op == ISD::UMIN && CC != ISD::SETULT && CC != ISD::SETULE) ||
9171 (Op == ISD::FMAXNUM && CC != ISD::SETOGT && CC != ISD::SETOGE &&
9172 CC != ISD::SETUGT && CC != ISD::SETUGE && CC != ISD::SETGT &&
9173 CC != ISD::SETGE) ||
9174 (Op == ISD::FMINNUM && CC != ISD::SETOLT && CC != ISD::SETOLE &&
9175 CC != ISD::SETULT && CC != ISD::SETULE && CC != ISD::SETLT &&
9176 CC != ISD::SETLE))
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009177 return SDValue();
9178
9179 // Expect to check only lane 0 from the vector SETCC.
Artyom Skrobov314ee042015-11-25 19:41:11 +00009180 if (!isNullConstant(N0.getOperand(1)))
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009181 return SDValue();
9182
9183 // Expect to extract the true value from lane 0.
Artyom Skrobov314ee042015-11-25 19:41:11 +00009184 if (!isNullConstant(IfTrue.getOperand(1)))
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009185 return SDValue();
9186
9187 // Expect to extract the false value from lane 1.
Artyom Skrobov314ee042015-11-25 19:41:11 +00009188 if (!isOneConstant(IfFalse.getOperand(1)))
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009189 return SDValue();
9190
9191 return tryMatchAcrossLaneShuffleForReduction(N, SetCC, Op, DAG);
9192}
9193
9194/// Target-specific DAG combine for the across vector add reduction.
9195/// This function specifically handles the final clean-up step of the vector
9196/// add reduction produced by the LoopVectorizer. It is the log2-shuffle
9197/// pattern, which adds all elements of a vector together.
9198/// For example, for a <4 x i32> vector :
9199/// %1 = vector_shuffle %0, <2,3,u,u>
9200/// %2 = add %0, %1
9201/// %3 = vector_shuffle %2, <1,u,u,u>
9202/// %4 = add %2, %3
9203/// %result = extract_vector_elt %4, 0
9204/// becomes :
9205/// %0 = uaddv %0
9206/// %result = extract_vector_elt %0, 0
9207static SDValue
9208performAcrossLaneAddReductionCombine(SDNode *N, SelectionDAG &DAG,
9209 const AArch64Subtarget *Subtarget) {
9210 if (!Subtarget->hasNEON())
9211 return SDValue();
9212 SDValue N0 = N->getOperand(0);
9213 SDValue N1 = N->getOperand(1);
9214
9215 // Check if the input vector is fed by the ADD.
9216 if (N0->getOpcode() != ISD::ADD)
9217 return SDValue();
9218
9219 // The vector extract idx must constant zero because we only expect the final
9220 // result of the reduction is placed in lane 0.
Artyom Skrobov314ee042015-11-25 19:41:11 +00009221 if (!isNullConstant(N1))
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009222 return SDValue();
9223
9224 EVT VTy = N0.getValueType();
9225 if (!VTy.isVector())
9226 return SDValue();
9227
9228 EVT EltTy = VTy.getVectorElementType();
9229 if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8)
9230 return SDValue();
9231
Jun Bum Lim0aace132015-10-09 14:11:25 +00009232 if (VTy.getSizeInBits() < 64)
9233 return SDValue();
9234
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009235 return tryMatchAcrossLaneShuffleForReduction(N, N0, ISD::ADD, DAG);
Chad Rosier6c36eff2015-09-03 18:13:57 +00009236}
9237
Tim Northover3b0846e2014-05-24 12:50:23 +00009238/// Target-specific DAG combine function for NEON load/store intrinsics
9239/// to merge base address updates.
9240static SDValue performNEONPostLDSTCombine(SDNode *N,
9241 TargetLowering::DAGCombinerInfo &DCI,
9242 SelectionDAG &DAG) {
9243 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9244 return SDValue();
9245
9246 unsigned AddrOpIdx = N->getNumOperands() - 1;
9247 SDValue Addr = N->getOperand(AddrOpIdx);
9248
9249 // Search for a use of the address operand that is an increment.
9250 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9251 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9252 SDNode *User = *UI;
9253 if (User->getOpcode() != ISD::ADD ||
9254 UI.getUse().getResNo() != Addr.getResNo())
9255 continue;
9256
9257 // Check that the add is independent of the load/store. Otherwise, folding
9258 // it would create a cycle.
9259 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9260 continue;
9261
9262 // Find the new opcode for the updating load/store.
9263 bool IsStore = false;
9264 bool IsLaneOp = false;
9265 bool IsDupOp = false;
9266 unsigned NewOpc = 0;
9267 unsigned NumVecs = 0;
9268 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9269 switch (IntNo) {
9270 default: llvm_unreachable("unexpected intrinsic for Neon base update");
9271 case Intrinsic::aarch64_neon_ld2: NewOpc = AArch64ISD::LD2post;
9272 NumVecs = 2; break;
9273 case Intrinsic::aarch64_neon_ld3: NewOpc = AArch64ISD::LD3post;
9274 NumVecs = 3; break;
9275 case Intrinsic::aarch64_neon_ld4: NewOpc = AArch64ISD::LD4post;
9276 NumVecs = 4; break;
9277 case Intrinsic::aarch64_neon_st2: NewOpc = AArch64ISD::ST2post;
9278 NumVecs = 2; IsStore = true; break;
9279 case Intrinsic::aarch64_neon_st3: NewOpc = AArch64ISD::ST3post;
9280 NumVecs = 3; IsStore = true; break;
9281 case Intrinsic::aarch64_neon_st4: NewOpc = AArch64ISD::ST4post;
9282 NumVecs = 4; IsStore = true; break;
9283 case Intrinsic::aarch64_neon_ld1x2: NewOpc = AArch64ISD::LD1x2post;
9284 NumVecs = 2; break;
9285 case Intrinsic::aarch64_neon_ld1x3: NewOpc = AArch64ISD::LD1x3post;
9286 NumVecs = 3; break;
9287 case Intrinsic::aarch64_neon_ld1x4: NewOpc = AArch64ISD::LD1x4post;
9288 NumVecs = 4; break;
9289 case Intrinsic::aarch64_neon_st1x2: NewOpc = AArch64ISD::ST1x2post;
9290 NumVecs = 2; IsStore = true; break;
9291 case Intrinsic::aarch64_neon_st1x3: NewOpc = AArch64ISD::ST1x3post;
9292 NumVecs = 3; IsStore = true; break;
9293 case Intrinsic::aarch64_neon_st1x4: NewOpc = AArch64ISD::ST1x4post;
9294 NumVecs = 4; IsStore = true; break;
9295 case Intrinsic::aarch64_neon_ld2r: NewOpc = AArch64ISD::LD2DUPpost;
9296 NumVecs = 2; IsDupOp = true; break;
9297 case Intrinsic::aarch64_neon_ld3r: NewOpc = AArch64ISD::LD3DUPpost;
9298 NumVecs = 3; IsDupOp = true; break;
9299 case Intrinsic::aarch64_neon_ld4r: NewOpc = AArch64ISD::LD4DUPpost;
9300 NumVecs = 4; IsDupOp = true; break;
9301 case Intrinsic::aarch64_neon_ld2lane: NewOpc = AArch64ISD::LD2LANEpost;
9302 NumVecs = 2; IsLaneOp = true; break;
9303 case Intrinsic::aarch64_neon_ld3lane: NewOpc = AArch64ISD::LD3LANEpost;
9304 NumVecs = 3; IsLaneOp = true; break;
9305 case Intrinsic::aarch64_neon_ld4lane: NewOpc = AArch64ISD::LD4LANEpost;
9306 NumVecs = 4; IsLaneOp = true; break;
9307 case Intrinsic::aarch64_neon_st2lane: NewOpc = AArch64ISD::ST2LANEpost;
9308 NumVecs = 2; IsStore = true; IsLaneOp = true; break;
9309 case Intrinsic::aarch64_neon_st3lane: NewOpc = AArch64ISD::ST3LANEpost;
9310 NumVecs = 3; IsStore = true; IsLaneOp = true; break;
9311 case Intrinsic::aarch64_neon_st4lane: NewOpc = AArch64ISD::ST4LANEpost;
9312 NumVecs = 4; IsStore = true; IsLaneOp = true; break;
9313 }
9314
9315 EVT VecTy;
9316 if (IsStore)
9317 VecTy = N->getOperand(2).getValueType();
9318 else
9319 VecTy = N->getValueType(0);
9320
9321 // If the increment is a constant, it must match the memory ref size.
9322 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9323 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9324 uint32_t IncVal = CInc->getZExtValue();
9325 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9326 if (IsLaneOp || IsDupOp)
9327 NumBytes /= VecTy.getVectorNumElements();
9328 if (IncVal != NumBytes)
9329 continue;
9330 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
9331 }
9332 SmallVector<SDValue, 8> Ops;
9333 Ops.push_back(N->getOperand(0)); // Incoming chain
9334 // Load lane and store have vector list as input.
9335 if (IsLaneOp || IsStore)
9336 for (unsigned i = 2; i < AddrOpIdx; ++i)
9337 Ops.push_back(N->getOperand(i));
9338 Ops.push_back(Addr); // Base register
9339 Ops.push_back(Inc);
9340
9341 // Return Types.
9342 EVT Tys[6];
9343 unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
9344 unsigned n;
9345 for (n = 0; n < NumResultVecs; ++n)
9346 Tys[n] = VecTy;
9347 Tys[n++] = MVT::i64; // Type of write back register
9348 Tys[n] = MVT::Other; // Type of the chain
Craig Toppere1d12942014-08-27 05:25:25 +00009349 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
Tim Northover3b0846e2014-05-24 12:50:23 +00009350
9351 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9352 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
9353 MemInt->getMemoryVT(),
9354 MemInt->getMemOperand());
9355
9356 // Update the uses.
9357 std::vector<SDValue> NewResults;
9358 for (unsigned i = 0; i < NumResultVecs; ++i) {
9359 NewResults.push_back(SDValue(UpdN.getNode(), i));
9360 }
9361 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
9362 DCI.CombineTo(N, NewResults);
9363 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9364
9365 break;
9366 }
9367 return SDValue();
9368}
9369
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009370// Checks to see if the value is the prescribed width and returns information
9371// about its extension mode.
9372static
9373bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
9374 ExtType = ISD::NON_EXTLOAD;
9375 switch(V.getNode()->getOpcode()) {
9376 default:
9377 return false;
9378 case ISD::LOAD: {
9379 LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
9380 if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
9381 || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
9382 ExtType = LoadNode->getExtensionType();
9383 return true;
9384 }
9385 return false;
9386 }
9387 case ISD::AssertSext: {
9388 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9389 if ((TypeNode->getVT() == MVT::i8 && width == 8)
9390 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9391 ExtType = ISD::SEXTLOAD;
9392 return true;
9393 }
9394 return false;
9395 }
9396 case ISD::AssertZext: {
9397 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9398 if ((TypeNode->getVT() == MVT::i8 && width == 8)
9399 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9400 ExtType = ISD::ZEXTLOAD;
9401 return true;
9402 }
9403 return false;
9404 }
9405 case ISD::Constant:
9406 case ISD::TargetConstant: {
Eric Christopher114fa1c2016-02-29 22:50:49 +00009407 return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
9408 1LL << (width - 1);
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009409 }
9410 }
9411
9412 return true;
9413}
9414
9415// This function does a whole lot of voodoo to determine if the tests are
9416// equivalent without and with a mask. Essentially what happens is that given a
9417// DAG resembling:
9418//
9419// +-------------+ +-------------+ +-------------+ +-------------+
9420// | Input | | AddConstant | | CompConstant| | CC |
9421// +-------------+ +-------------+ +-------------+ +-------------+
9422// | | | |
9423// V V | +----------+
9424// +-------------+ +----+ | |
9425// | ADD | |0xff| | |
9426// +-------------+ +----+ | |
9427// | | | |
9428// V V | |
9429// +-------------+ | |
9430// | AND | | |
9431// +-------------+ | |
9432// | | |
9433// +-----+ | |
9434// | | |
9435// V V V
9436// +-------------+
9437// | CMP |
9438// +-------------+
9439//
9440// The AND node may be safely removed for some combinations of inputs. In
9441// particular we need to take into account the extension type of the Input,
9442// the exact values of AddConstant, CompConstant, and CC, along with the nominal
9443// width of the input (this can work for any width inputs, the above graph is
9444// specific to 8 bits.
9445//
9446// The specific equations were worked out by generating output tables for each
9447// AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
9448// problem was simplified by working with 4 bit inputs, which means we only
9449// needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
9450// extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
9451// patterns present in both extensions (0,7). For every distinct set of
9452// AddConstant and CompConstants bit patterns we can consider the masked and
9453// unmasked versions to be equivalent if the result of this function is true for
9454// all 16 distinct bit patterns of for the current extension type of Input (w0).
9455//
9456// sub w8, w0, w1
9457// and w10, w8, #0x0f
9458// cmp w8, w2
9459// cset w9, AArch64CC
9460// cmp w10, w2
9461// cset w11, AArch64CC
9462// cmp w9, w11
9463// cset w0, eq
9464// ret
9465//
9466// Since the above function shows when the outputs are equivalent it defines
9467// when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
9468// would be expensive to run during compiles. The equations below were written
9469// in a test harness that confirmed they gave equivalent outputs to the above
9470// for all inputs function, so they can be used determine if the removal is
9471// legal instead.
9472//
9473// isEquivalentMaskless() is the code for testing if the AND can be removed
9474// factored out of the DAG recognition as the DAG can take several forms.
9475
David Majnemere61e4bf2016-06-21 05:10:24 +00009476static bool isEquivalentMaskless(unsigned CC, unsigned width,
9477 ISD::LoadExtType ExtType, int AddConstant,
9478 int CompConstant) {
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009479 // By being careful about our equations and only writing the in term
9480 // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
9481 // make them generally applicable to all bit widths.
David Majnemere61e4bf2016-06-21 05:10:24 +00009482 int MaxUInt = (1 << width);
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009483
9484 // For the purposes of these comparisons sign extending the type is
9485 // equivalent to zero extending the add and displacing it by half the integer
9486 // width. Provided we are careful and make sure our equations are valid over
9487 // the whole range we can just adjust the input and avoid writing equations
9488 // for sign extended inputs.
9489 if (ExtType == ISD::SEXTLOAD)
9490 AddConstant -= (1 << (width-1));
9491
9492 switch(CC) {
9493 case AArch64CC::LE:
9494 case AArch64CC::GT: {
9495 if ((AddConstant == 0) ||
9496 (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
9497 (AddConstant >= 0 && CompConstant < 0) ||
9498 (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
9499 return true;
9500 } break;
9501 case AArch64CC::LT:
9502 case AArch64CC::GE: {
9503 if ((AddConstant == 0) ||
9504 (AddConstant >= 0 && CompConstant <= 0) ||
9505 (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
9506 return true;
9507 } break;
9508 case AArch64CC::HI:
9509 case AArch64CC::LS: {
9510 if ((AddConstant >= 0 && CompConstant < 0) ||
9511 (AddConstant <= 0 && CompConstant >= -1 &&
9512 CompConstant < AddConstant + MaxUInt))
9513 return true;
9514 } break;
9515 case AArch64CC::PL:
9516 case AArch64CC::MI: {
9517 if ((AddConstant == 0) ||
9518 (AddConstant > 0 && CompConstant <= 0) ||
9519 (AddConstant < 0 && CompConstant <= AddConstant))
9520 return true;
9521 } break;
9522 case AArch64CC::LO:
9523 case AArch64CC::HS: {
9524 if ((AddConstant >= 0 && CompConstant <= 0) ||
9525 (AddConstant <= 0 && CompConstant >= 0 &&
9526 CompConstant <= AddConstant + MaxUInt))
9527 return true;
9528 } break;
9529 case AArch64CC::EQ:
9530 case AArch64CC::NE: {
9531 if ((AddConstant > 0 && CompConstant < 0) ||
9532 (AddConstant < 0 && CompConstant >= 0 &&
9533 CompConstant < AddConstant + MaxUInt) ||
9534 (AddConstant >= 0 && CompConstant >= 0 &&
9535 CompConstant >= AddConstant) ||
9536 (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
9537
9538 return true;
9539 } break;
9540 case AArch64CC::VS:
9541 case AArch64CC::VC:
9542 case AArch64CC::AL:
9543 case AArch64CC::NV:
9544 return true;
9545 case AArch64CC::Invalid:
9546 break;
9547 }
9548
9549 return false;
9550}
9551
9552static
9553SDValue performCONDCombine(SDNode *N,
9554 TargetLowering::DAGCombinerInfo &DCI,
9555 SelectionDAG &DAG, unsigned CCIndex,
9556 unsigned CmpIndex) {
9557 unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
9558 SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
9559 unsigned CondOpcode = SubsNode->getOpcode();
9560
9561 if (CondOpcode != AArch64ISD::SUBS)
9562 return SDValue();
9563
9564 // There is a SUBS feeding this condition. Is it fed by a mask we can
9565 // use?
9566
9567 SDNode *AndNode = SubsNode->getOperand(0).getNode();
9568 unsigned MaskBits = 0;
9569
9570 if (AndNode->getOpcode() != ISD::AND)
9571 return SDValue();
9572
9573 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
9574 uint32_t CNV = CN->getZExtValue();
9575 if (CNV == 255)
9576 MaskBits = 8;
9577 else if (CNV == 65535)
9578 MaskBits = 16;
9579 }
9580
9581 if (!MaskBits)
9582 return SDValue();
9583
9584 SDValue AddValue = AndNode->getOperand(0);
9585
9586 if (AddValue.getOpcode() != ISD::ADD)
9587 return SDValue();
9588
9589 // The basic dag structure is correct, grab the inputs and validate them.
9590
9591 SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
9592 SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
9593 SDValue SubsInputValue = SubsNode->getOperand(1);
9594
9595 // The mask is present and the provenance of all the values is a smaller type,
9596 // lets see if the mask is superfluous.
9597
9598 if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
9599 !isa<ConstantSDNode>(SubsInputValue.getNode()))
9600 return SDValue();
9601
9602 ISD::LoadExtType ExtType;
9603
9604 if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
9605 !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
9606 !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
9607 return SDValue();
9608
9609 if(!isEquivalentMaskless(CC, MaskBits, ExtType,
9610 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
9611 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
9612 return SDValue();
9613
9614 // The AND is not necessary, remove it.
9615
9616 SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
9617 SubsNode->getValueType(1));
9618 SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
9619
9620 SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
9621 DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
9622
9623 return SDValue(N, 0);
9624}
9625
Tim Northover3b0846e2014-05-24 12:50:23 +00009626// Optimize compare with zero and branch.
9627static SDValue performBRCONDCombine(SDNode *N,
9628 TargetLowering::DAGCombinerInfo &DCI,
9629 SelectionDAG &DAG) {
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00009630 if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3))
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009631 N = NV.getNode();
Tim Northover3b0846e2014-05-24 12:50:23 +00009632 SDValue Chain = N->getOperand(0);
9633 SDValue Dest = N->getOperand(1);
9634 SDValue CCVal = N->getOperand(2);
9635 SDValue Cmp = N->getOperand(3);
9636
9637 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
9638 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
9639 if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
9640 return SDValue();
9641
9642 unsigned CmpOpc = Cmp.getOpcode();
9643 if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
9644 return SDValue();
9645
9646 // Only attempt folding if there is only one use of the flag and no use of the
9647 // value.
9648 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
9649 return SDValue();
9650
9651 SDValue LHS = Cmp.getOperand(0);
9652 SDValue RHS = Cmp.getOperand(1);
9653
9654 assert(LHS.getValueType() == RHS.getValueType() &&
9655 "Expected the value type to be the same for both operands!");
9656 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
9657 return SDValue();
9658
Artyom Skrobov314ee042015-11-25 19:41:11 +00009659 if (isNullConstant(LHS))
Tim Northover3b0846e2014-05-24 12:50:23 +00009660 std::swap(LHS, RHS);
9661
Artyom Skrobov314ee042015-11-25 19:41:11 +00009662 if (!isNullConstant(RHS))
Tim Northover3b0846e2014-05-24 12:50:23 +00009663 return SDValue();
9664
9665 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
9666 LHS.getOpcode() == ISD::SRL)
9667 return SDValue();
9668
9669 // Fold the compare into the branch instruction.
9670 SDValue BR;
9671 if (CC == AArch64CC::EQ)
9672 BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9673 else
9674 BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9675
9676 // Do not add new nodes to DAG combiner worklist.
9677 DCI.CombineTo(N, BR, false);
9678
9679 return SDValue();
9680}
9681
Geoff Berry9e934b02016-01-04 18:55:47 +00009682// Optimize some simple tbz/tbnz cases. Returns the new operand and bit to test
9683// as well as whether the test should be inverted. This code is required to
9684// catch these cases (as opposed to standard dag combines) because
9685// AArch64ISD::TBZ is matched during legalization.
9686static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert,
9687 SelectionDAG &DAG) {
9688
9689 if (!Op->hasOneUse())
9690 return Op;
9691
9692 // We don't handle undef/constant-fold cases below, as they should have
9693 // already been taken care of (e.g. and of 0, test of undefined shifted bits,
9694 // etc.)
9695
9696 // (tbz (trunc x), b) -> (tbz x, b)
9697 // This case is just here to enable more of the below cases to be caught.
9698 if (Op->getOpcode() == ISD::TRUNCATE &&
9699 Bit < Op->getValueType(0).getSizeInBits()) {
9700 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9701 }
9702
9703 if (Op->getNumOperands() != 2)
9704 return Op;
9705
9706 auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
9707 if (!C)
9708 return Op;
9709
9710 switch (Op->getOpcode()) {
9711 default:
9712 return Op;
9713
9714 // (tbz (and x, m), b) -> (tbz x, b)
9715 case ISD::AND:
9716 if ((C->getZExtValue() >> Bit) & 1)
9717 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9718 return Op;
9719
9720 // (tbz (shl x, c), b) -> (tbz x, b-c)
9721 case ISD::SHL:
9722 if (C->getZExtValue() <= Bit &&
9723 (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
9724 Bit = Bit - C->getZExtValue();
9725 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9726 }
9727 return Op;
9728
9729 // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
9730 case ISD::SRA:
9731 Bit = Bit + C->getZExtValue();
9732 if (Bit >= Op->getValueType(0).getSizeInBits())
9733 Bit = Op->getValueType(0).getSizeInBits() - 1;
9734 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9735
9736 // (tbz (srl x, c), b) -> (tbz x, b+c)
9737 case ISD::SRL:
9738 if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
9739 Bit = Bit + C->getZExtValue();
9740 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9741 }
9742 return Op;
9743
9744 // (tbz (xor x, -1), b) -> (tbnz x, b)
9745 case ISD::XOR:
9746 if ((C->getZExtValue() >> Bit) & 1)
9747 Invert = !Invert;
9748 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9749 }
9750}
9751
9752// Optimize test single bit zero/non-zero and branch.
9753static SDValue performTBZCombine(SDNode *N,
9754 TargetLowering::DAGCombinerInfo &DCI,
9755 SelectionDAG &DAG) {
9756 unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
9757 bool Invert = false;
9758 SDValue TestSrc = N->getOperand(1);
9759 SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG);
9760
9761 if (TestSrc == NewTestSrc)
9762 return SDValue();
9763
9764 unsigned NewOpc = N->getOpcode();
9765 if (Invert) {
9766 if (NewOpc == AArch64ISD::TBZ)
9767 NewOpc = AArch64ISD::TBNZ;
9768 else {
9769 assert(NewOpc == AArch64ISD::TBNZ);
9770 NewOpc = AArch64ISD::TBZ;
9771 }
9772 }
9773
9774 SDLoc DL(N);
9775 return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc,
9776 DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3));
9777}
9778
Tim Northover3b0846e2014-05-24 12:50:23 +00009779// vselect (v1i1 setcc) ->
9780// vselect (v1iXX setcc) (XX is the size of the compared operand type)
9781// FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
9782// condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
9783// such VSELECT.
9784static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
9785 SDValue N0 = N->getOperand(0);
9786 EVT CCVT = N0.getValueType();
9787
9788 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
9789 CCVT.getVectorElementType() != MVT::i1)
9790 return SDValue();
9791
9792 EVT ResVT = N->getValueType(0);
9793 EVT CmpVT = N0.getOperand(0).getValueType();
9794 // Only combine when the result type is of the same size as the compared
9795 // operands.
9796 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
9797 return SDValue();
9798
9799 SDValue IfTrue = N->getOperand(1);
9800 SDValue IfFalse = N->getOperand(2);
9801 SDValue SetCC =
9802 DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
9803 N0.getOperand(0), N0.getOperand(1),
9804 cast<CondCodeSDNode>(N0.getOperand(2))->get());
9805 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
9806 IfTrue, IfFalse);
9807}
9808
9809/// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
9810/// the compare-mask instructions rather than going via NZCV, even if LHS and
9811/// RHS are really scalar. This replaces any scalar setcc in the above pattern
9812/// with a vector one followed by a DUP shuffle on the result.
Ahmed Bougachac004c602015-04-27 21:43:12 +00009813static SDValue performSelectCombine(SDNode *N,
9814 TargetLowering::DAGCombinerInfo &DCI) {
9815 SelectionDAG &DAG = DCI.DAG;
Tim Northover3b0846e2014-05-24 12:50:23 +00009816 SDValue N0 = N->getOperand(0);
9817 EVT ResVT = N->getValueType(0);
Tim Northover3c0915e2014-08-29 15:34:58 +00009818
Ahmed Bougachac004c602015-04-27 21:43:12 +00009819 if (N0.getOpcode() != ISD::SETCC)
Tim Northover3c0915e2014-08-29 15:34:58 +00009820 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00009821
Ahmed Bougachac004c602015-04-27 21:43:12 +00009822 // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
9823 // scalar SetCCResultType. We also don't expect vectors, because we assume
9824 // that selects fed by vector SETCCs are canonicalized to VSELECT.
9825 assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
9826 "Scalar-SETCC feeding SELECT has unexpected result type!");
9827
Tim Northoverc1c05ae2014-08-29 13:05:18 +00009828 // If NumMaskElts == 0, the comparison is larger than select result. The
9829 // largest real NEON comparison is 64-bits per lane, which means the result is
9830 // at most 32-bits and an illegal vector. Just bail out for now.
Tim Northover3c0915e2014-08-29 15:34:58 +00009831 EVT SrcVT = N0.getOperand(0).getValueType();
Ahmed Bougachad0ce0582014-12-01 20:59:00 +00009832
9833 // Don't try to do this optimization when the setcc itself has i1 operands.
9834 // There are no legal vectors of i1, so this would be pointless.
9835 if (SrcVT == MVT::i1)
9836 return SDValue();
9837
Tim Northover3c0915e2014-08-29 15:34:58 +00009838 int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
Tim Northoverc1c05ae2014-08-29 13:05:18 +00009839 if (!ResVT.isVector() || NumMaskElts == 0)
Tim Northover3b0846e2014-05-24 12:50:23 +00009840 return SDValue();
9841
Tim Northoverc1c05ae2014-08-29 13:05:18 +00009842 SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
Tim Northover3b0846e2014-05-24 12:50:23 +00009843 EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
9844
Ahmed Bougacha89bba612015-04-27 21:01:20 +00009845 // Also bail out if the vector CCVT isn't the same size as ResVT.
9846 // This can happen if the SETCC operand size doesn't divide the ResVT size
9847 // (e.g., f64 vs v3f32).
9848 if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
9849 return SDValue();
9850
Ahmed Bougachac004c602015-04-27 21:43:12 +00009851 // Make sure we didn't create illegal types, if we're not supposed to.
9852 assert(DCI.isBeforeLegalize() ||
9853 DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
9854
Tim Northover3b0846e2014-05-24 12:50:23 +00009855 // First perform a vector comparison, where lane 0 is the one we're interested
9856 // in.
Tim Northoverc1c05ae2014-08-29 13:05:18 +00009857 SDLoc DL(N0);
Tim Northover3b0846e2014-05-24 12:50:23 +00009858 SDValue LHS =
9859 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
9860 SDValue RHS =
9861 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
9862 SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
9863
9864 // Now duplicate the comparison mask we want across all other lanes.
9865 SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
9866 SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask.data());
Tim Northoverc1c05ae2014-08-29 13:05:18 +00009867 Mask = DAG.getNode(ISD::BITCAST, DL,
9868 ResVT.changeVectorElementTypeToInteger(), Mask);
Tim Northover3b0846e2014-05-24 12:50:23 +00009869
9870 return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
9871}
9872
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009873/// Get rid of unnecessary NVCASTs (that don't change the type).
9874static SDValue performNVCASTCombine(SDNode *N) {
9875 if (N->getValueType(0) == N->getOperand(0).getValueType())
9876 return N->getOperand(0);
9877
9878 return SDValue();
9879}
9880
Tim Northover3b0846e2014-05-24 12:50:23 +00009881SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
9882 DAGCombinerInfo &DCI) const {
9883 SelectionDAG &DAG = DCI.DAG;
9884 switch (N->getOpcode()) {
9885 default:
9886 break;
9887 case ISD::ADD:
9888 case ISD::SUB:
9889 return performAddSubLongCombine(N, DCI, DAG);
9890 case ISD::XOR:
9891 return performXorCombine(N, DAG, DCI, Subtarget);
9892 case ISD::MUL:
9893 return performMulCombine(N, DAG, DCI, Subtarget);
9894 case ISD::SINT_TO_FP:
9895 case ISD::UINT_TO_FP:
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00009896 return performIntToFpCombine(N, DAG, Subtarget);
Chad Rosierfa30c9b2015-10-07 17:39:18 +00009897 case ISD::FP_TO_SINT:
9898 case ISD::FP_TO_UINT:
9899 return performFpToIntCombine(N, DAG, Subtarget);
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00009900 case ISD::FDIV:
9901 return performFDivCombine(N, DAG, Subtarget);
Tim Northover3b0846e2014-05-24 12:50:23 +00009902 case ISD::OR:
9903 return performORCombine(N, DCI, Subtarget);
Chad Rosier14aa2ad2016-05-26 19:41:33 +00009904 case ISD::SRL:
9905 return performSRLCombine(N, DCI);
Tim Northover3b0846e2014-05-24 12:50:23 +00009906 case ISD::INTRINSIC_WO_CHAIN:
9907 return performIntrinsicCombine(N, DCI, Subtarget);
9908 case ISD::ANY_EXTEND:
9909 case ISD::ZERO_EXTEND:
9910 case ISD::SIGN_EXTEND:
9911 return performExtendCombine(N, DCI, DAG);
9912 case ISD::BITCAST:
9913 return performBitcastCombine(N, DCI, DAG);
9914 case ISD::CONCAT_VECTORS:
9915 return performConcatVectorsCombine(N, DCI, DAG);
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009916 case ISD::SELECT: {
9917 SDValue RV = performSelectCombine(N, DCI);
9918 if (!RV.getNode())
9919 RV = performAcrossLaneMinMaxReductionCombine(N, DAG, Subtarget);
9920 return RV;
9921 }
Tim Northover3b0846e2014-05-24 12:50:23 +00009922 case ISD::VSELECT:
9923 return performVSelectCombine(N, DCI.DAG);
Tim Northover339c83e2015-11-10 00:44:23 +00009924 case ISD::LOAD:
9925 if (performTBISimplification(N->getOperand(1), DCI, DAG))
9926 return SDValue(N, 0);
9927 break;
Tim Northover3b0846e2014-05-24 12:50:23 +00009928 case ISD::STORE:
9929 return performSTORECombine(N, DCI, DAG, Subtarget);
9930 case AArch64ISD::BRCOND:
9931 return performBRCONDCombine(N, DCI, DAG);
Geoff Berry9e934b02016-01-04 18:55:47 +00009932 case AArch64ISD::TBNZ:
9933 case AArch64ISD::TBZ:
9934 return performTBZCombine(N, DCI, DAG);
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009935 case AArch64ISD::CSEL:
9936 return performCONDCombine(N, DCI, DAG, 2, 3);
Tim Northover3b0846e2014-05-24 12:50:23 +00009937 case AArch64ISD::DUP:
9938 return performPostLD1Combine(N, DCI, false);
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009939 case AArch64ISD::NVCAST:
9940 return performNVCASTCombine(N);
Tim Northover3b0846e2014-05-24 12:50:23 +00009941 case ISD::INSERT_VECTOR_ELT:
9942 return performPostLD1Combine(N, DCI, true);
Chad Rosier6c36eff2015-09-03 18:13:57 +00009943 case ISD::EXTRACT_VECTOR_ELT:
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009944 return performAcrossLaneAddReductionCombine(N, DAG, Subtarget);
Tim Northover3b0846e2014-05-24 12:50:23 +00009945 case ISD::INTRINSIC_VOID:
9946 case ISD::INTRINSIC_W_CHAIN:
9947 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9948 case Intrinsic::aarch64_neon_ld2:
9949 case Intrinsic::aarch64_neon_ld3:
9950 case Intrinsic::aarch64_neon_ld4:
9951 case Intrinsic::aarch64_neon_ld1x2:
9952 case Intrinsic::aarch64_neon_ld1x3:
9953 case Intrinsic::aarch64_neon_ld1x4:
9954 case Intrinsic::aarch64_neon_ld2lane:
9955 case Intrinsic::aarch64_neon_ld3lane:
9956 case Intrinsic::aarch64_neon_ld4lane:
9957 case Intrinsic::aarch64_neon_ld2r:
9958 case Intrinsic::aarch64_neon_ld3r:
9959 case Intrinsic::aarch64_neon_ld4r:
9960 case Intrinsic::aarch64_neon_st2:
9961 case Intrinsic::aarch64_neon_st3:
9962 case Intrinsic::aarch64_neon_st4:
9963 case Intrinsic::aarch64_neon_st1x2:
9964 case Intrinsic::aarch64_neon_st1x3:
9965 case Intrinsic::aarch64_neon_st1x4:
9966 case Intrinsic::aarch64_neon_st2lane:
9967 case Intrinsic::aarch64_neon_st3lane:
9968 case Intrinsic::aarch64_neon_st4lane:
9969 return performNEONPostLDSTCombine(N, DCI, DAG);
9970 default:
9971 break;
9972 }
9973 }
9974 return SDValue();
9975}
9976
9977// Check if the return value is used as only a return value, as otherwise
9978// we can't perform a tail-call. In particular, we need to check for
9979// target ISD nodes that are returns and any other "odd" constructs
9980// that the generic analysis code won't necessarily catch.
9981bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
9982 SDValue &Chain) const {
9983 if (N->getNumValues() != 1)
9984 return false;
9985 if (!N->hasNUsesOfValue(1, 0))
9986 return false;
9987
9988 SDValue TCChain = Chain;
9989 SDNode *Copy = *N->use_begin();
9990 if (Copy->getOpcode() == ISD::CopyToReg) {
9991 // If the copy has a glue operand, we conservatively assume it isn't safe to
9992 // perform a tail call.
9993 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
9994 MVT::Glue)
9995 return false;
9996 TCChain = Copy->getOperand(0);
9997 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
9998 return false;
9999
10000 bool HasRet = false;
10001 for (SDNode *Node : Copy->uses()) {
10002 if (Node->getOpcode() != AArch64ISD::RET_FLAG)
10003 return false;
10004 HasRet = true;
10005 }
10006
10007 if (!HasRet)
10008 return false;
10009
10010 Chain = TCChain;
10011 return true;
10012}
10013
10014// Return whether the an instruction can potentially be optimized to a tail
10015// call. This will cause the optimizers to attempt to move, or duplicate,
10016// return instructions to help enable tail call optimizations for this
10017// instruction.
10018bool AArch64TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
Eric Christopher114fa1c2016-02-29 22:50:49 +000010019 return CI->isTailCall();
Tim Northover3b0846e2014-05-24 12:50:23 +000010020}
10021
10022bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
10023 SDValue &Offset,
10024 ISD::MemIndexedMode &AM,
10025 bool &IsInc,
10026 SelectionDAG &DAG) const {
10027 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
10028 return false;
10029
10030 Base = Op->getOperand(0);
10031 // All of the indexed addressing mode instructions take a signed
10032 // 9 bit immediate offset.
10033 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
10034 int64_t RHSC = (int64_t)RHS->getZExtValue();
10035 if (RHSC >= 256 || RHSC <= -256)
10036 return false;
10037 IsInc = (Op->getOpcode() == ISD::ADD);
10038 Offset = Op->getOperand(1);
10039 return true;
10040 }
10041 return false;
10042}
10043
10044bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10045 SDValue &Offset,
10046 ISD::MemIndexedMode &AM,
10047 SelectionDAG &DAG) const {
10048 EVT VT;
10049 SDValue Ptr;
10050 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10051 VT = LD->getMemoryVT();
10052 Ptr = LD->getBasePtr();
10053 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10054 VT = ST->getMemoryVT();
10055 Ptr = ST->getBasePtr();
10056 } else
10057 return false;
10058
10059 bool IsInc;
10060 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
10061 return false;
10062 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
10063 return true;
10064}
10065
10066bool AArch64TargetLowering::getPostIndexedAddressParts(
10067 SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
10068 ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
10069 EVT VT;
10070 SDValue Ptr;
10071 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10072 VT = LD->getMemoryVT();
10073 Ptr = LD->getBasePtr();
10074 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10075 VT = ST->getMemoryVT();
10076 Ptr = ST->getBasePtr();
10077 } else
10078 return false;
10079
10080 bool IsInc;
10081 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
10082 return false;
10083 // Post-indexing updates the base, so it's not a valid transform
10084 // if that's not the same as the load's pointer.
10085 if (Ptr != Base)
10086 return false;
10087 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
10088 return true;
10089}
10090
Tim Northoverf8bfe212014-07-18 13:07:05 +000010091static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
10092 SelectionDAG &DAG) {
Tim Northoverf8bfe212014-07-18 13:07:05 +000010093 SDLoc DL(N);
10094 SDValue Op = N->getOperand(0);
Ahmed Bougacha87946322014-12-01 20:52:32 +000010095
10096 if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
10097 return;
10098
Tim Northoverf8bfe212014-07-18 13:07:05 +000010099 Op = SDValue(
10100 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
10101 DAG.getUNDEF(MVT::i32), Op,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010102 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
Tim Northoverf8bfe212014-07-18 13:07:05 +000010103 0);
10104 Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
10105 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
10106}
10107
Charlie Turner434d4592015-10-16 15:38:25 +000010108static void ReplaceReductionResults(SDNode *N,
10109 SmallVectorImpl<SDValue> &Results,
10110 SelectionDAG &DAG, unsigned InterOp,
10111 unsigned AcrossOp) {
10112 EVT LoVT, HiVT;
10113 SDValue Lo, Hi;
10114 SDLoc dl(N);
10115 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
10116 std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
10117 SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
10118 SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
10119 Results.push_back(SplitVal);
10120}
10121
Tim Northovercdf15292016-04-14 17:03:29 +000010122static void ReplaceCMP_SWAP_128Results(SDNode *N,
10123 SmallVectorImpl<SDValue> & Results,
10124 SelectionDAG &DAG) {
10125 assert(N->getValueType(0) == MVT::i128 &&
10126 "AtomicCmpSwap on types less than 128 should be legal");
10127 SDValue Ops[] = {N->getOperand(1),
10128 N->getOperand(2)->getOperand(0),
10129 N->getOperand(2)->getOperand(1),
10130 N->getOperand(3)->getOperand(0),
10131 N->getOperand(3)->getOperand(1),
10132 N->getOperand(0)};
10133 SDNode *CmpSwap = DAG.getMachineNode(
10134 AArch64::CMP_SWAP_128, SDLoc(N),
10135 DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops);
10136
10137 MachineFunction &MF = DAG.getMachineFunction();
10138 MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1);
10139 MemOp[0] = cast<MemSDNode>(N)->getMemOperand();
10140 cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1);
10141
10142 Results.push_back(SDValue(CmpSwap, 0));
10143 Results.push_back(SDValue(CmpSwap, 1));
10144 Results.push_back(SDValue(CmpSwap, 3));
10145}
10146
Tim Northover3b0846e2014-05-24 12:50:23 +000010147void AArch64TargetLowering::ReplaceNodeResults(
10148 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
10149 switch (N->getOpcode()) {
10150 default:
10151 llvm_unreachable("Don't know how to custom expand this");
Tim Northoverf8bfe212014-07-18 13:07:05 +000010152 case ISD::BITCAST:
10153 ReplaceBITCASTResults(N, Results, DAG);
10154 return;
Charlie Turner434d4592015-10-16 15:38:25 +000010155 case AArch64ISD::SADDV:
10156 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
10157 return;
10158 case AArch64ISD::UADDV:
10159 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
10160 return;
10161 case AArch64ISD::SMINV:
10162 ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
10163 return;
10164 case AArch64ISD::UMINV:
10165 ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
10166 return;
10167 case AArch64ISD::SMAXV:
10168 ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
10169 return;
10170 case AArch64ISD::UMAXV:
10171 ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
10172 return;
Tim Northover3b0846e2014-05-24 12:50:23 +000010173 case ISD::FP_TO_UINT:
10174 case ISD::FP_TO_SINT:
10175 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
10176 // Let normal code take care of it by not adding anything to Results.
10177 return;
Tim Northovercdf15292016-04-14 17:03:29 +000010178 case ISD::ATOMIC_CMP_SWAP:
10179 ReplaceCMP_SWAP_128Results(N, Results, DAG);
10180 return;
Tim Northover3b0846e2014-05-24 12:50:23 +000010181 }
10182}
10183
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +000010184bool AArch64TargetLowering::useLoadStackGuardNode() const {
Tim Shene885d5e2016-04-19 19:40:37 +000010185 if (!Subtarget->isTargetAndroid())
10186 return true;
10187 return TargetLowering::useLoadStackGuardNode();
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +000010188}
10189
Sanjay Patel1dd15592015-07-28 23:05:48 +000010190unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
Hao Liu44e5d7a2014-11-21 06:39:58 +000010191 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
10192 // reciprocal if there are three or more FDIVs.
Sanjay Patel1dd15592015-07-28 23:05:48 +000010193 return 3;
Hao Liu44e5d7a2014-11-21 06:39:58 +000010194}
10195
Chandler Carruth9d010ff2014-07-03 00:23:43 +000010196TargetLoweringBase::LegalizeTypeAction
10197AArch64TargetLowering::getPreferredVectorAction(EVT VT) const {
10198 MVT SVT = VT.getSimpleVT();
10199 // During type legalization, we prefer to widen v1i8, v1i16, v1i32 to v8i8,
10200 // v4i16, v2i32 instead of to promote.
10201 if (SVT == MVT::v1i8 || SVT == MVT::v1i16 || SVT == MVT::v1i32
10202 || SVT == MVT::v1f32)
10203 return TypeWidenVector;
10204
10205 return TargetLoweringBase::getPreferredVectorAction(VT);
10206}
10207
Robin Morisseted3d48f2014-09-03 21:29:59 +000010208// Loads and stores less than 128-bits are already atomic; ones above that
10209// are doomed anyway, so defer to the default libcall and blame the OS when
10210// things go wrong.
10211bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
10212 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
10213 return Size == 128;
10214}
10215
10216// Loads and stores less than 128-bits are already atomic; ones above that
10217// are doomed anyway, so defer to the default libcall and blame the OS when
10218// things go wrong.
Ahmed Bougacha52468672015-09-11 17:08:28 +000010219TargetLowering::AtomicExpansionKind
10220AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
Robin Morisseted3d48f2014-09-03 21:29:59 +000010221 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
Ahmed Bougacha52468672015-09-11 17:08:28 +000010222 return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
Robin Morisseted3d48f2014-09-03 21:29:59 +000010223}
10224
10225// For the real atomic operations, we have ldxr/stxr up to 128 bits,
Ahmed Bougacha52468672015-09-11 17:08:28 +000010226TargetLowering::AtomicExpansionKind
JF Bastienf14889e2015-03-04 15:47:57 +000010227AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
Robin Morisseted3d48f2014-09-03 21:29:59 +000010228 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
Ahmed Bougacha9d677132015-09-11 17:08:17 +000010229 return Size <= 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
Robin Morisseted3d48f2014-09-03 21:29:59 +000010230}
10231
Ahmed Bougacha52468672015-09-11 17:08:28 +000010232bool AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
10233 AtomicCmpXchgInst *AI) const {
Tim Northovercdf15292016-04-14 17:03:29 +000010234 // At -O0, fast-regalloc cannot cope with the live vregs necessary to
10235 // implement cmpxchg without spilling. If the address being exchanged is also
10236 // on the stack and close enough to the spill slot, this can lead to a
10237 // situation where the monitor always gets cleared and the atomic operation
10238 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
10239 return getTargetMachine().getOptLevel() != 0;
Robin Morisset25c8e312014-09-17 00:06:58 +000010240}
10241
Tim Northover3b0846e2014-05-24 12:50:23 +000010242Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
10243 AtomicOrdering Ord) const {
10244 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10245 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
JF Bastien800f87a2016-04-06 21:19:33 +000010246 bool IsAcquire = isAcquireOrStronger(Ord);
Tim Northover3b0846e2014-05-24 12:50:23 +000010247
10248 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
10249 // intrinsic must return {i64, i64} and we have to recombine them into a
10250 // single i128 here.
10251 if (ValTy->getPrimitiveSizeInBits() == 128) {
10252 Intrinsic::ID Int =
10253 IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
10254 Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int);
10255
10256 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10257 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
10258
10259 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
10260 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
10261 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
10262 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
10263 return Builder.CreateOr(
10264 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
10265 }
10266
10267 Type *Tys[] = { Addr->getType() };
10268 Intrinsic::ID Int =
10269 IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
10270 Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int, Tys);
10271
10272 return Builder.CreateTruncOrBitCast(
10273 Builder.CreateCall(Ldxr, Addr),
10274 cast<PointerType>(Addr->getType())->getElementType());
10275}
10276
Ahmed Bougacha07a844d2015-09-22 17:21:44 +000010277void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
10278 IRBuilder<> &Builder) const {
10279 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10280 Builder.CreateCall(
10281 llvm::Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
10282}
10283
Tim Northover3b0846e2014-05-24 12:50:23 +000010284Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
10285 Value *Val, Value *Addr,
10286 AtomicOrdering Ord) const {
10287 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
JF Bastien800f87a2016-04-06 21:19:33 +000010288 bool IsRelease = isReleaseOrStronger(Ord);
Tim Northover3b0846e2014-05-24 12:50:23 +000010289
10290 // Since the intrinsics must have legal type, the i128 intrinsics take two
10291 // parameters: "i64, i64". We must marshal Val into the appropriate form
10292 // before the call.
10293 if (Val->getType()->getPrimitiveSizeInBits() == 128) {
10294 Intrinsic::ID Int =
10295 IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
10296 Function *Stxr = Intrinsic::getDeclaration(M, Int);
10297 Type *Int64Ty = Type::getInt64Ty(M->getContext());
10298
10299 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
10300 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
10301 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
David Blaikieff6409d2015-05-18 22:13:54 +000010302 return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
Tim Northover3b0846e2014-05-24 12:50:23 +000010303 }
10304
10305 Intrinsic::ID Int =
10306 IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
10307 Type *Tys[] = { Addr->getType() };
10308 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
10309
David Blaikieff6409d2015-05-18 22:13:54 +000010310 return Builder.CreateCall(Stxr,
10311 {Builder.CreateZExtOrBitCast(
10312 Val, Stxr->getFunctionType()->getParamType(0)),
10313 Addr});
Tim Northover3b0846e2014-05-24 12:50:23 +000010314}
Tim Northover3c55cca2014-11-27 21:02:42 +000010315
10316bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
10317 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
10318 return Ty->isArrayTy();
10319}
Matthias Braunaf7d7702015-07-16 20:02:37 +000010320
10321bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
10322 EVT) const {
10323 return false;
10324}
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000010325
Tim Shen00127562016-04-08 21:26:31 +000010326Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const {
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +000010327 if (!Subtarget->isTargetAndroid())
Tim Shen00127562016-04-08 21:26:31 +000010328 return TargetLowering::getIRStackGuard(IRB);
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +000010329
10330 // Android provides a fixed TLS slot for the stack cookie. See the definition
10331 // of TLS_SLOT_STACK_GUARD in
10332 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
10333 const unsigned TlsOffset = 0x28;
10334 Module *M = IRB.GetInsertBlock()->getParent()->getParent();
10335 Function *ThreadPointerFunc =
Marcin Koscielnicki3fdc2572016-04-19 20:51:05 +000010336 Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +000010337 return IRB.CreatePointerCast(
10338 IRB.CreateConstGEP1_32(IRB.CreateCall(ThreadPointerFunc), TlsOffset),
10339 Type::getInt8PtrTy(IRB.getContext())->getPointerTo(0));
10340}
10341
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000010342Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
10343 if (!Subtarget->isTargetAndroid())
10344 return TargetLowering::getSafeStackPointerLocation(IRB);
10345
10346 // Android provides a fixed TLS slot for the SafeStack pointer. See the
10347 // definition of TLS_SLOT_SAFESTACK in
10348 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
10349 const unsigned TlsOffset = 0x48;
10350 Module *M = IRB.GetInsertBlock()->getParent()->getParent();
10351 Function *ThreadPointerFunc =
Marcin Koscielnicki3fdc2572016-04-19 20:51:05 +000010352 Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000010353 return IRB.CreatePointerCast(
10354 IRB.CreateConstGEP1_32(IRB.CreateCall(ThreadPointerFunc), TlsOffset),
10355 Type::getInt8PtrTy(IRB.getContext())->getPointerTo(0));
10356}
Manman Rencbe4f942015-12-16 21:04:19 +000010357
10358void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
10359 // Update IsSplitCSR in AArch64unctionInfo.
10360 AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>();
10361 AFI->setIsSplitCSR(true);
10362}
10363
10364void AArch64TargetLowering::insertCopiesSplitCSR(
10365 MachineBasicBlock *Entry,
10366 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
10367 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
10368 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
10369 if (!IStart)
10370 return;
10371
10372 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10373 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
Manman Ren4632e8e2016-01-15 20:13:28 +000010374 MachineBasicBlock::iterator MBBI = Entry->begin();
Manman Rencbe4f942015-12-16 21:04:19 +000010375 for (const MCPhysReg *I = IStart; *I; ++I) {
10376 const TargetRegisterClass *RC = nullptr;
10377 if (AArch64::GPR64RegClass.contains(*I))
10378 RC = &AArch64::GPR64RegClass;
10379 else if (AArch64::FPR64RegClass.contains(*I))
10380 RC = &AArch64::FPR64RegClass;
10381 else
10382 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
10383
10384 unsigned NewVR = MRI->createVirtualRegister(RC);
10385 // Create copy from CSR to a virtual register.
10386 // FIXME: this currently does not emit CFI pseudo-instructions, it works
10387 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
10388 // nounwind. If we want to generalize this later, we may need to emit
10389 // CFI pseudo-instructions.
10390 assert(Entry->getParent()->getFunction()->hasFnAttribute(
10391 Attribute::NoUnwind) &&
10392 "Function should be nounwind in insertCopiesSplitCSR!");
10393 Entry->addLiveIn(*I);
Manman Ren4632e8e2016-01-15 20:13:28 +000010394 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
Manman Rencbe4f942015-12-16 21:04:19 +000010395 .addReg(*I);
10396
Manman Ren4632e8e2016-01-15 20:13:28 +000010397 // Insert the copy-back instructions right before the terminator.
Manman Rencbe4f942015-12-16 21:04:19 +000010398 for (auto *Exit : Exits)
Manman Ren4632e8e2016-01-15 20:13:28 +000010399 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
10400 TII->get(TargetOpcode::COPY), *I)
Manman Rencbe4f942015-12-16 21:04:19 +000010401 .addReg(NewVR);
10402 }
10403}
Haicheng Wu6a6bc752016-03-28 18:17:07 +000010404
10405bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeSet Attr) const {
10406 // Integer division on AArch64 is expensive. However, when aggressively
10407 // optimizing for code size, we prefer to use a div instruction, as it is
10408 // usually smaller than the alternative sequence.
10409 // The exception to this is vector division. Since AArch64 doesn't have vector
10410 // integer division, leaving the division as-is is a loss even in terms of
10411 // size, because it will have to be scalarized, while the alternative code
10412 // sequence can be performed in vector form.
10413 bool OptSize =
10414 Attr.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
10415 return OptSize && !VT.isVector();
10416}