blob: c8200c23d4916b980ee5a4685f19057ef71eb4b0 [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
141 // Virtually no operation on f128 is legal, but LLVM can't expand them when
142 // there's a valid register class, so we need custom operations in most cases.
143 setOperationAction(ISD::FABS, MVT::f128, Expand);
144 setOperationAction(ISD::FADD, MVT::f128, Custom);
145 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
146 setOperationAction(ISD::FCOS, MVT::f128, Expand);
147 setOperationAction(ISD::FDIV, MVT::f128, Custom);
148 setOperationAction(ISD::FMA, MVT::f128, Expand);
149 setOperationAction(ISD::FMUL, MVT::f128, Custom);
150 setOperationAction(ISD::FNEG, MVT::f128, Expand);
151 setOperationAction(ISD::FPOW, MVT::f128, Expand);
152 setOperationAction(ISD::FREM, MVT::f128, Expand);
153 setOperationAction(ISD::FRINT, MVT::f128, Expand);
154 setOperationAction(ISD::FSIN, MVT::f128, Expand);
155 setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
156 setOperationAction(ISD::FSQRT, MVT::f128, Expand);
157 setOperationAction(ISD::FSUB, MVT::f128, Custom);
158 setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
159 setOperationAction(ISD::SETCC, MVT::f128, Custom);
160 setOperationAction(ISD::BR_CC, MVT::f128, Custom);
161 setOperationAction(ISD::SELECT, MVT::f128, Custom);
162 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
163 setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
164
165 // Lowering for many of the conversions is actually specified by the non-f128
166 // type. The LowerXXX function will be trivial when f128 isn't involved.
167 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
168 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
169 setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
170 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
171 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
172 setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
173 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
174 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
175 setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
176 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
177 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
178 setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
179 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
180 setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
181
182 // Variable arguments.
183 setOperationAction(ISD::VASTART, MVT::Other, Custom);
184 setOperationAction(ISD::VAARG, MVT::Other, Custom);
185 setOperationAction(ISD::VACOPY, MVT::Other, Custom);
186 setOperationAction(ISD::VAEND, MVT::Other, Expand);
187
188 // Variable-sized objects.
189 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
190 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
191 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
192
Tim Northover3b0846e2014-05-24 12:50:23 +0000193 // Constant pool entries
194 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
195
196 // BlockAddress
197 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
198
199 // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
200 setOperationAction(ISD::ADDC, MVT::i32, Custom);
201 setOperationAction(ISD::ADDE, MVT::i32, Custom);
202 setOperationAction(ISD::SUBC, MVT::i32, Custom);
203 setOperationAction(ISD::SUBE, MVT::i32, Custom);
204 setOperationAction(ISD::ADDC, MVT::i64, Custom);
205 setOperationAction(ISD::ADDE, MVT::i64, Custom);
206 setOperationAction(ISD::SUBC, MVT::i64, Custom);
207 setOperationAction(ISD::SUBE, MVT::i64, Custom);
208
209 // AArch64 lacks both left-rotate and popcount instructions.
210 setOperationAction(ISD::ROTL, MVT::i32, Expand);
211 setOperationAction(ISD::ROTL, MVT::i64, Expand);
Charlie Turner458e79b2015-10-27 10:25:20 +0000212 for (MVT VT : MVT::vector_valuetypes()) {
213 setOperationAction(ISD::ROTL, VT, Expand);
214 setOperationAction(ISD::ROTR, VT, Expand);
215 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000216
217 // AArch64 doesn't have {U|S}MUL_LOHI.
218 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
219 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
220
221
Tim Northover3b0846e2014-05-24 12:50:23 +0000222 setOperationAction(ISD::CTPOP, MVT::i32, Custom);
223 setOperationAction(ISD::CTPOP, MVT::i64, Custom);
224
225 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
226 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
Chad Rosierf3491492015-12-04 21:38:44 +0000227 for (MVT VT : MVT::vector_valuetypes()) {
228 setOperationAction(ISD::SDIVREM, VT, Expand);
229 setOperationAction(ISD::UDIVREM, VT, Expand);
230 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000231 setOperationAction(ISD::SREM, MVT::i32, Expand);
232 setOperationAction(ISD::SREM, MVT::i64, Expand);
233 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
234 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
235 setOperationAction(ISD::UREM, MVT::i32, Expand);
236 setOperationAction(ISD::UREM, MVT::i64, Expand);
237
238 // Custom lower Add/Sub/Mul with overflow.
239 setOperationAction(ISD::SADDO, MVT::i32, Custom);
240 setOperationAction(ISD::SADDO, MVT::i64, Custom);
241 setOperationAction(ISD::UADDO, MVT::i32, Custom);
242 setOperationAction(ISD::UADDO, MVT::i64, Custom);
243 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
244 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
245 setOperationAction(ISD::USUBO, MVT::i32, Custom);
246 setOperationAction(ISD::USUBO, MVT::i64, Custom);
247 setOperationAction(ISD::SMULO, MVT::i32, Custom);
248 setOperationAction(ISD::SMULO, MVT::i64, Custom);
249 setOperationAction(ISD::UMULO, MVT::i32, Custom);
250 setOperationAction(ISD::UMULO, MVT::i64, Custom);
251
252 setOperationAction(ISD::FSIN, MVT::f32, Expand);
253 setOperationAction(ISD::FSIN, MVT::f64, Expand);
254 setOperationAction(ISD::FCOS, MVT::f32, Expand);
255 setOperationAction(ISD::FCOS, MVT::f64, Expand);
256 setOperationAction(ISD::FPOW, MVT::f32, Expand);
257 setOperationAction(ISD::FPOW, MVT::f64, Expand);
258 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
259 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
260
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +0000261 // f16 is a storage-only type, always promote it to f32.
262 setOperationAction(ISD::SETCC, MVT::f16, Promote);
263 setOperationAction(ISD::BR_CC, MVT::f16, Promote);
264 setOperationAction(ISD::SELECT_CC, MVT::f16, Promote);
265 setOperationAction(ISD::SELECT, MVT::f16, Promote);
266 setOperationAction(ISD::FADD, MVT::f16, Promote);
267 setOperationAction(ISD::FSUB, MVT::f16, Promote);
268 setOperationAction(ISD::FMUL, MVT::f16, Promote);
269 setOperationAction(ISD::FDIV, MVT::f16, Promote);
270 setOperationAction(ISD::FREM, MVT::f16, Promote);
271 setOperationAction(ISD::FMA, MVT::f16, Promote);
272 setOperationAction(ISD::FNEG, MVT::f16, Promote);
273 setOperationAction(ISD::FABS, MVT::f16, Promote);
274 setOperationAction(ISD::FCEIL, MVT::f16, Promote);
275 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote);
276 setOperationAction(ISD::FCOS, MVT::f16, Promote);
277 setOperationAction(ISD::FFLOOR, MVT::f16, Promote);
278 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote);
279 setOperationAction(ISD::FPOW, MVT::f16, Promote);
280 setOperationAction(ISD::FPOWI, MVT::f16, Promote);
281 setOperationAction(ISD::FRINT, MVT::f16, Promote);
282 setOperationAction(ISD::FSIN, MVT::f16, Promote);
283 setOperationAction(ISD::FSINCOS, MVT::f16, Promote);
284 setOperationAction(ISD::FSQRT, MVT::f16, Promote);
285 setOperationAction(ISD::FEXP, MVT::f16, Promote);
286 setOperationAction(ISD::FEXP2, MVT::f16, Promote);
287 setOperationAction(ISD::FLOG, MVT::f16, Promote);
288 setOperationAction(ISD::FLOG2, MVT::f16, Promote);
289 setOperationAction(ISD::FLOG10, MVT::f16, Promote);
290 setOperationAction(ISD::FROUND, MVT::f16, Promote);
291 setOperationAction(ISD::FTRUNC, MVT::f16, Promote);
292 setOperationAction(ISD::FMINNUM, MVT::f16, Promote);
293 setOperationAction(ISD::FMAXNUM, MVT::f16, Promote);
James Molloy63be1982015-08-14 09:08:50 +0000294 setOperationAction(ISD::FMINNAN, MVT::f16, Promote);
295 setOperationAction(ISD::FMAXNAN, MVT::f16, Promote);
Oliver Stannardf5469be2014-08-18 14:22:39 +0000296
Oliver Stannard89d15422014-08-27 16:16:04 +0000297 // v4f16 is also a storage-only type, so promote it to v4f32 when that is
298 // known to be safe.
299 setOperationAction(ISD::FADD, MVT::v4f16, Promote);
300 setOperationAction(ISD::FSUB, MVT::v4f16, Promote);
301 setOperationAction(ISD::FMUL, MVT::v4f16, Promote);
302 setOperationAction(ISD::FDIV, MVT::v4f16, Promote);
303 setOperationAction(ISD::FP_EXTEND, MVT::v4f16, Promote);
304 setOperationAction(ISD::FP_ROUND, MVT::v4f16, Promote);
305 AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32);
306 AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32);
307 AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32);
308 AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32);
309 AddPromotedToType(ISD::FP_EXTEND, MVT::v4f16, MVT::v4f32);
310 AddPromotedToType(ISD::FP_ROUND, MVT::v4f16, MVT::v4f32);
311
312 // Expand all other v4f16 operations.
313 // FIXME: We could generate better code by promoting some operations to
314 // a pair of v4f32s
315 setOperationAction(ISD::FABS, MVT::v4f16, Expand);
316 setOperationAction(ISD::FCEIL, MVT::v4f16, Expand);
317 setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand);
318 setOperationAction(ISD::FCOS, MVT::v4f16, Expand);
319 setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand);
320 setOperationAction(ISD::FMA, MVT::v4f16, Expand);
321 setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand);
322 setOperationAction(ISD::FNEG, MVT::v4f16, Expand);
323 setOperationAction(ISD::FPOW, MVT::v4f16, Expand);
324 setOperationAction(ISD::FPOWI, MVT::v4f16, Expand);
325 setOperationAction(ISD::FREM, MVT::v4f16, Expand);
326 setOperationAction(ISD::FROUND, MVT::v4f16, Expand);
327 setOperationAction(ISD::FRINT, MVT::v4f16, Expand);
328 setOperationAction(ISD::FSIN, MVT::v4f16, Expand);
329 setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand);
330 setOperationAction(ISD::FSQRT, MVT::v4f16, Expand);
331 setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand);
332 setOperationAction(ISD::SETCC, MVT::v4f16, Expand);
333 setOperationAction(ISD::BR_CC, MVT::v4f16, Expand);
334 setOperationAction(ISD::SELECT, MVT::v4f16, Expand);
335 setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand);
336 setOperationAction(ISD::FEXP, MVT::v4f16, Expand);
337 setOperationAction(ISD::FEXP2, MVT::v4f16, Expand);
338 setOperationAction(ISD::FLOG, MVT::v4f16, Expand);
339 setOperationAction(ISD::FLOG2, MVT::v4f16, Expand);
340 setOperationAction(ISD::FLOG10, MVT::v4f16, Expand);
341
342
343 // v8f16 is also a storage-only type, so expand it.
344 setOperationAction(ISD::FABS, MVT::v8f16, Expand);
345 setOperationAction(ISD::FADD, MVT::v8f16, Expand);
346 setOperationAction(ISD::FCEIL, MVT::v8f16, Expand);
347 setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand);
348 setOperationAction(ISD::FCOS, MVT::v8f16, Expand);
349 setOperationAction(ISD::FDIV, MVT::v8f16, Expand);
350 setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand);
351 setOperationAction(ISD::FMA, MVT::v8f16, Expand);
352 setOperationAction(ISD::FMUL, MVT::v8f16, Expand);
353 setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand);
354 setOperationAction(ISD::FNEG, MVT::v8f16, Expand);
355 setOperationAction(ISD::FPOW, MVT::v8f16, Expand);
356 setOperationAction(ISD::FPOWI, MVT::v8f16, Expand);
357 setOperationAction(ISD::FREM, MVT::v8f16, Expand);
358 setOperationAction(ISD::FROUND, MVT::v8f16, Expand);
359 setOperationAction(ISD::FRINT, MVT::v8f16, Expand);
360 setOperationAction(ISD::FSIN, MVT::v8f16, Expand);
361 setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
362 setOperationAction(ISD::FSQRT, MVT::v8f16, Expand);
363 setOperationAction(ISD::FSUB, MVT::v8f16, Expand);
364 setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand);
365 setOperationAction(ISD::SETCC, MVT::v8f16, Expand);
366 setOperationAction(ISD::BR_CC, MVT::v8f16, Expand);
367 setOperationAction(ISD::SELECT, MVT::v8f16, Expand);
368 setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand);
369 setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand);
370 setOperationAction(ISD::FEXP, MVT::v8f16, Expand);
371 setOperationAction(ISD::FEXP2, MVT::v8f16, Expand);
372 setOperationAction(ISD::FLOG, MVT::v8f16, Expand);
373 setOperationAction(ISD::FLOG2, MVT::v8f16, Expand);
374 setOperationAction(ISD::FLOG10, MVT::v8f16, Expand);
375
Tim Northover3b0846e2014-05-24 12:50:23 +0000376 // AArch64 has implementations of a lot of rounding-like FP operations.
Benjamin Kramer57a3d082015-03-08 16:07:39 +0000377 for (MVT Ty : {MVT::f32, MVT::f64}) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000378 setOperationAction(ISD::FFLOOR, Ty, Legal);
379 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
380 setOperationAction(ISD::FCEIL, Ty, Legal);
381 setOperationAction(ISD::FRINT, Ty, Legal);
382 setOperationAction(ISD::FTRUNC, Ty, Legal);
383 setOperationAction(ISD::FROUND, Ty, Legal);
James Molloyb7b2a1e2015-08-11 12:06:37 +0000384 setOperationAction(ISD::FMINNUM, Ty, Legal);
385 setOperationAction(ISD::FMAXNUM, Ty, Legal);
James Molloy88edc822015-08-17 07:13:20 +0000386 setOperationAction(ISD::FMINNAN, Ty, Legal);
387 setOperationAction(ISD::FMAXNAN, Ty, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000388 }
389
390 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
391
Tim Northovercdf15292016-04-14 17:03:29 +0000392 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
393
Ahmed Bougachab0ff6432015-09-01 16:23:45 +0000394 // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
395 // This requires the Performance Monitors extension.
396 if (Subtarget->hasPerfMon())
397 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
398
Tim Northover3b0846e2014-05-24 12:50:23 +0000399 if (Subtarget->isTargetMachO()) {
400 // For iOS, we don't want to the normal expansion of a libcall to
401 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
402 // traffic.
403 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
404 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
405 } else {
406 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
407 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
408 }
409
Juergen Ributzka23266502014-12-10 19:43:32 +0000410 // Make floating-point constants legal for the large code model, so they don't
411 // become loads from the constant pool.
412 if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
413 setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
414 setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
415 }
416
Tim Northover3b0846e2014-05-24 12:50:23 +0000417 // AArch64 does not have floating-point extending loads, i1 sign-extending
418 // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000419 for (MVT VT : MVT::fp_valuetypes()) {
420 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
421 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
422 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
423 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
424 }
425 for (MVT VT : MVT::integer_valuetypes())
426 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
427
Tim Northover3b0846e2014-05-24 12:50:23 +0000428 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
429 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
430 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
431 setTruncStoreAction(MVT::f128, MVT::f80, Expand);
432 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
433 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
434 setTruncStoreAction(MVT::f128, MVT::f16, Expand);
Tim Northoverf8bfe212014-07-18 13:07:05 +0000435
436 setOperationAction(ISD::BITCAST, MVT::i16, Custom);
437 setOperationAction(ISD::BITCAST, MVT::f16, Custom);
438
Tim Northover3b0846e2014-05-24 12:50:23 +0000439 // Indexed loads and stores are supported.
440 for (unsigned im = (unsigned)ISD::PRE_INC;
441 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
442 setIndexedLoadAction(im, MVT::i8, Legal);
443 setIndexedLoadAction(im, MVT::i16, Legal);
444 setIndexedLoadAction(im, MVT::i32, Legal);
445 setIndexedLoadAction(im, MVT::i64, Legal);
446 setIndexedLoadAction(im, MVT::f64, Legal);
447 setIndexedLoadAction(im, MVT::f32, Legal);
Ahmed Bougachae0e12db2015-08-04 01:29:38 +0000448 setIndexedLoadAction(im, MVT::f16, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000449 setIndexedStoreAction(im, MVT::i8, Legal);
450 setIndexedStoreAction(im, MVT::i16, Legal);
451 setIndexedStoreAction(im, MVT::i32, Legal);
452 setIndexedStoreAction(im, MVT::i64, Legal);
453 setIndexedStoreAction(im, MVT::f64, Legal);
454 setIndexedStoreAction(im, MVT::f32, Legal);
Ahmed Bougachae0e12db2015-08-04 01:29:38 +0000455 setIndexedStoreAction(im, MVT::f16, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000456 }
457
458 // Trap.
459 setOperationAction(ISD::TRAP, MVT::Other, Legal);
460
461 // We combine OR nodes for bitfield operations.
462 setTargetDAGCombine(ISD::OR);
463
464 // Vector add and sub nodes may conceal a high-half opportunity.
465 // Also, try to fold ADD into CSINC/CSINV..
466 setTargetDAGCombine(ISD::ADD);
467 setTargetDAGCombine(ISD::SUB);
Chad Rosier14aa2ad2016-05-26 19:41:33 +0000468 setTargetDAGCombine(ISD::SRL);
Tim Northover3b0846e2014-05-24 12:50:23 +0000469 setTargetDAGCombine(ISD::XOR);
470 setTargetDAGCombine(ISD::SINT_TO_FP);
471 setTargetDAGCombine(ISD::UINT_TO_FP);
472
Chad Rosierfa30c9b2015-10-07 17:39:18 +0000473 setTargetDAGCombine(ISD::FP_TO_SINT);
474 setTargetDAGCombine(ISD::FP_TO_UINT);
Chad Rosier7c6ac2b2015-10-07 17:51:37 +0000475 setTargetDAGCombine(ISD::FDIV);
Chad Rosierfa30c9b2015-10-07 17:39:18 +0000476
Tim Northover3b0846e2014-05-24 12:50:23 +0000477 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
478
479 setTargetDAGCombine(ISD::ANY_EXTEND);
480 setTargetDAGCombine(ISD::ZERO_EXTEND);
481 setTargetDAGCombine(ISD::SIGN_EXTEND);
482 setTargetDAGCombine(ISD::BITCAST);
483 setTargetDAGCombine(ISD::CONCAT_VECTORS);
484 setTargetDAGCombine(ISD::STORE);
Tim Northover339c83e2015-11-10 00:44:23 +0000485 if (Subtarget->supportsAddressTopByteIgnored())
486 setTargetDAGCombine(ISD::LOAD);
Tim Northover3b0846e2014-05-24 12:50:23 +0000487
488 setTargetDAGCombine(ISD::MUL);
489
490 setTargetDAGCombine(ISD::SELECT);
491 setTargetDAGCombine(ISD::VSELECT);
492
493 setTargetDAGCombine(ISD::INTRINSIC_VOID);
494 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
495 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
Chad Rosier6c36eff2015-09-03 18:13:57 +0000496 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
Tim Northover3b0846e2014-05-24 12:50:23 +0000497
498 MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 8;
499 MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 4;
500 MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = 4;
501
502 setStackPointerRegisterToSaveRestore(AArch64::SP);
503
504 setSchedulingPreference(Sched::Hybrid);
505
506 // Enable TBZ/TBNZ
507 MaskAndBranchFoldingIsLegal = true;
Quentin Colombet6843ac42015-03-31 20:52:32 +0000508 EnableExtLdPromotion = true;
Tim Northover3b0846e2014-05-24 12:50:23 +0000509
Evandro Menezesa3a0a602016-06-10 16:00:18 +0000510 // Set required alignment.
Tim Northover3b0846e2014-05-24 12:50:23 +0000511 setMinFunctionAlignment(2);
Evandro Menezesa3a0a602016-06-10 16:00:18 +0000512 // Set preferred alignments.
513 setPrefFunctionAlignment(STI.getPrefFunctionAlignment());
514 setPrefLoopAlignment(STI.getPrefLoopAlignment());
Tim Northover3b0846e2014-05-24 12:50:23 +0000515
Evandro Menezese45de8a2016-09-26 15:32:33 +0000516 // Only change the limit for entries in a jump table if specified by
517 // the subtarget, but not at the command line.
518 unsigned MaxJT = STI.getMaximumJumpTableSize();
519 if (MaxJT && getMaximumJumpTableSize() == 0)
520 setMaximumJumpTableSize(MaxJT);
521
Tim Northover3b0846e2014-05-24 12:50:23 +0000522 setHasExtractBitsInsn(true);
523
Adhemerval Zanella7bc33192015-07-28 13:03:31 +0000524 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
525
Tim Northover3b0846e2014-05-24 12:50:23 +0000526 if (Subtarget->hasNEON()) {
527 // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
528 // silliness like this:
529 setOperationAction(ISD::FABS, MVT::v1f64, Expand);
530 setOperationAction(ISD::FADD, MVT::v1f64, Expand);
531 setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
532 setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
533 setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
534 setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
535 setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
536 setOperationAction(ISD::FMA, MVT::v1f64, Expand);
537 setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
538 setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
539 setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
540 setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
541 setOperationAction(ISD::FREM, MVT::v1f64, Expand);
542 setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
543 setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
544 setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
545 setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
546 setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
547 setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
548 setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
549 setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
550 setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
551 setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
552 setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
553 setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
554
555 setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
556 setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
557 setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
558 setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
559 setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
560
561 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
562
563 // AArch64 doesn't have a direct vector ->f32 conversion instructions for
564 // elements smaller than i32, so promote the input to i32 first.
565 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Promote);
566 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Promote);
567 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Promote);
568 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Promote);
Pirama Arumuga Nainarb1881532015-04-23 17:16:27 +0000569 // i8 and i16 vector elements also need promotion to i32 for v8i8 or v8i16
570 // -> v8f16 conversions.
571 setOperationAction(ISD::SINT_TO_FP, MVT::v8i8, Promote);
572 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Promote);
573 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
574 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Promote);
Tim Northover3b0846e2014-05-24 12:50:23 +0000575 // Similarly, there is no direct i32 -> f64 vector conversion instruction.
576 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
577 setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
578 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
579 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
Pirama Arumuga Nainarb1881532015-04-23 17:16:27 +0000580 // Or, direct i32 -> f16 vector conversion. Set it so custom, so the
581 // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
582 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
583 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000584
Craig Topperc5551bf2016-04-26 05:26:51 +0000585 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand);
586 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand);
587
Craig Topper3b4842b2016-04-28 01:58:21 +0000588 setOperationAction(ISD::CTTZ, MVT::v2i8, Expand);
589 setOperationAction(ISD::CTTZ, MVT::v4i16, Expand);
590 setOperationAction(ISD::CTTZ, MVT::v2i32, Expand);
591 setOperationAction(ISD::CTTZ, MVT::v1i64, Expand);
592 setOperationAction(ISD::CTTZ, MVT::v16i8, Expand);
593 setOperationAction(ISD::CTTZ, MVT::v8i16, Expand);
594 setOperationAction(ISD::CTTZ, MVT::v4i32, Expand);
595 setOperationAction(ISD::CTTZ, MVT::v2i64, Expand);
596
Tim Northover3b0846e2014-05-24 12:50:23 +0000597 // AArch64 doesn't have MUL.2d:
598 setOperationAction(ISD::MUL, MVT::v2i64, Expand);
Chad Rosierd9d0f862014-10-08 02:31:24 +0000599 // Custom handling for some quad-vector types to detect MULL.
600 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
601 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
602 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
603
Tim Northover3b0846e2014-05-24 12:50:23 +0000604 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
605 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
606 // Likewise, narrowing and extending vector loads/stores aren't handled
607 // directly.
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000608 for (MVT VT : MVT::vector_valuetypes()) {
609 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000610
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000611 setOperationAction(ISD::MULHS, VT, Expand);
612 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
613 setOperationAction(ISD::MULHU, VT, Expand);
614 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000615
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000616 setOperationAction(ISD::BSWAP, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000617
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000618 for (MVT InnerVT : MVT::vector_valuetypes()) {
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000619 setTruncStoreAction(VT, InnerVT, Expand);
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000620 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
621 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
622 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
623 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000624 }
625
626 // AArch64 has implementations of a lot of rounding-like FP operations.
Benjamin Kramer57a3d082015-03-08 16:07:39 +0000627 for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000628 setOperationAction(ISD::FFLOOR, Ty, Legal);
629 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
630 setOperationAction(ISD::FCEIL, Ty, Legal);
631 setOperationAction(ISD::FRINT, Ty, Legal);
632 setOperationAction(ISD::FTRUNC, Ty, Legal);
633 setOperationAction(ISD::FROUND, Ty, Legal);
634 }
635 }
James Molloyf089ab72014-08-06 10:42:18 +0000636
Matthias Braun651cff42016-06-02 18:03:53 +0000637 PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive();
Tim Northover3b0846e2014-05-24 12:50:23 +0000638}
639
Craig Topper18e69f42016-04-15 06:20:21 +0000640void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) {
Jiangning Liu08f4cda2014-08-29 01:31:42 +0000641 if (VT == MVT::v2f32 || VT == MVT::v4f16) {
Craig Topper18e69f42016-04-15 06:20:21 +0000642 setOperationAction(ISD::LOAD, VT, Promote);
643 AddPromotedToType(ISD::LOAD, VT, MVT::v2i32);
Tim Northover3b0846e2014-05-24 12:50:23 +0000644
Craig Topper18e69f42016-04-15 06:20:21 +0000645 setOperationAction(ISD::STORE, VT, Promote);
646 AddPromotedToType(ISD::STORE, VT, MVT::v2i32);
Jiangning Liu08f4cda2014-08-29 01:31:42 +0000647 } else if (VT == MVT::v2f64 || VT == MVT::v4f32 || VT == MVT::v8f16) {
Craig Topper18e69f42016-04-15 06:20:21 +0000648 setOperationAction(ISD::LOAD, VT, Promote);
649 AddPromotedToType(ISD::LOAD, VT, MVT::v2i64);
Tim Northover3b0846e2014-05-24 12:50:23 +0000650
Craig Topper18e69f42016-04-15 06:20:21 +0000651 setOperationAction(ISD::STORE, VT, Promote);
652 AddPromotedToType(ISD::STORE, VT, MVT::v2i64);
Tim Northover3b0846e2014-05-24 12:50:23 +0000653 }
654
655 // Mark vector float intrinsics as expand.
656 if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
Craig Topper18e69f42016-04-15 06:20:21 +0000657 setOperationAction(ISD::FSIN, VT, Expand);
658 setOperationAction(ISD::FCOS, VT, Expand);
659 setOperationAction(ISD::FPOWI, VT, Expand);
660 setOperationAction(ISD::FPOW, VT, Expand);
661 setOperationAction(ISD::FLOG, VT, Expand);
662 setOperationAction(ISD::FLOG2, VT, Expand);
663 setOperationAction(ISD::FLOG10, VT, Expand);
664 setOperationAction(ISD::FEXP, VT, Expand);
665 setOperationAction(ISD::FEXP2, VT, Expand);
Ahmed Bougachab0ae36f2015-08-04 00:42:34 +0000666
667 // But we do support custom-lowering for FCOPYSIGN.
Craig Topper18e69f42016-04-15 06:20:21 +0000668 setOperationAction(ISD::FCOPYSIGN, VT, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000669 }
670
Craig Topper18e69f42016-04-15 06:20:21 +0000671 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
672 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
673 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
674 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
675 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
676 setOperationAction(ISD::SRA, VT, Custom);
677 setOperationAction(ISD::SRL, VT, Custom);
678 setOperationAction(ISD::SHL, VT, Custom);
679 setOperationAction(ISD::AND, VT, Custom);
680 setOperationAction(ISD::OR, VT, Custom);
681 setOperationAction(ISD::SETCC, VT, Custom);
682 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000683
Craig Topper18e69f42016-04-15 06:20:21 +0000684 setOperationAction(ISD::SELECT, VT, Expand);
685 setOperationAction(ISD::SELECT_CC, VT, Expand);
686 setOperationAction(ISD::VSELECT, VT, Expand);
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000687 for (MVT InnerVT : MVT::all_valuetypes())
Craig Topper18e69f42016-04-15 06:20:21 +0000688 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000689
690 // CNT supports only B element sizes.
691 if (VT != MVT::v8i8 && VT != MVT::v16i8)
Craig Topper18e69f42016-04-15 06:20:21 +0000692 setOperationAction(ISD::CTPOP, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000693
Craig Topper18e69f42016-04-15 06:20:21 +0000694 setOperationAction(ISD::UDIV, VT, Expand);
695 setOperationAction(ISD::SDIV, VT, Expand);
696 setOperationAction(ISD::UREM, VT, Expand);
697 setOperationAction(ISD::SREM, VT, Expand);
698 setOperationAction(ISD::FREM, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000699
Craig Topper18e69f42016-04-15 06:20:21 +0000700 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
701 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000702
Hal Finkelcd8664c2015-12-11 23:11:52 +0000703 // [SU][MIN|MAX] are available for all NEON types apart from i64.
Craig Topper18e69f42016-04-15 06:20:21 +0000704 if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64)
Hal Finkelcd8664c2015-12-11 23:11:52 +0000705 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
Craig Topper18e69f42016-04-15 06:20:21 +0000706 setOperationAction(Opcode, VT, Legal);
James Molloycfb04432015-05-15 16:15:57 +0000707
James Molloy63be1982015-08-14 09:08:50 +0000708 // F[MIN|MAX][NUM|NAN] are available for all FP NEON types (not f16 though!).
709 if (VT.isFloatingPoint() && VT.getVectorElementType() != MVT::f16)
James Molloyb7b2a1e2015-08-11 12:06:37 +0000710 for (unsigned Opcode : {ISD::FMINNAN, ISD::FMAXNAN,
711 ISD::FMINNUM, ISD::FMAXNUM})
Craig Topper18e69f42016-04-15 06:20:21 +0000712 setOperationAction(Opcode, VT, Legal);
James Molloyedf38f02015-08-11 12:06:33 +0000713
Tim Northover3b0846e2014-05-24 12:50:23 +0000714 if (Subtarget->isLittleEndian()) {
715 for (unsigned im = (unsigned)ISD::PRE_INC;
716 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
Craig Topper18e69f42016-04-15 06:20:21 +0000717 setIndexedLoadAction(im, VT, Legal);
718 setIndexedStoreAction(im, VT, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000719 }
720 }
721}
722
723void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
724 addRegisterClass(VT, &AArch64::FPR64RegClass);
725 addTypeForNEON(VT, MVT::v2i32);
726}
727
728void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
729 addRegisterClass(VT, &AArch64::FPR128RegClass);
730 addTypeForNEON(VT, MVT::v4i32);
731}
732
Mehdi Amini44ede332015-07-09 02:09:04 +0000733EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
734 EVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +0000735 if (!VT.isVector())
736 return MVT::i32;
737 return VT.changeVectorElementTypeToInteger();
738}
739
740/// computeKnownBitsForTargetNode - Determine which of the bits specified in
741/// Mask are known to be either zero or one and return them in the
742/// KnownZero/KnownOne bitsets.
743void AArch64TargetLowering::computeKnownBitsForTargetNode(
744 const SDValue Op, APInt &KnownZero, APInt &KnownOne,
745 const SelectionDAG &DAG, unsigned Depth) const {
746 switch (Op.getOpcode()) {
747 default:
748 break;
749 case AArch64ISD::CSEL: {
750 APInt KnownZero2, KnownOne2;
751 DAG.computeKnownBits(Op->getOperand(0), KnownZero, KnownOne, Depth + 1);
752 DAG.computeKnownBits(Op->getOperand(1), KnownZero2, KnownOne2, Depth + 1);
753 KnownZero &= KnownZero2;
754 KnownOne &= KnownOne2;
755 break;
756 }
757 case ISD::INTRINSIC_W_CHAIN: {
Jun Bum Lim4d3c5982015-09-08 16:11:22 +0000758 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +0000759 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
760 switch (IntID) {
761 default: return;
762 case Intrinsic::aarch64_ldaxr:
763 case Intrinsic::aarch64_ldxr: {
764 unsigned BitWidth = KnownOne.getBitWidth();
765 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
Sanjay Patelbd6fca12016-09-14 15:21:00 +0000766 unsigned MemBits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +0000767 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
768 return;
769 }
770 }
771 break;
772 }
773 case ISD::INTRINSIC_WO_CHAIN:
774 case ISD::INTRINSIC_VOID: {
775 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
776 switch (IntNo) {
777 default:
778 break;
779 case Intrinsic::aarch64_neon_umaxv:
780 case Intrinsic::aarch64_neon_uminv: {
781 // Figure out the datatype of the vector operand. The UMINV instruction
782 // will zero extend the result, so we can mark as known zero all the
783 // bits larger than the element datatype. 32-bit or larget doesn't need
784 // this as those are legal types and will be handled by isel directly.
785 MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
786 unsigned BitWidth = KnownZero.getBitWidth();
787 if (VT == MVT::v8i8 || VT == MVT::v16i8) {
788 assert(BitWidth >= 8 && "Unexpected width!");
789 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
790 KnownZero |= Mask;
791 } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
792 assert(BitWidth >= 16 && "Unexpected width!");
793 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
794 KnownZero |= Mask;
795 }
796 break;
797 } break;
798 }
799 }
800 }
801}
802
Mehdi Aminieaabc512015-07-09 15:12:23 +0000803MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
804 EVT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +0000805 return MVT::i64;
806}
807
Akira Hatanakaf53b0402015-07-29 14:17:26 +0000808bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
809 unsigned AddrSpace,
810 unsigned Align,
811 bool *Fast) const {
812 if (Subtarget->requiresStrictAlign())
813 return false;
Sanjay Patelbbbf9a12015-09-25 21:49:48 +0000814
Sanjay Patelbbbf9a12015-09-25 21:49:48 +0000815 if (Fast) {
Matthias Braun651cff42016-06-02 18:03:53 +0000816 // Some CPUs are fine with unaligned stores except for 128-bit ones.
817 *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 ||
Sanjay Patelbbbf9a12015-09-25 21:49:48 +0000818 // See comments in performSTORECombine() for more details about
819 // these conditions.
820
821 // Code that uses clang vector extensions can mark that it
822 // wants unaligned accesses to be treated as fast by
823 // underspecifying alignment to be 1 or 2.
824 Align <= 2 ||
825
826 // Disregard v2i64. Memcpy lowering produces those and splitting
827 // them regresses performance on micro-benchmarks and olden/bh.
828 VT == MVT::v2i64;
829 }
Akira Hatanakaf53b0402015-07-29 14:17:26 +0000830 return true;
831}
832
Tim Northover3b0846e2014-05-24 12:50:23 +0000833FastISel *
834AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
835 const TargetLibraryInfo *libInfo) const {
836 return AArch64::createFastISel(funcInfo, libInfo);
837}
838
839const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
Matthias Braund04893f2015-05-07 21:33:59 +0000840 switch ((AArch64ISD::NodeType)Opcode) {
841 case AArch64ISD::FIRST_NUMBER: break;
Tim Northover3b0846e2014-05-24 12:50:23 +0000842 case AArch64ISD::CALL: return "AArch64ISD::CALL";
843 case AArch64ISD::ADRP: return "AArch64ISD::ADRP";
844 case AArch64ISD::ADDlow: return "AArch64ISD::ADDlow";
845 case AArch64ISD::LOADgot: return "AArch64ISD::LOADgot";
846 case AArch64ISD::RET_FLAG: return "AArch64ISD::RET_FLAG";
847 case AArch64ISD::BRCOND: return "AArch64ISD::BRCOND";
848 case AArch64ISD::CSEL: return "AArch64ISD::CSEL";
849 case AArch64ISD::FCSEL: return "AArch64ISD::FCSEL";
850 case AArch64ISD::CSINV: return "AArch64ISD::CSINV";
851 case AArch64ISD::CSNEG: return "AArch64ISD::CSNEG";
852 case AArch64ISD::CSINC: return "AArch64ISD::CSINC";
853 case AArch64ISD::THREAD_POINTER: return "AArch64ISD::THREAD_POINTER";
Kristof Beylsaea84612015-03-04 09:12:08 +0000854 case AArch64ISD::TLSDESC_CALLSEQ: return "AArch64ISD::TLSDESC_CALLSEQ";
Tim Northover3b0846e2014-05-24 12:50:23 +0000855 case AArch64ISD::ADC: return "AArch64ISD::ADC";
856 case AArch64ISD::SBC: return "AArch64ISD::SBC";
857 case AArch64ISD::ADDS: return "AArch64ISD::ADDS";
858 case AArch64ISD::SUBS: return "AArch64ISD::SUBS";
859 case AArch64ISD::ADCS: return "AArch64ISD::ADCS";
860 case AArch64ISD::SBCS: return "AArch64ISD::SBCS";
861 case AArch64ISD::ANDS: return "AArch64ISD::ANDS";
Matthias Braunaf7d7702015-07-16 20:02:37 +0000862 case AArch64ISD::CCMP: return "AArch64ISD::CCMP";
863 case AArch64ISD::CCMN: return "AArch64ISD::CCMN";
864 case AArch64ISD::FCCMP: return "AArch64ISD::FCCMP";
Tim Northover3b0846e2014-05-24 12:50:23 +0000865 case AArch64ISD::FCMP: return "AArch64ISD::FCMP";
Tim Northover3b0846e2014-05-24 12:50:23 +0000866 case AArch64ISD::DUP: return "AArch64ISD::DUP";
867 case AArch64ISD::DUPLANE8: return "AArch64ISD::DUPLANE8";
868 case AArch64ISD::DUPLANE16: return "AArch64ISD::DUPLANE16";
869 case AArch64ISD::DUPLANE32: return "AArch64ISD::DUPLANE32";
870 case AArch64ISD::DUPLANE64: return "AArch64ISD::DUPLANE64";
871 case AArch64ISD::MOVI: return "AArch64ISD::MOVI";
872 case AArch64ISD::MOVIshift: return "AArch64ISD::MOVIshift";
873 case AArch64ISD::MOVIedit: return "AArch64ISD::MOVIedit";
874 case AArch64ISD::MOVImsl: return "AArch64ISD::MOVImsl";
875 case AArch64ISD::FMOV: return "AArch64ISD::FMOV";
876 case AArch64ISD::MVNIshift: return "AArch64ISD::MVNIshift";
877 case AArch64ISD::MVNImsl: return "AArch64ISD::MVNImsl";
878 case AArch64ISD::BICi: return "AArch64ISD::BICi";
879 case AArch64ISD::ORRi: return "AArch64ISD::ORRi";
880 case AArch64ISD::BSL: return "AArch64ISD::BSL";
881 case AArch64ISD::NEG: return "AArch64ISD::NEG";
882 case AArch64ISD::EXTR: return "AArch64ISD::EXTR";
883 case AArch64ISD::ZIP1: return "AArch64ISD::ZIP1";
884 case AArch64ISD::ZIP2: return "AArch64ISD::ZIP2";
885 case AArch64ISD::UZP1: return "AArch64ISD::UZP1";
886 case AArch64ISD::UZP2: return "AArch64ISD::UZP2";
887 case AArch64ISD::TRN1: return "AArch64ISD::TRN1";
888 case AArch64ISD::TRN2: return "AArch64ISD::TRN2";
889 case AArch64ISD::REV16: return "AArch64ISD::REV16";
890 case AArch64ISD::REV32: return "AArch64ISD::REV32";
891 case AArch64ISD::REV64: return "AArch64ISD::REV64";
892 case AArch64ISD::EXT: return "AArch64ISD::EXT";
893 case AArch64ISD::VSHL: return "AArch64ISD::VSHL";
894 case AArch64ISD::VLSHR: return "AArch64ISD::VLSHR";
895 case AArch64ISD::VASHR: return "AArch64ISD::VASHR";
896 case AArch64ISD::CMEQ: return "AArch64ISD::CMEQ";
897 case AArch64ISD::CMGE: return "AArch64ISD::CMGE";
898 case AArch64ISD::CMGT: return "AArch64ISD::CMGT";
899 case AArch64ISD::CMHI: return "AArch64ISD::CMHI";
900 case AArch64ISD::CMHS: return "AArch64ISD::CMHS";
901 case AArch64ISD::FCMEQ: return "AArch64ISD::FCMEQ";
902 case AArch64ISD::FCMGE: return "AArch64ISD::FCMGE";
903 case AArch64ISD::FCMGT: return "AArch64ISD::FCMGT";
904 case AArch64ISD::CMEQz: return "AArch64ISD::CMEQz";
905 case AArch64ISD::CMGEz: return "AArch64ISD::CMGEz";
906 case AArch64ISD::CMGTz: return "AArch64ISD::CMGTz";
907 case AArch64ISD::CMLEz: return "AArch64ISD::CMLEz";
908 case AArch64ISD::CMLTz: return "AArch64ISD::CMLTz";
909 case AArch64ISD::FCMEQz: return "AArch64ISD::FCMEQz";
910 case AArch64ISD::FCMGEz: return "AArch64ISD::FCMGEz";
911 case AArch64ISD::FCMGTz: return "AArch64ISD::FCMGTz";
912 case AArch64ISD::FCMLEz: return "AArch64ISD::FCMLEz";
913 case AArch64ISD::FCMLTz: return "AArch64ISD::FCMLTz";
Ahmed Bougachafab58922015-03-10 20:45:38 +0000914 case AArch64ISD::SADDV: return "AArch64ISD::SADDV";
915 case AArch64ISD::UADDV: return "AArch64ISD::UADDV";
916 case AArch64ISD::SMINV: return "AArch64ISD::SMINV";
917 case AArch64ISD::UMINV: return "AArch64ISD::UMINV";
918 case AArch64ISD::SMAXV: return "AArch64ISD::SMAXV";
919 case AArch64ISD::UMAXV: return "AArch64ISD::UMAXV";
Tim Northover3b0846e2014-05-24 12:50:23 +0000920 case AArch64ISD::NOT: return "AArch64ISD::NOT";
921 case AArch64ISD::BIT: return "AArch64ISD::BIT";
922 case AArch64ISD::CBZ: return "AArch64ISD::CBZ";
923 case AArch64ISD::CBNZ: return "AArch64ISD::CBNZ";
924 case AArch64ISD::TBZ: return "AArch64ISD::TBZ";
925 case AArch64ISD::TBNZ: return "AArch64ISD::TBNZ";
926 case AArch64ISD::TC_RETURN: return "AArch64ISD::TC_RETURN";
Matthias Braund04893f2015-05-07 21:33:59 +0000927 case AArch64ISD::PREFETCH: return "AArch64ISD::PREFETCH";
Tim Northover3b0846e2014-05-24 12:50:23 +0000928 case AArch64ISD::SITOF: return "AArch64ISD::SITOF";
929 case AArch64ISD::UITOF: return "AArch64ISD::UITOF";
Asiri Rathnayake530b3ed2014-10-01 09:59:45 +0000930 case AArch64ISD::NVCAST: return "AArch64ISD::NVCAST";
Tim Northover3b0846e2014-05-24 12:50:23 +0000931 case AArch64ISD::SQSHL_I: return "AArch64ISD::SQSHL_I";
932 case AArch64ISD::UQSHL_I: return "AArch64ISD::UQSHL_I";
933 case AArch64ISD::SRSHR_I: return "AArch64ISD::SRSHR_I";
934 case AArch64ISD::URSHR_I: return "AArch64ISD::URSHR_I";
935 case AArch64ISD::SQSHLU_I: return "AArch64ISD::SQSHLU_I";
936 case AArch64ISD::WrapperLarge: return "AArch64ISD::WrapperLarge";
937 case AArch64ISD::LD2post: return "AArch64ISD::LD2post";
938 case AArch64ISD::LD3post: return "AArch64ISD::LD3post";
939 case AArch64ISD::LD4post: return "AArch64ISD::LD4post";
940 case AArch64ISD::ST2post: return "AArch64ISD::ST2post";
941 case AArch64ISD::ST3post: return "AArch64ISD::ST3post";
942 case AArch64ISD::ST4post: return "AArch64ISD::ST4post";
943 case AArch64ISD::LD1x2post: return "AArch64ISD::LD1x2post";
944 case AArch64ISD::LD1x3post: return "AArch64ISD::LD1x3post";
945 case AArch64ISD::LD1x4post: return "AArch64ISD::LD1x4post";
946 case AArch64ISD::ST1x2post: return "AArch64ISD::ST1x2post";
947 case AArch64ISD::ST1x3post: return "AArch64ISD::ST1x3post";
948 case AArch64ISD::ST1x4post: return "AArch64ISD::ST1x4post";
949 case AArch64ISD::LD1DUPpost: return "AArch64ISD::LD1DUPpost";
950 case AArch64ISD::LD2DUPpost: return "AArch64ISD::LD2DUPpost";
951 case AArch64ISD::LD3DUPpost: return "AArch64ISD::LD3DUPpost";
952 case AArch64ISD::LD4DUPpost: return "AArch64ISD::LD4DUPpost";
953 case AArch64ISD::LD1LANEpost: return "AArch64ISD::LD1LANEpost";
954 case AArch64ISD::LD2LANEpost: return "AArch64ISD::LD2LANEpost";
955 case AArch64ISD::LD3LANEpost: return "AArch64ISD::LD3LANEpost";
956 case AArch64ISD::LD4LANEpost: return "AArch64ISD::LD4LANEpost";
957 case AArch64ISD::ST2LANEpost: return "AArch64ISD::ST2LANEpost";
958 case AArch64ISD::ST3LANEpost: return "AArch64ISD::ST3LANEpost";
959 case AArch64ISD::ST4LANEpost: return "AArch64ISD::ST4LANEpost";
Chad Rosierd9d0f862014-10-08 02:31:24 +0000960 case AArch64ISD::SMULL: return "AArch64ISD::SMULL";
961 case AArch64ISD::UMULL: return "AArch64ISD::UMULL";
Evandro Menezeseff2bd92016-10-24 16:14:58 +0000962 case AArch64ISD::FRECPE: return "AArch64ISD::FRECPE";
Evandro Menezes9fc54822016-11-14 23:29:01 +0000963 case AArch64ISD::FRECPS: return "AArch64ISD::FRECPS";
964 case AArch64ISD::FRSQRTE: return "AArch64ISD::FRSQRTE";
965 case AArch64ISD::FRSQRTS: return "AArch64ISD::FRSQRTS";
Tim Northover3b0846e2014-05-24 12:50:23 +0000966 }
Matthias Braund04893f2015-05-07 21:33:59 +0000967 return nullptr;
Tim Northover3b0846e2014-05-24 12:50:23 +0000968}
969
970MachineBasicBlock *
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +0000971AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI,
Tim Northover3b0846e2014-05-24 12:50:23 +0000972 MachineBasicBlock *MBB) const {
973 // We materialise the F128CSEL pseudo-instruction as some control flow and a
974 // phi node:
975
976 // OrigBB:
977 // [... previous instrs leading to comparison ...]
978 // b.ne TrueBB
979 // b EndBB
980 // TrueBB:
981 // ; Fallthrough
982 // EndBB:
983 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
984
Tim Northover3b0846e2014-05-24 12:50:23 +0000985 MachineFunction *MF = MBB->getParent();
Eric Christopher905f12d2015-01-29 00:19:42 +0000986 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +0000987 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +0000988 DebugLoc DL = MI.getDebugLoc();
Duncan P. N. Exon Smithd3b9df02015-10-13 20:02:15 +0000989 MachineFunction::iterator It = ++MBB->getIterator();
Tim Northover3b0846e2014-05-24 12:50:23 +0000990
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +0000991 unsigned DestReg = MI.getOperand(0).getReg();
992 unsigned IfTrueReg = MI.getOperand(1).getReg();
993 unsigned IfFalseReg = MI.getOperand(2).getReg();
994 unsigned CondCode = MI.getOperand(3).getImm();
995 bool NZCVKilled = MI.getOperand(4).isKill();
Tim Northover3b0846e2014-05-24 12:50:23 +0000996
997 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
998 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
999 MF->insert(It, TrueBB);
1000 MF->insert(It, EndBB);
1001
1002 // Transfer rest of current basic-block to EndBB
1003 EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
1004 MBB->end());
1005 EndBB->transferSuccessorsAndUpdatePHIs(MBB);
1006
1007 BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
1008 BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
1009 MBB->addSuccessor(TrueBB);
1010 MBB->addSuccessor(EndBB);
1011
1012 // TrueBB falls through to the end.
1013 TrueBB->addSuccessor(EndBB);
1014
1015 if (!NZCVKilled) {
1016 TrueBB->addLiveIn(AArch64::NZCV);
1017 EndBB->addLiveIn(AArch64::NZCV);
1018 }
1019
1020 BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
1021 .addReg(IfTrueReg)
1022 .addMBB(TrueBB)
1023 .addReg(IfFalseReg)
1024 .addMBB(MBB);
1025
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001026 MI.eraseFromParent();
Tim Northover3b0846e2014-05-24 12:50:23 +00001027 return EndBB;
1028}
1029
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001030MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter(
1031 MachineInstr &MI, MachineBasicBlock *BB) const {
1032 switch (MI.getOpcode()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001033 default:
1034#ifndef NDEBUG
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001035 MI.dump();
Tim Northover3b0846e2014-05-24 12:50:23 +00001036#endif
Craig Topper35b2f752014-06-19 06:10:58 +00001037 llvm_unreachable("Unexpected instruction for custom inserter!");
Tim Northover3b0846e2014-05-24 12:50:23 +00001038
1039 case AArch64::F128CSEL:
1040 return EmitF128CSEL(MI, BB);
1041
1042 case TargetOpcode::STACKMAP:
1043 case TargetOpcode::PATCHPOINT:
1044 return emitPatchPoint(MI, BB);
1045 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001046}
1047
1048//===----------------------------------------------------------------------===//
1049// AArch64 Lowering private implementation.
1050//===----------------------------------------------------------------------===//
1051
1052//===----------------------------------------------------------------------===//
1053// Lowering Code
1054//===----------------------------------------------------------------------===//
1055
1056/// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1057/// CC
1058static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1059 switch (CC) {
1060 default:
1061 llvm_unreachable("Unknown condition code!");
1062 case ISD::SETNE:
1063 return AArch64CC::NE;
1064 case ISD::SETEQ:
1065 return AArch64CC::EQ;
1066 case ISD::SETGT:
1067 return AArch64CC::GT;
1068 case ISD::SETGE:
1069 return AArch64CC::GE;
1070 case ISD::SETLT:
1071 return AArch64CC::LT;
1072 case ISD::SETLE:
1073 return AArch64CC::LE;
1074 case ISD::SETUGT:
1075 return AArch64CC::HI;
1076 case ISD::SETUGE:
1077 return AArch64CC::HS;
1078 case ISD::SETULT:
1079 return AArch64CC::LO;
1080 case ISD::SETULE:
1081 return AArch64CC::LS;
1082 }
1083}
1084
1085/// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1086static void changeFPCCToAArch64CC(ISD::CondCode CC,
1087 AArch64CC::CondCode &CondCode,
1088 AArch64CC::CondCode &CondCode2) {
1089 CondCode2 = AArch64CC::AL;
1090 switch (CC) {
1091 default:
1092 llvm_unreachable("Unknown FP condition!");
1093 case ISD::SETEQ:
1094 case ISD::SETOEQ:
1095 CondCode = AArch64CC::EQ;
1096 break;
1097 case ISD::SETGT:
1098 case ISD::SETOGT:
1099 CondCode = AArch64CC::GT;
1100 break;
1101 case ISD::SETGE:
1102 case ISD::SETOGE:
1103 CondCode = AArch64CC::GE;
1104 break;
1105 case ISD::SETOLT:
1106 CondCode = AArch64CC::MI;
1107 break;
1108 case ISD::SETOLE:
1109 CondCode = AArch64CC::LS;
1110 break;
1111 case ISD::SETONE:
1112 CondCode = AArch64CC::MI;
1113 CondCode2 = AArch64CC::GT;
1114 break;
1115 case ISD::SETO:
1116 CondCode = AArch64CC::VC;
1117 break;
1118 case ISD::SETUO:
1119 CondCode = AArch64CC::VS;
1120 break;
1121 case ISD::SETUEQ:
1122 CondCode = AArch64CC::EQ;
1123 CondCode2 = AArch64CC::VS;
1124 break;
1125 case ISD::SETUGT:
1126 CondCode = AArch64CC::HI;
1127 break;
1128 case ISD::SETUGE:
1129 CondCode = AArch64CC::PL;
1130 break;
1131 case ISD::SETLT:
1132 case ISD::SETULT:
1133 CondCode = AArch64CC::LT;
1134 break;
1135 case ISD::SETLE:
1136 case ISD::SETULE:
1137 CondCode = AArch64CC::LE;
1138 break;
1139 case ISD::SETNE:
1140 case ISD::SETUNE:
1141 CondCode = AArch64CC::NE;
1142 break;
1143 }
1144}
1145
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001146/// Convert a DAG fp condition code to an AArch64 CC.
1147/// This differs from changeFPCCToAArch64CC in that it returns cond codes that
1148/// should be AND'ed instead of OR'ed.
1149static void changeFPCCToANDAArch64CC(ISD::CondCode CC,
1150 AArch64CC::CondCode &CondCode,
1151 AArch64CC::CondCode &CondCode2) {
1152 CondCode2 = AArch64CC::AL;
1153 switch (CC) {
1154 default:
1155 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1156 assert(CondCode2 == AArch64CC::AL);
1157 break;
1158 case ISD::SETONE:
1159 // (a one b)
1160 // == ((a olt b) || (a ogt b))
1161 // == ((a ord b) && (a une b))
1162 CondCode = AArch64CC::VC;
1163 CondCode2 = AArch64CC::NE;
1164 break;
1165 case ISD::SETUEQ:
1166 // (a ueq b)
1167 // == ((a uno b) || (a oeq b))
1168 // == ((a ule b) && (a uge b))
1169 CondCode = AArch64CC::PL;
1170 CondCode2 = AArch64CC::LE;
1171 break;
1172 }
1173}
1174
Tim Northover3b0846e2014-05-24 12:50:23 +00001175/// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1176/// CC usable with the vector instructions. Fewer operations are available
1177/// without a real NZCV register, so we have to use less efficient combinations
1178/// to get the same effect.
1179static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1180 AArch64CC::CondCode &CondCode,
1181 AArch64CC::CondCode &CondCode2,
1182 bool &Invert) {
1183 Invert = false;
1184 switch (CC) {
1185 default:
1186 // Mostly the scalar mappings work fine.
1187 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1188 break;
1189 case ISD::SETUO:
Justin Bognerb03fd122016-08-17 05:10:15 +00001190 Invert = true;
1191 LLVM_FALLTHROUGH;
Tim Northover3b0846e2014-05-24 12:50:23 +00001192 case ISD::SETO:
1193 CondCode = AArch64CC::MI;
1194 CondCode2 = AArch64CC::GE;
1195 break;
1196 case ISD::SETUEQ:
1197 case ISD::SETULT:
1198 case ISD::SETULE:
1199 case ISD::SETUGT:
1200 case ISD::SETUGE:
1201 // All of the compare-mask comparisons are ordered, but we can switch
1202 // between the two by a double inversion. E.g. ULE == !OGT.
1203 Invert = true;
1204 changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1205 break;
1206 }
1207}
1208
1209static bool isLegalArithImmed(uint64_t C) {
1210 // Matches AArch64DAGToDAGISel::SelectArithImmed().
1211 return (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1212}
1213
1214static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00001215 const SDLoc &dl, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001216 EVT VT = LHS.getValueType();
1217
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001218 if (VT.isFloatingPoint()) {
1219 assert(VT != MVT::f128);
1220 if (VT == MVT::f16) {
1221 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
1222 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
Weiming Zhao095c2712016-05-11 01:26:32 +00001223 VT = MVT::f32;
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001224 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001225 return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001226 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001227
1228 // The CMP instruction is just an alias for SUBS, and representing it as
1229 // SUBS means that it's possible to get CSE with subtract operations.
1230 // A later phase can perform the optimization of setting the destination
1231 // register to WZR/XZR if it ends up being unused.
1232 unsigned Opcode = AArch64ISD::SUBS;
1233
Artyom Skrobov314ee042015-11-25 19:41:11 +00001234 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001235 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1236 // We'd like to combine a (CMP op1, (sub 0, op2) into a CMN instruction on
1237 // the grounds that "op1 - (-op2) == op1 + op2". However, the C and V flags
1238 // can be set differently by this operation. It comes down to whether
1239 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1240 // everything is fine. If not then the optimization is wrong. Thus general
1241 // comparisons are only valid if op2 != 0.
1242
1243 // So, finally, the only LLVM-native comparisons that don't mention C and V
1244 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1245 // the absence of information about op2.
1246 Opcode = AArch64ISD::ADDS;
1247 RHS = RHS.getOperand(1);
Artyom Skrobov314ee042015-11-25 19:41:11 +00001248 } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001249 !isUnsignedIntSetCC(CC)) {
1250 // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1251 // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1252 // of the signed comparisons.
1253 Opcode = AArch64ISD::ANDS;
1254 RHS = LHS.getOperand(1);
1255 LHS = LHS.getOperand(0);
1256 }
1257
Matthias Braunaf7d7702015-07-16 20:02:37 +00001258 return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
Tim Northover3b0846e2014-05-24 12:50:23 +00001259 .getValue(1);
1260}
1261
Matthias Braunaf7d7702015-07-16 20:02:37 +00001262/// \defgroup AArch64CCMP CMP;CCMP matching
1263///
1264/// These functions deal with the formation of CMP;CCMP;... sequences.
1265/// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1266/// a comparison. They set the NZCV flags to a predefined value if their
1267/// predicate is false. This allows to express arbitrary conjunctions, for
1268/// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B))))"
1269/// expressed as:
1270/// cmp A
1271/// ccmp B, inv(CB), CA
1272/// check for CB flags
1273///
1274/// In general we can create code for arbitrary "... (and (and A B) C)"
1275/// sequences. We can also implement some "or" expressions, because "(or A B)"
1276/// is equivalent to "not (and (not A) (not B))" and we can implement some
1277/// negation operations:
1278/// We can negate the results of a single comparison by inverting the flags
1279/// used when the predicate fails and inverting the flags tested in the next
1280/// instruction; We can also negate the results of the whole previous
1281/// conditional compare sequence by inverting the flags tested in the next
1282/// instruction. However there is no way to negate the result of a partial
1283/// sequence.
1284///
1285/// Therefore on encountering an "or" expression we can negate the subtree on
1286/// one side and have to be able to push the negate to the leafs of the subtree
1287/// on the other side (see also the comments in code). As complete example:
1288/// "or (or (setCA (cmp A)) (setCB (cmp B)))
1289/// (and (setCC (cmp C)) (setCD (cmp D)))"
1290/// is transformed to
1291/// "not (and (not (and (setCC (cmp C)) (setCC (cmp D))))
1292/// (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1293/// and implemented as:
1294/// cmp C
1295/// ccmp D, inv(CD), CC
1296/// ccmp A, CA, inv(CD)
1297/// ccmp B, CB, inv(CA)
1298/// check for CB flags
1299/// A counterexample is "or (and A B) (and C D)" which cannot be implemented
1300/// by conditional compare sequences.
1301/// @{
1302
Geoff Berrye41c2df2015-07-20 22:03:52 +00001303/// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001304static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1305 ISD::CondCode CC, SDValue CCOp,
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001306 AArch64CC::CondCode Predicate,
1307 AArch64CC::CondCode OutCC,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00001308 const SDLoc &DL, SelectionDAG &DAG) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001309 unsigned Opcode = 0;
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001310 if (LHS.getValueType().isFloatingPoint()) {
1311 assert(LHS.getValueType() != MVT::f128);
1312 if (LHS.getValueType() == MVT::f16) {
1313 LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS);
1314 RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS);
1315 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001316 Opcode = AArch64ISD::FCCMP;
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001317 } else if (RHS.getOpcode() == ISD::SUB) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001318 SDValue SubOp0 = RHS.getOperand(0);
Artyom Skrobov314ee042015-11-25 19:41:11 +00001319 if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
Matthias Braunfd13c142016-01-23 04:05:16 +00001320 // See emitComparison() on why we can only do this for SETEQ and SETNE.
1321 Opcode = AArch64ISD::CCMN;
1322 RHS = RHS.getOperand(1);
1323 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001324 }
1325 if (Opcode == 0)
1326 Opcode = AArch64ISD::CCMP;
1327
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001328 SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC);
1329 AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1330 unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001331 SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1332 return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1333}
1334
1335/// Returns true if @p Val is a tree of AND/OR/SETCC operations.
1336/// CanPushNegate is set to true if we can push a negate operation through
1337/// the tree in a was that we are left with AND operations and negate operations
1338/// at the leafs only. i.e. "not (or (or x y) z)" can be changed to
1339/// "and (and (not x) (not y)) (not z)"; "not (or (and x y) z)" cannot be
1340/// brought into such a form.
Matthias Braunfdef49b2016-01-23 04:05:22 +00001341static bool isConjunctionDisjunctionTree(const SDValue Val, bool &CanNegate,
Matthias Braunaf7d7702015-07-16 20:02:37 +00001342 unsigned Depth = 0) {
1343 if (!Val.hasOneUse())
1344 return false;
1345 unsigned Opcode = Val->getOpcode();
1346 if (Opcode == ISD::SETCC) {
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001347 if (Val->getOperand(0).getValueType() == MVT::f128)
1348 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001349 CanNegate = true;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001350 return true;
1351 }
Matthias Braun985bdf92016-01-23 04:05:18 +00001352 // Protect against exponential runtime and stack overflow.
1353 if (Depth > 6)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001354 return false;
1355 if (Opcode == ISD::AND || Opcode == ISD::OR) {
1356 SDValue O0 = Val->getOperand(0);
1357 SDValue O1 = Val->getOperand(1);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001358 bool CanNegateL;
1359 if (!isConjunctionDisjunctionTree(O0, CanNegateL, Depth+1))
Matthias Braunaf7d7702015-07-16 20:02:37 +00001360 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001361 bool CanNegateR;
1362 if (!isConjunctionDisjunctionTree(O1, CanNegateR, Depth+1))
Matthias Braunaf7d7702015-07-16 20:02:37 +00001363 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001364
1365 if (Opcode == ISD::OR) {
1366 // For an OR expression we need to be able to negate at least one side or
1367 // we cannot do the transformation at all.
1368 if (!CanNegateL && !CanNegateR)
1369 return false;
1370 // We can however change a (not (or x y)) to (and (not x) (not y)) if we
1371 // can negate the x and y subtrees.
1372 CanNegate = CanNegateL && CanNegateR;
1373 } else {
1374 // If the operands are OR expressions then we finally need to negate their
1375 // outputs, we can only do that for the operand with emitted last by
1376 // negating OutCC, not for both operands.
1377 bool NeedsNegOutL = O0->getOpcode() == ISD::OR;
1378 bool NeedsNegOutR = O1->getOpcode() == ISD::OR;
1379 if (NeedsNegOutL && NeedsNegOutR)
1380 return false;
1381 // We cannot negate an AND operation (it would become an OR),
1382 CanNegate = false;
1383 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001384 return true;
1385 }
1386 return false;
1387}
1388
1389/// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1390/// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1391/// Tries to transform the given i1 producing node @p Val to a series compare
1392/// and conditional compare operations. @returns an NZCV flags producing node
1393/// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1394/// transformation was not possible.
1395/// On recursive invocations @p PushNegate may be set to true to have negation
1396/// effects pushed to the tree leafs; @p Predicate is an NZCV flag predicate
1397/// for the comparisons in the current subtree; @p Depth limits the search
1398/// depth to avoid stack overflow.
Matthias Braunfdef49b2016-01-23 04:05:22 +00001399static SDValue emitConjunctionDisjunctionTreeRec(SelectionDAG &DAG, SDValue Val,
1400 AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp,
1401 AArch64CC::CondCode Predicate) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001402 // We're at a tree leaf, produce a conditional comparison operation.
1403 unsigned Opcode = Val->getOpcode();
1404 if (Opcode == ISD::SETCC) {
1405 SDValue LHS = Val->getOperand(0);
1406 SDValue RHS = Val->getOperand(1);
1407 ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1408 bool isInteger = LHS.getValueType().isInteger();
Matthias Braunfdef49b2016-01-23 04:05:22 +00001409 if (Negate)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001410 CC = getSetCCInverse(CC, isInteger);
1411 SDLoc DL(Val);
1412 // Determine OutCC and handle FP special case.
1413 if (isInteger) {
1414 OutCC = changeIntCCToAArch64CC(CC);
1415 } else {
1416 assert(LHS.getValueType().isFloatingPoint());
1417 AArch64CC::CondCode ExtraCC;
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001418 changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
1419 // Some floating point conditions can't be tested with a single condition
1420 // code. Construct an additional comparison in this case.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001421 if (ExtraCC != AArch64CC::AL) {
1422 SDValue ExtraCmp;
1423 if (!CCOp.getNode())
1424 ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001425 else
1426 ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate,
1427 ExtraCC, DL, DAG);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001428 CCOp = ExtraCmp;
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001429 Predicate = ExtraCC;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001430 }
1431 }
1432
1433 // Produce a normal comparison if we are first in the chain
Matthias Braunfdef49b2016-01-23 04:05:22 +00001434 if (!CCOp)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001435 return emitComparison(LHS, RHS, CC, DL, DAG);
1436 // Otherwise produce a ccmp.
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001437 return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL,
Matthias Braunaf7d7702015-07-16 20:02:37 +00001438 DAG);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001439 }
Junmo Park3ca3e192016-01-25 10:17:17 +00001440 assert((Opcode == ISD::AND || (Opcode == ISD::OR && Val->hasOneUse())) &&
1441 "Valid conjunction/disjunction tree");
Matthias Braunaf7d7702015-07-16 20:02:37 +00001442
1443 // Check if both sides can be transformed.
1444 SDValue LHS = Val->getOperand(0);
1445 SDValue RHS = Val->getOperand(1);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001446
Matthias Braunfdef49b2016-01-23 04:05:22 +00001447 // In case of an OR we need to negate our operands and the result.
1448 // (A v B) <=> not(not(A) ^ not(B))
1449 bool NegateOpsAndResult = Opcode == ISD::OR;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001450 // We can negate the results of all previous operations by inverting the
Matthias Braunfdef49b2016-01-23 04:05:22 +00001451 // predicate flags giving us a free negation for one side. The other side
1452 // must be negatable by itself.
1453 if (NegateOpsAndResult) {
1454 // See which side we can negate.
1455 bool CanNegateL;
1456 bool isValidL = isConjunctionDisjunctionTree(LHS, CanNegateL);
1457 assert(isValidL && "Valid conjunction/disjunction tree");
1458 (void)isValidL;
1459
1460#ifndef NDEBUG
1461 bool CanNegateR;
1462 bool isValidR = isConjunctionDisjunctionTree(RHS, CanNegateR);
1463 assert(isValidR && "Valid conjunction/disjunction tree");
1464 assert((CanNegateL || CanNegateR) && "Valid conjunction/disjunction tree");
1465#endif
1466
1467 // Order the side which we cannot negate to RHS so we can emit it first.
1468 if (!CanNegateL)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001469 std::swap(LHS, RHS);
Matthias Braun46e56392015-08-20 23:33:34 +00001470 } else {
1471 bool NeedsNegOutL = LHS->getOpcode() == ISD::OR;
Matthias Braun327bca72016-01-23 06:49:29 +00001472 assert((!NeedsNegOutL || RHS->getOpcode() != ISD::OR) &&
Matthias Braunfdef49b2016-01-23 04:05:22 +00001473 "Valid conjunction/disjunction tree");
Matthias Braun46e56392015-08-20 23:33:34 +00001474 // Order the side where we need to negate the output flags to RHS so it
1475 // gets emitted first.
1476 if (NeedsNegOutL)
1477 std::swap(LHS, RHS);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001478 }
1479
1480 // Emit RHS. If we want to negate the tree we only need to push a negate
1481 // through if we are already in a PushNegate case, otherwise we can negate
1482 // the "flags to test" afterwards.
1483 AArch64CC::CondCode RHSCC;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001484 SDValue CmpR = emitConjunctionDisjunctionTreeRec(DAG, RHS, RHSCC, Negate,
1485 CCOp, Predicate);
1486 if (NegateOpsAndResult && !Negate)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001487 RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001488 // Emit LHS. We may need to negate it.
1489 SDValue CmpL = emitConjunctionDisjunctionTreeRec(DAG, LHS, OutCC,
1490 NegateOpsAndResult, CmpR,
1491 RHSCC);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001492 // If we transformed an OR to and AND then we have to negate the result
Matthias Braunfdef49b2016-01-23 04:05:22 +00001493 // (or absorb the Negate parameter).
1494 if (NegateOpsAndResult && !Negate)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001495 OutCC = AArch64CC::getInvertedCondCode(OutCC);
1496 return CmpL;
1497}
1498
Matthias Braunfdef49b2016-01-23 04:05:22 +00001499/// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1500/// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1501/// \see emitConjunctionDisjunctionTreeRec().
1502static SDValue emitConjunctionDisjunctionTree(SelectionDAG &DAG, SDValue Val,
1503 AArch64CC::CondCode &OutCC) {
1504 bool CanNegate;
1505 if (!isConjunctionDisjunctionTree(Val, CanNegate))
1506 return SDValue();
1507
1508 return emitConjunctionDisjunctionTreeRec(DAG, Val, OutCC, false, SDValue(),
1509 AArch64CC::AL);
1510}
1511
Matthias Braunaf7d7702015-07-16 20:02:37 +00001512/// @}
1513
Tim Northover3b0846e2014-05-24 12:50:23 +00001514static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00001515 SDValue &AArch64cc, SelectionDAG &DAG,
1516 const SDLoc &dl) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001517 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1518 EVT VT = RHS.getValueType();
1519 uint64_t C = RHSC->getZExtValue();
1520 if (!isLegalArithImmed(C)) {
1521 // Constant does not fit, try adjusting it by one?
1522 switch (CC) {
1523 default:
1524 break;
1525 case ISD::SETLT:
1526 case ISD::SETGE:
1527 if ((VT == MVT::i32 && C != 0x80000000 &&
1528 isLegalArithImmed((uint32_t)(C - 1))) ||
1529 (VT == MVT::i64 && C != 0x80000000ULL &&
1530 isLegalArithImmed(C - 1ULL))) {
1531 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1532 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001533 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001534 }
1535 break;
1536 case ISD::SETULT:
1537 case ISD::SETUGE:
1538 if ((VT == MVT::i32 && C != 0 &&
1539 isLegalArithImmed((uint32_t)(C - 1))) ||
1540 (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1541 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1542 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001543 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001544 }
1545 break;
1546 case ISD::SETLE:
1547 case ISD::SETGT:
Oliver Stannard269a275c2014-11-03 15:28:40 +00001548 if ((VT == MVT::i32 && C != INT32_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001549 isLegalArithImmed((uint32_t)(C + 1))) ||
Oliver Stannard269a275c2014-11-03 15:28:40 +00001550 (VT == MVT::i64 && C != INT64_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001551 isLegalArithImmed(C + 1ULL))) {
1552 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1553 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001554 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001555 }
1556 break;
1557 case ISD::SETULE:
1558 case ISD::SETUGT:
Oliver Stannard269a275c2014-11-03 15:28:40 +00001559 if ((VT == MVT::i32 && C != UINT32_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001560 isLegalArithImmed((uint32_t)(C + 1))) ||
Oliver Stannard269a275c2014-11-03 15:28:40 +00001561 (VT == MVT::i64 && C != UINT64_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001562 isLegalArithImmed(C + 1ULL))) {
1563 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1564 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001565 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001566 }
1567 break;
1568 }
1569 }
1570 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001571 SDValue Cmp;
1572 AArch64CC::CondCode AArch64CC;
David Xuee978202014-08-28 04:59:53 +00001573 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001574 const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
1575
1576 // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
1577 // For the i8 operand, the largest immediate is 255, so this can be easily
1578 // encoded in the compare instruction. For the i16 operand, however, the
1579 // largest immediate cannot be encoded in the compare.
1580 // Therefore, use a sign extending load and cmn to avoid materializing the
1581 // -1 constant. For example,
1582 // movz w1, #65535
1583 // ldrh w0, [x0, #0]
1584 // cmp w0, w1
1585 // >
1586 // ldrsh w0, [x0, #0]
1587 // cmn w0, #1
1588 // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
1589 // if and only if (sext LHS) == (sext RHS). The checks are in place to
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001590 // ensure both the LHS and RHS are truly zero extended and to make sure the
Matthias Braunaf7d7702015-07-16 20:02:37 +00001591 // transformation is profitable.
1592 if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
1593 cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
1594 cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
1595 LHS.getNode()->hasNUsesOfValue(1, 0)) {
1596 int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
1597 if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
1598 SDValue SExt =
1599 DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
1600 DAG.getValueType(MVT::i16));
1601 Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
1602 RHS.getValueType()),
1603 CC, dl, DAG);
1604 AArch64CC = changeIntCCToAArch64CC(CC);
1605 }
1606 }
1607
1608 if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
1609 if ((Cmp = emitConjunctionDisjunctionTree(DAG, LHS, AArch64CC))) {
1610 if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
1611 AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
David Xuee978202014-08-28 04:59:53 +00001612 }
1613 }
1614 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001615
1616 if (!Cmp) {
1617 Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
1618 AArch64CC = changeIntCCToAArch64CC(CC);
1619 }
1620 AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
Tim Northover3b0846e2014-05-24 12:50:23 +00001621 return Cmp;
1622}
1623
1624static std::pair<SDValue, SDValue>
1625getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
1626 assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
1627 "Unsupported value type");
1628 SDValue Value, Overflow;
1629 SDLoc DL(Op);
1630 SDValue LHS = Op.getOperand(0);
1631 SDValue RHS = Op.getOperand(1);
1632 unsigned Opc = 0;
1633 switch (Op.getOpcode()) {
1634 default:
1635 llvm_unreachable("Unknown overflow instruction!");
1636 case ISD::SADDO:
1637 Opc = AArch64ISD::ADDS;
1638 CC = AArch64CC::VS;
1639 break;
1640 case ISD::UADDO:
1641 Opc = AArch64ISD::ADDS;
1642 CC = AArch64CC::HS;
1643 break;
1644 case ISD::SSUBO:
1645 Opc = AArch64ISD::SUBS;
1646 CC = AArch64CC::VS;
1647 break;
1648 case ISD::USUBO:
1649 Opc = AArch64ISD::SUBS;
1650 CC = AArch64CC::LO;
1651 break;
1652 // Multiply needs a little bit extra work.
1653 case ISD::SMULO:
1654 case ISD::UMULO: {
1655 CC = AArch64CC::NE;
David Blaikie186d2cb2015-03-24 16:24:01 +00001656 bool IsSigned = Op.getOpcode() == ISD::SMULO;
Tim Northover3b0846e2014-05-24 12:50:23 +00001657 if (Op.getValueType() == MVT::i32) {
1658 unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1659 // For a 32 bit multiply with overflow check we want the instruction
1660 // selector to generate a widening multiply (SMADDL/UMADDL). For that we
1661 // need to generate the following pattern:
1662 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
1663 LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
1664 RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
1665 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1666 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001667 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001668 // On AArch64 the upper 32 bits are always zero extended for a 32 bit
1669 // operation. We need to clear out the upper 32 bits, because we used a
1670 // widening multiply that wrote all 64 bits. In the end this should be a
1671 // noop.
1672 Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
1673 if (IsSigned) {
1674 // The signed overflow check requires more than just a simple check for
1675 // any bit set in the upper 32 bits of the result. These bits could be
1676 // just the sign bits of a negative number. To perform the overflow
1677 // check we have to arithmetic shift right the 32nd bit of the result by
1678 // 31 bits. Then we compare the result to the upper 32 bits.
1679 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001680 DAG.getConstant(32, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001681 UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
1682 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001683 DAG.getConstant(31, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001684 // It is important that LowerBits is last, otherwise the arithmetic
1685 // shift will not be folded into the compare (SUBS).
1686 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
1687 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1688 .getValue(1);
1689 } else {
1690 // The overflow check for unsigned multiply is easy. We only need to
1691 // check if any of the upper 32 bits are set. This can be done with a
1692 // CMP (shifted register). For that we need to generate the following
1693 // pattern:
1694 // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
1695 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001696 DAG.getConstant(32, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001697 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1698 Overflow =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001699 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1700 DAG.getConstant(0, DL, MVT::i64),
Tim Northover3b0846e2014-05-24 12:50:23 +00001701 UpperBits).getValue(1);
1702 }
1703 break;
1704 }
1705 assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
1706 // For the 64 bit multiply
1707 Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1708 if (IsSigned) {
1709 SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
1710 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001711 DAG.getConstant(63, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001712 // It is important that LowerBits is last, otherwise the arithmetic
1713 // shift will not be folded into the compare (SUBS).
1714 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1715 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1716 .getValue(1);
1717 } else {
1718 SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
1719 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 } // switch (...)
1728
1729 if (Opc) {
1730 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
1731
1732 // Emit the AArch64 operation with overflow check.
1733 Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
1734 Overflow = Value.getValue(1);
1735 }
1736 return std::make_pair(Value, Overflow);
1737}
1738
1739SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
1740 RTLIB::Libcall Call) const {
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00001741 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
Craig Topper8fe40e02015-10-22 17:05:00 +00001742 return makeLibCall(DAG, Call, MVT::f128, Ops, false, SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00001743}
1744
1745static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
1746 SDValue Sel = Op.getOperand(0);
1747 SDValue Other = Op.getOperand(1);
1748
1749 // If neither operand is a SELECT_CC, give up.
1750 if (Sel.getOpcode() != ISD::SELECT_CC)
1751 std::swap(Sel, Other);
1752 if (Sel.getOpcode() != ISD::SELECT_CC)
1753 return Op;
1754
1755 // The folding we want to perform is:
1756 // (xor x, (select_cc a, b, cc, 0, -1) )
1757 // -->
1758 // (csel x, (xor x, -1), cc ...)
1759 //
1760 // The latter will get matched to a CSINV instruction.
1761
1762 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
1763 SDValue LHS = Sel.getOperand(0);
1764 SDValue RHS = Sel.getOperand(1);
1765 SDValue TVal = Sel.getOperand(2);
1766 SDValue FVal = Sel.getOperand(3);
1767 SDLoc dl(Sel);
1768
1769 // FIXME: This could be generalized to non-integer comparisons.
1770 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
1771 return Op;
1772
1773 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
1774 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
1775
Eric Christopher572e03a2015-06-19 01:53:21 +00001776 // The values aren't constants, this isn't the pattern we're looking for.
Tim Northover3b0846e2014-05-24 12:50:23 +00001777 if (!CFVal || !CTVal)
1778 return Op;
1779
1780 // We can commute the SELECT_CC by inverting the condition. This
1781 // might be needed to make this fit into a CSINV pattern.
1782 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
1783 std::swap(TVal, FVal);
1784 std::swap(CTVal, CFVal);
1785 CC = ISD::getSetCCInverse(CC, true);
1786 }
1787
1788 // If the constants line up, perform the transform!
1789 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
1790 SDValue CCVal;
1791 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
1792
1793 FVal = Other;
1794 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001795 DAG.getConstant(-1ULL, dl, Other.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00001796
1797 return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
1798 CCVal, Cmp);
1799 }
1800
1801 return Op;
1802}
1803
1804static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
1805 EVT VT = Op.getValueType();
1806
1807 // Let legalize expand this if it isn't a legal type yet.
1808 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
1809 return SDValue();
1810
1811 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
1812
1813 unsigned Opc;
1814 bool ExtraOp = false;
1815 switch (Op.getOpcode()) {
1816 default:
Craig Topper2a30d782014-06-18 05:05:13 +00001817 llvm_unreachable("Invalid code");
Tim Northover3b0846e2014-05-24 12:50:23 +00001818 case ISD::ADDC:
1819 Opc = AArch64ISD::ADDS;
1820 break;
1821 case ISD::SUBC:
1822 Opc = AArch64ISD::SUBS;
1823 break;
1824 case ISD::ADDE:
1825 Opc = AArch64ISD::ADCS;
1826 ExtraOp = true;
1827 break;
1828 case ISD::SUBE:
1829 Opc = AArch64ISD::SBCS;
1830 ExtraOp = true;
1831 break;
1832 }
1833
1834 if (!ExtraOp)
1835 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
1836 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
1837 Op.getOperand(2));
1838}
1839
1840static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
1841 // Let legalize expand this if it isn't a legal type yet.
1842 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
1843 return SDValue();
1844
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001845 SDLoc dl(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00001846 AArch64CC::CondCode CC;
1847 // The actual operation that sets the overflow or carry flag.
1848 SDValue Value, Overflow;
1849 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
1850
1851 // We use 0 and 1 as false and true values.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001852 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
1853 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00001854
1855 // We use an inverted condition, because the conditional select is inverted
1856 // too. This will allow it to be selected to a single instruction:
1857 // CSINC Wd, WZR, WZR, invert(cond).
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001858 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
1859 Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
Tim Northover3b0846e2014-05-24 12:50:23 +00001860 CCVal, Overflow);
1861
1862 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001863 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
Tim Northover3b0846e2014-05-24 12:50:23 +00001864}
1865
1866// Prefetch operands are:
1867// 1: Address to prefetch
1868// 2: bool isWrite
1869// 3: int locality (0 = no locality ... 3 = extreme locality)
1870// 4: bool isDataCache
1871static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
1872 SDLoc DL(Op);
1873 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
1874 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
Yi Konge56de692014-08-05 12:46:47 +00001875 unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00001876
1877 bool IsStream = !Locality;
1878 // When the locality number is set
1879 if (Locality) {
1880 // The front-end should have filtered out the out-of-range values
1881 assert(Locality <= 3 && "Prefetch locality out-of-range");
1882 // The locality degree is the opposite of the cache speed.
1883 // Put the number the other way around.
1884 // The encoding starts at 0 for level 1
1885 Locality = 3 - Locality;
1886 }
1887
1888 // built the mask value encoding the expected behavior.
1889 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit
Yi Konge56de692014-08-05 12:46:47 +00001890 (!IsData << 3) | // IsDataCache bit
Tim Northover3b0846e2014-05-24 12:50:23 +00001891 (Locality << 1) | // Cache level bits
1892 (unsigned)IsStream; // Stream bit
1893 return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001894 DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00001895}
1896
1897SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
1898 SelectionDAG &DAG) const {
1899 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
1900
1901 RTLIB::Libcall LC;
1902 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
1903
1904 return LowerF128Call(Op, DAG, LC);
1905}
1906
1907SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
1908 SelectionDAG &DAG) const {
1909 if (Op.getOperand(0).getValueType() != MVT::f128) {
1910 // It's legal except when f128 is involved
1911 return Op;
1912 }
1913
1914 RTLIB::Libcall LC;
1915 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
1916
1917 // FP_ROUND node has a second operand indicating whether it is known to be
1918 // precise. That doesn't take part in the LibCall so we can't directly use
1919 // LowerF128Call.
1920 SDValue SrcVal = Op.getOperand(0);
Craig Topper8fe40e02015-10-22 17:05:00 +00001921 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
1922 SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00001923}
1924
1925static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
1926 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1927 // Any additional optimization in this function should be recorded
1928 // in the cost tables.
1929 EVT InVT = Op.getOperand(0).getValueType();
1930 EVT VT = Op.getValueType();
Pirama Arumuga Nainar1317d5f2015-12-10 17:16:49 +00001931 unsigned NumElts = InVT.getVectorNumElements();
1932
1933 // f16 vectors are promoted to f32 before a conversion.
1934 if (InVT.getVectorElementType() == MVT::f16) {
1935 MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
1936 SDLoc dl(Op);
1937 return DAG.getNode(
1938 Op.getOpcode(), dl, Op.getValueType(),
1939 DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
1940 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001941
Tim Northoverdbecc3b2014-06-15 09:27:15 +00001942 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001943 SDLoc dl(Op);
1944 SDValue Cv =
1945 DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
1946 Op.getOperand(0));
1947 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
Tim Northoverdbecc3b2014-06-15 09:27:15 +00001948 }
1949
1950 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001951 SDLoc dl(Op);
Oliver Stannard89d15422014-08-27 16:16:04 +00001952 MVT ExtVT =
1953 MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
1954 VT.getVectorNumElements());
1955 SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
Tim Northover3b0846e2014-05-24 12:50:23 +00001956 return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
1957 }
1958
1959 // Type changing conversions are illegal.
Tim Northoverdbecc3b2014-06-15 09:27:15 +00001960 return Op;
Tim Northover3b0846e2014-05-24 12:50:23 +00001961}
1962
1963SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
1964 SelectionDAG &DAG) const {
1965 if (Op.getOperand(0).getValueType().isVector())
1966 return LowerVectorFP_TO_INT(Op, DAG);
1967
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00001968 // f16 conversions are promoted to f32.
1969 if (Op.getOperand(0).getValueType() == MVT::f16) {
1970 SDLoc dl(Op);
1971 return DAG.getNode(
1972 Op.getOpcode(), dl, Op.getValueType(),
1973 DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
1974 }
1975
Tim Northover3b0846e2014-05-24 12:50:23 +00001976 if (Op.getOperand(0).getValueType() != MVT::f128) {
1977 // It's legal except when f128 is involved
1978 return Op;
1979 }
1980
1981 RTLIB::Libcall LC;
1982 if (Op.getOpcode() == ISD::FP_TO_SINT)
1983 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
1984 else
1985 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
1986
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00001987 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
Craig Topper8fe40e02015-10-22 17:05:00 +00001988 return makeLibCall(DAG, LC, Op.getValueType(), Ops, false, SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00001989}
1990
1991static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
1992 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1993 // Any additional optimization in this function should be recorded
1994 // in the cost tables.
1995 EVT VT = Op.getValueType();
1996 SDLoc dl(Op);
1997 SDValue In = Op.getOperand(0);
1998 EVT InVT = In.getValueType();
1999
Tim Northoveref0d7602014-06-15 09:27:06 +00002000 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2001 MVT CastVT =
2002 MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
2003 InVT.getVectorNumElements());
2004 In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002005 return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
Tim Northover3b0846e2014-05-24 12:50:23 +00002006 }
2007
Tim Northoveref0d7602014-06-15 09:27:06 +00002008 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2009 unsigned CastOpc =
2010 Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2011 EVT CastVT = VT.changeVectorElementTypeToInteger();
2012 In = DAG.getNode(CastOpc, dl, CastVT, In);
2013 return DAG.getNode(Op.getOpcode(), dl, VT, In);
Tim Northover3b0846e2014-05-24 12:50:23 +00002014 }
2015
Tim Northoveref0d7602014-06-15 09:27:06 +00002016 return Op;
Tim Northover3b0846e2014-05-24 12:50:23 +00002017}
2018
2019SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
2020 SelectionDAG &DAG) const {
2021 if (Op.getValueType().isVector())
2022 return LowerVectorINT_TO_FP(Op, DAG);
2023
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00002024 // f16 conversions are promoted to f32.
2025 if (Op.getValueType() == MVT::f16) {
2026 SDLoc dl(Op);
2027 return DAG.getNode(
2028 ISD::FP_ROUND, dl, MVT::f16,
2029 DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002030 DAG.getIntPtrConstant(0, dl));
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00002031 }
2032
Tim Northover3b0846e2014-05-24 12:50:23 +00002033 // i128 conversions are libcalls.
2034 if (Op.getOperand(0).getValueType() == MVT::i128)
2035 return SDValue();
2036
2037 // Other conversions are legal, unless it's to the completely software-based
2038 // fp128.
2039 if (Op.getValueType() != MVT::f128)
2040 return Op;
2041
2042 RTLIB::Libcall LC;
2043 if (Op.getOpcode() == ISD::SINT_TO_FP)
2044 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2045 else
2046 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2047
2048 return LowerF128Call(Op, DAG, LC);
2049}
2050
2051SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
2052 SelectionDAG &DAG) const {
2053 // For iOS, we want to call an alternative entry point: __sincos_stret,
2054 // which returns the values in two S / D registers.
2055 SDLoc dl(Op);
2056 SDValue Arg = Op.getOperand(0);
2057 EVT ArgVT = Arg.getValueType();
2058 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2059
2060 ArgListTy Args;
2061 ArgListEntry Entry;
2062
2063 Entry.Node = Arg;
2064 Entry.Ty = ArgTy;
2065 Entry.isSExt = false;
2066 Entry.isZExt = false;
2067 Args.push_back(Entry);
2068
2069 const char *LibcallName =
2070 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
Mehdi Amini44ede332015-07-09 02:09:04 +00002071 SDValue Callee =
2072 DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00002073
Reid Kleckner343c3952014-11-20 23:51:47 +00002074 StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
Tim Northover3b0846e2014-05-24 12:50:23 +00002075 TargetLowering::CallLoweringInfo CLI(DAG);
2076 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
Krzysztof Parzyszeke116d5002016-06-22 12:54:25 +00002077 .setCallee(CallingConv::Fast, RetTy, Callee, std::move(Args));
Tim Northover3b0846e2014-05-24 12:50:23 +00002078
2079 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2080 return CallResult.first;
2081}
2082
Tim Northoverf8bfe212014-07-18 13:07:05 +00002083static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
2084 if (Op.getValueType() != MVT::f16)
2085 return SDValue();
2086
2087 assert(Op.getOperand(0).getValueType() == MVT::i16);
2088 SDLoc DL(Op);
2089
2090 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
2091 Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
2092 return SDValue(
2093 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002094 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
Tim Northoverf8bfe212014-07-18 13:07:05 +00002095 0);
2096}
2097
Chad Rosierd9d0f862014-10-08 02:31:24 +00002098static EVT getExtensionTo64Bits(const EVT &OrigVT) {
2099 if (OrigVT.getSizeInBits() >= 64)
2100 return OrigVT;
2101
2102 assert(OrigVT.isSimple() && "Expecting a simple value type");
2103
2104 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
2105 switch (OrigSimpleTy) {
2106 default: llvm_unreachable("Unexpected Vector Type");
2107 case MVT::v2i8:
2108 case MVT::v2i16:
2109 return MVT::v2i32;
2110 case MVT::v4i8:
2111 return MVT::v4i16;
2112 }
2113}
2114
2115static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2116 const EVT &OrigTy,
2117 const EVT &ExtTy,
2118 unsigned ExtOpcode) {
2119 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2120 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2121 // 64-bits we need to insert a new extension so that it will be 64-bits.
2122 assert(ExtTy.is128BitVector() && "Unexpected extension size");
2123 if (OrigTy.getSizeInBits() >= 64)
2124 return N;
2125
2126 // Must extend size to at least 64 bits to be used as an operand for VMULL.
2127 EVT NewVT = getExtensionTo64Bits(OrigTy);
2128
2129 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2130}
2131
2132static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2133 bool isSigned) {
2134 EVT VT = N->getValueType(0);
2135
2136 if (N->getOpcode() != ISD::BUILD_VECTOR)
2137 return false;
2138
Pete Cooper3af9a252015-06-26 18:17:36 +00002139 for (const SDValue &Elt : N->op_values()) {
Chad Rosierd9d0f862014-10-08 02:31:24 +00002140 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
Sanjay Patel1ed771f2016-09-14 16:37:15 +00002141 unsigned EltSize = VT.getScalarSizeInBits();
Chad Rosierd9d0f862014-10-08 02:31:24 +00002142 unsigned HalfSize = EltSize / 2;
2143 if (isSigned) {
2144 if (!isIntN(HalfSize, C->getSExtValue()))
2145 return false;
2146 } else {
2147 if (!isUIntN(HalfSize, C->getZExtValue()))
2148 return false;
2149 }
2150 continue;
2151 }
2152 return false;
2153 }
2154
2155 return true;
2156}
2157
2158static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2159 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2160 return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2161 N->getOperand(0)->getValueType(0),
2162 N->getValueType(0),
2163 N->getOpcode());
2164
2165 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2166 EVT VT = N->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002167 SDLoc dl(N);
Sanjay Patel1ed771f2016-09-14 16:37:15 +00002168 unsigned EltSize = VT.getScalarSizeInBits() / 2;
Chad Rosierd9d0f862014-10-08 02:31:24 +00002169 unsigned NumElts = VT.getVectorNumElements();
2170 MVT TruncVT = MVT::getIntegerVT(EltSize);
2171 SmallVector<SDValue, 8> Ops;
2172 for (unsigned i = 0; i != NumElts; ++i) {
2173 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2174 const APInt &CInt = C->getAPIntValue();
2175 // Element types smaller than 32 bits are not legal, so use i32 elements.
2176 // The values are implicitly truncated so sext vs. zext doesn't matter.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002177 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
Chad Rosierd9d0f862014-10-08 02:31:24 +00002178 }
Ahmed Bougacha128f8732016-04-26 21:15:30 +00002179 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002180}
2181
2182static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
2183 if (N->getOpcode() == ISD::SIGN_EXTEND)
2184 return true;
2185 if (isExtendedBUILD_VECTOR(N, DAG, true))
2186 return true;
2187 return false;
2188}
2189
2190static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
2191 if (N->getOpcode() == ISD::ZERO_EXTEND)
2192 return true;
2193 if (isExtendedBUILD_VECTOR(N, DAG, false))
2194 return true;
2195 return false;
2196}
2197
2198static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2199 unsigned Opcode = N->getOpcode();
2200 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2201 SDNode *N0 = N->getOperand(0).getNode();
2202 SDNode *N1 = N->getOperand(1).getNode();
2203 return N0->hasOneUse() && N1->hasOneUse() &&
2204 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2205 }
2206 return false;
2207}
2208
2209static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2210 unsigned Opcode = N->getOpcode();
2211 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2212 SDNode *N0 = N->getOperand(0).getNode();
2213 SDNode *N1 = N->getOperand(1).getNode();
2214 return N0->hasOneUse() && N1->hasOneUse() &&
2215 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2216 }
2217 return false;
2218}
2219
2220static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2221 // Multiplications are only custom-lowered for 128-bit vectors so that
2222 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
2223 EVT VT = Op.getValueType();
2224 assert(VT.is128BitVector() && VT.isInteger() &&
2225 "unexpected type for custom-lowering ISD::MUL");
2226 SDNode *N0 = Op.getOperand(0).getNode();
2227 SDNode *N1 = Op.getOperand(1).getNode();
2228 unsigned NewOpc = 0;
2229 bool isMLA = false;
2230 bool isN0SExt = isSignExtended(N0, DAG);
2231 bool isN1SExt = isSignExtended(N1, DAG);
2232 if (isN0SExt && isN1SExt)
2233 NewOpc = AArch64ISD::SMULL;
2234 else {
2235 bool isN0ZExt = isZeroExtended(N0, DAG);
2236 bool isN1ZExt = isZeroExtended(N1, DAG);
2237 if (isN0ZExt && isN1ZExt)
2238 NewOpc = AArch64ISD::UMULL;
2239 else if (isN1SExt || isN1ZExt) {
2240 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2241 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2242 if (isN1SExt && isAddSubSExt(N0, DAG)) {
2243 NewOpc = AArch64ISD::SMULL;
2244 isMLA = true;
2245 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2246 NewOpc = AArch64ISD::UMULL;
2247 isMLA = true;
2248 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2249 std::swap(N0, N1);
2250 NewOpc = AArch64ISD::UMULL;
2251 isMLA = true;
2252 }
2253 }
2254
2255 if (!NewOpc) {
2256 if (VT == MVT::v2i64)
2257 // Fall through to expand this. It is not legal.
2258 return SDValue();
2259 else
2260 // Other vector multiplications are legal.
2261 return Op;
2262 }
2263 }
2264
2265 // Legalize to a S/UMULL instruction
2266 SDLoc DL(Op);
2267 SDValue Op0;
2268 SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2269 if (!isMLA) {
2270 Op0 = skipExtensionForVectorMULL(N0, DAG);
2271 assert(Op0.getValueType().is64BitVector() &&
2272 Op1.getValueType().is64BitVector() &&
2273 "unexpected types for extended operands to VMULL");
2274 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2275 }
2276 // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2277 // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2278 // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2279 SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2280 SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2281 EVT Op1VT = Op1.getValueType();
2282 return DAG.getNode(N0->getOpcode(), DL, VT,
2283 DAG.getNode(NewOpc, DL, VT,
2284 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2285 DAG.getNode(NewOpc, DL, VT,
2286 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2287}
Tim Northoverf8bfe212014-07-18 13:07:05 +00002288
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002289SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2290 SelectionDAG &DAG) const {
2291 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2292 SDLoc dl(Op);
2293 switch (IntNo) {
2294 default: return SDValue(); // Don't custom lower most intrinsics.
Marcin Koscielnicki3fdc2572016-04-19 20:51:05 +00002295 case Intrinsic::thread_pointer: {
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002296 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2297 return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
2298 }
Silviu Barangadb1ddb32015-08-26 11:11:14 +00002299 case Intrinsic::aarch64_neon_smax:
2300 return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
2301 Op.getOperand(1), Op.getOperand(2));
2302 case Intrinsic::aarch64_neon_umax:
2303 return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
2304 Op.getOperand(1), Op.getOperand(2));
2305 case Intrinsic::aarch64_neon_smin:
2306 return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
2307 Op.getOperand(1), Op.getOperand(2));
2308 case Intrinsic::aarch64_neon_umin:
2309 return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
2310 Op.getOperand(1), Op.getOperand(2));
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002311 }
2312}
2313
Tim Northover3b0846e2014-05-24 12:50:23 +00002314SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
2315 SelectionDAG &DAG) const {
2316 switch (Op.getOpcode()) {
2317 default:
2318 llvm_unreachable("unimplemented operand");
2319 return SDValue();
Tim Northoverf8bfe212014-07-18 13:07:05 +00002320 case ISD::BITCAST:
2321 return LowerBITCAST(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002322 case ISD::GlobalAddress:
2323 return LowerGlobalAddress(Op, DAG);
2324 case ISD::GlobalTLSAddress:
2325 return LowerGlobalTLSAddress(Op, DAG);
2326 case ISD::SETCC:
2327 return LowerSETCC(Op, DAG);
2328 case ISD::BR_CC:
2329 return LowerBR_CC(Op, DAG);
2330 case ISD::SELECT:
2331 return LowerSELECT(Op, DAG);
2332 case ISD::SELECT_CC:
2333 return LowerSELECT_CC(Op, DAG);
2334 case ISD::JumpTable:
2335 return LowerJumpTable(Op, DAG);
2336 case ISD::ConstantPool:
2337 return LowerConstantPool(Op, DAG);
2338 case ISD::BlockAddress:
2339 return LowerBlockAddress(Op, DAG);
2340 case ISD::VASTART:
2341 return LowerVASTART(Op, DAG);
2342 case ISD::VACOPY:
2343 return LowerVACOPY(Op, DAG);
2344 case ISD::VAARG:
2345 return LowerVAARG(Op, DAG);
2346 case ISD::ADDC:
2347 case ISD::ADDE:
2348 case ISD::SUBC:
2349 case ISD::SUBE:
2350 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
2351 case ISD::SADDO:
2352 case ISD::UADDO:
2353 case ISD::SSUBO:
2354 case ISD::USUBO:
2355 case ISD::SMULO:
2356 case ISD::UMULO:
2357 return LowerXALUO(Op, DAG);
2358 case ISD::FADD:
2359 return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
2360 case ISD::FSUB:
2361 return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
2362 case ISD::FMUL:
2363 return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
2364 case ISD::FDIV:
2365 return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
2366 case ISD::FP_ROUND:
2367 return LowerFP_ROUND(Op, DAG);
2368 case ISD::FP_EXTEND:
2369 return LowerFP_EXTEND(Op, DAG);
2370 case ISD::FRAMEADDR:
2371 return LowerFRAMEADDR(Op, DAG);
2372 case ISD::RETURNADDR:
2373 return LowerRETURNADDR(Op, DAG);
2374 case ISD::INSERT_VECTOR_ELT:
2375 return LowerINSERT_VECTOR_ELT(Op, DAG);
2376 case ISD::EXTRACT_VECTOR_ELT:
2377 return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2378 case ISD::BUILD_VECTOR:
2379 return LowerBUILD_VECTOR(Op, DAG);
2380 case ISD::VECTOR_SHUFFLE:
2381 return LowerVECTOR_SHUFFLE(Op, DAG);
2382 case ISD::EXTRACT_SUBVECTOR:
2383 return LowerEXTRACT_SUBVECTOR(Op, DAG);
2384 case ISD::SRA:
2385 case ISD::SRL:
2386 case ISD::SHL:
2387 return LowerVectorSRA_SRL_SHL(Op, DAG);
2388 case ISD::SHL_PARTS:
2389 return LowerShiftLeftParts(Op, DAG);
2390 case ISD::SRL_PARTS:
2391 case ISD::SRA_PARTS:
2392 return LowerShiftRightParts(Op, DAG);
2393 case ISD::CTPOP:
2394 return LowerCTPOP(Op, DAG);
2395 case ISD::FCOPYSIGN:
2396 return LowerFCOPYSIGN(Op, DAG);
2397 case ISD::AND:
Balaram Makamd4acd7e2016-07-05 20:24:05 +00002398 return LowerVectorAND(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002399 case ISD::OR:
Balaram Makamd4acd7e2016-07-05 20:24:05 +00002400 return LowerVectorOR(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002401 case ISD::XOR:
2402 return LowerXOR(Op, DAG);
2403 case ISD::PREFETCH:
2404 return LowerPREFETCH(Op, DAG);
2405 case ISD::SINT_TO_FP:
2406 case ISD::UINT_TO_FP:
2407 return LowerINT_TO_FP(Op, DAG);
2408 case ISD::FP_TO_SINT:
2409 case ISD::FP_TO_UINT:
2410 return LowerFP_TO_INT(Op, DAG);
2411 case ISD::FSINCOS:
2412 return LowerFSINCOS(Op, DAG);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002413 case ISD::MUL:
2414 return LowerMUL(Op, DAG);
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002415 case ISD::INTRINSIC_WO_CHAIN:
2416 return LowerINTRINSIC_WO_CHAIN(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002417 }
2418}
2419
Tim Northover3b0846e2014-05-24 12:50:23 +00002420//===----------------------------------------------------------------------===//
2421// Calling Convention Implementation
2422//===----------------------------------------------------------------------===//
2423
2424#include "AArch64GenCallingConv.inc"
2425
Robin Morisset039781e2014-08-29 21:53:01 +00002426/// Selects the correct CCAssignFn for a given CallingConvention value.
Tim Northover3b0846e2014-05-24 12:50:23 +00002427CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2428 bool IsVarArg) const {
2429 switch (CC) {
2430 default:
2431 llvm_unreachable("Unsupported calling convention.");
2432 case CallingConv::WebKit_JS:
2433 return CC_AArch64_WebKit_JS;
Greg Fitzgeraldfa78d082015-01-19 17:40:05 +00002434 case CallingConv::GHC:
2435 return CC_AArch64_GHC;
Tim Northover3b0846e2014-05-24 12:50:23 +00002436 case CallingConv::C:
2437 case CallingConv::Fast:
Roman Levenstein2792b3f2016-03-10 04:35:09 +00002438 case CallingConv::PreserveMost:
Manman Ren2828c572016-03-18 23:38:49 +00002439 case CallingConv::CXX_FAST_TLS:
Manman Ren66b54e92016-08-26 19:28:17 +00002440 case CallingConv::Swift:
Tim Northover3b0846e2014-05-24 12:50:23 +00002441 if (!Subtarget->isTargetDarwin())
2442 return CC_AArch64_AAPCS;
2443 return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
2444 }
2445}
2446
Tim Northover406024a2016-08-10 21:44:01 +00002447CCAssignFn *
2448AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const {
2449 return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
2450 : RetCC_AArch64_AAPCS;
2451}
2452
Tim Northover3b0846e2014-05-24 12:50:23 +00002453SDValue AArch64TargetLowering::LowerFormalArguments(
2454 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00002455 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2456 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00002457 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braun941a7052016-07-28 18:40:00 +00002458 MachineFrameInfo &MFI = MF.getFrameInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00002459
2460 // Assign locations to all of the incoming arguments.
2461 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002462 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2463 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002464
2465 // At this point, Ins[].VT may already be promoted to i32. To correctly
2466 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2467 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2468 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
2469 // we use a special version of AnalyzeFormalArguments to pass in ValVT and
2470 // LocVT.
2471 unsigned NumArgs = Ins.size();
2472 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2473 unsigned CurArgIdx = 0;
2474 for (unsigned i = 0; i != NumArgs; ++i) {
2475 MVT ValVT = Ins[i].VT;
Andrew Trick05938a52015-02-16 18:10:47 +00002476 if (Ins[i].isOrigArg()) {
2477 std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
2478 CurArgIdx = Ins[i].getOrigArgIndex();
Tim Northover3b0846e2014-05-24 12:50:23 +00002479
Andrew Trick05938a52015-02-16 18:10:47 +00002480 // Get type of the original argument.
Mehdi Amini44ede332015-07-09 02:09:04 +00002481 EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
2482 /*AllowUnknown*/ true);
Andrew Trick05938a52015-02-16 18:10:47 +00002483 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
2484 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2485 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2486 ValVT = MVT::i8;
2487 else if (ActualMVT == MVT::i16)
2488 ValVT = MVT::i16;
2489 }
Tim Northover3b0846e2014-05-24 12:50:23 +00002490 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2491 bool Res =
Tim Northover47e003c2014-05-26 17:21:53 +00002492 AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00002493 assert(!Res && "Call operand has unhandled type");
2494 (void)Res;
2495 }
2496 assert(ArgLocs.size() == Ins.size());
2497 SmallVector<SDValue, 16> ArgValues;
2498 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2499 CCValAssign &VA = ArgLocs[i];
2500
2501 if (Ins[i].Flags.isByVal()) {
2502 // Byval is used for HFAs in the PCS, but the system should work in a
2503 // non-compliant manner for larger structs.
Mehdi Amini44ede332015-07-09 02:09:04 +00002504 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00002505 int Size = Ins[i].Flags.getByValSize();
2506 unsigned NumRegs = (Size + 7) / 8;
2507
2508 // FIXME: This works on big-endian for composite byvals, which are the common
2509 // case. It should also work for fundamental types too.
2510 unsigned FrameIdx =
Matthias Braun941a7052016-07-28 18:40:00 +00002511 MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
Mehdi Amini44ede332015-07-09 02:09:04 +00002512 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00002513 InVals.push_back(FrameIdxN);
2514
2515 continue;
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002516 }
Junmo Park3b8c7152016-01-05 09:36:47 +00002517
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002518 if (VA.isRegLoc()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00002519 // Arguments stored in registers.
2520 EVT RegVT = VA.getLocVT();
2521
2522 SDValue ArgValue;
2523 const TargetRegisterClass *RC;
2524
2525 if (RegVT == MVT::i32)
2526 RC = &AArch64::GPR32RegClass;
2527 else if (RegVT == MVT::i64)
2528 RC = &AArch64::GPR64RegClass;
Oliver Stannard6eda6ff2014-07-11 13:33:46 +00002529 else if (RegVT == MVT::f16)
2530 RC = &AArch64::FPR16RegClass;
Tim Northover3b0846e2014-05-24 12:50:23 +00002531 else if (RegVT == MVT::f32)
2532 RC = &AArch64::FPR32RegClass;
2533 else if (RegVT == MVT::f64 || RegVT.is64BitVector())
2534 RC = &AArch64::FPR64RegClass;
2535 else if (RegVT == MVT::f128 || RegVT.is128BitVector())
2536 RC = &AArch64::FPR128RegClass;
2537 else
2538 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2539
2540 // Transform the arguments in physical registers into virtual ones.
2541 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2542 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2543
2544 // If this is an 8, 16 or 32-bit value, it is really passed promoted
2545 // to 64 bits. Insert an assert[sz]ext to capture this, then
2546 // truncate to the right size.
2547 switch (VA.getLocInfo()) {
2548 default:
2549 llvm_unreachable("Unknown loc info!");
2550 case CCValAssign::Full:
2551 break;
2552 case CCValAssign::BCvt:
2553 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
2554 break;
Tim Northover47e003c2014-05-26 17:21:53 +00002555 case CCValAssign::AExt:
Tim Northover3b0846e2014-05-24 12:50:23 +00002556 case CCValAssign::SExt:
Tim Northover3b0846e2014-05-24 12:50:23 +00002557 case CCValAssign::ZExt:
Tim Northover47e003c2014-05-26 17:21:53 +00002558 // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
2559 // nodes after our lowering.
2560 assert(RegVT == Ins[i].VT && "incorrect register location selected");
Tim Northover3b0846e2014-05-24 12:50:23 +00002561 break;
2562 }
2563
2564 InVals.push_back(ArgValue);
2565
2566 } else { // VA.isRegLoc()
2567 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
2568 unsigned ArgOffset = VA.getLocMemOffset();
Amara Emerson82da7d02014-08-15 14:29:57 +00002569 unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
Tim Northover3b0846e2014-05-24 12:50:23 +00002570
2571 uint32_t BEAlign = 0;
Tim Northover293d4142014-12-03 17:49:26 +00002572 if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
2573 !Ins[i].Flags.isInConsecutiveRegs())
Tim Northover3b0846e2014-05-24 12:50:23 +00002574 BEAlign = 8 - ArgSize;
2575
Matthias Braun941a7052016-07-28 18:40:00 +00002576 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
Tim Northover3b0846e2014-05-24 12:50:23 +00002577
2578 // Create load nodes to retrieve arguments from the stack.
Mehdi Amini44ede332015-07-09 02:09:04 +00002579 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00002580 SDValue ArgValue;
2581
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002582 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
Tim Northover47e003c2014-05-26 17:21:53 +00002583 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002584 MVT MemVT = VA.getValVT();
2585
Tim Northover47e003c2014-05-26 17:21:53 +00002586 switch (VA.getLocInfo()) {
2587 default:
2588 break;
Tim Northover6890add2014-06-03 13:54:53 +00002589 case CCValAssign::BCvt:
2590 MemVT = VA.getLocVT();
2591 break;
Tim Northover47e003c2014-05-26 17:21:53 +00002592 case CCValAssign::SExt:
2593 ExtType = ISD::SEXTLOAD;
2594 break;
2595 case CCValAssign::ZExt:
2596 ExtType = ISD::ZEXTLOAD;
2597 break;
2598 case CCValAssign::AExt:
2599 ExtType = ISD::EXTLOAD;
2600 break;
Tim Northover3b0846e2014-05-24 12:50:23 +00002601 }
2602
Alex Lorenze40c8a22015-08-11 23:09:45 +00002603 ArgValue = DAG.getExtLoad(
2604 ExtType, DL, VA.getLocVT(), Chain, FIN,
2605 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
Justin Lebar9c375812016-07-15 18:27:10 +00002606 MemVT);
Tim Northover47e003c2014-05-26 17:21:53 +00002607
Tim Northover3b0846e2014-05-24 12:50:23 +00002608 InVals.push_back(ArgValue);
2609 }
2610 }
2611
2612 // varargs
Matthias Braundff243e2016-04-12 02:16:13 +00002613 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Tim Northover3b0846e2014-05-24 12:50:23 +00002614 if (isVarArg) {
2615 if (!Subtarget->isTargetDarwin()) {
2616 // The AAPCS variadic function ABI is identical to the non-variadic
2617 // one. As a result there may be more arguments in registers and we should
2618 // save them for future reference.
2619 saveVarArgRegisters(CCInfo, DAG, DL, Chain);
2620 }
2621
Tim Northover3b0846e2014-05-24 12:50:23 +00002622 // This will point to the next argument passed via stack.
2623 unsigned StackOffset = CCInfo.getNextStackOffset();
2624 // We currently pass all varargs at 8-byte alignment.
2625 StackOffset = ((StackOffset + 7) & ~7);
Matthias Braun941a7052016-07-28 18:40:00 +00002626 FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true));
Tim Northover3b0846e2014-05-24 12:50:23 +00002627 }
2628
Tim Northover3b0846e2014-05-24 12:50:23 +00002629 unsigned StackArgSize = CCInfo.getNextStackOffset();
2630 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2631 if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
2632 // This is a non-standard ABI so by fiat I say we're allowed to make full
2633 // use of the stack area to be popped, which must be aligned to 16 bytes in
2634 // any case:
Rui Ueyamada00f2f2016-01-14 21:06:47 +00002635 StackArgSize = alignTo(StackArgSize, 16);
Tim Northover3b0846e2014-05-24 12:50:23 +00002636
2637 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
2638 // a multiple of 16.
2639 FuncInfo->setArgumentStackToRestore(StackArgSize);
2640
2641 // This realignment carries over to the available bytes below. Our own
2642 // callers will guarantee the space is free by giving an aligned value to
2643 // CALLSEQ_START.
2644 }
2645 // Even if we're not expected to free up the space, it's useful to know how
2646 // much is there while considering tail calls (because we can reuse it).
2647 FuncInfo->setBytesInStackArgArea(StackArgSize);
2648
2649 return Chain;
2650}
2651
2652void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00002653 SelectionDAG &DAG,
2654 const SDLoc &DL,
Tim Northover3b0846e2014-05-24 12:50:23 +00002655 SDValue &Chain) const {
2656 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braun941a7052016-07-28 18:40:00 +00002657 MachineFrameInfo &MFI = MF.getFrameInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00002658 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Mehdi Amini44ede332015-07-09 02:09:04 +00002659 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00002660
2661 SmallVector<SDValue, 8> MemOps;
2662
2663 static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
2664 AArch64::X3, AArch64::X4, AArch64::X5,
2665 AArch64::X6, AArch64::X7 };
2666 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
Tim Northover3b6b7ca2015-02-21 02:11:17 +00002667 unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
Tim Northover3b0846e2014-05-24 12:50:23 +00002668
2669 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
2670 int GPRIdx = 0;
2671 if (GPRSaveSize != 0) {
Matthias Braun941a7052016-07-28 18:40:00 +00002672 GPRIdx = MFI.CreateStackObject(GPRSaveSize, 8, false);
Tim Northover3b0846e2014-05-24 12:50:23 +00002673
Mehdi Amini44ede332015-07-09 02:09:04 +00002674 SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00002675
2676 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
2677 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
2678 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
Alex Lorenze40c8a22015-08-11 23:09:45 +00002679 SDValue Store = DAG.getStore(
2680 Val.getValue(1), DL, Val, FIN,
Justin Lebar9c375812016-07-15 18:27:10 +00002681 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00002682 MemOps.push_back(Store);
Mehdi Amini44ede332015-07-09 02:09:04 +00002683 FIN =
2684 DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00002685 }
2686 }
2687 FuncInfo->setVarArgsGPRIndex(GPRIdx);
2688 FuncInfo->setVarArgsGPRSize(GPRSaveSize);
2689
2690 if (Subtarget->hasFPARMv8()) {
2691 static const MCPhysReg FPRArgRegs[] = {
2692 AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
2693 AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
2694 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
Tim Northover3b6b7ca2015-02-21 02:11:17 +00002695 unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
Tim Northover3b0846e2014-05-24 12:50:23 +00002696
2697 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
2698 int FPRIdx = 0;
2699 if (FPRSaveSize != 0) {
Matthias Braun941a7052016-07-28 18:40:00 +00002700 FPRIdx = MFI.CreateStackObject(FPRSaveSize, 16, false);
Tim Northover3b0846e2014-05-24 12:50:23 +00002701
Mehdi Amini44ede332015-07-09 02:09:04 +00002702 SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00002703
2704 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
2705 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
2706 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
2707
Alex Lorenze40c8a22015-08-11 23:09:45 +00002708 SDValue Store = DAG.getStore(
2709 Val.getValue(1), DL, Val, FIN,
Justin Lebar9c375812016-07-15 18:27:10 +00002710 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16));
Tim Northover3b0846e2014-05-24 12:50:23 +00002711 MemOps.push_back(Store);
Mehdi Amini44ede332015-07-09 02:09:04 +00002712 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
2713 DAG.getConstant(16, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00002714 }
2715 }
2716 FuncInfo->setVarArgsFPRIndex(FPRIdx);
2717 FuncInfo->setVarArgsFPRSize(FPRSaveSize);
2718 }
2719
2720 if (!MemOps.empty()) {
2721 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
2722 }
2723}
2724
2725/// LowerCallResult - Lower the result values of a call into the
2726/// appropriate copies out of appropriate physical registers.
2727SDValue AArch64TargetLowering::LowerCallResult(
2728 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00002729 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2730 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
Tim Northover3b0846e2014-05-24 12:50:23 +00002731 SDValue ThisVal) const {
2732 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
2733 ? RetCC_AArch64_WebKit_JS
2734 : RetCC_AArch64_AAPCS;
2735 // Assign locations to each value returned by this call.
2736 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002737 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2738 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002739 CCInfo.AnalyzeCallResult(Ins, RetCC);
2740
2741 // Copy all of the result registers out of their specified physreg.
2742 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2743 CCValAssign VA = RVLocs[i];
2744
2745 // Pass 'this' value directly from the argument to return value, to avoid
2746 // reg unit interference
David Majnemer5d261272016-07-20 04:13:01 +00002747 if (i == 0 && isThisReturn) {
Tim Northover3b0846e2014-05-24 12:50:23 +00002748 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
2749 "unexpected return calling convention register assignment");
2750 InVals.push_back(ThisVal);
2751 continue;
2752 }
2753
2754 SDValue Val =
2755 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2756 Chain = Val.getValue(1);
2757 InFlag = Val.getValue(2);
2758
2759 switch (VA.getLocInfo()) {
2760 default:
2761 llvm_unreachable("Unknown loc info!");
2762 case CCValAssign::Full:
2763 break;
2764 case CCValAssign::BCvt:
2765 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2766 break;
2767 }
2768
2769 InVals.push_back(Val);
2770 }
2771
2772 return Chain;
2773}
2774
Matthias Braun1af14142016-09-13 19:27:38 +00002775/// Return true if the calling convention is one that we can guarantee TCO for.
2776static bool canGuaranteeTCO(CallingConv::ID CC) {
2777 return CC == CallingConv::Fast;
2778}
2779
2780/// Return true if we might ever do TCO for calls with this calling convention.
2781static bool mayTailCallThisCC(CallingConv::ID CC) {
2782 switch (CC) {
2783 case CallingConv::C:
2784 case CallingConv::PreserveMost:
2785 case CallingConv::Swift:
2786 return true;
2787 default:
2788 return canGuaranteeTCO(CC);
2789 }
2790}
2791
Tim Northover3b0846e2014-05-24 12:50:23 +00002792bool AArch64TargetLowering::isEligibleForTailCallOptimization(
2793 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
Tim Northover3b0846e2014-05-24 12:50:23 +00002794 const SmallVectorImpl<ISD::OutputArg> &Outs,
2795 const SmallVectorImpl<SDValue> &OutVals,
2796 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
Matthias Braun1af14142016-09-13 19:27:38 +00002797 if (!mayTailCallThisCC(CalleeCC))
Tim Northover3b0846e2014-05-24 12:50:23 +00002798 return false;
2799
Matthias Braun8d414362016-03-30 22:46:04 +00002800 MachineFunction &MF = DAG.getMachineFunction();
Tim Northover3b0846e2014-05-24 12:50:23 +00002801 const Function *CallerF = MF.getFunction();
2802 CallingConv::ID CallerCC = CallerF->getCallingConv();
2803 bool CCMatch = CallerCC == CalleeCC;
2804
2805 // Byval parameters hand the function a pointer directly into the stack area
2806 // we want to reuse during a tail call. Working around this *is* possible (see
2807 // X86) but less efficient and uglier in LowerCall.
2808 for (Function::const_arg_iterator i = CallerF->arg_begin(),
2809 e = CallerF->arg_end();
2810 i != e; ++i)
2811 if (i->hasByValAttr())
2812 return false;
2813
Matthias Braun1af14142016-09-13 19:27:38 +00002814 if (getTargetMachine().Options.GuaranteedTailCallOpt)
2815 return canGuaranteeTCO(CalleeCC) && CCMatch;
Tim Northover3b0846e2014-05-24 12:50:23 +00002816
Oliver Stannard12993dd2014-08-18 12:42:15 +00002817 // Externally-defined functions with weak linkage should not be
2818 // tail-called on AArch64 when the OS does not support dynamic
2819 // pre-emption of symbols, as the AAELF spec requires normal calls
2820 // to undefined weak functions to be replaced with a NOP or jump to the
2821 // next instruction. The behaviour of branch instructions in this
2822 // situation (as used for tail calls) is implementation-defined, so we
2823 // cannot rely on the linker replacing the tail call with a return.
2824 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2825 const GlobalValue *GV = G->getGlobal();
Daniel Sandersc81f4502015-06-16 15:44:21 +00002826 const Triple &TT = getTargetMachine().getTargetTriple();
Saleem Abdulrasool67f72992015-01-03 21:35:00 +00002827 if (GV->hasExternalWeakLinkage() &&
2828 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
Oliver Stannard12993dd2014-08-18 12:42:15 +00002829 return false;
2830 }
2831
Tim Northover3b0846e2014-05-24 12:50:23 +00002832 // Now we search for cases where we can use a tail call without changing the
2833 // ABI. Sibcall is used in some places (particularly gcc) to refer to this
2834 // concept.
2835
2836 // I want anyone implementing a new calling convention to think long and hard
2837 // about this assert.
2838 assert((!isVarArg || CalleeCC == CallingConv::C) &&
2839 "Unexpected variadic calling convention");
2840
Matthias Braun8d414362016-03-30 22:46:04 +00002841 LLVMContext &C = *DAG.getContext();
Tim Northover3b0846e2014-05-24 12:50:23 +00002842 if (isVarArg && !Outs.empty()) {
2843 // At least two cases here: if caller is fastcc then we can't have any
2844 // memory arguments (we'd be expected to clean up the stack afterwards). If
2845 // caller is C then we could potentially use its argument area.
2846
2847 // FIXME: for now we take the most conservative of these in both cases:
2848 // disallow all variadic memory operands.
2849 SmallVector<CCValAssign, 16> ArgLocs;
Matthias Braun8d414362016-03-30 22:46:04 +00002850 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
Tim Northover3b0846e2014-05-24 12:50:23 +00002851
2852 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
Pete Cooper7be8f8f2015-08-03 19:04:32 +00002853 for (const CCValAssign &ArgLoc : ArgLocs)
2854 if (!ArgLoc.isRegLoc())
Tim Northover3b0846e2014-05-24 12:50:23 +00002855 return false;
2856 }
2857
Matthias Braun8d414362016-03-30 22:46:04 +00002858 // Check that the call results are passed in the same way.
2859 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
2860 CCAssignFnForCall(CalleeCC, isVarArg),
2861 CCAssignFnForCall(CallerCC, isVarArg)))
2862 return false;
Matthias Braun870c34f2016-04-04 18:56:13 +00002863 // The callee has to preserve all registers the caller needs to preserve.
Matthias Braun74a0bd32016-04-13 21:43:16 +00002864 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
2865 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
Matthias Braun870c34f2016-04-04 18:56:13 +00002866 if (!CCMatch) {
Matthias Braun74a0bd32016-04-13 21:43:16 +00002867 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2868 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
Matthias Braun870c34f2016-04-04 18:56:13 +00002869 return false;
2870 }
Tim Northover3b0846e2014-05-24 12:50:23 +00002871
2872 // Nothing more to check if the callee is taking no arguments
2873 if (Outs.empty())
2874 return true;
2875
2876 SmallVector<CCValAssign, 16> ArgLocs;
Matthias Braun8d414362016-03-30 22:46:04 +00002877 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
Tim Northover3b0846e2014-05-24 12:50:23 +00002878
2879 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2880
2881 const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2882
Matthias Braun74a0bd32016-04-13 21:43:16 +00002883 // If the stack arguments for this call do not fit into our own save area then
2884 // the call cannot be made tail.
2885 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2886 return false;
2887
Matthias Braun46b0f032016-04-14 01:10:42 +00002888 const MachineRegisterInfo &MRI = MF.getRegInfo();
2889 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
2890 return false;
Matthias Braun74a0bd32016-04-13 21:43:16 +00002891
2892 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +00002893}
2894
2895SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
2896 SelectionDAG &DAG,
Matthias Braun941a7052016-07-28 18:40:00 +00002897 MachineFrameInfo &MFI,
Tim Northover3b0846e2014-05-24 12:50:23 +00002898 int ClobberedFI) const {
2899 SmallVector<SDValue, 8> ArgChains;
Matthias Braun941a7052016-07-28 18:40:00 +00002900 int64_t FirstByte = MFI.getObjectOffset(ClobberedFI);
2901 int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1;
Tim Northover3b0846e2014-05-24 12:50:23 +00002902
2903 // Include the original chain at the beginning of the list. When this is
2904 // used by target LowerCall hooks, this helps legalize find the
2905 // CALLSEQ_BEGIN node.
2906 ArgChains.push_back(Chain);
2907
2908 // Add a chain value for each stack argument corresponding
2909 for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
2910 UE = DAG.getEntryNode().getNode()->use_end();
2911 U != UE; ++U)
2912 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
2913 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
2914 if (FI->getIndex() < 0) {
Matthias Braun941a7052016-07-28 18:40:00 +00002915 int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex());
Tim Northover3b0846e2014-05-24 12:50:23 +00002916 int64_t InLastByte = InFirstByte;
Matthias Braun941a7052016-07-28 18:40:00 +00002917 InLastByte += MFI.getObjectSize(FI->getIndex()) - 1;
Tim Northover3b0846e2014-05-24 12:50:23 +00002918
2919 if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
2920 (FirstByte <= InFirstByte && InFirstByte <= LastByte))
2921 ArgChains.push_back(SDValue(L, 1));
2922 }
2923
2924 // Build a tokenfactor for all the chains.
2925 return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
2926}
2927
2928bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
2929 bool TailCallOpt) const {
2930 return CallCC == CallingConv::Fast && TailCallOpt;
2931}
2932
Tim Northover3b0846e2014-05-24 12:50:23 +00002933/// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
2934/// and add input and output parameter nodes.
2935SDValue
2936AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
2937 SmallVectorImpl<SDValue> &InVals) const {
2938 SelectionDAG &DAG = CLI.DAG;
2939 SDLoc &DL = CLI.DL;
2940 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2941 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2942 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2943 SDValue Chain = CLI.Chain;
2944 SDValue Callee = CLI.Callee;
2945 bool &IsTailCall = CLI.IsTailCall;
2946 CallingConv::ID CallConv = CLI.CallConv;
2947 bool IsVarArg = CLI.IsVarArg;
2948
2949 MachineFunction &MF = DAG.getMachineFunction();
Tim Northover3b0846e2014-05-24 12:50:23 +00002950 bool IsThisReturn = false;
2951
2952 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2953 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2954 bool IsSibCall = false;
2955
2956 if (IsTailCall) {
2957 // Check if it's really possible to do a tail call.
2958 IsTailCall = isEligibleForTailCallOptimization(
Matthias Brauncc7fba42016-04-01 02:49:17 +00002959 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002960 if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
2961 report_fatal_error("failed to perform tail call elimination on a call "
2962 "site marked musttail");
2963
2964 // A sibling call is one where we're under the usual C ABI and not planning
2965 // to change that but can still do a tail call:
2966 if (!TailCallOpt && IsTailCall)
2967 IsSibCall = true;
2968
2969 if (IsTailCall)
2970 ++NumTailCalls;
2971 }
2972
2973 // Analyze operands of the call, assigning locations to each operand.
2974 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002975 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
2976 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002977
2978 if (IsVarArg) {
2979 // Handle fixed and variable vector arguments differently.
2980 // Variable vector arguments always go into memory.
2981 unsigned NumArgs = Outs.size();
2982
2983 for (unsigned i = 0; i != NumArgs; ++i) {
2984 MVT ArgVT = Outs[i].VT;
2985 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2986 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
2987 /*IsVarArg=*/ !Outs[i].IsFixed);
2988 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
2989 assert(!Res && "Call operand has unhandled type");
2990 (void)Res;
2991 }
2992 } else {
2993 // At this point, Outs[].VT may already be promoted to i32. To correctly
2994 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2995 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2996 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
2997 // we use a special version of AnalyzeCallOperands to pass in ValVT and
2998 // LocVT.
2999 unsigned NumArgs = Outs.size();
3000 for (unsigned i = 0; i != NumArgs; ++i) {
3001 MVT ValVT = Outs[i].VT;
3002 // Get type of the original argument.
Mehdi Amini44ede332015-07-09 02:09:04 +00003003 EVT ActualVT = getValueType(DAG.getDataLayout(),
3004 CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
Tim Northover3b0846e2014-05-24 12:50:23 +00003005 /*AllowUnknown*/ true);
3006 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
3007 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3008 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
Tim Northover3b0846e2014-05-24 12:50:23 +00003009 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
Tim Northover47e003c2014-05-26 17:21:53 +00003010 ValVT = MVT::i8;
Tim Northover3b0846e2014-05-24 12:50:23 +00003011 else if (ActualMVT == MVT::i16)
Tim Northover47e003c2014-05-26 17:21:53 +00003012 ValVT = MVT::i16;
Tim Northover3b0846e2014-05-24 12:50:23 +00003013
3014 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
Tim Northover47e003c2014-05-26 17:21:53 +00003015 bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00003016 assert(!Res && "Call operand has unhandled type");
3017 (void)Res;
3018 }
3019 }
3020
3021 // Get a count of how many bytes are to be pushed on the stack.
3022 unsigned NumBytes = CCInfo.getNextStackOffset();
3023
3024 if (IsSibCall) {
3025 // Since we're not changing the ABI to make this a tail call, the memory
3026 // operands are already available in the caller's incoming argument space.
3027 NumBytes = 0;
3028 }
3029
3030 // FPDiff is the byte offset of the call's argument area from the callee's.
3031 // Stores to callee stack arguments will be placed in FixedStackSlots offset
3032 // by this amount for a tail call. In a sibling call it must be 0 because the
3033 // caller will deallocate the entire stack and the callee still expects its
3034 // arguments to begin at SP+0. Completely unused for non-tail calls.
3035 int FPDiff = 0;
3036
3037 if (IsTailCall && !IsSibCall) {
3038 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
3039
3040 // Since callee will pop argument stack as a tail call, we must keep the
3041 // popped size 16-byte aligned.
Rui Ueyamada00f2f2016-01-14 21:06:47 +00003042 NumBytes = alignTo(NumBytes, 16);
Tim Northover3b0846e2014-05-24 12:50:23 +00003043
3044 // FPDiff will be negative if this tail call requires more space than we
3045 // would automatically have in our incoming argument space. Positive if we
3046 // can actually shrink the stack.
3047 FPDiff = NumReusableBytes - NumBytes;
3048
3049 // The stack pointer must be 16-byte aligned at all times it's used for a
3050 // memory operation, which in practice means at *all* times and in
3051 // particular across call boundaries. Therefore our own arguments started at
3052 // a 16-byte aligned SP and the delta applied for the tail call should
3053 // satisfy the same constraint.
3054 assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
3055 }
3056
3057 // Adjust the stack pointer for the new arguments...
3058 // These operations are automatically eliminated by the prolog/epilog pass
3059 if (!IsSibCall)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003060 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, DL,
3061 true),
3062 DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003063
Mehdi Amini44ede332015-07-09 02:09:04 +00003064 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
3065 getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00003066
3067 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3068 SmallVector<SDValue, 8> MemOpChains;
Mehdi Amini44ede332015-07-09 02:09:04 +00003069 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003070
3071 // Walk the register/memloc assignments, inserting copies/loads.
3072 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
3073 ++i, ++realArgIdx) {
3074 CCValAssign &VA = ArgLocs[i];
3075 SDValue Arg = OutVals[realArgIdx];
3076 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
3077
3078 // Promote the value if needed.
3079 switch (VA.getLocInfo()) {
3080 default:
3081 llvm_unreachable("Unknown loc info!");
3082 case CCValAssign::Full:
3083 break;
3084 case CCValAssign::SExt:
3085 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3086 break;
3087 case CCValAssign::ZExt:
3088 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3089 break;
3090 case CCValAssign::AExt:
Tim Northover68ae5032014-05-26 17:22:07 +00003091 if (Outs[realArgIdx].ArgVT == MVT::i1) {
3092 // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
3093 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3094 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
3095 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003096 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3097 break;
3098 case CCValAssign::BCvt:
3099 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3100 break;
3101 case CCValAssign::FPExt:
3102 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3103 break;
3104 }
3105
3106 if (VA.isRegLoc()) {
3107 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i64) {
3108 assert(VA.getLocVT() == MVT::i64 &&
3109 "unexpected calling convention register assignment");
3110 assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
3111 "unexpected use of 'returned'");
3112 IsThisReturn = true;
3113 }
3114 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3115 } else {
3116 assert(VA.isMemLoc());
3117
3118 SDValue DstAddr;
3119 MachinePointerInfo DstInfo;
3120
3121 // FIXME: This works on big-endian for composite byvals, which are the
3122 // common case. It should also work for fundamental types too.
3123 uint32_t BEAlign = 0;
3124 unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
Amara Emerson82da7d02014-08-15 14:29:57 +00003125 : VA.getValVT().getSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00003126 OpSize = (OpSize + 7) / 8;
Tim Northover293d4142014-12-03 17:49:26 +00003127 if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
3128 !Flags.isInConsecutiveRegs()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003129 if (OpSize < 8)
3130 BEAlign = 8 - OpSize;
3131 }
3132 unsigned LocMemOffset = VA.getLocMemOffset();
3133 int32_t Offset = LocMemOffset + BEAlign;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003134 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
Mehdi Amini44ede332015-07-09 02:09:04 +00003135 PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
Tim Northover3b0846e2014-05-24 12:50:23 +00003136
3137 if (IsTailCall) {
3138 Offset = Offset + FPDiff;
Matthias Braun941a7052016-07-28 18:40:00 +00003139 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
Tim Northover3b0846e2014-05-24 12:50:23 +00003140
Mehdi Amini44ede332015-07-09 02:09:04 +00003141 DstAddr = DAG.getFrameIndex(FI, PtrVT);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003142 DstInfo =
3143 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
Tim Northover3b0846e2014-05-24 12:50:23 +00003144
3145 // Make sure any stack arguments overlapping with where we're storing
3146 // are loaded before this eventual operation. Otherwise they'll be
3147 // clobbered.
3148 Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
3149 } else {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003150 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003151
Mehdi Amini44ede332015-07-09 02:09:04 +00003152 DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003153 DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
3154 LocMemOffset);
Tim Northover3b0846e2014-05-24 12:50:23 +00003155 }
3156
3157 if (Outs[i].Flags.isByVal()) {
3158 SDValue SizeNode =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003159 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00003160 SDValue Cpy = DAG.getMemcpy(
3161 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
Krzysztof Parzyszeka46c36b2015-04-13 17:16:45 +00003162 /*isVol = */ false, /*AlwaysInline = */ false,
3163 /*isTailCall = */ false,
3164 DstInfo, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00003165
3166 MemOpChains.push_back(Cpy);
3167 } else {
3168 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
3169 // promoted to a legal register type i32, we should truncate Arg back to
3170 // i1/i8/i16.
Tim Northover6890add2014-06-03 13:54:53 +00003171 if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
3172 VA.getValVT() == MVT::i16)
3173 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
Tim Northover3b0846e2014-05-24 12:50:23 +00003174
Justin Lebar9c375812016-07-15 18:27:10 +00003175 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00003176 MemOpChains.push_back(Store);
3177 }
3178 }
3179 }
3180
3181 if (!MemOpChains.empty())
3182 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3183
3184 // Build a sequence of copy-to-reg nodes chained together with token chain
3185 // and flag operands which copy the outgoing args into the appropriate regs.
3186 SDValue InFlag;
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003187 for (auto &RegToPass : RegsToPass) {
3188 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3189 RegToPass.second, InFlag);
Tim Northover3b0846e2014-05-24 12:50:23 +00003190 InFlag = Chain.getValue(1);
3191 }
3192
3193 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3194 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3195 // node so that legalize doesn't hack it.
3196 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3197 Subtarget->isTargetMachO()) {
3198 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3199 const GlobalValue *GV = G->getGlobal();
3200 bool InternalLinkage = GV->hasInternalLinkage();
3201 if (InternalLinkage)
Mehdi Amini44ede332015-07-09 02:09:04 +00003202 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00003203 else {
Mehdi Amini44ede332015-07-09 02:09:04 +00003204 Callee =
3205 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT);
3206 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
Tim Northover3b0846e2014-05-24 12:50:23 +00003207 }
3208 } else if (ExternalSymbolSDNode *S =
3209 dyn_cast<ExternalSymbolSDNode>(Callee)) {
3210 const char *Sym = S->getSymbol();
Mehdi Amini44ede332015-07-09 02:09:04 +00003211 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
3212 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
Tim Northover3b0846e2014-05-24 12:50:23 +00003213 }
3214 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3215 const GlobalValue *GV = G->getGlobal();
Mehdi Amini44ede332015-07-09 02:09:04 +00003216 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00003217 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3218 const char *Sym = S->getSymbol();
Mehdi Amini44ede332015-07-09 02:09:04 +00003219 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00003220 }
3221
3222 // We don't usually want to end the call-sequence here because we would tidy
3223 // the frame up *after* the call, however in the ABI-changing tail-call case
3224 // we've carefully laid out the parameters so that when sp is reset they'll be
3225 // in the correct location.
3226 if (IsTailCall && !IsSibCall) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003227 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3228 DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003229 InFlag = Chain.getValue(1);
3230 }
3231
3232 std::vector<SDValue> Ops;
3233 Ops.push_back(Chain);
3234 Ops.push_back(Callee);
3235
3236 if (IsTailCall) {
3237 // Each tail call may have to adjust the stack by a different amount, so
3238 // this information must travel along with the operation for eventual
3239 // consumption by emitEpilogue.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003240 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00003241 }
3242
3243 // Add argument registers to the end of the list so that they are known live
3244 // into the call.
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003245 for (auto &RegToPass : RegsToPass)
3246 Ops.push_back(DAG.getRegister(RegToPass.first,
3247 RegToPass.second.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00003248
3249 // Add a register mask operand representing the call-preserved registers.
3250 const uint32_t *Mask;
Eric Christopher905f12d2015-01-29 00:19:42 +00003251 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00003252 if (IsThisReturn) {
3253 // For 'this' returns, use the X0-preserving mask if applicable
Eric Christopher9deb75d2015-03-11 22:42:13 +00003254 Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003255 if (!Mask) {
3256 IsThisReturn = false;
Eric Christopher9deb75d2015-03-11 22:42:13 +00003257 Mask = TRI->getCallPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003258 }
3259 } else
Eric Christopher9deb75d2015-03-11 22:42:13 +00003260 Mask = TRI->getCallPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003261
3262 assert(Mask && "Missing call preserved mask for calling convention");
3263 Ops.push_back(DAG.getRegisterMask(Mask));
3264
3265 if (InFlag.getNode())
3266 Ops.push_back(InFlag);
3267
3268 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3269
3270 // If we're doing a tall call, use a TC_RETURN here rather than an
3271 // actual call instruction.
Arnold Schwaighoferf54b73d2015-05-08 23:52:00 +00003272 if (IsTailCall) {
Matthias Braun941a7052016-07-28 18:40:00 +00003273 MF.getFrameInfo().setHasTailCall();
Tim Northover3b0846e2014-05-24 12:50:23 +00003274 return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
Arnold Schwaighoferf54b73d2015-05-08 23:52:00 +00003275 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003276
3277 // Returns a chain and a flag for retval copy to use.
3278 Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
3279 InFlag = Chain.getValue(1);
3280
Rui Ueyamada00f2f2016-01-14 21:06:47 +00003281 uint64_t CalleePopBytes =
3282 DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00003283
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003284 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3285 DAG.getIntPtrConstant(CalleePopBytes, DL, true),
Tim Northover3b0846e2014-05-24 12:50:23 +00003286 InFlag, DL);
3287 if (!Ins.empty())
3288 InFlag = Chain.getValue(1);
3289
3290 // Handle result values, copying them out of physregs into vregs that we
3291 // return.
3292 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3293 InVals, IsThisReturn,
3294 IsThisReturn ? OutVals[0] : SDValue());
3295}
3296
3297bool AArch64TargetLowering::CanLowerReturn(
3298 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
3299 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
3300 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3301 ? RetCC_AArch64_WebKit_JS
3302 : RetCC_AArch64_AAPCS;
3303 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003304 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
Tim Northover3b0846e2014-05-24 12:50:23 +00003305 return CCInfo.CheckReturn(Outs, RetCC);
3306}
3307
3308SDValue
3309AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3310 bool isVarArg,
3311 const SmallVectorImpl<ISD::OutputArg> &Outs,
3312 const SmallVectorImpl<SDValue> &OutVals,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003313 const SDLoc &DL, SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00003314 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3315 ? RetCC_AArch64_WebKit_JS
3316 : RetCC_AArch64_AAPCS;
3317 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003318 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3319 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00003320 CCInfo.AnalyzeReturn(Outs, RetCC);
3321
3322 // Copy the result values into the output registers.
3323 SDValue Flag;
3324 SmallVector<SDValue, 4> RetOps(1, Chain);
3325 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
3326 ++i, ++realRVLocIdx) {
3327 CCValAssign &VA = RVLocs[i];
3328 assert(VA.isRegLoc() && "Can only return in registers!");
3329 SDValue Arg = OutVals[realRVLocIdx];
3330
3331 switch (VA.getLocInfo()) {
3332 default:
3333 llvm_unreachable("Unknown loc info!");
3334 case CCValAssign::Full:
Tim Northover68ae5032014-05-26 17:22:07 +00003335 if (Outs[i].ArgVT == MVT::i1) {
3336 // AAPCS requires i1 to be zero-extended to i8 by the producer of the
3337 // value. This is strictly redundant on Darwin (which uses "zeroext
3338 // i1"), but will be optimised out before ISel.
3339 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3340 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3341 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003342 break;
3343 case CCValAssign::BCvt:
3344 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3345 break;
3346 }
3347
3348 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
3349 Flag = Chain.getValue(1);
3350 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3351 }
Manman Rencbe4f942015-12-16 21:04:19 +00003352 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3353 const MCPhysReg *I =
3354 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
3355 if (I) {
3356 for (; *I; ++I) {
3357 if (AArch64::GPR64RegClass.contains(*I))
3358 RetOps.push_back(DAG.getRegister(*I, MVT::i64));
3359 else if (AArch64::FPR64RegClass.contains(*I))
3360 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
3361 else
3362 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
3363 }
3364 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003365
3366 RetOps[0] = Chain; // Update chain.
3367
3368 // Add the flag if we have it.
3369 if (Flag.getNode())
3370 RetOps.push_back(Flag);
3371
3372 return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
3373}
3374
3375//===----------------------------------------------------------------------===//
3376// Other Lowering Code
3377//===----------------------------------------------------------------------===//
3378
3379SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
3380 SelectionDAG &DAG) const {
Mehdi Amini44ede332015-07-09 02:09:04 +00003381 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003382 SDLoc DL(Op);
Asiri Rathnayake369c0302014-09-10 13:54:38 +00003383 const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
3384 const GlobalValue *GV = GN->getGlobal();
Tim Northover3b0846e2014-05-24 12:50:23 +00003385 unsigned char OpFlags =
3386 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
3387
3388 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
3389 "unexpected offset in global node");
3390
3391 // This also catched the large code model case for Darwin.
3392 if ((OpFlags & AArch64II::MO_GOT) != 0) {
3393 SDValue GotAddr = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
3394 // FIXME: Once remat is capable of dealing with instructions with register
3395 // operands, expand this into two nodes instead of using a wrapper node.
3396 return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
3397 }
3398
3399 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
3400 const unsigned char MO_NC = AArch64II::MO_NC;
3401 return DAG.getNode(
3402 AArch64ISD::WrapperLarge, DL, PtrVT,
3403 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G3),
3404 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
3405 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
3406 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
3407 } else {
3408 // Use ADRP/ADD or ADRP/LDR for everything else: the small model on ELF and
3409 // the only correct model on Darwin.
3410 SDValue Hi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
3411 OpFlags | AArch64II::MO_PAGE);
3412 unsigned char LoFlags = OpFlags | AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
3413 SDValue Lo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, LoFlags);
3414
3415 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3416 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3417 }
3418}
3419
3420/// \brief Convert a TLS address reference into the correct sequence of loads
3421/// and calls to compute the variable's address (for Darwin, currently) and
3422/// return an SDValue containing the final node.
3423
3424/// Darwin only has one TLS scheme which must be capable of dealing with the
3425/// fully general situation, in the worst case. This means:
3426/// + "extern __thread" declaration.
3427/// + Defined in a possibly unknown dynamic library.
3428///
3429/// The general system is that each __thread variable has a [3 x i64] descriptor
3430/// which contains information used by the runtime to calculate the address. The
3431/// only part of this the compiler needs to know about is the first xword, which
3432/// contains a function pointer that must be called with the address of the
3433/// entire descriptor in "x0".
3434///
3435/// Since this descriptor may be in a different unit, in general even the
3436/// descriptor must be accessed via an indirect load. The "ideal" code sequence
3437/// is:
3438/// adrp x0, _var@TLVPPAGE
3439/// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor
3440/// ldr x1, [x0] ; x1 contains 1st entry of descriptor,
3441/// ; the function pointer
3442/// blr x1 ; Uses descriptor address in x0
3443/// ; Address of _var is now in x0.
3444///
3445/// If the address of _var's descriptor *is* known to the linker, then it can
3446/// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
3447/// a slight efficiency gain.
3448SDValue
3449AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
3450 SelectionDAG &DAG) const {
3451 assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
3452
3453 SDLoc DL(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00003454 MVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003455 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3456
3457 SDValue TLVPAddr =
3458 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3459 SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
3460
3461 // The first entry in the descriptor is a function pointer that we must call
3462 // to obtain the address of the variable.
3463 SDValue Chain = DAG.getEntryNode();
Justin Lebaradbf09e2016-09-11 01:38:58 +00003464 SDValue FuncTLVGet = DAG.getLoad(
3465 MVT::i64, DL, Chain, DescAddr,
3466 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
3467 /* Alignment = */ 8,
3468 MachineMemOperand::MONonTemporal | MachineMemOperand::MOInvariant |
3469 MachineMemOperand::MODereferenceable);
Tim Northover3b0846e2014-05-24 12:50:23 +00003470 Chain = FuncTLVGet.getValue(1);
3471
Matthias Braun941a7052016-07-28 18:40:00 +00003472 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
3473 MFI.setAdjustsStack(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00003474
3475 // TLS calls preserve all registers except those that absolutely must be
3476 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
3477 // silly).
Eric Christopher6c901622015-01-28 03:51:33 +00003478 const uint32_t *Mask =
Eric Christopher905f12d2015-01-29 00:19:42 +00003479 Subtarget->getRegisterInfo()->getTLSCallPreservedMask();
Tim Northover3b0846e2014-05-24 12:50:23 +00003480
3481 // Finally, we can make the call. This is just a degenerate version of a
3482 // normal AArch64 call node: x0 takes the address of the descriptor, and
3483 // returns the address of the variable in this thread.
3484 Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
3485 Chain =
3486 DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3487 Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
3488 DAG.getRegisterMask(Mask), Chain.getValue(1));
3489 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
3490}
3491
3492/// When accessing thread-local variables under either the general-dynamic or
3493/// local-dynamic system, we make a "TLS-descriptor" call. The variable will
3494/// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
Kristof Beylsaea84612015-03-04 09:12:08 +00003495/// is a function pointer to carry out the resolution.
Tim Northover3b0846e2014-05-24 12:50:23 +00003496///
Kristof Beylsaea84612015-03-04 09:12:08 +00003497/// The sequence is:
3498/// adrp x0, :tlsdesc:var
3499/// ldr x1, [x0, #:tlsdesc_lo12:var]
3500/// add x0, x0, #:tlsdesc_lo12:var
3501/// .tlsdesccall var
3502/// blr x1
3503/// (TPIDR_EL0 offset now in x0)
Tim Northover3b0846e2014-05-24 12:50:23 +00003504///
Kristof Beylsaea84612015-03-04 09:12:08 +00003505/// The above sequence must be produced unscheduled, to enable the linker to
3506/// optimize/relax this sequence.
3507/// Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
3508/// above sequence, and expanded really late in the compilation flow, to ensure
3509/// the sequence is produced as per above.
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003510SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr,
3511 const SDLoc &DL,
Kristof Beylsaea84612015-03-04 09:12:08 +00003512 SelectionDAG &DAG) const {
Mehdi Amini44ede332015-07-09 02:09:04 +00003513 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003514
Kristof Beylsaea84612015-03-04 09:12:08 +00003515 SDValue Chain = DAG.getEntryNode();
Tim Northover3b0846e2014-05-24 12:50:23 +00003516 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
Kristof Beylsaea84612015-03-04 09:12:08 +00003517
Benjamin Kramer3bc1edf2016-07-02 11:41:39 +00003518 Chain =
3519 DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr});
Kristof Beylsaea84612015-03-04 09:12:08 +00003520 SDValue Glue = Chain.getValue(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00003521
3522 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
3523}
3524
3525SDValue
3526AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
3527 SelectionDAG &DAG) const {
3528 assert(Subtarget->isTargetELF() && "This function expects an ELF target");
3529 assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
3530 "ELF TLS only supported in small memory model");
Kristof Beylsaea84612015-03-04 09:12:08 +00003531 // Different choices can be made for the maximum size of the TLS area for a
3532 // module. For the small address model, the default TLS size is 16MiB and the
3533 // maximum TLS size is 4GiB.
3534 // FIXME: add -mtls-size command line option and make it control the 16MiB
3535 // vs. 4GiB code sequence generation.
Tim Northover3b0846e2014-05-24 12:50:23 +00003536 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3537
3538 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
Chih-Hung Hsieh1e859582015-07-28 16:24:05 +00003539
3540 if (DAG.getTarget().Options.EmulatedTLS)
3541 return LowerToTLSEmulatedModel(GA, DAG);
3542
Kristof Beylsaea84612015-03-04 09:12:08 +00003543 if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
3544 if (Model == TLSModel::LocalDynamic)
3545 Model = TLSModel::GeneralDynamic;
3546 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003547
3548 SDValue TPOff;
Mehdi Amini44ede332015-07-09 02:09:04 +00003549 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003550 SDLoc DL(Op);
3551 const GlobalValue *GV = GA->getGlobal();
3552
3553 SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
3554
3555 if (Model == TLSModel::LocalExec) {
3556 SDValue HiVar = DAG.getTargetGlobalAddress(
Kristof Beylsaea84612015-03-04 09:12:08 +00003557 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
Tim Northover3b0846e2014-05-24 12:50:23 +00003558 SDValue LoVar = DAG.getTargetGlobalAddress(
3559 GV, DL, PtrVT, 0,
Kristof Beylsaea84612015-03-04 09:12:08 +00003560 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
Tim Northover3b0846e2014-05-24 12:50:23 +00003561
Kristof Beylsaea84612015-03-04 09:12:08 +00003562 SDValue TPWithOff_lo =
3563 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003564 HiVar,
3565 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003566 0);
3567 SDValue TPWithOff =
3568 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003569 LoVar,
3570 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003571 0);
3572 return TPWithOff;
Tim Northover3b0846e2014-05-24 12:50:23 +00003573 } else if (Model == TLSModel::InitialExec) {
3574 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3575 TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
3576 } else if (Model == TLSModel::LocalDynamic) {
3577 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
3578 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
3579 // the beginning of the module's TLS region, followed by a DTPREL offset
3580 // calculation.
3581
3582 // These accesses will need deduplicating if there's more than one.
3583 AArch64FunctionInfo *MFI =
3584 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
3585 MFI->incNumLocalDynamicTLSAccesses();
3586
Tim Northover3b0846e2014-05-24 12:50:23 +00003587 // The call needs a relocation too for linker relaxation. It doesn't make
3588 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3589 // the address.
3590 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
3591 AArch64II::MO_TLS);
3592
3593 // Now we can calculate the offset from TPIDR_EL0 to this module's
3594 // thread-local area.
Kristof Beylsaea84612015-03-04 09:12:08 +00003595 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00003596
3597 // Now use :dtprel_whatever: operations to calculate this variable's offset
3598 // in its thread-storage area.
3599 SDValue HiVar = DAG.getTargetGlobalAddress(
Kristof Beylsaea84612015-03-04 09:12:08 +00003600 GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
Tim Northover3b0846e2014-05-24 12:50:23 +00003601 SDValue LoVar = DAG.getTargetGlobalAddress(
3602 GV, DL, MVT::i64, 0,
Tim Northover3b0846e2014-05-24 12:50:23 +00003603 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3604
Kristof Beylsaea84612015-03-04 09:12:08 +00003605 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003606 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003607 0);
3608 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003609 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003610 0);
3611 } else if (Model == TLSModel::GeneralDynamic) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003612 // The call needs a relocation too for linker relaxation. It doesn't make
3613 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3614 // the address.
3615 SDValue SymAddr =
3616 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3617
3618 // Finally we can make a call to calculate the offset from tpidr_el0.
Kristof Beylsaea84612015-03-04 09:12:08 +00003619 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00003620 } else
3621 llvm_unreachable("Unsupported ELF TLS access model");
3622
3623 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
3624}
3625
3626SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
3627 SelectionDAG &DAG) const {
3628 if (Subtarget->isTargetDarwin())
3629 return LowerDarwinGlobalTLSAddress(Op, DAG);
3630 else if (Subtarget->isTargetELF())
3631 return LowerELFGlobalTLSAddress(Op, DAG);
3632
3633 llvm_unreachable("Unexpected platform trying to use TLS");
3634}
3635SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3636 SDValue Chain = Op.getOperand(0);
3637 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3638 SDValue LHS = Op.getOperand(2);
3639 SDValue RHS = Op.getOperand(3);
3640 SDValue Dest = Op.getOperand(4);
3641 SDLoc dl(Op);
3642
3643 // Handle f128 first, since lowering it will result in comparing the return
3644 // value of a libcall against zero, which is just what the rest of LowerBR_CC
3645 // is expecting to deal with.
3646 if (LHS.getValueType() == MVT::f128) {
3647 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3648
3649 // If softenSetCCOperands returned a scalar, we need to compare the result
3650 // against zero to select between true and false values.
3651 if (!RHS.getNode()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003652 RHS = DAG.getConstant(0, dl, LHS.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00003653 CC = ISD::SETNE;
3654 }
3655 }
3656
3657 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
3658 // instruction.
3659 unsigned Opc = LHS.getOpcode();
Artyom Skrobov314ee042015-11-25 19:41:11 +00003660 if (LHS.getResNo() == 1 && isOneConstant(RHS) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00003661 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3662 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
3663 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
3664 "Unexpected condition code.");
3665 // Only lower legal XALUO ops.
3666 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
3667 return SDValue();
3668
3669 // The actual operation with overflow check.
3670 AArch64CC::CondCode OFCC;
3671 SDValue Value, Overflow;
3672 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
3673
3674 if (CC == ISD::SETNE)
3675 OFCC = getInvertedCondCode(OFCC);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003676 SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003677
Ahmed Bougachadf956a22015-02-06 23:15:39 +00003678 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3679 Overflow);
Tim Northover3b0846e2014-05-24 12:50:23 +00003680 }
3681
3682 if (LHS.getValueType().isInteger()) {
3683 assert((LHS.getValueType() == RHS.getValueType()) &&
3684 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3685
3686 // If the RHS of the comparison is zero, we can potentially fold this
3687 // to a specialized branch.
3688 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
3689 if (RHSC && RHSC->getZExtValue() == 0) {
3690 if (CC == ISD::SETEQ) {
3691 // See if we can use a TBZ to fold in an AND as well.
3692 // TBZ has a smaller branch displacement than CBZ. If the offset is
3693 // out of bounds, a late MI-layer pass rewrites branches.
3694 // 403.gcc is an example that hits this case.
3695 if (LHS.getOpcode() == ISD::AND &&
3696 isa<ConstantSDNode>(LHS.getOperand(1)) &&
3697 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3698 SDValue Test = LHS.getOperand(0);
3699 uint64_t Mask = LHS.getConstantOperandVal(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00003700 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003701 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3702 Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00003703 }
3704
3705 return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
3706 } else if (CC == ISD::SETNE) {
3707 // See if we can use a TBZ to fold in an AND as well.
3708 // TBZ has a smaller branch displacement than CBZ. If the offset is
3709 // out of bounds, a late MI-layer pass rewrites branches.
3710 // 403.gcc is an example that hits this case.
3711 if (LHS.getOpcode() == ISD::AND &&
3712 isa<ConstantSDNode>(LHS.getOperand(1)) &&
3713 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3714 SDValue Test = LHS.getOperand(0);
3715 uint64_t Mask = LHS.getConstantOperandVal(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00003716 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003717 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3718 Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00003719 }
3720
3721 return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
Chad Rosier579c02c2014-08-01 14:48:56 +00003722 } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
3723 // Don't combine AND since emitComparison converts the AND to an ANDS
3724 // (a.k.a. TST) and the test in the test bit and branch instruction
3725 // becomes redundant. This would also increase register pressure.
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00003726 uint64_t Mask = LHS.getValueSizeInBits() - 1;
Chad Rosier579c02c2014-08-01 14:48:56 +00003727 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003728 DAG.getConstant(Mask, dl, MVT::i64), Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00003729 }
3730 }
Chad Rosier579c02c2014-08-01 14:48:56 +00003731 if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
3732 LHS.getOpcode() != ISD::AND) {
3733 // Don't combine AND since emitComparison converts the AND to an ANDS
3734 // (a.k.a. TST) and the test in the test bit and branch instruction
3735 // becomes redundant. This would also increase register pressure.
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00003736 uint64_t Mask = LHS.getValueSizeInBits() - 1;
Chad Rosier579c02c2014-08-01 14:48:56 +00003737 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003738 DAG.getConstant(Mask, dl, MVT::i64), Dest);
Chad Rosier579c02c2014-08-01 14:48:56 +00003739 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003740
3741 SDValue CCVal;
3742 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3743 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3744 Cmp);
3745 }
3746
3747 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3748
3749 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
3750 // clean. Some of them require two branches to implement.
3751 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3752 AArch64CC::CondCode CC1, CC2;
3753 changeFPCCToAArch64CC(CC, CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003754 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003755 SDValue BR1 =
3756 DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
3757 if (CC2 != AArch64CC::AL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003758 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003759 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
3760 Cmp);
3761 }
3762
3763 return BR1;
3764}
3765
3766SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
3767 SelectionDAG &DAG) const {
3768 EVT VT = Op.getValueType();
3769 SDLoc DL(Op);
3770
3771 SDValue In1 = Op.getOperand(0);
3772 SDValue In2 = Op.getOperand(1);
3773 EVT SrcVT = In2.getValueType();
Ahmed Bougacha2a97b1b2015-08-13 01:13:56 +00003774
3775 if (SrcVT.bitsLT(VT))
3776 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
3777 else if (SrcVT.bitsGT(VT))
3778 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
Tim Northover3b0846e2014-05-24 12:50:23 +00003779
3780 EVT VecVT;
3781 EVT EltVT;
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00003782 uint64_t EltMask;
3783 SDValue VecVal1, VecVal2;
Tim Northover3b0846e2014-05-24 12:50:23 +00003784 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
3785 EltVT = MVT::i32;
Ahmed Bougachab0ae36f2015-08-04 00:42:34 +00003786 VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00003787 EltMask = 0x80000000ULL;
Tim Northover3b0846e2014-05-24 12:50:23 +00003788
3789 if (!VT.isVector()) {
3790 VecVal1 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3791 DAG.getUNDEF(VecVT), In1);
3792 VecVal2 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3793 DAG.getUNDEF(VecVT), In2);
3794 } else {
3795 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3796 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3797 }
3798 } else if (VT == MVT::f64 || VT == MVT::v2f64) {
3799 EltVT = MVT::i64;
3800 VecVT = MVT::v2i64;
3801
Eric Christopher572e03a2015-06-19 01:53:21 +00003802 // We want to materialize a mask with the high bit set, but the AdvSIMD
Tim Northover3b0846e2014-05-24 12:50:23 +00003803 // immediate moves cannot materialize that in a single instruction for
3804 // 64-bit elements. Instead, materialize zero and then negate it.
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00003805 EltMask = 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00003806
3807 if (!VT.isVector()) {
3808 VecVal1 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3809 DAG.getUNDEF(VecVT), In1);
3810 VecVal2 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3811 DAG.getUNDEF(VecVT), In2);
3812 } else {
3813 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3814 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3815 }
3816 } else {
3817 llvm_unreachable("Invalid type for copysign!");
3818 }
3819
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003820 SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00003821
3822 // If we couldn't materialize the mask above, then the mask vector will be
3823 // the zero vector, and we need to negate it here.
3824 if (VT == MVT::f64 || VT == MVT::v2f64) {
3825 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
3826 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
3827 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
3828 }
3829
3830 SDValue Sel =
3831 DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
3832
3833 if (VT == MVT::f32)
3834 return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
3835 else if (VT == MVT::f64)
3836 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
3837 else
3838 return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
3839}
3840
3841SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
Duncan P. N. Exon Smith003bb7d2015-02-14 02:09:06 +00003842 if (DAG.getMachineFunction().getFunction()->hasFnAttribute(
3843 Attribute::NoImplicitFloat))
Tim Northover3b0846e2014-05-24 12:50:23 +00003844 return SDValue();
3845
Weiming Zhao7a2d1562014-11-19 00:29:14 +00003846 if (!Subtarget->hasNEON())
3847 return SDValue();
3848
Tim Northover3b0846e2014-05-24 12:50:23 +00003849 // While there is no integer popcount instruction, it can
3850 // be more efficiently lowered to the following sequence that uses
3851 // AdvSIMD registers/instructions as long as the copies to/from
3852 // the AdvSIMD registers are cheap.
3853 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd
3854 // CNT V0.8B, V0.8B // 8xbyte pop-counts
3855 // ADDV B0, V0.8B // sum 8xbyte pop-counts
3856 // UMOV X0, V0.B[0] // copy byte result back to integer reg
3857 SDValue Val = Op.getOperand(0);
3858 SDLoc DL(Op);
3859 EVT VT = Op.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00003860
Hao Liue0335d72015-01-30 02:13:53 +00003861 if (VT == MVT::i32)
3862 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
3863 Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
Tim Northover3b0846e2014-05-24 12:50:23 +00003864
Hao Liue0335d72015-01-30 02:13:53 +00003865 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
Tim Northover3b0846e2014-05-24 12:50:23 +00003866 SDValue UaddLV = DAG.getNode(
3867 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003868 DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
Tim Northover3b0846e2014-05-24 12:50:23 +00003869
3870 if (VT == MVT::i64)
3871 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
3872 return UaddLV;
3873}
3874
3875SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3876
3877 if (Op.getValueType().isVector())
3878 return LowerVSETCC(Op, DAG);
3879
3880 SDValue LHS = Op.getOperand(0);
3881 SDValue RHS = Op.getOperand(1);
3882 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3883 SDLoc dl(Op);
3884
3885 // We chose ZeroOrOneBooleanContents, so use zero and one.
3886 EVT VT = Op.getValueType();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003887 SDValue TVal = DAG.getConstant(1, dl, VT);
3888 SDValue FVal = DAG.getConstant(0, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00003889
3890 // Handle f128 first, since one possible outcome is a normal integer
3891 // comparison which gets picked up by the next if statement.
3892 if (LHS.getValueType() == MVT::f128) {
3893 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3894
3895 // If softenSetCCOperands returned a scalar, use it.
3896 if (!RHS.getNode()) {
3897 assert(LHS.getValueType() == Op.getValueType() &&
3898 "Unexpected setcc expansion!");
3899 return LHS;
3900 }
3901 }
3902
3903 if (LHS.getValueType().isInteger()) {
3904 SDValue CCVal;
3905 SDValue Cmp =
3906 getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
3907
3908 // Note that we inverted the condition above, so we reverse the order of
3909 // the true and false operands here. This will allow the setcc to be
3910 // matched to a single CSINC instruction.
3911 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
3912 }
3913
3914 // Now we know we're dealing with FP values.
3915 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3916
3917 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
3918 // and do the comparison.
3919 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3920
3921 AArch64CC::CondCode CC1, CC2;
3922 changeFPCCToAArch64CC(CC, CC1, CC2);
3923 if (CC2 == AArch64CC::AL) {
3924 changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003925 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003926
3927 // Note that we inverted the condition above, so we reverse the order of
3928 // the true and false operands here. This will allow the setcc to be
3929 // matched to a single CSINC instruction.
3930 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
3931 } else {
3932 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
3933 // totally clean. Some of them require two CSELs to implement. As is in
3934 // this case, we emit the first CSEL and then emit a second using the output
3935 // of the first as the RHS. We're effectively OR'ing the two CC's together.
3936
3937 // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003938 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003939 SDValue CS1 =
3940 DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3941
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003942 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003943 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3944 }
3945}
3946
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00003947SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
3948 SDValue RHS, SDValue TVal,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003949 SDValue FVal, const SDLoc &dl,
Tim Northover3b0846e2014-05-24 12:50:23 +00003950 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00003951 // Handle f128 first, because it will result in a comparison of some RTLIB
3952 // call result against zero.
3953 if (LHS.getValueType() == MVT::f128) {
3954 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3955
3956 // If softenSetCCOperands returned a scalar, we need to compare the result
3957 // against zero to select between true and false values.
3958 if (!RHS.getNode()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003959 RHS = DAG.getConstant(0, dl, LHS.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00003960 CC = ISD::SETNE;
3961 }
3962 }
3963
Ahmed Bougacha88ddeae2015-11-17 16:45:40 +00003964 // Also handle f16, for which we need to do a f32 comparison.
3965 if (LHS.getValueType() == MVT::f16) {
3966 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
3967 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
3968 }
3969
3970 // Next, handle integers.
Tim Northover3b0846e2014-05-24 12:50:23 +00003971 if (LHS.getValueType().isInteger()) {
3972 assert((LHS.getValueType() == RHS.getValueType()) &&
3973 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3974
3975 unsigned Opcode = AArch64ISD::CSEL;
3976
3977 // If both the TVal and the FVal are constants, see if we can swap them in
3978 // order to for a CSINV or CSINC out of them.
3979 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
3980 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
3981
3982 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
3983 std::swap(TVal, FVal);
3984 std::swap(CTVal, CFVal);
3985 CC = ISD::getSetCCInverse(CC, true);
3986 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
3987 std::swap(TVal, FVal);
3988 std::swap(CTVal, CFVal);
3989 CC = ISD::getSetCCInverse(CC, true);
3990 } else if (TVal.getOpcode() == ISD::XOR) {
3991 // If TVal is a NOT we want to swap TVal and FVal so that we can match
3992 // with a CSINV rather than a CSEL.
Artyom Skrobov314ee042015-11-25 19:41:11 +00003993 if (isAllOnesConstant(TVal.getOperand(1))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003994 std::swap(TVal, FVal);
3995 std::swap(CTVal, CFVal);
3996 CC = ISD::getSetCCInverse(CC, true);
3997 }
3998 } else if (TVal.getOpcode() == ISD::SUB) {
3999 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
4000 // that we can match with a CSNEG rather than a CSEL.
Artyom Skrobov314ee042015-11-25 19:41:11 +00004001 if (isNullConstant(TVal.getOperand(0))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004002 std::swap(TVal, FVal);
4003 std::swap(CTVal, CFVal);
4004 CC = ISD::getSetCCInverse(CC, true);
4005 }
4006 } else if (CTVal && CFVal) {
4007 const int64_t TrueVal = CTVal->getSExtValue();
4008 const int64_t FalseVal = CFVal->getSExtValue();
4009 bool Swap = false;
4010
4011 // If both TVal and FVal are constants, see if FVal is the
4012 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
4013 // instead of a CSEL in that case.
4014 if (TrueVal == ~FalseVal) {
4015 Opcode = AArch64ISD::CSINV;
4016 } else if (TrueVal == -FalseVal) {
4017 Opcode = AArch64ISD::CSNEG;
4018 } else if (TVal.getValueType() == MVT::i32) {
4019 // If our operands are only 32-bit wide, make sure we use 32-bit
4020 // arithmetic for the check whether we can use CSINC. This ensures that
4021 // the addition in the check will wrap around properly in case there is
4022 // an overflow (which would not be the case if we do the check with
4023 // 64-bit arithmetic).
4024 const uint32_t TrueVal32 = CTVal->getZExtValue();
4025 const uint32_t FalseVal32 = CFVal->getZExtValue();
4026
4027 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
4028 Opcode = AArch64ISD::CSINC;
4029
4030 if (TrueVal32 > FalseVal32) {
4031 Swap = true;
4032 }
4033 }
4034 // 64-bit check whether we can use CSINC.
4035 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
4036 Opcode = AArch64ISD::CSINC;
4037
4038 if (TrueVal > FalseVal) {
4039 Swap = true;
4040 }
4041 }
4042
4043 // Swap TVal and FVal if necessary.
4044 if (Swap) {
4045 std::swap(TVal, FVal);
4046 std::swap(CTVal, CFVal);
4047 CC = ISD::getSetCCInverse(CC, true);
4048 }
4049
4050 if (Opcode != AArch64ISD::CSEL) {
4051 // Drop FVal since we can get its value by simply inverting/negating
4052 // TVal.
4053 FVal = TVal;
4054 }
4055 }
4056
Chad Rosier58f505b2016-08-26 18:05:50 +00004057 // Avoid materializing a constant when possible by reusing a known value in
4058 // a register. However, don't perform this optimization if the known value
Chad Rosier0c621fd2016-10-26 18:15:32 +00004059 // is one, zero or negative one in the case of a CSEL. We can always
4060 // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the
4061 // FVal, respectively.
Chad Rosier58f505b2016-08-26 18:05:50 +00004062 ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS);
4063 if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() &&
4064 !RHSVal->isNullValue() && !RHSVal->isAllOnesValue()) {
4065 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
4066 // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to
4067 // "a != C ? x : a" to avoid materializing C.
4068 if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ)
4069 TVal = LHS;
4070 else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE)
4071 FVal = LHS;
Chad Rosier0c621fd2016-10-26 18:15:32 +00004072 } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) {
4073 assert (CTVal && CFVal && "Expected constant operands for CSNEG.");
4074 // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to
4075 // avoid materializing C.
4076 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
4077 if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) {
4078 Opcode = AArch64ISD::CSINV;
4079 TVal = LHS;
4080 FVal = DAG.getConstant(0, dl, FVal.getValueType());
4081 }
Chad Rosier58f505b2016-08-26 18:05:50 +00004082 }
4083
Tim Northover3b0846e2014-05-24 12:50:23 +00004084 SDValue CCVal;
4085 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
4086
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004087 EVT VT = TVal.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00004088 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
4089 }
4090
4091 // Now we know we're dealing with FP values.
4092 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
4093 assert(LHS.getValueType() == RHS.getValueType());
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004094 EVT VT = TVal.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00004095 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
4096
4097 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4098 // clean. Some of them require two CSELs to implement.
4099 AArch64CC::CondCode CC1, CC2;
4100 changeFPCCToAArch64CC(CC, CC1, CC2);
Evandro Menezesce8d6012016-10-18 20:37:35 +00004101
4102 if (DAG.getTarget().Options.UnsafeFPMath) {
4103 // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and
4104 // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0.
4105 ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS);
4106 if (RHSVal && RHSVal->isZero()) {
4107 ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal);
4108 ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal);
4109
4110 if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) &&
Roger Ferrer Ibanez80c0f332016-11-08 13:34:41 +00004111 CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType())
Evandro Menezesce8d6012016-10-18 20:37:35 +00004112 TVal = LHS;
4113 else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) &&
Roger Ferrer Ibanez80c0f332016-11-08 13:34:41 +00004114 CFVal && CFVal->isZero() &&
4115 FVal.getValueType() == LHS.getValueType())
Evandro Menezesce8d6012016-10-18 20:37:35 +00004116 FVal = LHS;
4117 }
4118 }
4119
4120 // Emit first, and possibly only, CSEL.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004121 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004122 SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4123
4124 // If we need a second CSEL, emit it, using the output of the first as the
4125 // RHS. We're effectively OR'ing the two CC's together.
4126 if (CC2 != AArch64CC::AL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004127 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004128 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4129 }
4130
4131 // Otherwise, return the output of the first CSEL.
4132 return CS1;
4133}
4134
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004135SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
4136 SelectionDAG &DAG) const {
4137 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4138 SDValue LHS = Op.getOperand(0);
4139 SDValue RHS = Op.getOperand(1);
4140 SDValue TVal = Op.getOperand(2);
4141 SDValue FVal = Op.getOperand(3);
4142 SDLoc DL(Op);
4143 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4144}
4145
4146SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
4147 SelectionDAG &DAG) const {
4148 SDValue CCVal = Op->getOperand(0);
4149 SDValue TVal = Op->getOperand(1);
4150 SDValue FVal = Op->getOperand(2);
4151 SDLoc DL(Op);
4152
4153 unsigned Opc = CCVal.getOpcode();
4154 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
4155 // instruction.
4156 if (CCVal.getResNo() == 1 &&
4157 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4158 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
4159 // Only lower legal XALUO ops.
4160 if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
4161 return SDValue();
4162
4163 AArch64CC::CondCode OFCC;
4164 SDValue Value, Overflow;
4165 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004166 SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004167
4168 return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
4169 CCVal, Overflow);
4170 }
4171
4172 // Lower it the same way as we would lower a SELECT_CC node.
4173 ISD::CondCode CC;
4174 SDValue LHS, RHS;
4175 if (CCVal.getOpcode() == ISD::SETCC) {
4176 LHS = CCVal.getOperand(0);
4177 RHS = CCVal.getOperand(1);
4178 CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
4179 } else {
4180 LHS = CCVal;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004181 RHS = DAG.getConstant(0, DL, CCVal.getValueType());
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004182 CC = ISD::SETNE;
4183 }
4184 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4185}
4186
Tim Northover3b0846e2014-05-24 12:50:23 +00004187SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
4188 SelectionDAG &DAG) const {
4189 // Jump table entries as PC relative offsets. No additional tweaking
4190 // is necessary here. Just get the address of the jump table.
4191 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00004192 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004193 SDLoc DL(Op);
4194
4195 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4196 !Subtarget->isTargetMachO()) {
4197 const unsigned char MO_NC = AArch64II::MO_NC;
4198 return DAG.getNode(
4199 AArch64ISD::WrapperLarge, DL, PtrVT,
4200 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G3),
4201 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G2 | MO_NC),
4202 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G1 | MO_NC),
4203 DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4204 AArch64II::MO_G0 | MO_NC));
4205 }
4206
4207 SDValue Hi =
4208 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_PAGE);
4209 SDValue Lo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4210 AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4211 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4212 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4213}
4214
4215SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
4216 SelectionDAG &DAG) const {
4217 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00004218 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004219 SDLoc DL(Op);
4220
4221 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4222 // Use the GOT for the large code model on iOS.
4223 if (Subtarget->isTargetMachO()) {
4224 SDValue GotAddr = DAG.getTargetConstantPool(
4225 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4226 AArch64II::MO_GOT);
4227 return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
4228 }
4229
4230 const unsigned char MO_NC = AArch64II::MO_NC;
4231 return DAG.getNode(
4232 AArch64ISD::WrapperLarge, DL, PtrVT,
4233 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4234 CP->getOffset(), AArch64II::MO_G3),
4235 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4236 CP->getOffset(), AArch64II::MO_G2 | MO_NC),
4237 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4238 CP->getOffset(), AArch64II::MO_G1 | MO_NC),
4239 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4240 CP->getOffset(), AArch64II::MO_G0 | MO_NC));
4241 } else {
4242 // Use ADRP/ADD or ADRP/LDR for everything else: the small memory model on
4243 // ELF, the only valid one on Darwin.
4244 SDValue Hi =
4245 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4246 CP->getOffset(), AArch64II::MO_PAGE);
4247 SDValue Lo = DAG.getTargetConstantPool(
4248 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4249 AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4250
4251 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4252 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4253 }
4254}
4255
4256SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
4257 SelectionDAG &DAG) const {
4258 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
Mehdi Amini44ede332015-07-09 02:09:04 +00004259 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004260 SDLoc DL(Op);
4261 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4262 !Subtarget->isTargetMachO()) {
4263 const unsigned char MO_NC = AArch64II::MO_NC;
4264 return DAG.getNode(
4265 AArch64ISD::WrapperLarge, DL, PtrVT,
4266 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G3),
4267 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
4268 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
4269 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
4270 } else {
4271 SDValue Hi = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGE);
4272 SDValue Lo = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGEOFF |
4273 AArch64II::MO_NC);
4274 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4275 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4276 }
4277}
4278
4279SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
4280 SelectionDAG &DAG) const {
4281 AArch64FunctionInfo *FuncInfo =
4282 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4283
4284 SDLoc DL(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00004285 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
4286 getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00004287 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4288 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
Justin Lebar9c375812016-07-15 18:27:10 +00004289 MachinePointerInfo(SV));
Tim Northover3b0846e2014-05-24 12:50:23 +00004290}
4291
4292SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
4293 SelectionDAG &DAG) const {
4294 // The layout of the va_list struct is specified in the AArch64 Procedure Call
4295 // Standard, section B.3.
4296 MachineFunction &MF = DAG.getMachineFunction();
4297 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Mehdi Amini44ede332015-07-09 02:09:04 +00004298 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004299 SDLoc DL(Op);
4300
4301 SDValue Chain = Op.getOperand(0);
4302 SDValue VAList = Op.getOperand(1);
4303 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4304 SmallVector<SDValue, 4> MemOps;
4305
4306 // void *__stack at offset 0
Mehdi Amini44ede332015-07-09 02:09:04 +00004307 SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004308 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
Justin Lebar9c375812016-07-15 18:27:10 +00004309 MachinePointerInfo(SV), /* Alignment = */ 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00004310
4311 // void *__gr_top at offset 8
4312 int GPRSize = FuncInfo->getVarArgsGPRSize();
4313 if (GPRSize > 0) {
4314 SDValue GRTop, GRTopAddr;
4315
Mehdi Amini44ede332015-07-09 02:09:04 +00004316 GRTopAddr =
4317 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004318
Mehdi Amini44ede332015-07-09 02:09:04 +00004319 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
4320 GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
4321 DAG.getConstant(GPRSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004322
4323 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
Justin Lebar9c375812016-07-15 18:27:10 +00004324 MachinePointerInfo(SV, 8),
4325 /* Alignment = */ 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00004326 }
4327
4328 // void *__vr_top at offset 16
4329 int FPRSize = FuncInfo->getVarArgsFPRSize();
4330 if (FPRSize > 0) {
4331 SDValue VRTop, VRTopAddr;
Mehdi Amini44ede332015-07-09 02:09:04 +00004332 VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4333 DAG.getConstant(16, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004334
Mehdi Amini44ede332015-07-09 02:09:04 +00004335 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
4336 VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
4337 DAG.getConstant(FPRSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004338
4339 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
Justin Lebar9c375812016-07-15 18:27:10 +00004340 MachinePointerInfo(SV, 16),
4341 /* Alignment = */ 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00004342 }
4343
4344 // int __gr_offs at offset 24
Mehdi Amini44ede332015-07-09 02:09:04 +00004345 SDValue GROffsAddr =
4346 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
Justin Lebar9c375812016-07-15 18:27:10 +00004347 MemOps.push_back(DAG.getStore(
4348 Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32), GROffsAddr,
4349 MachinePointerInfo(SV, 24), /* Alignment = */ 4));
Tim Northover3b0846e2014-05-24 12:50:23 +00004350
4351 // int __vr_offs at offset 28
Mehdi Amini44ede332015-07-09 02:09:04 +00004352 SDValue VROffsAddr =
4353 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
Justin Lebar9c375812016-07-15 18:27:10 +00004354 MemOps.push_back(DAG.getStore(
4355 Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32), VROffsAddr,
4356 MachinePointerInfo(SV, 28), /* Alignment = */ 4));
Tim Northover3b0846e2014-05-24 12:50:23 +00004357
4358 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
4359}
4360
4361SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
4362 SelectionDAG &DAG) const {
4363 return Subtarget->isTargetDarwin() ? LowerDarwin_VASTART(Op, DAG)
4364 : LowerAAPCS_VASTART(Op, DAG);
4365}
4366
4367SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
4368 SelectionDAG &DAG) const {
4369 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
4370 // pointer.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004371 SDLoc DL(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00004372 unsigned VaListSize = Subtarget->isTargetDarwin() ? 8 : 32;
4373 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4374 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4375
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004376 return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1),
4377 Op.getOperand(2),
4378 DAG.getConstant(VaListSize, DL, MVT::i32),
Krzysztof Parzyszeka46c36b2015-04-13 17:16:45 +00004379 8, false, false, false, MachinePointerInfo(DestSV),
Tim Northover3b0846e2014-05-24 12:50:23 +00004380 MachinePointerInfo(SrcSV));
4381}
4382
4383SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
4384 assert(Subtarget->isTargetDarwin() &&
4385 "automatic va_arg instruction only works on Darwin");
4386
4387 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4388 EVT VT = Op.getValueType();
4389 SDLoc DL(Op);
4390 SDValue Chain = Op.getOperand(0);
4391 SDValue Addr = Op.getOperand(1);
4392 unsigned Align = Op.getConstantOperandVal(3);
Mehdi Amini44ede332015-07-09 02:09:04 +00004393 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004394
Justin Lebar9c375812016-07-15 18:27:10 +00004395 SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V));
Tim Northover3b0846e2014-05-24 12:50:23 +00004396 Chain = VAList.getValue(1);
4397
4398 if (Align > 8) {
4399 assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
Mehdi Amini44ede332015-07-09 02:09:04 +00004400 VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4401 DAG.getConstant(Align - 1, DL, PtrVT));
4402 VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
4403 DAG.getConstant(-(int64_t)Align, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004404 }
4405
4406 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
Mehdi Amini44ede332015-07-09 02:09:04 +00004407 uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
Tim Northover3b0846e2014-05-24 12:50:23 +00004408
4409 // Scalar integer and FP values smaller than 64 bits are implicitly extended
4410 // up to 64 bits. At the very least, we have to increase the striding of the
4411 // vaargs list to match this, and for FP values we need to introduce
4412 // FP_ROUND nodes as well.
4413 if (VT.isInteger() && !VT.isVector())
4414 ArgSize = 8;
4415 bool NeedFPTrunc = false;
4416 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
4417 ArgSize = 8;
4418 NeedFPTrunc = true;
4419 }
4420
4421 // Increment the pointer, VAList, to the next vaarg
Mehdi Amini44ede332015-07-09 02:09:04 +00004422 SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4423 DAG.getConstant(ArgSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004424 // Store the incremented VAList to the legalized pointer
Justin Lebar9c375812016-07-15 18:27:10 +00004425 SDValue APStore =
4426 DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V));
Tim Northover3b0846e2014-05-24 12:50:23 +00004427
4428 // Load the actual argument out of the pointer VAList
4429 if (NeedFPTrunc) {
4430 // Load the value as an f64.
Justin Lebar9c375812016-07-15 18:27:10 +00004431 SDValue WideFP =
4432 DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00004433 // Round the value down to an f32.
4434 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004435 DAG.getIntPtrConstant(1, DL));
Tim Northover3b0846e2014-05-24 12:50:23 +00004436 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
4437 // Merge the rounded value with the chain output of the load.
4438 return DAG.getMergeValues(Ops, DL);
4439 }
4440
Justin Lebar9c375812016-07-15 18:27:10 +00004441 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00004442}
4443
4444SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
4445 SelectionDAG &DAG) const {
Matthias Braun941a7052016-07-28 18:40:00 +00004446 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
4447 MFI.setFrameAddressIsTaken(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00004448
4449 EVT VT = Op.getValueType();
4450 SDLoc DL(Op);
4451 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4452 SDValue FrameAddr =
4453 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
4454 while (Depth--)
4455 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
Justin Lebar9c375812016-07-15 18:27:10 +00004456 MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00004457 return FrameAddr;
4458}
4459
4460// FIXME? Maybe this could be a TableGen attribute on some registers and
4461// this table could be generated automatically from RegInfo.
Pat Gavlina717f252015-07-09 17:40:29 +00004462unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT,
4463 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004464 unsigned Reg = StringSwitch<unsigned>(RegName)
4465 .Case("sp", AArch64::SP)
4466 .Default(0);
4467 if (Reg)
4468 return Reg;
Luke Cheeseman85fd06d2015-06-01 12:02:47 +00004469 report_fatal_error(Twine("Invalid register name \""
4470 + StringRef(RegName) + "\"."));
Tim Northover3b0846e2014-05-24 12:50:23 +00004471}
4472
4473SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
4474 SelectionDAG &DAG) const {
4475 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braun941a7052016-07-28 18:40:00 +00004476 MachineFrameInfo &MFI = MF.getFrameInfo();
4477 MFI.setReturnAddressIsTaken(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00004478
4479 EVT VT = Op.getValueType();
4480 SDLoc DL(Op);
4481 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4482 if (Depth) {
4483 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
Mehdi Amini44ede332015-07-09 02:09:04 +00004484 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00004485 return DAG.getLoad(VT, DL, DAG.getEntryNode(),
4486 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
Justin Lebar9c375812016-07-15 18:27:10 +00004487 MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00004488 }
4489
4490 // Return LR, which contains the return address. Mark it an implicit live-in.
4491 unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
4492 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4493}
4494
4495/// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4496/// i64 values and take a 2 x i64 value to shift plus a shift amount.
4497SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
4498 SelectionDAG &DAG) const {
4499 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4500 EVT VT = Op.getValueType();
4501 unsigned VTBits = VT.getSizeInBits();
4502 SDLoc dl(Op);
4503 SDValue ShOpLo = Op.getOperand(0);
4504 SDValue ShOpHi = Op.getOperand(1);
4505 SDValue ShAmt = Op.getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00004506 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4507
4508 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4509
4510 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004511 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
Tim Northoverf3be9d52015-12-02 00:33:54 +00004512 SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4513
4514 // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
4515 // is "undef". We wanted 0, so CSEL it directly.
4516 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
4517 ISD::SETEQ, dl, DAG);
4518 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
4519 HiBitsForLo =
4520 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
4521 HiBitsForLo, CCVal, Cmp);
4522
Tim Northover3b0846e2014-05-24 12:50:23 +00004523 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004524 DAG.getConstant(VTBits, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00004525
Tim Northoverf3be9d52015-12-02 00:33:54 +00004526 SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4527 SDValue LoForNormalShift =
4528 DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
Tim Northover3b0846e2014-05-24 12:50:23 +00004529
Tim Northoverf3be9d52015-12-02 00:33:54 +00004530 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
4531 dl, DAG);
4532 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4533 SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4534 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
4535 LoForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00004536
4537 // AArch64 shifts larger than the register width are wrapped rather than
4538 // clamped, so we can't just emit "hi >> x".
Tim Northoverf3be9d52015-12-02 00:33:54 +00004539 SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4540 SDValue HiForBigShift =
4541 Opc == ISD::SRA
4542 ? DAG.getNode(Opc, dl, VT, ShOpHi,
4543 DAG.getConstant(VTBits - 1, dl, MVT::i64))
4544 : DAG.getConstant(0, dl, VT);
4545 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
4546 HiForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00004547
4548 SDValue Ops[2] = { Lo, Hi };
4549 return DAG.getMergeValues(Ops, dl);
4550}
4551
Tim Northoverf3be9d52015-12-02 00:33:54 +00004552
Tim Northover3b0846e2014-05-24 12:50:23 +00004553/// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4554/// i64 values and take a 2 x i64 value to shift plus a shift amount.
4555SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
Tim Northoverf3be9d52015-12-02 00:33:54 +00004556 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004557 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4558 EVT VT = Op.getValueType();
4559 unsigned VTBits = VT.getSizeInBits();
4560 SDLoc dl(Op);
4561 SDValue ShOpLo = Op.getOperand(0);
4562 SDValue ShOpHi = Op.getOperand(1);
4563 SDValue ShAmt = Op.getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00004564
4565 assert(Op.getOpcode() == ISD::SHL_PARTS);
4566 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004567 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
Tim Northoverf3be9d52015-12-02 00:33:54 +00004568 SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4569
4570 // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
4571 // is "undef". We wanted 0, so CSEL it directly.
4572 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
4573 ISD::SETEQ, dl, DAG);
4574 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
4575 LoBitsForHi =
4576 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
4577 LoBitsForHi, CCVal, Cmp);
4578
Tim Northover3b0846e2014-05-24 12:50:23 +00004579 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004580 DAG.getConstant(VTBits, dl, MVT::i64));
Tim Northoverf3be9d52015-12-02 00:33:54 +00004581 SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4582 SDValue HiForNormalShift =
4583 DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
Tim Northover3b0846e2014-05-24 12:50:23 +00004584
Tim Northoverf3be9d52015-12-02 00:33:54 +00004585 SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
Tim Northover3b0846e2014-05-24 12:50:23 +00004586
Tim Northoverf3be9d52015-12-02 00:33:54 +00004587 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
4588 dl, DAG);
4589 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4590 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
4591 HiForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00004592
4593 // AArch64 shifts of larger than register sizes are wrapped rather than
4594 // clamped, so we can't just emit "lo << a" if a is too big.
Tim Northoverf3be9d52015-12-02 00:33:54 +00004595 SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
4596 SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4597 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
4598 LoForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00004599
4600 SDValue Ops[2] = { Lo, Hi };
4601 return DAG.getMergeValues(Ops, dl);
4602}
4603
4604bool AArch64TargetLowering::isOffsetFoldingLegal(
4605 const GlobalAddressSDNode *GA) const {
4606 // The AArch64 target doesn't support folding offsets into global addresses.
4607 return false;
4608}
4609
4610bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4611 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
4612 // FIXME: We should be able to handle f128 as well with a clever lowering.
4613 if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32))
4614 return true;
4615
4616 if (VT == MVT::f64)
4617 return AArch64_AM::getFP64Imm(Imm) != -1;
4618 else if (VT == MVT::f32)
4619 return AArch64_AM::getFP32Imm(Imm) != -1;
4620 return false;
4621}
4622
4623//===----------------------------------------------------------------------===//
4624// AArch64 Optimization Hooks
4625//===----------------------------------------------------------------------===//
4626
Evandro Menezeseff2bd92016-10-24 16:14:58 +00004627static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode,
4628 SDValue Operand, SelectionDAG &DAG,
4629 int &ExtraSteps) {
4630 EVT VT = Operand.getValueType();
4631 if (ST->hasNEON() &&
4632 (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 ||
4633 VT == MVT::f32 || VT == MVT::v1f32 ||
4634 VT == MVT::v2f32 || VT == MVT::v4f32)) {
4635 if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified)
4636 // For the reciprocal estimates, convergence is quadratic, so the number
4637 // of digits is doubled after each iteration. In ARMv8, the accuracy of
4638 // the initial estimate is 2^-8. Thus the number of extra steps to refine
4639 // the result for float (23 mantissa bits) is 2 and for double (52
4640 // mantissa bits) is 3.
4641 ExtraSteps = VT == MVT::f64 ? 3 : 2;
4642
4643 return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand);
4644 }
4645
4646 return SDValue();
4647}
4648
Evandro Menezes21f9ce12016-11-10 23:31:06 +00004649SDValue AArch64TargetLowering::getSqrtEstimate(SDValue Operand,
4650 SelectionDAG &DAG, int Enabled,
4651 int &ExtraSteps,
4652 bool &UseOneConst,
4653 bool Reciprocal) const {
Evandro Menezeseff2bd92016-10-24 16:14:58 +00004654 if (Enabled == ReciprocalEstimate::Enabled ||
4655 (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt()))
4656 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, Operand,
4657 DAG, ExtraSteps)) {
Evandro Menezes9fc54822016-11-14 23:29:01 +00004658 SDLoc DL(Operand);
4659 EVT VT = Operand.getValueType();
4660
4661 SDNodeFlags Flags;
4662 Flags.setUnsafeAlgebra(true);
4663
4664 // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2)
4665 // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N)
4666 for (int i = ExtraSteps; i > 0; --i) {
4667 SDValue Step = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Estimate,
4668 &Flags);
4669 Step = DAG.getNode(AArch64ISD::FRSQRTS, DL, VT, Operand, Step, &Flags);
4670 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, &Flags);
4671 }
4672
4673 if (!Reciprocal) {
4674 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
4675 VT);
4676 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
4677 SDValue Eq = DAG.getSetCC(DL, CCVT, Operand, FPZero, ISD::SETEQ);
4678
4679 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Operand, Estimate, &Flags);
4680 // Correct the result if the operand is 0.0.
4681 Estimate = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL,
4682 VT, Eq, Operand, Estimate);
4683 }
4684
4685 ExtraSteps = 0;
Evandro Menezeseff2bd92016-10-24 16:14:58 +00004686 return Estimate;
4687 }
4688
4689 return SDValue();
4690}
4691
4692SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand,
4693 SelectionDAG &DAG, int Enabled,
4694 int &ExtraSteps) const {
4695 if (Enabled == ReciprocalEstimate::Enabled)
4696 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand,
Evandro Menezes9fc54822016-11-14 23:29:01 +00004697 DAG, ExtraSteps)) {
4698 SDLoc DL(Operand);
4699 EVT VT = Operand.getValueType();
4700
4701 SDNodeFlags Flags;
4702 Flags.setUnsafeAlgebra(true);
4703
4704 // Newton reciprocal iteration: E * (2 - X * E)
4705 // AArch64 reciprocal iteration instruction: (2 - M * N)
4706 for (int i = ExtraSteps; i > 0; --i) {
4707 SDValue Step = DAG.getNode(AArch64ISD::FRECPS, DL, VT, Operand,
4708 Estimate, &Flags);
4709 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, &Flags);
4710 }
4711
4712 ExtraSteps = 0;
Evandro Menezeseff2bd92016-10-24 16:14:58 +00004713 return Estimate;
Evandro Menezes9fc54822016-11-14 23:29:01 +00004714 }
Evandro Menezeseff2bd92016-10-24 16:14:58 +00004715
4716 return SDValue();
4717}
4718
Tim Northover3b0846e2014-05-24 12:50:23 +00004719//===----------------------------------------------------------------------===//
4720// AArch64 Inline Assembly Support
4721//===----------------------------------------------------------------------===//
4722
4723// Table of Constraints
4724// TODO: This is the current set of constraints supported by ARM for the
4725// compiler, not all of them may make sense, e.g. S may be difficult to support.
4726//
4727// r - A general register
4728// w - An FP/SIMD register of some size in the range v0-v31
4729// x - An FP/SIMD register of some size in the range v0-v15
4730// I - Constant that can be used with an ADD instruction
4731// J - Constant that can be used with a SUB instruction
4732// K - Constant that can be used with a 32-bit logical instruction
4733// L - Constant that can be used with a 64-bit logical instruction
4734// M - Constant that can be used as a 32-bit MOV immediate
4735// N - Constant that can be used as a 64-bit MOV immediate
4736// Q - A memory reference with base register and no offset
4737// S - A symbolic address
4738// Y - Floating point constant zero
4739// Z - Integer constant zero
4740//
4741// Note that general register operands will be output using their 64-bit x
4742// register name, whatever the size of the variable, unless the asm operand
4743// is prefixed by the %w modifier. Floating-point and SIMD register operands
4744// will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
4745// %q modifier.
Silviu Barangaf60be282016-05-09 11:10:44 +00004746const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
4747 // At this point, we have to lower this constraint to something else, so we
4748 // lower it to an "r" or "w". However, by doing this we will force the result
4749 // to be in register, while the X constraint is much more permissive.
4750 //
4751 // Although we are correct (we are free to emit anything, without
4752 // constraints), we might break use cases that would expect us to be more
4753 // efficient and emit something else.
4754 if (!Subtarget->hasFPARMv8())
4755 return "r";
4756
4757 if (ConstraintVT.isFloatingPoint())
4758 return "w";
4759
4760 if (ConstraintVT.isVector() &&
4761 (ConstraintVT.getSizeInBits() == 64 ||
4762 ConstraintVT.getSizeInBits() == 128))
4763 return "w";
4764
4765 return "r";
4766}
Tim Northover3b0846e2014-05-24 12:50:23 +00004767
4768/// getConstraintType - Given a constraint letter, return the type of
4769/// constraint it is for this target.
4770AArch64TargetLowering::ConstraintType
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00004771AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004772 if (Constraint.size() == 1) {
4773 switch (Constraint[0]) {
4774 default:
4775 break;
4776 case 'z':
4777 return C_Other;
4778 case 'x':
4779 case 'w':
4780 return C_RegisterClass;
4781 // An address with a single base register. Due to the way we
4782 // currently handle addresses it is the same as 'r'.
4783 case 'Q':
4784 return C_Memory;
4785 }
4786 }
4787 return TargetLowering::getConstraintType(Constraint);
4788}
4789
4790/// Examine constraint type and operand type and determine a weight value.
4791/// This object must already have been set up with the operand type
4792/// and the current alternative constraint selected.
4793TargetLowering::ConstraintWeight
4794AArch64TargetLowering::getSingleConstraintMatchWeight(
4795 AsmOperandInfo &info, const char *constraint) const {
4796 ConstraintWeight weight = CW_Invalid;
4797 Value *CallOperandVal = info.CallOperandVal;
4798 // If we don't have a value, we can't do a match,
4799 // but allow it at the lowest weight.
4800 if (!CallOperandVal)
4801 return CW_Default;
4802 Type *type = CallOperandVal->getType();
4803 // Look at the constraint type.
4804 switch (*constraint) {
4805 default:
4806 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
4807 break;
4808 case 'x':
4809 case 'w':
4810 if (type->isFloatingPointTy() || type->isVectorTy())
4811 weight = CW_Register;
4812 break;
4813 case 'z':
4814 weight = CW_Constant;
4815 break;
4816 }
4817 return weight;
4818}
4819
4820std::pair<unsigned, const TargetRegisterClass *>
4821AArch64TargetLowering::getRegForInlineAsmConstraint(
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00004822 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004823 if (Constraint.size() == 1) {
4824 switch (Constraint[0]) {
4825 case 'r':
4826 if (VT.getSizeInBits() == 64)
4827 return std::make_pair(0U, &AArch64::GPR64commonRegClass);
4828 return std::make_pair(0U, &AArch64::GPR32commonRegClass);
4829 case 'w':
Amara Emerson614b44b2016-11-07 15:42:12 +00004830 if (VT.getSizeInBits() == 16)
4831 return std::make_pair(0U, &AArch64::FPR16RegClass);
Akira Hatanakab8d28732016-07-21 21:39:05 +00004832 if (VT.getSizeInBits() == 32)
Tim Northover3b0846e2014-05-24 12:50:23 +00004833 return std::make_pair(0U, &AArch64::FPR32RegClass);
4834 if (VT.getSizeInBits() == 64)
4835 return std::make_pair(0U, &AArch64::FPR64RegClass);
4836 if (VT.getSizeInBits() == 128)
4837 return std::make_pair(0U, &AArch64::FPR128RegClass);
4838 break;
4839 // The instructions that this constraint is designed for can
4840 // only take 128-bit registers so just use that regclass.
4841 case 'x':
4842 if (VT.getSizeInBits() == 128)
4843 return std::make_pair(0U, &AArch64::FPR128_loRegClass);
4844 break;
4845 }
4846 }
4847 if (StringRef("{cc}").equals_lower(Constraint))
4848 return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
4849
4850 // Use the default implementation in TargetLowering to convert the register
4851 // constraint into a member of a register class.
4852 std::pair<unsigned, const TargetRegisterClass *> Res;
Eric Christopher11e4df72015-02-26 22:38:43 +00004853 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004854
4855 // Not found as a standard register?
4856 if (!Res.second) {
4857 unsigned Size = Constraint.size();
4858 if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
4859 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00004860 int RegNo;
4861 bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
4862 if (!Failed && RegNo >= 0 && RegNo <= 31) {
Tim Northover9508a702016-05-10 22:26:45 +00004863 // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size.
Tim Northover3b0846e2014-05-24 12:50:23 +00004864 // By default we'll emit v0-v31 for this unless there's a modifier where
4865 // we'll emit the correct register as well.
Tim Northover9508a702016-05-10 22:26:45 +00004866 if (VT != MVT::Other && VT.getSizeInBits() == 64) {
4867 Res.first = AArch64::FPR64RegClass.getRegister(RegNo);
4868 Res.second = &AArch64::FPR64RegClass;
4869 } else {
4870 Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
4871 Res.second = &AArch64::FPR128RegClass;
4872 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004873 }
4874 }
4875 }
4876
4877 return Res;
4878}
4879
4880/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
4881/// vector. If it is invalid, don't add anything to Ops.
4882void AArch64TargetLowering::LowerAsmOperandForConstraint(
4883 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
4884 SelectionDAG &DAG) const {
4885 SDValue Result;
4886
4887 // Currently only support length 1 constraints.
4888 if (Constraint.length() != 1)
4889 return;
4890
4891 char ConstraintLetter = Constraint[0];
4892 switch (ConstraintLetter) {
4893 default:
4894 break;
4895
4896 // This set of constraints deal with valid constants for various instructions.
4897 // Validate and return a target constant for them if we can.
4898 case 'z': {
4899 // 'z' maps to xzr or wzr so it needs an input of 0.
Artyom Skrobov314ee042015-11-25 19:41:11 +00004900 if (!isNullConstant(Op))
Tim Northover3b0846e2014-05-24 12:50:23 +00004901 return;
4902
4903 if (Op.getValueType() == MVT::i64)
4904 Result = DAG.getRegister(AArch64::XZR, MVT::i64);
4905 else
4906 Result = DAG.getRegister(AArch64::WZR, MVT::i32);
4907 break;
4908 }
4909
4910 case 'I':
4911 case 'J':
4912 case 'K':
4913 case 'L':
4914 case 'M':
4915 case 'N':
4916 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4917 if (!C)
4918 return;
4919
4920 // Grab the value and do some validation.
4921 uint64_t CVal = C->getZExtValue();
4922 switch (ConstraintLetter) {
4923 // The I constraint applies only to simple ADD or SUB immediate operands:
4924 // i.e. 0 to 4095 with optional shift by 12
4925 // The J constraint applies only to ADD or SUB immediates that would be
4926 // valid when negated, i.e. if [an add pattern] were to be output as a SUB
4927 // instruction [or vice versa], in other words -1 to -4095 with optional
4928 // left shift by 12.
4929 case 'I':
4930 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
4931 break;
4932 return;
4933 case 'J': {
4934 uint64_t NVal = -C->getSExtValue();
Tim Northover2c46beb2014-07-27 07:10:29 +00004935 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
4936 CVal = C->getSExtValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00004937 break;
Tim Northover2c46beb2014-07-27 07:10:29 +00004938 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004939 return;
4940 }
4941 // The K and L constraints apply *only* to logical immediates, including
4942 // what used to be the MOVI alias for ORR (though the MOVI alias has now
4943 // been removed and MOV should be used). So these constraints have to
4944 // distinguish between bit patterns that are valid 32-bit or 64-bit
4945 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
4946 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
4947 // versa.
4948 case 'K':
4949 if (AArch64_AM::isLogicalImmediate(CVal, 32))
4950 break;
4951 return;
4952 case 'L':
4953 if (AArch64_AM::isLogicalImmediate(CVal, 64))
4954 break;
4955 return;
4956 // The M and N constraints are a superset of K and L respectively, for use
4957 // with the MOV (immediate) alias. As well as the logical immediates they
4958 // also match 32 or 64-bit immediates that can be loaded either using a
4959 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
4960 // (M) or 64-bit 0x1234000000000000 (N) etc.
4961 // As a note some of this code is liberally stolen from the asm parser.
4962 case 'M': {
4963 if (!isUInt<32>(CVal))
4964 return;
4965 if (AArch64_AM::isLogicalImmediate(CVal, 32))
4966 break;
4967 if ((CVal & 0xFFFF) == CVal)
4968 break;
4969 if ((CVal & 0xFFFF0000ULL) == CVal)
4970 break;
4971 uint64_t NCVal = ~(uint32_t)CVal;
4972 if ((NCVal & 0xFFFFULL) == NCVal)
4973 break;
4974 if ((NCVal & 0xFFFF0000ULL) == NCVal)
4975 break;
4976 return;
4977 }
4978 case 'N': {
4979 if (AArch64_AM::isLogicalImmediate(CVal, 64))
4980 break;
4981 if ((CVal & 0xFFFFULL) == CVal)
4982 break;
4983 if ((CVal & 0xFFFF0000ULL) == CVal)
4984 break;
4985 if ((CVal & 0xFFFF00000000ULL) == CVal)
4986 break;
4987 if ((CVal & 0xFFFF000000000000ULL) == CVal)
4988 break;
4989 uint64_t NCVal = ~CVal;
4990 if ((NCVal & 0xFFFFULL) == NCVal)
4991 break;
4992 if ((NCVal & 0xFFFF0000ULL) == NCVal)
4993 break;
4994 if ((NCVal & 0xFFFF00000000ULL) == NCVal)
4995 break;
4996 if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
4997 break;
4998 return;
4999 }
5000 default:
5001 return;
5002 }
5003
5004 // All assembler immediates are 64-bit integers.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005005 Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00005006 break;
5007 }
5008
5009 if (Result.getNode()) {
5010 Ops.push_back(Result);
5011 return;
5012 }
5013
5014 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
5015}
5016
5017//===----------------------------------------------------------------------===//
5018// AArch64 Advanced SIMD Support
5019//===----------------------------------------------------------------------===//
5020
5021/// WidenVector - Given a value in the V64 register class, produce the
5022/// equivalent value in the V128 register class.
5023static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
5024 EVT VT = V64Reg.getValueType();
5025 unsigned NarrowSize = VT.getVectorNumElements();
5026 MVT EltTy = VT.getVectorElementType().getSimpleVT();
5027 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
5028 SDLoc DL(V64Reg);
5029
5030 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005031 V64Reg, DAG.getConstant(0, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005032}
5033
5034/// getExtFactor - Determine the adjustment factor for the position when
5035/// generating an "extract from vector registers" instruction.
5036static unsigned getExtFactor(SDValue &V) {
5037 EVT EltType = V.getValueType().getVectorElementType();
5038 return EltType.getSizeInBits() / 8;
5039}
5040
5041/// NarrowVector - Given a value in the V128 register class, produce the
5042/// equivalent value in the V64 register class.
5043static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
5044 EVT VT = V128Reg.getValueType();
5045 unsigned WideSize = VT.getVectorNumElements();
5046 MVT EltTy = VT.getVectorElementType().getSimpleVT();
5047 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
5048 SDLoc DL(V128Reg);
5049
5050 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
5051}
5052
5053// Gather data to see if the operation can be modelled as a
5054// shuffle in combination with VEXTs.
5055SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
5056 SelectionDAG &DAG) const {
Kevin Qinf0ec9af2014-06-18 05:54:42 +00005057 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
Tim Northover3b0846e2014-05-24 12:50:23 +00005058 SDLoc dl(Op);
5059 EVT VT = Op.getValueType();
5060 unsigned NumElts = VT.getVectorNumElements();
5061
Tim Northover7324e842014-07-24 15:39:55 +00005062 struct ShuffleSourceInfo {
5063 SDValue Vec;
5064 unsigned MinElt;
5065 unsigned MaxElt;
Tim Northover3b0846e2014-05-24 12:50:23 +00005066
Tim Northover7324e842014-07-24 15:39:55 +00005067 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
5068 // be compatible with the shuffle we intend to construct. As a result
5069 // ShuffleVec will be some sliding window into the original Vec.
5070 SDValue ShuffleVec;
5071
5072 // Code should guarantee that element i in Vec starts at element "WindowBase
5073 // + i * WindowScale in ShuffleVec".
5074 int WindowBase;
5075 int WindowScale;
5076
5077 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
5078 ShuffleSourceInfo(SDValue Vec)
5079 : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
5080 WindowScale(1) {}
5081 };
5082
5083 // First gather all vectors used as an immediate source for this BUILD_VECTOR
5084 // node.
5085 SmallVector<ShuffleSourceInfo, 2> Sources;
Tim Northover3b0846e2014-05-24 12:50:23 +00005086 for (unsigned i = 0; i < NumElts; ++i) {
5087 SDValue V = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00005088 if (V.isUndef())
Tim Northover3b0846e2014-05-24 12:50:23 +00005089 continue;
Ahmed Bougachadfc77352016-01-14 02:12:30 +00005090 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5091 !isa<ConstantSDNode>(V.getOperand(1))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005092 // A shuffle can only come from building a vector from various
Ahmed Bougachadfc77352016-01-14 02:12:30 +00005093 // elements of other vectors, provided their indices are constant.
Tim Northover3b0846e2014-05-24 12:50:23 +00005094 return SDValue();
5095 }
5096
Tim Northover7324e842014-07-24 15:39:55 +00005097 // Add this element source to the list if it's not already there.
Tim Northover3b0846e2014-05-24 12:50:23 +00005098 SDValue SourceVec = V.getOperand(0);
David Majnemer0d955d02016-08-11 22:21:41 +00005099 auto Source = find(Sources, SourceVec);
Tim Northover7324e842014-07-24 15:39:55 +00005100 if (Source == Sources.end())
James Molloyf497d552014-10-17 17:06:31 +00005101 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
Tim Northover3b0846e2014-05-24 12:50:23 +00005102
Tim Northover7324e842014-07-24 15:39:55 +00005103 // Update the minimum and maximum lane number seen.
5104 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5105 Source->MinElt = std::min(Source->MinElt, EltNo);
5106 Source->MaxElt = std::max(Source->MaxElt, EltNo);
Tim Northover3b0846e2014-05-24 12:50:23 +00005107 }
5108
5109 // Currently only do something sane when at most two source vectors
Tim Northover7324e842014-07-24 15:39:55 +00005110 // are involved.
5111 if (Sources.size() > 2)
Tim Northover3b0846e2014-05-24 12:50:23 +00005112 return SDValue();
5113
Kevin Qin9a2a2c52014-07-24 02:05:42 +00005114 // Find out the smallest element size among result and two sources, and use
5115 // it as element size to build the shuffle_vector.
5116 EVT SmallestEltTy = VT.getVectorElementType();
Tim Northover7324e842014-07-24 15:39:55 +00005117 for (auto &Source : Sources) {
5118 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00005119 if (SrcEltTy.bitsLT(SmallestEltTy)) {
5120 SmallestEltTy = SrcEltTy;
5121 }
5122 }
5123 unsigned ResMultiplier =
Sanjay Patel1ed771f2016-09-14 16:37:15 +00005124 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00005125 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
5126 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
Tim Northover3b0846e2014-05-24 12:50:23 +00005127
Tim Northover7324e842014-07-24 15:39:55 +00005128 // If the source vector is too wide or too narrow, we may nevertheless be able
5129 // to construct a compatible shuffle either by concatenating it with UNDEF or
5130 // extracting a suitable range of elements.
5131 for (auto &Src : Sources) {
5132 EVT SrcVT = Src.ShuffleVec.getValueType();
Kevin Qinf0ec9af2014-06-18 05:54:42 +00005133
Tim Northover7324e842014-07-24 15:39:55 +00005134 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
Tim Northover3b0846e2014-05-24 12:50:23 +00005135 continue;
Tim Northover7324e842014-07-24 15:39:55 +00005136
5137 // This stage of the search produces a source with the same element type as
5138 // the original, but with a total width matching the BUILD_VECTOR output.
5139 EVT EltVT = SrcVT.getVectorElementType();
James Molloyf497d552014-10-17 17:06:31 +00005140 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
5141 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
Tim Northover7324e842014-07-24 15:39:55 +00005142
5143 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
5144 assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00005145 // We can pad out the smaller vector for free, so if it's part of a
5146 // shuffle...
Tim Northover7324e842014-07-24 15:39:55 +00005147 Src.ShuffleVec =
5148 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
5149 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00005150 continue;
5151 }
5152
Tim Northover7324e842014-07-24 15:39:55 +00005153 assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00005154
James Molloyf497d552014-10-17 17:06:31 +00005155 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005156 // Span too large for a VEXT to cope
5157 return SDValue();
5158 }
5159
James Molloyf497d552014-10-17 17:06:31 +00005160 if (Src.MinElt >= NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005161 // The extraction can just take the second half
Tim Northover7324e842014-07-24 15:39:55 +00005162 Src.ShuffleVec =
5163 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005164 DAG.getConstant(NumSrcElts, dl, MVT::i64));
James Molloyf497d552014-10-17 17:06:31 +00005165 Src.WindowBase = -NumSrcElts;
5166 } else if (Src.MaxElt < NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005167 // The extraction can just take the first half
Tim Northover5e84fe32014-12-06 00:33:37 +00005168 Src.ShuffleVec =
5169 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005170 DAG.getConstant(0, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005171 } else {
5172 // An actual VEXT is needed
Tim Northover5e84fe32014-12-06 00:33:37 +00005173 SDValue VEXTSrc1 =
5174 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005175 DAG.getConstant(0, dl, MVT::i64));
Tim Northover7324e842014-07-24 15:39:55 +00005176 SDValue VEXTSrc2 =
5177 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005178 DAG.getConstant(NumSrcElts, dl, MVT::i64));
Tim Northover7324e842014-07-24 15:39:55 +00005179 unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
5180
5181 Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005182 VEXTSrc2,
5183 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover7324e842014-07-24 15:39:55 +00005184 Src.WindowBase = -Src.MinElt;
Tim Northover3b0846e2014-05-24 12:50:23 +00005185 }
5186 }
5187
Tim Northover7324e842014-07-24 15:39:55 +00005188 // Another possible incompatibility occurs from the vector element types. We
5189 // can fix this by bitcasting the source vectors to the same type we intend
5190 // for the shuffle.
5191 for (auto &Src : Sources) {
5192 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
5193 if (SrcEltTy == SmallestEltTy)
5194 continue;
5195 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
5196 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
5197 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
5198 Src.WindowBase *= Src.WindowScale;
5199 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005200
Tim Northover7324e842014-07-24 15:39:55 +00005201 // Final sanity check before we try to actually produce a shuffle.
5202 DEBUG(
5203 for (auto Src : Sources)
5204 assert(Src.ShuffleVec.getValueType() == ShuffleVT);
5205 );
5206
5207 // The stars all align, our next step is to produce the mask for the shuffle.
5208 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
Sanjay Patel1ed771f2016-09-14 16:37:15 +00005209 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00005210 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005211 SDValue Entry = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00005212 if (Entry.isUndef())
Tim Northover7324e842014-07-24 15:39:55 +00005213 continue;
Tim Northover3b0846e2014-05-24 12:50:23 +00005214
David Majnemer0d955d02016-08-11 22:21:41 +00005215 auto Src = find(Sources, Entry.getOperand(0));
Tim Northover7324e842014-07-24 15:39:55 +00005216 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
5217
5218 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
5219 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
5220 // segment.
5221 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
Sanjay Patel1ed771f2016-09-14 16:37:15 +00005222 int BitsDefined =
5223 std::min(OrigEltTy.getSizeInBits(), VT.getScalarSizeInBits());
Tim Northover7324e842014-07-24 15:39:55 +00005224 int LanesDefined = BitsDefined / BitsPerShuffleLane;
5225
5226 // This source is expected to fill ResMultiplier lanes of the final shuffle,
5227 // starting at the appropriate offset.
5228 int *LaneMask = &Mask[i * ResMultiplier];
5229
5230 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
5231 ExtractBase += NumElts * (Src - Sources.begin());
5232 for (int j = 0; j < LanesDefined; ++j)
5233 LaneMask[j] = ExtractBase + j;
Tim Northover3b0846e2014-05-24 12:50:23 +00005234 }
5235
5236 // Final check before we try to produce nonsense...
Tim Northover7324e842014-07-24 15:39:55 +00005237 if (!isShuffleMaskLegal(Mask, ShuffleVT))
5238 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00005239
Tim Northover7324e842014-07-24 15:39:55 +00005240 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
5241 for (unsigned i = 0; i < Sources.size(); ++i)
5242 ShuffleOps[i] = Sources[i].ShuffleVec;
5243
5244 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
Craig Topper2bd8b4b2016-07-01 06:54:47 +00005245 ShuffleOps[1], Mask);
Tim Northover7324e842014-07-24 15:39:55 +00005246 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
Tim Northover3b0846e2014-05-24 12:50:23 +00005247}
5248
5249// check if an EXT instruction can handle the shuffle mask when the
5250// vector sources of the shuffle are the same.
5251static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
5252 unsigned NumElts = VT.getVectorNumElements();
5253
5254 // Assume that the first shuffle index is not UNDEF. Fail if it is.
5255 if (M[0] < 0)
5256 return false;
5257
5258 Imm = M[0];
5259
5260 // If this is a VEXT shuffle, the immediate value is the index of the first
5261 // element. The other shuffle indices must be the successive elements after
5262 // the first one.
5263 unsigned ExpectedElt = Imm;
5264 for (unsigned i = 1; i < NumElts; ++i) {
5265 // Increment the expected index. If it wraps around, just follow it
5266 // back to index zero and keep going.
5267 ++ExpectedElt;
5268 if (ExpectedElt == NumElts)
5269 ExpectedElt = 0;
5270
5271 if (M[i] < 0)
5272 continue; // ignore UNDEF indices
5273 if (ExpectedElt != static_cast<unsigned>(M[i]))
5274 return false;
5275 }
5276
5277 return true;
5278}
5279
5280// check if an EXT instruction can handle the shuffle mask when the
5281// vector sources of the shuffle are different.
5282static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
5283 unsigned &Imm) {
5284 // Look for the first non-undef element.
David Majnemer562e8292016-08-12 00:18:03 +00005285 const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; });
Tim Northover3b0846e2014-05-24 12:50:23 +00005286
5287 // Benefit form APInt to handle overflow when calculating expected element.
5288 unsigned NumElts = VT.getVectorNumElements();
5289 unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
5290 APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
5291 // The following shuffle indices must be the successive elements after the
5292 // first real element.
5293 const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
5294 [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
5295 if (FirstWrongElt != M.end())
5296 return false;
5297
5298 // The index of an EXT is the first element if it is not UNDEF.
5299 // Watch out for the beginning UNDEFs. The EXT index should be the expected
Junmo Park3b8c7152016-01-05 09:36:47 +00005300 // value of the first element. E.g.
Tim Northover3b0846e2014-05-24 12:50:23 +00005301 // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
5302 // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
5303 // ExpectedElt is the last mask index plus 1.
5304 Imm = ExpectedElt.getZExtValue();
5305
5306 // There are two difference cases requiring to reverse input vectors.
5307 // For example, for vector <4 x i32> we have the following cases,
5308 // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
5309 // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
5310 // For both cases, we finally use mask <5, 6, 7, 0>, which requires
5311 // to reverse two input vectors.
5312 if (Imm < NumElts)
5313 ReverseEXT = true;
5314 else
5315 Imm -= NumElts;
5316
5317 return true;
5318}
5319
5320/// isREVMask - Check if a vector shuffle corresponds to a REV
5321/// instruction with the specified blocksize. (The order of the elements
5322/// within each block of the vector is reversed.)
5323static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5324 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
5325 "Only possible block sizes for REV are: 16, 32, 64");
5326
Sanjay Patel1ed771f2016-09-14 16:37:15 +00005327 unsigned EltSz = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00005328 if (EltSz == 64)
5329 return false;
5330
5331 unsigned NumElts = VT.getVectorNumElements();
5332 unsigned BlockElts = M[0] + 1;
5333 // If the first shuffle index is UNDEF, be optimistic.
5334 if (M[0] < 0)
5335 BlockElts = BlockSize / EltSz;
5336
5337 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5338 return false;
5339
5340 for (unsigned i = 0; i < NumElts; ++i) {
5341 if (M[i] < 0)
5342 continue; // ignore UNDEF indices
5343 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
5344 return false;
5345 }
5346
5347 return true;
5348}
5349
5350static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5351 unsigned NumElts = VT.getVectorNumElements();
5352 WhichResult = (M[0] == 0 ? 0 : 1);
5353 unsigned Idx = WhichResult * NumElts / 2;
5354 for (unsigned i = 0; i != NumElts; i += 2) {
5355 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5356 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
5357 return false;
5358 Idx += 1;
5359 }
5360
5361 return true;
5362}
5363
5364static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5365 unsigned NumElts = VT.getVectorNumElements();
5366 WhichResult = (M[0] == 0 ? 0 : 1);
5367 for (unsigned i = 0; i != NumElts; ++i) {
5368 if (M[i] < 0)
5369 continue; // ignore UNDEF indices
5370 if ((unsigned)M[i] != 2 * i + WhichResult)
5371 return false;
5372 }
5373
5374 return true;
5375}
5376
5377static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5378 unsigned NumElts = VT.getVectorNumElements();
5379 WhichResult = (M[0] == 0 ? 0 : 1);
5380 for (unsigned i = 0; i < NumElts; i += 2) {
5381 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5382 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
5383 return false;
5384 }
5385 return true;
5386}
5387
5388/// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
5389/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5390/// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5391static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5392 unsigned NumElts = VT.getVectorNumElements();
5393 WhichResult = (M[0] == 0 ? 0 : 1);
5394 unsigned Idx = WhichResult * NumElts / 2;
5395 for (unsigned i = 0; i != NumElts; i += 2) {
5396 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5397 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
5398 return false;
5399 Idx += 1;
5400 }
5401
5402 return true;
5403}
5404
5405/// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
5406/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5407/// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5408static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5409 unsigned Half = VT.getVectorNumElements() / 2;
5410 WhichResult = (M[0] == 0 ? 0 : 1);
5411 for (unsigned j = 0; j != 2; ++j) {
5412 unsigned Idx = WhichResult;
5413 for (unsigned i = 0; i != Half; ++i) {
5414 int MIdx = M[i + j * Half];
5415 if (MIdx >= 0 && (unsigned)MIdx != Idx)
5416 return false;
5417 Idx += 2;
5418 }
5419 }
5420
5421 return true;
5422}
5423
5424/// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
5425/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5426/// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5427static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5428 unsigned NumElts = VT.getVectorNumElements();
5429 WhichResult = (M[0] == 0 ? 0 : 1);
5430 for (unsigned i = 0; i < NumElts; i += 2) {
5431 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5432 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
5433 return false;
5434 }
5435 return true;
5436}
5437
5438static bool isINSMask(ArrayRef<int> M, int NumInputElements,
5439 bool &DstIsLeft, int &Anomaly) {
5440 if (M.size() != static_cast<size_t>(NumInputElements))
5441 return false;
5442
5443 int NumLHSMatch = 0, NumRHSMatch = 0;
5444 int LastLHSMismatch = -1, LastRHSMismatch = -1;
5445
5446 for (int i = 0; i < NumInputElements; ++i) {
5447 if (M[i] == -1) {
5448 ++NumLHSMatch;
5449 ++NumRHSMatch;
5450 continue;
5451 }
5452
5453 if (M[i] == i)
5454 ++NumLHSMatch;
5455 else
5456 LastLHSMismatch = i;
5457
5458 if (M[i] == i + NumInputElements)
5459 ++NumRHSMatch;
5460 else
5461 LastRHSMismatch = i;
5462 }
5463
5464 if (NumLHSMatch == NumInputElements - 1) {
5465 DstIsLeft = true;
5466 Anomaly = LastLHSMismatch;
5467 return true;
5468 } else if (NumRHSMatch == NumInputElements - 1) {
5469 DstIsLeft = false;
5470 Anomaly = LastRHSMismatch;
5471 return true;
5472 }
5473
5474 return false;
5475}
5476
5477static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
5478 if (VT.getSizeInBits() != 128)
5479 return false;
5480
5481 unsigned NumElts = VT.getVectorNumElements();
5482
5483 for (int I = 0, E = NumElts / 2; I != E; I++) {
5484 if (Mask[I] != I)
5485 return false;
5486 }
5487
5488 int Offset = NumElts / 2;
5489 for (int I = NumElts / 2, E = NumElts; I != E; I++) {
5490 if (Mask[I] != I + SplitLHS * Offset)
5491 return false;
5492 }
5493
5494 return true;
5495}
5496
5497static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
5498 SDLoc DL(Op);
5499 EVT VT = Op.getValueType();
5500 SDValue V0 = Op.getOperand(0);
5501 SDValue V1 = Op.getOperand(1);
5502 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
5503
5504 if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
5505 VT.getVectorElementType() != V1.getValueType().getVectorElementType())
5506 return SDValue();
5507
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00005508 bool SplitV0 = V0.getValueSizeInBits() == 128;
Tim Northover3b0846e2014-05-24 12:50:23 +00005509
5510 if (!isConcatMask(Mask, VT, SplitV0))
5511 return SDValue();
5512
5513 EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
5514 VT.getVectorNumElements() / 2);
5515 if (SplitV0) {
5516 V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005517 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005518 }
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00005519 if (V1.getValueSizeInBits() == 128) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005520 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005521 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005522 }
5523 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
5524}
5525
5526/// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5527/// the specified operations to build the shuffle.
5528static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5529 SDValue RHS, SelectionDAG &DAG,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00005530 const SDLoc &dl) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005531 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5532 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
5533 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
5534
5535 enum {
5536 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5537 OP_VREV,
5538 OP_VDUP0,
5539 OP_VDUP1,
5540 OP_VDUP2,
5541 OP_VDUP3,
5542 OP_VEXT1,
5543 OP_VEXT2,
5544 OP_VEXT3,
5545 OP_VUZPL, // VUZP, left result
5546 OP_VUZPR, // VUZP, right result
5547 OP_VZIPL, // VZIP, left result
5548 OP_VZIPR, // VZIP, right result
5549 OP_VTRNL, // VTRN, left result
5550 OP_VTRNR // VTRN, right result
5551 };
5552
5553 if (OpNum == OP_COPY) {
5554 if (LHSID == (1 * 9 + 2) * 9 + 3)
5555 return LHS;
5556 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
5557 return RHS;
5558 }
5559
5560 SDValue OpLHS, OpRHS;
5561 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5562 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5563 EVT VT = OpLHS.getValueType();
5564
5565 switch (OpNum) {
5566 default:
5567 llvm_unreachable("Unknown shuffle opcode!");
5568 case OP_VREV:
5569 // VREV divides the vector in half and swaps within the half.
5570 if (VT.getVectorElementType() == MVT::i32 ||
5571 VT.getVectorElementType() == MVT::f32)
5572 return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
5573 // vrev <4 x i16> -> REV32
Oliver Stannard89d15422014-08-27 16:16:04 +00005574 if (VT.getVectorElementType() == MVT::i16 ||
5575 VT.getVectorElementType() == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00005576 return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
5577 // vrev <4 x i8> -> REV16
5578 assert(VT.getVectorElementType() == MVT::i8);
5579 return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
5580 case OP_VDUP0:
5581 case OP_VDUP1:
5582 case OP_VDUP2:
5583 case OP_VDUP3: {
5584 EVT EltTy = VT.getVectorElementType();
5585 unsigned Opcode;
5586 if (EltTy == MVT::i8)
5587 Opcode = AArch64ISD::DUPLANE8;
Ahmed Bougacha941420d2015-04-16 23:57:07 +00005588 else if (EltTy == MVT::i16 || EltTy == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00005589 Opcode = AArch64ISD::DUPLANE16;
5590 else if (EltTy == MVT::i32 || EltTy == MVT::f32)
5591 Opcode = AArch64ISD::DUPLANE32;
5592 else if (EltTy == MVT::i64 || EltTy == MVT::f64)
5593 Opcode = AArch64ISD::DUPLANE64;
5594 else
5595 llvm_unreachable("Invalid vector element type?");
5596
5597 if (VT.getSizeInBits() == 64)
5598 OpLHS = WidenVector(OpLHS, DAG);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005599 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00005600 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
5601 }
5602 case OP_VEXT1:
5603 case OP_VEXT2:
5604 case OP_VEXT3: {
5605 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
5606 return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005607 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005608 }
5609 case OP_VUZPL:
5610 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
5611 OpRHS);
5612 case OP_VUZPR:
5613 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
5614 OpRHS);
5615 case OP_VZIPL:
5616 return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
5617 OpRHS);
5618 case OP_VZIPR:
5619 return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
5620 OpRHS);
5621 case OP_VTRNL:
5622 return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
5623 OpRHS);
5624 case OP_VTRNR:
5625 return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
5626 OpRHS);
5627 }
5628}
5629
5630static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
5631 SelectionDAG &DAG) {
5632 // Check to see if we can use the TBL instruction.
5633 SDValue V1 = Op.getOperand(0);
5634 SDValue V2 = Op.getOperand(1);
5635 SDLoc DL(Op);
5636
5637 EVT EltVT = Op.getValueType().getVectorElementType();
5638 unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
5639
5640 SmallVector<SDValue, 8> TBLMask;
5641 for (int Val : ShuffleMask) {
5642 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
5643 unsigned Offset = Byte + Val * BytesPerElt;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005644 TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005645 }
5646 }
5647
5648 MVT IndexVT = MVT::v8i8;
5649 unsigned IndexLen = 8;
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00005650 if (Op.getValueSizeInBits() == 128) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005651 IndexVT = MVT::v16i8;
5652 IndexLen = 16;
5653 }
5654
5655 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
5656 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
5657
5658 SDValue Shuffle;
Sanjay Patel57195842016-03-14 17:28:46 +00005659 if (V2.getNode()->isUndef()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005660 if (IndexLen == 8)
5661 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
5662 Shuffle = DAG.getNode(
5663 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005664 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00005665 DAG.getBuildVector(IndexVT, DL,
5666 makeArrayRef(TBLMask.data(), IndexLen)));
Tim Northover3b0846e2014-05-24 12:50:23 +00005667 } else {
5668 if (IndexLen == 8) {
5669 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
5670 Shuffle = DAG.getNode(
5671 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005672 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00005673 DAG.getBuildVector(IndexVT, DL,
5674 makeArrayRef(TBLMask.data(), IndexLen)));
Tim Northover3b0846e2014-05-24 12:50:23 +00005675 } else {
5676 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
5677 // cannot currently represent the register constraints on the input
5678 // table registers.
5679 // Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00005680 // DAG.getBuildVector(IndexVT, DL, &TBLMask[0],
5681 // IndexLen));
Tim Northover3b0846e2014-05-24 12:50:23 +00005682 Shuffle = DAG.getNode(
5683 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00005684 DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst,
5685 V2Cst, DAG.getBuildVector(IndexVT, DL,
5686 makeArrayRef(TBLMask.data(), IndexLen)));
Tim Northover3b0846e2014-05-24 12:50:23 +00005687 }
5688 }
5689 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
5690}
5691
5692static unsigned getDUPLANEOp(EVT EltType) {
5693 if (EltType == MVT::i8)
5694 return AArch64ISD::DUPLANE8;
Oliver Stannard89d15422014-08-27 16:16:04 +00005695 if (EltType == MVT::i16 || EltType == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00005696 return AArch64ISD::DUPLANE16;
5697 if (EltType == MVT::i32 || EltType == MVT::f32)
5698 return AArch64ISD::DUPLANE32;
5699 if (EltType == MVT::i64 || EltType == MVT::f64)
5700 return AArch64ISD::DUPLANE64;
5701
5702 llvm_unreachable("Invalid vector element type?");
5703}
5704
5705SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5706 SelectionDAG &DAG) const {
5707 SDLoc dl(Op);
5708 EVT VT = Op.getValueType();
5709
5710 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5711
5712 // Convert shuffles that are directly supported on NEON to target-specific
5713 // DAG nodes, instead of keeping them as shuffles and matching them again
5714 // during code selection. This is more efficient and avoids the possibility
5715 // of inconsistencies between legalization and selection.
5716 ArrayRef<int> ShuffleMask = SVN->getMask();
5717
5718 SDValue V1 = Op.getOperand(0);
5719 SDValue V2 = Op.getOperand(1);
5720
Craig Topperbc56e3b2016-06-30 04:38:51 +00005721 if (SVN->isSplat()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005722 int Lane = SVN->getSplatIndex();
5723 // If this is undef splat, generate it via "just" vdup, if possible.
5724 if (Lane == -1)
5725 Lane = 0;
5726
5727 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
5728 return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
5729 V1.getOperand(0));
5730 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
5731 // constant. If so, we can just reference the lane's definition directly.
5732 if (V1.getOpcode() == ISD::BUILD_VECTOR &&
5733 !isa<ConstantSDNode>(V1.getOperand(Lane)))
5734 return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
5735
5736 // Otherwise, duplicate from the lane of the input vector.
5737 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
5738
5739 // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
5740 // to make a vector of the same size as this SHUFFLE. We can ignore the
5741 // extract entirely, and canonicalise the concat using WidenVector.
5742 if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
5743 Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
5744 V1 = V1.getOperand(0);
5745 } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
5746 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
5747 Lane -= Idx * VT.getVectorNumElements() / 2;
5748 V1 = WidenVector(V1.getOperand(Idx), DAG);
5749 } else if (VT.getSizeInBits() == 64)
5750 V1 = WidenVector(V1, DAG);
5751
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005752 return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005753 }
5754
5755 if (isREVMask(ShuffleMask, VT, 64))
5756 return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
5757 if (isREVMask(ShuffleMask, VT, 32))
5758 return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
5759 if (isREVMask(ShuffleMask, VT, 16))
5760 return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
5761
5762 bool ReverseEXT = false;
5763 unsigned Imm;
5764 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
5765 if (ReverseEXT)
5766 std::swap(V1, V2);
5767 Imm *= getExtFactor(V1);
5768 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005769 DAG.getConstant(Imm, dl, MVT::i32));
Sanjay Patel57195842016-03-14 17:28:46 +00005770 } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005771 Imm *= getExtFactor(V1);
5772 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005773 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005774 }
5775
5776 unsigned WhichResult;
5777 if (isZIPMask(ShuffleMask, VT, WhichResult)) {
5778 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5779 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5780 }
5781 if (isUZPMask(ShuffleMask, VT, WhichResult)) {
5782 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5783 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5784 }
5785 if (isTRNMask(ShuffleMask, VT, WhichResult)) {
5786 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5787 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5788 }
5789
5790 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5791 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5792 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5793 }
5794 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5795 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5796 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5797 }
5798 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5799 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5800 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5801 }
5802
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00005803 if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00005804 return Concat;
5805
5806 bool DstIsLeft;
5807 int Anomaly;
5808 int NumInputElements = V1.getValueType().getVectorNumElements();
5809 if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
5810 SDValue DstVec = DstIsLeft ? V1 : V2;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005811 SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00005812
5813 SDValue SrcVec = V1;
5814 int SrcLane = ShuffleMask[Anomaly];
5815 if (SrcLane >= NumInputElements) {
5816 SrcVec = V2;
5817 SrcLane -= VT.getVectorNumElements();
5818 }
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005819 SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00005820
5821 EVT ScalarVT = VT.getVectorElementType();
Oliver Stannard89d15422014-08-27 16:16:04 +00005822
5823 if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00005824 ScalarVT = MVT::i32;
5825
5826 return DAG.getNode(
5827 ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5828 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
5829 DstLaneV);
5830 }
5831
5832 // If the shuffle is not directly supported and it has 4 elements, use
5833 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5834 unsigned NumElts = VT.getVectorNumElements();
5835 if (NumElts == 4) {
5836 unsigned PFIndexes[4];
5837 for (unsigned i = 0; i != 4; ++i) {
5838 if (ShuffleMask[i] < 0)
5839 PFIndexes[i] = 8;
5840 else
5841 PFIndexes[i] = ShuffleMask[i];
5842 }
5843
5844 // Compute the index in the perfect shuffle table.
5845 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
5846 PFIndexes[2] * 9 + PFIndexes[3];
5847 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5848 unsigned Cost = (PFEntry >> 30);
5849
5850 if (Cost <= 4)
5851 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5852 }
5853
5854 return GenerateTBL(Op, ShuffleMask, DAG);
5855}
5856
5857static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
5858 APInt &UndefBits) {
5859 EVT VT = BVN->getValueType(0);
5860 APInt SplatBits, SplatUndef;
5861 unsigned SplatBitSize;
5862 bool HasAnyUndefs;
5863 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5864 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
5865
5866 for (unsigned i = 0; i < NumSplats; ++i) {
5867 CnstBits <<= SplatBitSize;
5868 UndefBits <<= SplatBitSize;
5869 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
5870 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
5871 }
5872
5873 return true;
5874 }
5875
5876 return false;
5877}
5878
5879SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op,
5880 SelectionDAG &DAG) const {
5881 BuildVectorSDNode *BVN =
5882 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5883 SDValue LHS = Op.getOperand(0);
5884 SDLoc dl(Op);
5885 EVT VT = Op.getValueType();
5886
5887 if (!BVN)
5888 return Op;
5889
5890 APInt CnstBits(VT.getSizeInBits(), 0);
5891 APInt UndefBits(VT.getSizeInBits(), 0);
5892 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5893 // We only have BIC vector immediate instruction, which is and-not.
5894 CnstBits = ~CnstBits;
5895
5896 // We make use of a little bit of goto ickiness in order to avoid having to
5897 // duplicate the immediate matching logic for the undef toggled case.
5898 bool SecondTry = false;
5899 AttemptModImm:
5900
5901 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5902 CnstBits = CnstBits.zextOrTrunc(64);
5903 uint64_t CnstVal = CnstBits.getZExtValue();
5904
5905 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5906 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5907 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5908 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005909 DAG.getConstant(CnstVal, dl, MVT::i32),
5910 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005911 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005912 }
5913
5914 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5915 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5916 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5917 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005918 DAG.getConstant(CnstVal, dl, MVT::i32),
5919 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005920 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005921 }
5922
5923 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5924 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5925 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5926 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005927 DAG.getConstant(CnstVal, dl, MVT::i32),
5928 DAG.getConstant(16, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005929 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005930 }
5931
5932 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5933 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5934 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5935 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005936 DAG.getConstant(CnstVal, dl, MVT::i32),
5937 DAG.getConstant(24, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005938 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005939 }
5940
5941 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5942 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5943 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5944 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005945 DAG.getConstant(CnstVal, dl, MVT::i32),
5946 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005947 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005948 }
5949
5950 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5951 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5952 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5953 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005954 DAG.getConstant(CnstVal, dl, MVT::i32),
5955 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005956 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005957 }
5958 }
5959
5960 if (SecondTry)
5961 goto FailedModImm;
5962 SecondTry = true;
5963 CnstBits = ~UndefBits;
5964 goto AttemptModImm;
5965 }
5966
5967// We can always fall back to a non-immediate AND.
5968FailedModImm:
5969 return Op;
5970}
5971
5972// Specialized code to quickly find if PotentialBVec is a BuildVector that
5973// consists of only the same constant int value, returned in reference arg
5974// ConstVal
5975static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
5976 uint64_t &ConstVal) {
5977 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
5978 if (!Bvec)
5979 return false;
5980 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
5981 if (!FirstElt)
5982 return false;
5983 EVT VT = Bvec->getValueType(0);
5984 unsigned NumElts = VT.getVectorNumElements();
5985 for (unsigned i = 1; i < NumElts; ++i)
5986 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
5987 return false;
5988 ConstVal = FirstElt->getZExtValue();
5989 return true;
5990}
5991
5992static unsigned getIntrinsicID(const SDNode *N) {
5993 unsigned Opcode = N->getOpcode();
5994 switch (Opcode) {
5995 default:
5996 return Intrinsic::not_intrinsic;
5997 case ISD::INTRINSIC_WO_CHAIN: {
5998 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
5999 if (IID < Intrinsic::num_intrinsics)
6000 return IID;
6001 return Intrinsic::not_intrinsic;
6002 }
6003 }
6004}
6005
6006// Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
6007// to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
6008// BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
6009// Also, logical shift right -> sri, with the same structure.
6010static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
6011 EVT VT = N->getValueType(0);
6012
6013 if (!VT.isVector())
6014 return SDValue();
6015
6016 SDLoc DL(N);
6017
6018 // Is the first op an AND?
6019 const SDValue And = N->getOperand(0);
6020 if (And.getOpcode() != ISD::AND)
6021 return SDValue();
6022
6023 // Is the second op an shl or lshr?
6024 SDValue Shift = N->getOperand(1);
6025 // This will have been turned into: AArch64ISD::VSHL vector, #shift
6026 // or AArch64ISD::VLSHR vector, #shift
6027 unsigned ShiftOpc = Shift.getOpcode();
6028 if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
6029 return SDValue();
6030 bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
6031
6032 // Is the shift amount constant?
6033 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
6034 if (!C2node)
6035 return SDValue();
6036
6037 // Is the and mask vector all constant?
6038 uint64_t C1;
6039 if (!isAllConstantBuildVector(And.getOperand(1), C1))
6040 return SDValue();
6041
6042 // Is C1 == ~C2, taking into account how much one can shift elements of a
6043 // particular size?
6044 uint64_t C2 = C2node->getZExtValue();
Sanjay Patel1ed771f2016-09-14 16:37:15 +00006045 unsigned ElemSizeInBits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00006046 if (C2 > ElemSizeInBits)
6047 return SDValue();
6048 unsigned ElemMask = (1 << ElemSizeInBits) - 1;
6049 if ((C1 & ElemMask) != (~C2 & ElemMask))
6050 return SDValue();
6051
6052 SDValue X = And.getOperand(0);
6053 SDValue Y = Shift.getOperand(0);
6054
6055 unsigned Intrin =
6056 IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
6057 SDValue ResultSLI =
6058 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006059 DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
6060 Shift.getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00006061
6062 DEBUG(dbgs() << "aarch64-lower: transformed: \n");
6063 DEBUG(N->dump(&DAG));
6064 DEBUG(dbgs() << "into: \n");
6065 DEBUG(ResultSLI->dump(&DAG));
6066
6067 ++NumShiftInserts;
6068 return ResultSLI;
6069}
6070
6071SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
6072 SelectionDAG &DAG) const {
6073 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
6074 if (EnableAArch64SlrGeneration) {
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00006075 if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00006076 return Res;
6077 }
6078
6079 BuildVectorSDNode *BVN =
6080 dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
6081 SDValue LHS = Op.getOperand(1);
6082 SDLoc dl(Op);
6083 EVT VT = Op.getValueType();
6084
6085 // OR commutes, so try swapping the operands.
6086 if (!BVN) {
6087 LHS = Op.getOperand(0);
6088 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
6089 }
6090 if (!BVN)
6091 return Op;
6092
6093 APInt CnstBits(VT.getSizeInBits(), 0);
6094 APInt UndefBits(VT.getSizeInBits(), 0);
6095 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
6096 // We make use of a little bit of goto ickiness in order to avoid having to
6097 // duplicate the immediate matching logic for the undef toggled case.
6098 bool SecondTry = false;
6099 AttemptModImm:
6100
6101 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
6102 CnstBits = CnstBits.zextOrTrunc(64);
6103 uint64_t CnstVal = CnstBits.getZExtValue();
6104
6105 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6106 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6107 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6108 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006109 DAG.getConstant(CnstVal, dl, MVT::i32),
6110 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00006111 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006112 }
6113
6114 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6115 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6116 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6117 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006118 DAG.getConstant(CnstVal, dl, MVT::i32),
6119 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00006120 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006121 }
6122
6123 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6124 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6125 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6126 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006127 DAG.getConstant(CnstVal, dl, MVT::i32),
6128 DAG.getConstant(16, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00006129 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006130 }
6131
6132 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6133 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6134 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6135 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006136 DAG.getConstant(CnstVal, dl, MVT::i32),
6137 DAG.getConstant(24, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00006138 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006139 }
6140
6141 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6142 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6143 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6144 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006145 DAG.getConstant(CnstVal, dl, MVT::i32),
6146 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00006147 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006148 }
6149
6150 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6151 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6152 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6153 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006154 DAG.getConstant(CnstVal, dl, MVT::i32),
6155 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00006156 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006157 }
6158 }
6159
6160 if (SecondTry)
6161 goto FailedModImm;
6162 SecondTry = true;
6163 CnstBits = UndefBits;
6164 goto AttemptModImm;
6165 }
6166
6167// We can always fall back to a non-immediate OR.
6168FailedModImm:
6169 return Op;
6170}
6171
Kevin Qin4473c192014-07-07 02:45:40 +00006172// Normalize the operands of BUILD_VECTOR. The value of constant operands will
6173// be truncated to fit element width.
6174static SDValue NormalizeBuildVector(SDValue Op,
6175 SelectionDAG &DAG) {
6176 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
Tim Northover3b0846e2014-05-24 12:50:23 +00006177 SDLoc dl(Op);
6178 EVT VT = Op.getValueType();
Kevin Qin4473c192014-07-07 02:45:40 +00006179 EVT EltTy= VT.getVectorElementType();
6180
6181 if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
6182 return Op;
6183
6184 SmallVector<SDValue, 16> Ops;
Pete Cooper7be8f8f2015-08-03 19:04:32 +00006185 for (SDValue Lane : Op->ops()) {
6186 if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
Kevin Qin4473c192014-07-07 02:45:40 +00006187 APInt LowBits(EltTy.getSizeInBits(),
Pete Cooper7be8f8f2015-08-03 19:04:32 +00006188 CstLane->getZExtValue());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006189 Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
Kevin Qin4473c192014-07-07 02:45:40 +00006190 }
6191 Ops.push_back(Lane);
6192 }
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006193 return DAG.getBuildVector(VT, dl, Ops);
Kevin Qin4473c192014-07-07 02:45:40 +00006194}
6195
6196SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
6197 SelectionDAG &DAG) const {
6198 SDLoc dl(Op);
6199 EVT VT = Op.getValueType();
6200 Op = NormalizeBuildVector(Op, DAG);
6201 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
Tim Northover3b0846e2014-05-24 12:50:23 +00006202
6203 APInt CnstBits(VT.getSizeInBits(), 0);
6204 APInt UndefBits(VT.getSizeInBits(), 0);
6205 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
6206 // We make use of a little bit of goto ickiness in order to avoid having to
6207 // duplicate the immediate matching logic for the undef toggled case.
6208 bool SecondTry = false;
6209 AttemptModImm:
6210
6211 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
6212 CnstBits = CnstBits.zextOrTrunc(64);
6213 uint64_t CnstVal = CnstBits.getZExtValue();
6214
6215 // Certain magic vector constants (used to express things like NOT
6216 // and NEG) are passed through unmodified. This allows codegen patterns
6217 // for these operations to match. Special-purpose patterns will lower
6218 // these immediates to MOVIs if it proves necessary.
6219 if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL))
6220 return Op;
6221
6222 // The many faces of MOVI...
6223 if (AArch64_AM::isAdvSIMDModImmType10(CnstVal)) {
6224 CnstVal = AArch64_AM::encodeAdvSIMDModImmType10(CnstVal);
6225 if (VT.getSizeInBits() == 128) {
6226 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::v2i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006227 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006228 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006229 }
6230
6231 // Support the V64 version via subregister insertion.
6232 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::f64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006233 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006234 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006235 }
6236
6237 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6238 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6239 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6240 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006241 DAG.getConstant(CnstVal, dl, MVT::i32),
6242 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006243 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006244 }
6245
6246 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6247 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6248 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6249 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006250 DAG.getConstant(CnstVal, dl, MVT::i32),
6251 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006252 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006253 }
6254
6255 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6256 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6257 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6258 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006259 DAG.getConstant(CnstVal, dl, MVT::i32),
6260 DAG.getConstant(16, 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::isAdvSIMDModImmType4(CnstVal)) {
6265 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6266 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6267 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006268 DAG.getConstant(CnstVal, dl, MVT::i32),
6269 DAG.getConstant(24, 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::isAdvSIMDModImmType5(CnstVal)) {
6274 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6275 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6276 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006277 DAG.getConstant(CnstVal, dl, MVT::i32),
6278 DAG.getConstant(0, 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::isAdvSIMDModImmType6(CnstVal)) {
6283 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6284 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6285 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006286 DAG.getConstant(CnstVal, dl, MVT::i32),
6287 DAG.getConstant(8, 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::isAdvSIMDModImmType7(CnstVal)) {
6292 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6293 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6294 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006295 DAG.getConstant(CnstVal, dl, MVT::i32),
6296 DAG.getConstant(264, 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::isAdvSIMDModImmType8(CnstVal)) {
6301 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6302 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6303 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006304 DAG.getConstant(CnstVal, dl, MVT::i32),
6305 DAG.getConstant(272, 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::isAdvSIMDModImmType9(CnstVal)) {
6310 CnstVal = AArch64_AM::encodeAdvSIMDModImmType9(CnstVal);
6311 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
6312 SDValue Mov = DAG.getNode(AArch64ISD::MOVI, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006313 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006314 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006315 }
6316
6317 // The few faces of FMOV...
6318 if (AArch64_AM::isAdvSIMDModImmType11(CnstVal)) {
6319 CnstVal = AArch64_AM::encodeAdvSIMDModImmType11(CnstVal);
6320 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32;
6321 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006322 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006323 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006324 }
6325
6326 if (AArch64_AM::isAdvSIMDModImmType12(CnstVal) &&
6327 VT.getSizeInBits() == 128) {
6328 CnstVal = AArch64_AM::encodeAdvSIMDModImmType12(CnstVal);
6329 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MVT::v2f64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006330 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006331 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006332 }
6333
6334 // The many faces of MVNI...
6335 CnstVal = ~CnstVal;
6336 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6337 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6338 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6339 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006340 DAG.getConstant(CnstVal, dl, MVT::i32),
6341 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006342 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006343 }
6344
6345 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6346 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6347 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6348 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006349 DAG.getConstant(CnstVal, dl, MVT::i32),
6350 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006351 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006352 }
6353
6354 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6355 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6356 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6357 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006358 DAG.getConstant(CnstVal, dl, MVT::i32),
6359 DAG.getConstant(16, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006360 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006361 }
6362
6363 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6364 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6365 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6366 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006367 DAG.getConstant(CnstVal, dl, MVT::i32),
6368 DAG.getConstant(24, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006369 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006370 }
6371
6372 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6373 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6374 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6375 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006376 DAG.getConstant(CnstVal, dl, MVT::i32),
6377 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006378 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006379 }
6380
6381 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6382 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6383 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6384 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006385 DAG.getConstant(CnstVal, dl, MVT::i32),
6386 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006387 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006388 }
6389
6390 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6391 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6392 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6393 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006394 DAG.getConstant(CnstVal, dl, MVT::i32),
6395 DAG.getConstant(264, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006396 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006397 }
6398
6399 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6400 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6401 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6402 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006403 DAG.getConstant(CnstVal, dl, MVT::i32),
6404 DAG.getConstant(272, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006405 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006406 }
6407 }
6408
6409 if (SecondTry)
6410 goto FailedModImm;
6411 SecondTry = true;
6412 CnstBits = UndefBits;
6413 goto AttemptModImm;
6414 }
6415FailedModImm:
6416
6417 // Scan through the operands to find some interesting properties we can
6418 // exploit:
6419 // 1) If only one value is used, we can use a DUP, or
6420 // 2) if only the low element is not undef, we can just insert that, or
6421 // 3) if only one constant value is used (w/ some non-constant lanes),
6422 // we can splat the constant value into the whole vector then fill
6423 // in the non-constant lanes.
6424 // 4) FIXME: If different constant values are used, but we can intelligently
6425 // select the values we'll be overwriting for the non-constant
6426 // lanes such that we can directly materialize the vector
6427 // some other way (MOVI, e.g.), we can be sneaky.
6428 unsigned NumElts = VT.getVectorNumElements();
6429 bool isOnlyLowElement = true;
6430 bool usesOnlyOneValue = true;
6431 bool usesOnlyOneConstantValue = true;
6432 bool isConstant = true;
6433 unsigned NumConstantLanes = 0;
6434 SDValue Value;
6435 SDValue ConstantValue;
6436 for (unsigned i = 0; i < NumElts; ++i) {
6437 SDValue V = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00006438 if (V.isUndef())
Tim Northover3b0846e2014-05-24 12:50:23 +00006439 continue;
6440 if (i > 0)
6441 isOnlyLowElement = false;
6442 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6443 isConstant = false;
6444
6445 if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
6446 ++NumConstantLanes;
6447 if (!ConstantValue.getNode())
6448 ConstantValue = V;
6449 else if (ConstantValue != V)
6450 usesOnlyOneConstantValue = false;
6451 }
6452
6453 if (!Value.getNode())
6454 Value = V;
6455 else if (V != Value)
6456 usesOnlyOneValue = false;
6457 }
6458
6459 if (!Value.getNode())
6460 return DAG.getUNDEF(VT);
6461
6462 if (isOnlyLowElement)
6463 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
6464
6465 // Use DUP for non-constant splats. For f32 constant splats, reduce to
6466 // i32 and try again.
6467 if (usesOnlyOneValue) {
6468 if (!isConstant) {
6469 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6470 Value.getValueType() != VT)
6471 return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
6472
6473 // This is actually a DUPLANExx operation, which keeps everything vectory.
6474
6475 // DUPLANE works on 128-bit vectors, widen it if necessary.
6476 SDValue Lane = Value.getOperand(1);
6477 Value = Value.getOperand(0);
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00006478 if (Value.getValueSizeInBits() == 64)
Tim Northover3b0846e2014-05-24 12:50:23 +00006479 Value = WidenVector(Value, DAG);
6480
6481 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
6482 return DAG.getNode(Opcode, dl, VT, Value, Lane);
6483 }
6484
6485 if (VT.getVectorElementType().isFloatingPoint()) {
6486 SmallVector<SDValue, 8> Ops;
Pirama Arumuga Nainar12aeefc2015-03-17 23:10:29 +00006487 EVT EltTy = VT.getVectorElementType();
6488 assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
6489 "Unsupported floating-point vector type");
6490 MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00006491 for (unsigned i = 0; i < NumElts; ++i)
6492 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
6493 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006494 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
Tim Northover3b0846e2014-05-24 12:50:23 +00006495 Val = LowerBUILD_VECTOR(Val, DAG);
6496 if (Val.getNode())
6497 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6498 }
6499 }
6500
6501 // If there was only one constant value used and for more than one lane,
6502 // start by splatting that value, then replace the non-constant lanes. This
6503 // is better than the default, which will perform a separate initialization
6504 // for each lane.
6505 if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
6506 SDValue Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
6507 // Now insert the non-constant lanes.
6508 for (unsigned i = 0; i < NumElts; ++i) {
6509 SDValue V = Op.getOperand(i);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006510 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006511 if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) {
6512 // Note that type legalization likely mucked about with the VT of the
6513 // source operand, so we may have to convert it here before inserting.
6514 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
6515 }
6516 }
6517 return Val;
6518 }
6519
6520 // If all elements are constants and the case above didn't get hit, fall back
6521 // to the default expansion, which will generate a load from the constant
6522 // pool.
6523 if (isConstant)
6524 return SDValue();
6525
6526 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6527 if (NumElts >= 4) {
Ahmed Bougacha239d6352015-08-04 00:48:02 +00006528 if (SDValue shuffle = ReconstructShuffle(Op, DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00006529 return shuffle;
6530 }
6531
6532 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6533 // know the default expansion would otherwise fall back on something even
6534 // worse. For a vector with one or two non-undef values, that's
6535 // scalar_to_vector for the elements followed by a shuffle (provided the
6536 // shuffle is valid for the target) and materialization element by element
6537 // on the stack followed by a load for everything else.
6538 if (!isConstant && !usesOnlyOneValue) {
6539 SDValue Vec = DAG.getUNDEF(VT);
6540 SDValue Op0 = Op.getOperand(0);
Sanjay Patel1ed771f2016-09-14 16:37:15 +00006541 unsigned ElemSize = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00006542 unsigned i = 0;
6543 // For 32 and 64 bit types, use INSERT_SUBREG for lane zero to
6544 // a) Avoid a RMW dependency on the full vector register, and
6545 // b) Allow the register coalescer to fold away the copy if the
6546 // value is already in an S or D register.
Matthias Braun0acbd082015-08-31 18:25:15 +00006547 // Do not do this for UNDEF/LOAD nodes because we have better patterns
6548 // for those avoiding the SCALAR_TO_VECTOR/BUILD_VECTOR.
Sanjay Patel75068522016-03-14 18:09:43 +00006549 if (!Op0.isUndef() && Op0.getOpcode() != ISD::LOAD &&
Matthias Braun0acbd082015-08-31 18:25:15 +00006550 (ElemSize == 32 || ElemSize == 64)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006551 unsigned SubIdx = ElemSize == 32 ? AArch64::ssub : AArch64::dsub;
6552 MachineSDNode *N =
6553 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl, VT, Vec, Op0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006554 DAG.getTargetConstant(SubIdx, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006555 Vec = SDValue(N, 0);
6556 ++i;
6557 }
6558 for (; i < NumElts; ++i) {
6559 SDValue V = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00006560 if (V.isUndef())
Tim Northover3b0846e2014-05-24 12:50:23 +00006561 continue;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006562 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006563 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6564 }
6565 return Vec;
6566 }
6567
6568 // Just use the default expansion. We failed to find a better alternative.
6569 return SDValue();
6570}
6571
6572SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
6573 SelectionDAG &DAG) const {
6574 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
6575
Tim Northovere4b8e132014-07-15 10:00:26 +00006576 // Check for non-constant or out of range lane.
6577 EVT VT = Op.getOperand(0).getValueType();
6578 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
6579 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
Tim Northover3b0846e2014-05-24 12:50:23 +00006580 return SDValue();
6581
Tim Northover3b0846e2014-05-24 12:50:23 +00006582
6583 // Insertion/extraction are legal for V128 types.
6584 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
Oliver Stannard89d15422014-08-27 16:16:04 +00006585 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6586 VT == MVT::v8f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006587 return Op;
6588
6589 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
Oliver Stannard89d15422014-08-27 16:16:04 +00006590 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006591 return SDValue();
6592
6593 // For V64 types, we perform insertion by expanding the value
6594 // to a V128 type and perform the insertion on that.
6595 SDLoc DL(Op);
6596 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6597 EVT WideTy = WideVec.getValueType();
6598
6599 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
6600 Op.getOperand(1), Op.getOperand(2));
6601 // Re-narrow the resultant vector.
6602 return NarrowVector(Node, DAG);
6603}
6604
6605SDValue
6606AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6607 SelectionDAG &DAG) const {
6608 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
6609
Tim Northovere4b8e132014-07-15 10:00:26 +00006610 // Check for non-constant or out of range lane.
6611 EVT VT = Op.getOperand(0).getValueType();
6612 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6613 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
Tim Northover3b0846e2014-05-24 12:50:23 +00006614 return SDValue();
6615
Tim Northover3b0846e2014-05-24 12:50:23 +00006616
6617 // Insertion/extraction are legal for V128 types.
6618 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
Oliver Stannard89d15422014-08-27 16:16:04 +00006619 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6620 VT == MVT::v8f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006621 return Op;
6622
6623 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
Oliver Stannard89d15422014-08-27 16:16:04 +00006624 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006625 return SDValue();
6626
6627 // For V64 types, we perform extraction by expanding the value
6628 // to a V128 type and perform the extraction on that.
6629 SDLoc DL(Op);
6630 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6631 EVT WideTy = WideVec.getValueType();
6632
6633 EVT ExtrTy = WideTy.getVectorElementType();
6634 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
6635 ExtrTy = MVT::i32;
6636
6637 // For extractions, we just return the result directly.
6638 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
6639 Op.getOperand(1));
6640}
6641
6642SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
6643 SelectionDAG &DAG) const {
6644 EVT VT = Op.getOperand(0).getValueType();
6645 SDLoc dl(Op);
6646 // Just in case...
6647 if (!VT.isVector())
6648 return SDValue();
6649
6650 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6651 if (!Cst)
6652 return SDValue();
6653 unsigned Val = Cst->getZExtValue();
6654
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00006655 unsigned Size = Op.getValueSizeInBits();
Charlie Turner7b7b06f2015-11-09 12:45:11 +00006656
6657 // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
6658 if (Val == 0)
6659 return Op;
6660
Tim Northover3b0846e2014-05-24 12:50:23 +00006661 // If this is extracting the upper 64-bits of a 128-bit vector, we match
6662 // that directly.
Sanjay Patel1ed771f2016-09-14 16:37:15 +00006663 if (Size == 64 && Val * VT.getScalarSizeInBits() == 64)
Tim Northover3b0846e2014-05-24 12:50:23 +00006664 return Op;
6665
6666 return SDValue();
6667}
6668
6669bool AArch64TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
6670 EVT VT) const {
6671 if (VT.getVectorNumElements() == 4 &&
6672 (VT.is128BitVector() || VT.is64BitVector())) {
6673 unsigned PFIndexes[4];
6674 for (unsigned i = 0; i != 4; ++i) {
6675 if (M[i] < 0)
6676 PFIndexes[i] = 8;
6677 else
6678 PFIndexes[i] = M[i];
6679 }
6680
6681 // Compute the index in the perfect shuffle table.
6682 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6683 PFIndexes[2] * 9 + PFIndexes[3];
6684 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6685 unsigned Cost = (PFEntry >> 30);
6686
6687 if (Cost <= 4)
6688 return true;
6689 }
6690
6691 bool DummyBool;
6692 int DummyInt;
6693 unsigned DummyUnsigned;
6694
6695 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
6696 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
6697 isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
6698 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
6699 isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
6700 isZIPMask(M, VT, DummyUnsigned) ||
6701 isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
6702 isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
6703 isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
6704 isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
6705 isConcatMask(M, VT, VT.getSizeInBits() == 128));
6706}
6707
6708/// getVShiftImm - Check if this is a valid build_vector for the immediate
6709/// operand of a vector shift operation, where all the elements of the
6710/// build_vector must have the same constant integer value.
6711static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
6712 // Ignore bit_converts.
6713 while (Op.getOpcode() == ISD::BITCAST)
6714 Op = Op.getOperand(0);
6715 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6716 APInt SplatBits, SplatUndef;
6717 unsigned SplatBitSize;
6718 bool HasAnyUndefs;
6719 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
6720 HasAnyUndefs, ElementBits) ||
6721 SplatBitSize > ElementBits)
6722 return false;
6723 Cnt = SplatBits.getSExtValue();
6724 return true;
6725}
6726
6727/// isVShiftLImm - Check if this is a valid build_vector for the immediate
6728/// operand of a vector shift left operation. That value must be in the range:
6729/// 0 <= Value < ElementBits for a left shift; or
6730/// 0 <= Value <= ElementBits for a long left shift.
6731static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
6732 assert(VT.isVector() && "vector shift count is not a vector type");
Sanjay Patel1ed771f2016-09-14 16:37:15 +00006733 int64_t ElementBits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00006734 if (!getVShiftImm(Op, ElementBits, Cnt))
6735 return false;
6736 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
6737}
6738
6739/// isVShiftRImm - Check if this is a valid build_vector for the immediate
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00006740/// operand of a vector shift right operation. The value must be in the range:
6741/// 1 <= Value <= ElementBits for a right shift; or
6742static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006743 assert(VT.isVector() && "vector shift count is not a vector type");
Sanjay Patel1ed771f2016-09-14 16:37:15 +00006744 int64_t ElementBits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00006745 if (!getVShiftImm(Op, ElementBits, Cnt))
6746 return false;
Tim Northover3b0846e2014-05-24 12:50:23 +00006747 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
6748}
6749
6750SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
6751 SelectionDAG &DAG) const {
6752 EVT VT = Op.getValueType();
6753 SDLoc DL(Op);
6754 int64_t Cnt;
6755
6756 if (!Op.getOperand(1).getValueType().isVector())
6757 return Op;
Sanjay Patel1ed771f2016-09-14 16:37:15 +00006758 unsigned EltSize = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00006759
6760 switch (Op.getOpcode()) {
6761 default:
6762 llvm_unreachable("unexpected shift opcode");
6763
6764 case ISD::SHL:
6765 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006766 return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
6767 DAG.getConstant(Cnt, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006768 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006769 DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
6770 MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00006771 Op.getOperand(0), Op.getOperand(1));
6772 case ISD::SRA:
6773 case ISD::SRL:
6774 // Right shift immediate
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00006775 if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006776 unsigned Opc =
6777 (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006778 return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
6779 DAG.getConstant(Cnt, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006780 }
6781
6782 // Right shift register. Note, there is not a shift right register
6783 // instruction, but the shift left register instruction takes a signed
6784 // value, where negative numbers specify a right shift.
6785 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
6786 : Intrinsic::aarch64_neon_ushl;
6787 // negate the shift amount
6788 SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
6789 SDValue NegShiftLeft =
6790 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006791 DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
6792 NegShift);
Tim Northover3b0846e2014-05-24 12:50:23 +00006793 return NegShiftLeft;
6794 }
6795
6796 return SDValue();
6797}
6798
6799static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
6800 AArch64CC::CondCode CC, bool NoNans, EVT VT,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00006801 const SDLoc &dl, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006802 EVT SrcVT = LHS.getValueType();
Tim Northover45aa89c2015-02-08 00:50:47 +00006803 assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
6804 "function only supposed to emit natural comparisons");
Tim Northover3b0846e2014-05-24 12:50:23 +00006805
6806 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
6807 APInt CnstBits(VT.getSizeInBits(), 0);
6808 APInt UndefBits(VT.getSizeInBits(), 0);
6809 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
6810 bool IsZero = IsCnst && (CnstBits == 0);
6811
6812 if (SrcVT.getVectorElementType().isFloatingPoint()) {
6813 switch (CC) {
6814 default:
6815 return SDValue();
6816 case AArch64CC::NE: {
6817 SDValue Fcmeq;
6818 if (IsZero)
6819 Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6820 else
6821 Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6822 return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
6823 }
6824 case AArch64CC::EQ:
6825 if (IsZero)
6826 return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6827 return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6828 case AArch64CC::GE:
6829 if (IsZero)
6830 return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
6831 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
6832 case AArch64CC::GT:
6833 if (IsZero)
6834 return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
6835 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
6836 case AArch64CC::LS:
6837 if (IsZero)
6838 return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
6839 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
6840 case AArch64CC::LT:
6841 if (!NoNans)
6842 return SDValue();
Justin Bognerb03fd122016-08-17 05:10:15 +00006843 // If we ignore NaNs then we can use to the MI implementation.
6844 LLVM_FALLTHROUGH;
Tim Northover3b0846e2014-05-24 12:50:23 +00006845 case AArch64CC::MI:
6846 if (IsZero)
6847 return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
6848 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
6849 }
6850 }
6851
6852 switch (CC) {
6853 default:
6854 return SDValue();
6855 case AArch64CC::NE: {
6856 SDValue Cmeq;
6857 if (IsZero)
6858 Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6859 else
6860 Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6861 return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
6862 }
6863 case AArch64CC::EQ:
6864 if (IsZero)
6865 return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6866 return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6867 case AArch64CC::GE:
6868 if (IsZero)
6869 return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
6870 return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
6871 case AArch64CC::GT:
6872 if (IsZero)
6873 return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
6874 return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
6875 case AArch64CC::LE:
6876 if (IsZero)
6877 return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
6878 return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
6879 case AArch64CC::LS:
6880 return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
6881 case AArch64CC::LO:
6882 return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
6883 case AArch64CC::LT:
6884 if (IsZero)
6885 return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
6886 return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
6887 case AArch64CC::HI:
6888 return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
6889 case AArch64CC::HS:
6890 return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
6891 }
6892}
6893
6894SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
6895 SelectionDAG &DAG) const {
6896 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6897 SDValue LHS = Op.getOperand(0);
6898 SDValue RHS = Op.getOperand(1);
Tim Northover45aa89c2015-02-08 00:50:47 +00006899 EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
Tim Northover3b0846e2014-05-24 12:50:23 +00006900 SDLoc dl(Op);
6901
6902 if (LHS.getValueType().getVectorElementType().isInteger()) {
6903 assert(LHS.getValueType() == RHS.getValueType());
6904 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
Tim Northover45aa89c2015-02-08 00:50:47 +00006905 SDValue Cmp =
6906 EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
6907 return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00006908 }
6909
Pirama Arumuga Nainar71e9a2a2016-01-22 01:16:57 +00006910 if (LHS.getValueType().getVectorElementType() == MVT::f16)
6911 return SDValue();
6912
Tim Northover3b0846e2014-05-24 12:50:23 +00006913 assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
6914 LHS.getValueType().getVectorElementType() == MVT::f64);
6915
6916 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
6917 // clean. Some of them require two branches to implement.
6918 AArch64CC::CondCode CC1, CC2;
6919 bool ShouldInvert;
6920 changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
6921
6922 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
6923 SDValue Cmp =
Tim Northover45aa89c2015-02-08 00:50:47 +00006924 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00006925 if (!Cmp.getNode())
6926 return SDValue();
6927
6928 if (CC2 != AArch64CC::AL) {
6929 SDValue Cmp2 =
Tim Northover45aa89c2015-02-08 00:50:47 +00006930 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00006931 if (!Cmp2.getNode())
6932 return SDValue();
6933
Tim Northover45aa89c2015-02-08 00:50:47 +00006934 Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
Tim Northover3b0846e2014-05-24 12:50:23 +00006935 }
6936
Tim Northover45aa89c2015-02-08 00:50:47 +00006937 Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
6938
Tim Northover3b0846e2014-05-24 12:50:23 +00006939 if (ShouldInvert)
6940 return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
6941
6942 return Cmp;
6943}
6944
6945/// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
6946/// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
6947/// specified in the intrinsic calls.
6948bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
6949 const CallInst &I,
6950 unsigned Intrinsic) const {
Mehdi Aminia749f2a2015-07-09 02:09:52 +00006951 auto &DL = I.getModule()->getDataLayout();
Tim Northover3b0846e2014-05-24 12:50:23 +00006952 switch (Intrinsic) {
6953 case Intrinsic::aarch64_neon_ld2:
6954 case Intrinsic::aarch64_neon_ld3:
6955 case Intrinsic::aarch64_neon_ld4:
6956 case Intrinsic::aarch64_neon_ld1x2:
6957 case Intrinsic::aarch64_neon_ld1x3:
6958 case Intrinsic::aarch64_neon_ld1x4:
6959 case Intrinsic::aarch64_neon_ld2lane:
6960 case Intrinsic::aarch64_neon_ld3lane:
6961 case Intrinsic::aarch64_neon_ld4lane:
6962 case Intrinsic::aarch64_neon_ld2r:
6963 case Intrinsic::aarch64_neon_ld3r:
6964 case Intrinsic::aarch64_neon_ld4r: {
6965 Info.opc = ISD::INTRINSIC_W_CHAIN;
6966 // Conservatively set memVT to the entire set of vectors loaded.
Ahmed Bougacha97564c32015-12-09 01:19:50 +00006967 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00006968 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6969 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6970 Info.offset = 0;
6971 Info.align = 0;
6972 Info.vol = false; // volatile loads with NEON intrinsics not supported
6973 Info.readMem = true;
6974 Info.writeMem = false;
6975 return true;
6976 }
6977 case Intrinsic::aarch64_neon_st2:
6978 case Intrinsic::aarch64_neon_st3:
6979 case Intrinsic::aarch64_neon_st4:
6980 case Intrinsic::aarch64_neon_st1x2:
6981 case Intrinsic::aarch64_neon_st1x3:
6982 case Intrinsic::aarch64_neon_st1x4:
6983 case Intrinsic::aarch64_neon_st2lane:
6984 case Intrinsic::aarch64_neon_st3lane:
6985 case Intrinsic::aarch64_neon_st4lane: {
6986 Info.opc = ISD::INTRINSIC_VOID;
6987 // Conservatively set memVT to the entire set of vectors stored.
6988 unsigned NumElts = 0;
6989 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
6990 Type *ArgTy = I.getArgOperand(ArgI)->getType();
6991 if (!ArgTy->isVectorTy())
6992 break;
Ahmed Bougacha97564c32015-12-09 01:19:50 +00006993 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00006994 }
6995 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6996 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6997 Info.offset = 0;
6998 Info.align = 0;
6999 Info.vol = false; // volatile stores with NEON intrinsics not supported
7000 Info.readMem = false;
7001 Info.writeMem = true;
7002 return true;
7003 }
7004 case Intrinsic::aarch64_ldaxr:
7005 case Intrinsic::aarch64_ldxr: {
7006 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
7007 Info.opc = ISD::INTRINSIC_W_CHAIN;
7008 Info.memVT = MVT::getVT(PtrTy->getElementType());
7009 Info.ptrVal = I.getArgOperand(0);
7010 Info.offset = 0;
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007011 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
Tim Northover3b0846e2014-05-24 12:50:23 +00007012 Info.vol = true;
7013 Info.readMem = true;
7014 Info.writeMem = false;
7015 return true;
7016 }
7017 case Intrinsic::aarch64_stlxr:
7018 case Intrinsic::aarch64_stxr: {
7019 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
7020 Info.opc = ISD::INTRINSIC_W_CHAIN;
7021 Info.memVT = MVT::getVT(PtrTy->getElementType());
7022 Info.ptrVal = I.getArgOperand(1);
7023 Info.offset = 0;
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007024 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
Tim Northover3b0846e2014-05-24 12:50:23 +00007025 Info.vol = true;
7026 Info.readMem = false;
7027 Info.writeMem = true;
7028 return true;
7029 }
7030 case Intrinsic::aarch64_ldaxp:
7031 case Intrinsic::aarch64_ldxp: {
7032 Info.opc = ISD::INTRINSIC_W_CHAIN;
7033 Info.memVT = MVT::i128;
7034 Info.ptrVal = I.getArgOperand(0);
7035 Info.offset = 0;
7036 Info.align = 16;
7037 Info.vol = true;
7038 Info.readMem = true;
7039 Info.writeMem = false;
7040 return true;
7041 }
7042 case Intrinsic::aarch64_stlxp:
7043 case Intrinsic::aarch64_stxp: {
7044 Info.opc = ISD::INTRINSIC_W_CHAIN;
7045 Info.memVT = MVT::i128;
7046 Info.ptrVal = I.getArgOperand(2);
7047 Info.offset = 0;
7048 Info.align = 16;
7049 Info.vol = true;
7050 Info.readMem = false;
7051 Info.writeMem = true;
7052 return true;
7053 }
7054 default:
7055 break;
7056 }
7057
7058 return false;
7059}
7060
7061// Truncations from 64-bit GPR to 32-bit GPR is free.
7062bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
7063 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
7064 return false;
7065 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7066 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00007067 return NumBits1 > NumBits2;
Tim Northover3b0846e2014-05-24 12:50:23 +00007068}
7069bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
Hao Liu40914502014-05-29 09:19:07 +00007070 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00007071 return false;
7072 unsigned NumBits1 = VT1.getSizeInBits();
7073 unsigned NumBits2 = VT2.getSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00007074 return NumBits1 > NumBits2;
Tim Northover3b0846e2014-05-24 12:50:23 +00007075}
7076
Chad Rosier54390052015-02-23 19:15:16 +00007077/// Check if it is profitable to hoist instruction in then/else to if.
7078/// Not profitable if I and it's user can form a FMA instruction
7079/// because we prefer FMSUB/FMADD.
7080bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
7081 if (I->getOpcode() != Instruction::FMul)
7082 return true;
7083
7084 if (I->getNumUses() != 1)
7085 return true;
7086
7087 Instruction *User = I->user_back();
7088
7089 if (User &&
7090 !(User->getOpcode() == Instruction::FSub ||
7091 User->getOpcode() == Instruction::FAdd))
7092 return true;
7093
7094 const TargetOptions &Options = getTargetMachine().Options;
Mehdi Amini44ede332015-07-09 02:09:04 +00007095 const DataLayout &DL = I->getModule()->getDataLayout();
7096 EVT VT = getValueType(DL, User->getOperand(0)->getType());
Chad Rosier54390052015-02-23 19:15:16 +00007097
Eric Christopher114fa1c2016-02-29 22:50:49 +00007098 return !(isFMAFasterThanFMulAndFAdd(VT) &&
7099 isOperationLegalOrCustom(ISD::FMA, VT) &&
7100 (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7101 Options.UnsafeFPMath));
Chad Rosier54390052015-02-23 19:15:16 +00007102}
7103
Tim Northover3b0846e2014-05-24 12:50:23 +00007104// All 32-bit GPR operations implicitly zero the high-half of the corresponding
7105// 64-bit GPR.
7106bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
7107 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
7108 return false;
7109 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7110 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00007111 return NumBits1 == 32 && NumBits2 == 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00007112}
7113bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
Hao Liu40914502014-05-29 09:19:07 +00007114 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00007115 return false;
7116 unsigned NumBits1 = VT1.getSizeInBits();
7117 unsigned NumBits2 = VT2.getSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00007118 return NumBits1 == 32 && NumBits2 == 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00007119}
7120
7121bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
7122 EVT VT1 = Val.getValueType();
7123 if (isZExtFree(VT1, VT2)) {
7124 return true;
7125 }
7126
7127 if (Val.getOpcode() != ISD::LOAD)
7128 return false;
7129
7130 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
Hao Liu40914502014-05-29 09:19:07 +00007131 return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
7132 VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
7133 VT1.getSizeInBits() <= 32);
Tim Northover3b0846e2014-05-24 12:50:23 +00007134}
7135
Quentin Colombet6843ac42015-03-31 20:52:32 +00007136bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
7137 if (isa<FPExtInst>(Ext))
7138 return false;
7139
7140 // Vector types are next free.
7141 if (Ext->getType()->isVectorTy())
7142 return false;
7143
7144 for (const Use &U : Ext->uses()) {
7145 // The extension is free if we can fold it with a left shift in an
7146 // addressing mode or an arithmetic operation: add, sub, and cmp.
7147
7148 // Is there a shift?
7149 const Instruction *Instr = cast<Instruction>(U.getUser());
7150
7151 // Is this a constant shift?
7152 switch (Instr->getOpcode()) {
7153 case Instruction::Shl:
7154 if (!isa<ConstantInt>(Instr->getOperand(1)))
7155 return false;
7156 break;
7157 case Instruction::GetElementPtr: {
7158 gep_type_iterator GTI = gep_type_begin(Instr);
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007159 auto &DL = Ext->getModule()->getDataLayout();
Peter Collingbourneab85225b2016-12-02 02:24:42 +00007160 std::advance(GTI, U.getOperandNo()-1);
7161 Type *IdxTy = GTI.getIndexedType();
Quentin Colombet6843ac42015-03-31 20:52:32 +00007162 // This extension will end up with a shift because of the scaling factor.
7163 // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
7164 // Get the shift amount based on the scaling factor:
7165 // log2(sizeof(IdxTy)) - log2(8).
7166 uint64_t ShiftAmt =
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007167 countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3;
Quentin Colombet6843ac42015-03-31 20:52:32 +00007168 // Is the constant foldable in the shift of the addressing mode?
7169 // I.e., shift amount is between 1 and 4 inclusive.
7170 if (ShiftAmt == 0 || ShiftAmt > 4)
7171 return false;
7172 break;
7173 }
7174 case Instruction::Trunc:
7175 // Check if this is a noop.
7176 // trunc(sext ty1 to ty2) to ty1.
7177 if (Instr->getType() == Ext->getOperand(0)->getType())
7178 continue;
Justin Bognercd1d5aa2016-08-17 20:30:52 +00007179 LLVM_FALLTHROUGH;
Quentin Colombet6843ac42015-03-31 20:52:32 +00007180 default:
7181 return false;
7182 }
7183
7184 // At this point we can use the bfm family, so this extension is free
7185 // for that use.
7186 }
7187 return true;
7188}
7189
Tim Northover3b0846e2014-05-24 12:50:23 +00007190bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
7191 unsigned &RequiredAligment) const {
7192 if (!LoadedType.isSimple() ||
7193 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
7194 return false;
7195 // Cyclone supports unaligned accesses.
7196 RequiredAligment = 0;
7197 unsigned NumBits = LoadedType.getSizeInBits();
7198 return NumBits == 32 || NumBits == 64;
7199}
7200
Hao Liu7ec8ee32015-06-26 02:32:07 +00007201/// \brief Lower an interleaved load into a ldN intrinsic.
7202///
7203/// E.g. Lower an interleaved load (Factor = 2):
7204/// %wide.vec = load <8 x i32>, <8 x i32>* %ptr
7205/// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
7206/// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
7207///
7208/// Into:
7209/// %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
7210/// %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
7211/// %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
7212bool AArch64TargetLowering::lowerInterleavedLoad(
7213 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
7214 ArrayRef<unsigned> Indices, unsigned Factor) const {
7215 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7216 "Invalid interleave factor");
7217 assert(!Shuffles.empty() && "Empty shufflevector input");
7218 assert(Shuffles.size() == Indices.size() &&
7219 "Unmatched number of shufflevectors and indices");
7220
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007221 const DataLayout &DL = LI->getModule()->getDataLayout();
Hao Liu7ec8ee32015-06-26 02:32:07 +00007222
7223 VectorType *VecTy = Shuffles[0]->getType();
Ahmed Bougacha97564c32015-12-09 01:19:50 +00007224 unsigned VecSize = DL.getTypeSizeInBits(VecTy);
Hao Liu7ec8ee32015-06-26 02:32:07 +00007225
Jeroen Ketemaaebca092015-10-07 14:53:29 +00007226 // Skip if we do not have NEON and skip illegal vector types.
7227 if (!Subtarget->hasNEON() || (VecSize != 64 && VecSize != 128))
Hao Liu7ec8ee32015-06-26 02:32:07 +00007228 return false;
7229
7230 // A pointer vector can not be the return type of the ldN intrinsics. Need to
7231 // load integer vectors first and then convert to pointer vectors.
7232 Type *EltTy = VecTy->getVectorElementType();
7233 if (EltTy->isPointerTy())
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007234 VecTy =
7235 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
Hao Liu7ec8ee32015-06-26 02:32:07 +00007236
7237 Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
7238 Type *Tys[2] = {VecTy, PtrTy};
7239 static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
7240 Intrinsic::aarch64_neon_ld3,
7241 Intrinsic::aarch64_neon_ld4};
7242 Function *LdNFunc =
7243 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
7244
7245 IRBuilder<> Builder(LI);
7246 Value *Ptr = Builder.CreateBitCast(LI->getPointerOperand(), PtrTy);
7247
7248 CallInst *LdN = Builder.CreateCall(LdNFunc, Ptr, "ldN");
7249
7250 // Replace uses of each shufflevector with the corresponding vector loaded
7251 // by ldN.
7252 for (unsigned i = 0; i < Shuffles.size(); i++) {
7253 ShuffleVectorInst *SVI = Shuffles[i];
7254 unsigned Index = Indices[i];
7255
7256 Value *SubVec = Builder.CreateExtractValue(LdN, Index);
7257
7258 // Convert the integer vector to pointer vector if the element is pointer.
7259 if (EltTy->isPointerTy())
7260 SubVec = Builder.CreateIntToPtr(SubVec, SVI->getType());
7261
7262 SVI->replaceAllUsesWith(SubVec);
7263 }
7264
7265 return true;
7266}
7267
7268/// \brief Get a mask consisting of sequential integers starting from \p Start.
7269///
7270/// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
7271static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
7272 unsigned NumElts) {
7273 SmallVector<Constant *, 16> Mask;
7274 for (unsigned i = 0; i < NumElts; i++)
7275 Mask.push_back(Builder.getInt32(Start + i));
7276
7277 return ConstantVector::get(Mask);
7278}
7279
7280/// \brief Lower an interleaved store into a stN intrinsic.
7281///
7282/// E.g. Lower an interleaved store (Factor = 3):
7283/// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00007284/// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
Hao Liu7ec8ee32015-06-26 02:32:07 +00007285/// store <12 x i32> %i.vec, <12 x i32>* %ptr
7286///
7287/// Into:
7288/// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
7289/// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
7290/// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
7291/// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
7292///
7293/// Note that the new shufflevectors will be removed and we'll only generate one
7294/// st3 instruction in CodeGen.
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00007295///
7296/// Example for a more general valid mask (Factor 3). Lower:
7297/// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
7298/// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
7299/// store <12 x i32> %i.vec, <12 x i32>* %ptr
7300///
7301/// Into:
7302/// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
7303/// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
7304/// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
7305/// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
Hao Liu7ec8ee32015-06-26 02:32:07 +00007306bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
7307 ShuffleVectorInst *SVI,
7308 unsigned Factor) const {
7309 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7310 "Invalid interleave factor");
7311
7312 VectorType *VecTy = SVI->getType();
7313 assert(VecTy->getVectorNumElements() % Factor == 0 &&
7314 "Invalid interleaved store");
7315
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00007316 unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
Hao Liu7ec8ee32015-06-26 02:32:07 +00007317 Type *EltTy = VecTy->getVectorElementType();
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00007318 VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
Hao Liu7ec8ee32015-06-26 02:32:07 +00007319
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007320 const DataLayout &DL = SI->getModule()->getDataLayout();
Ahmed Bougacha97564c32015-12-09 01:19:50 +00007321 unsigned SubVecSize = DL.getTypeSizeInBits(SubVecTy);
Hao Liu7ec8ee32015-06-26 02:32:07 +00007322
Jeroen Ketemaaebca092015-10-07 14:53:29 +00007323 // Skip if we do not have NEON and skip illegal vector types.
7324 if (!Subtarget->hasNEON() || (SubVecSize != 64 && SubVecSize != 128))
Hao Liu7ec8ee32015-06-26 02:32:07 +00007325 return false;
7326
7327 Value *Op0 = SVI->getOperand(0);
7328 Value *Op1 = SVI->getOperand(1);
7329 IRBuilder<> Builder(SI);
7330
7331 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
7332 // vectors to integer vectors.
7333 if (EltTy->isPointerTy()) {
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007334 Type *IntTy = DL.getIntPtrType(EltTy);
Hao Liu7ec8ee32015-06-26 02:32:07 +00007335 unsigned NumOpElts =
7336 dyn_cast<VectorType>(Op0->getType())->getVectorNumElements();
7337
7338 // Convert to the corresponding integer vector.
7339 Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
7340 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
7341 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
7342
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00007343 SubVecTy = VectorType::get(IntTy, LaneLen);
Hao Liu7ec8ee32015-06-26 02:32:07 +00007344 }
7345
7346 Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
7347 Type *Tys[2] = {SubVecTy, PtrTy};
7348 static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
7349 Intrinsic::aarch64_neon_st3,
7350 Intrinsic::aarch64_neon_st4};
7351 Function *StNFunc =
7352 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
7353
7354 SmallVector<Value *, 5> Ops;
7355
7356 // Split the shufflevector operands into sub vectors for the new stN call.
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00007357 auto Mask = SVI->getShuffleMask();
7358 for (unsigned i = 0; i < Factor; i++) {
7359 if (Mask[i] >= 0) {
7360 Ops.push_back(Builder.CreateShuffleVector(
7361 Op0, Op1, getSequentialMask(Builder, Mask[i], LaneLen)));
7362 } else {
7363 unsigned StartMask = 0;
7364 for (unsigned j = 1; j < LaneLen; j++) {
7365 if (Mask[j*Factor + i] >= 0) {
7366 StartMask = Mask[j*Factor + i] - j;
7367 break;
7368 }
7369 }
7370 // Note: If all elements in a chunk are undefs, StartMask=0!
7371 // Note: Filling undef gaps with random elements is ok, since
7372 // those elements were being written anyway (with undefs).
7373 // In the case of all undefs we're defaulting to using elems from 0
7374 // Note: StartMask cannot be negative, it's checked in isReInterleaveMask
7375 Ops.push_back(Builder.CreateShuffleVector(
7376 Op0, Op1, getSequentialMask(Builder, StartMask, LaneLen)));
7377 }
7378 }
Hao Liu7ec8ee32015-06-26 02:32:07 +00007379
7380 Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), PtrTy));
7381 Builder.CreateCall(StNFunc, Ops);
7382 return true;
7383}
7384
Tim Northover3b0846e2014-05-24 12:50:23 +00007385static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
7386 unsigned AlignCheck) {
7387 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
7388 (DstAlign == 0 || DstAlign % AlignCheck == 0));
7389}
7390
7391EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
7392 unsigned SrcAlign, bool IsMemset,
7393 bool ZeroMemset,
7394 bool MemcpyStrSrc,
7395 MachineFunction &MF) const {
7396 // Don't use AdvSIMD to implement 16-byte memset. It would have taken one
7397 // instruction to materialize the v2i64 zero and one store (with restrictive
7398 // addressing mode). Just do two i64 store of zero-registers.
7399 bool Fast;
7400 const Function *F = MF.getFunction();
7401 if (Subtarget->hasFPARMv8() && !IsMemset && Size >= 16 &&
Duncan P. N. Exon Smith003bb7d2015-02-14 02:09:06 +00007402 !F->hasFnAttribute(Attribute::NoImplicitFloat) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00007403 (memOpAlign(SrcAlign, DstAlign, 16) ||
Matt Arsenault6f2a5262014-07-27 17:46:40 +00007404 (allowsMisalignedMemoryAccesses(MVT::f128, 0, 1, &Fast) && Fast)))
Tim Northover3b0846e2014-05-24 12:50:23 +00007405 return MVT::f128;
7406
Lang Hames90333852015-04-09 03:40:33 +00007407 if (Size >= 8 &&
7408 (memOpAlign(SrcAlign, DstAlign, 8) ||
7409 (allowsMisalignedMemoryAccesses(MVT::i64, 0, 1, &Fast) && Fast)))
7410 return MVT::i64;
7411
7412 if (Size >= 4 &&
7413 (memOpAlign(SrcAlign, DstAlign, 4) ||
7414 (allowsMisalignedMemoryAccesses(MVT::i32, 0, 1, &Fast) && Fast)))
Lang Hames522bf132015-04-09 05:34:57 +00007415 return MVT::i32;
Lang Hames90333852015-04-09 03:40:33 +00007416
7417 return MVT::Other;
Tim Northover3b0846e2014-05-24 12:50:23 +00007418}
7419
7420// 12-bit optionally shifted immediates are legal for adds.
7421bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
Geoff Berry486f49c2016-06-07 16:48:43 +00007422 // Avoid UB for INT64_MIN.
7423 if (Immed == std::numeric_limits<int64_t>::min())
7424 return false;
7425 // Same encoding for add/sub, just flip the sign.
7426 Immed = std::abs(Immed);
Eric Christopher114fa1c2016-02-29 22:50:49 +00007427 return ((Immed >> 12) == 0 || ((Immed & 0xfff) == 0 && Immed >> 24 == 0));
Tim Northover3b0846e2014-05-24 12:50:23 +00007428}
7429
7430// Integer comparisons are implemented with ADDS/SUBS, so the range of valid
7431// immediates is the same as for an add or a sub.
7432bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00007433 return isLegalAddImmediate(Immed);
7434}
7435
7436/// isLegalAddressingMode - Return true if the addressing mode represented
7437/// by AM is legal for this target, for a load/store of the specified type.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00007438bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
7439 const AddrMode &AM, Type *Ty,
Matt Arsenaultbd7d80a2015-06-01 05:31:59 +00007440 unsigned AS) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00007441 // AArch64 has five basic addressing modes:
7442 // reg
7443 // reg + 9-bit signed offset
7444 // reg + SIZE_IN_BYTES * 12-bit unsigned offset
7445 // reg1 + reg2
7446 // reg + SIZE_IN_BYTES * reg
7447
7448 // No global is ever allowed as a base.
7449 if (AM.BaseGV)
7450 return false;
7451
7452 // No reg+reg+imm addressing.
7453 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
7454 return false;
7455
7456 // check reg + imm case:
7457 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
7458 uint64_t NumBytes = 0;
7459 if (Ty->isSized()) {
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00007460 uint64_t NumBits = DL.getTypeSizeInBits(Ty);
Tim Northover3b0846e2014-05-24 12:50:23 +00007461 NumBytes = NumBits / 8;
7462 if (!isPowerOf2_64(NumBits))
7463 NumBytes = 0;
7464 }
7465
7466 if (!AM.Scale) {
7467 int64_t Offset = AM.BaseOffs;
7468
7469 // 9-bit signed offset
Haicheng Wuf8b83402016-12-07 01:45:04 +00007470 if (isInt<9>(Offset))
Tim Northover3b0846e2014-05-24 12:50:23 +00007471 return true;
7472
7473 // 12-bit unsigned offset
7474 unsigned shift = Log2_64(NumBytes);
7475 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
7476 // Must be a multiple of NumBytes (NumBytes is a power of 2)
7477 (Offset >> shift) << shift == Offset)
7478 return true;
7479 return false;
7480 }
7481
7482 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
7483
Haicheng Wu6bb0e392016-12-21 21:40:47 +00007484 return AM.Scale == 1 || (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes);
Tim Northover3b0846e2014-05-24 12:50:23 +00007485}
7486
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00007487int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
7488 const AddrMode &AM, Type *Ty,
Matt Arsenaultbd7d80a2015-06-01 05:31:59 +00007489 unsigned AS) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00007490 // Scaling factors are not free at all.
7491 // Operands | Rt Latency
7492 // -------------------------------------------
7493 // Rt, [Xn, Xm] | 4
7494 // -------------------------------------------
7495 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5
7496 // Rt, [Xn, Wm, <extend> #imm] |
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00007497 if (isLegalAddressingMode(DL, AM, Ty, AS))
Tim Northover3b0846e2014-05-24 12:50:23 +00007498 // Scale represents reg2 * scale, thus account for 1 if
7499 // it is not equal to 0 or 1.
7500 return AM.Scale != 0 && AM.Scale != 1;
7501 return -1;
7502}
7503
7504bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
7505 VT = VT.getScalarType();
7506
7507 if (!VT.isSimple())
7508 return false;
7509
7510 switch (VT.getSimpleVT().SimpleTy) {
7511 case MVT::f32:
7512 case MVT::f64:
7513 return true;
7514 default:
7515 break;
7516 }
7517
7518 return false;
7519}
7520
7521const MCPhysReg *
7522AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
7523 // LR is a callee-save register, but we must treat it as clobbered by any call
7524 // site. Hence we include LR in the scratch registers, which are in turn added
7525 // as implicit-defs for stackmaps and patchpoints.
7526 static const MCPhysReg ScratchRegs[] = {
7527 AArch64::X16, AArch64::X17, AArch64::LR, 0
7528 };
7529 return ScratchRegs;
7530}
7531
7532bool
7533AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N) const {
7534 EVT VT = N->getValueType(0);
7535 // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
7536 // it with shift to let it be lowered to UBFX.
7537 if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
7538 isa<ConstantSDNode>(N->getOperand(1))) {
7539 uint64_t TruncMask = N->getConstantOperandVal(1);
7540 if (isMask_64(TruncMask) &&
7541 N->getOperand(0).getOpcode() == ISD::SRL &&
7542 isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
7543 return false;
7544 }
7545 return true;
7546}
7547
7548bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
7549 Type *Ty) const {
7550 assert(Ty->isIntegerTy());
7551
7552 unsigned BitSize = Ty->getPrimitiveSizeInBits();
7553 if (BitSize == 0)
7554 return false;
7555
7556 int64_t Val = Imm.getSExtValue();
7557 if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
7558 return true;
7559
7560 if ((int64_t)Val < 0)
7561 Val = ~Val;
7562 if (BitSize == 32)
7563 Val &= (1LL << 32) - 1;
7564
7565 unsigned LZ = countLeadingZeros((uint64_t)Val);
7566 unsigned Shift = (63 - LZ) / 16;
7567 // MOVZ is free so return true for one or fewer MOVK.
David Blaikie186d2cb2015-03-24 16:24:01 +00007568 return Shift < 3;
Tim Northover3b0846e2014-05-24 12:50:23 +00007569}
7570
Sanjay Pateld6cb4ec2016-03-03 15:56:08 +00007571/// Turn vector tests of the signbit in the form of:
7572/// xor (sra X, elt_size(X)-1), -1
7573/// into:
7574/// cmge X, X, #0
7575static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
7576 const AArch64Subtarget *Subtarget) {
7577 EVT VT = N->getValueType(0);
7578 if (!Subtarget->hasNEON() || !VT.isVector())
7579 return SDValue();
7580
7581 // There must be a shift right algebraic before the xor, and the xor must be a
7582 // 'not' operation.
7583 SDValue Shift = N->getOperand(0);
7584 SDValue Ones = N->getOperand(1);
7585 if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() ||
7586 !ISD::isBuildVectorAllOnes(Ones.getNode()))
7587 return SDValue();
7588
7589 // The shift should be smearing the sign bit across each vector element.
7590 auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
7591 EVT ShiftEltTy = Shift.getValueType().getVectorElementType();
7592 if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1)
7593 return SDValue();
7594
7595 return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0));
7596}
7597
Tim Northover3b0846e2014-05-24 12:50:23 +00007598// Generate SUBS and CSEL for integer abs.
7599static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
7600 EVT VT = N->getValueType(0);
7601
7602 SDValue N0 = N->getOperand(0);
7603 SDValue N1 = N->getOperand(1);
7604 SDLoc DL(N);
7605
7606 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
7607 // and change it to SUB and CSEL.
7608 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
7609 N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
7610 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
7611 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
7612 if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007613 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
Tim Northover3b0846e2014-05-24 12:50:23 +00007614 N0.getOperand(0));
7615 // Generate SUBS & CSEL.
7616 SDValue Cmp =
7617 DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007618 N0.getOperand(0), DAG.getConstant(0, DL, VT));
Tim Northover3b0846e2014-05-24 12:50:23 +00007619 return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007620 DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00007621 SDValue(Cmp.getNode(), 1));
7622 }
7623 return SDValue();
7624}
7625
Tim Northover3b0846e2014-05-24 12:50:23 +00007626static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
7627 TargetLowering::DAGCombinerInfo &DCI,
7628 const AArch64Subtarget *Subtarget) {
7629 if (DCI.isBeforeLegalizeOps())
7630 return SDValue();
7631
Sanjay Pateld6cb4ec2016-03-03 15:56:08 +00007632 if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget))
7633 return Cmp;
7634
Tim Northover3b0846e2014-05-24 12:50:23 +00007635 return performIntegerAbsCombine(N, DAG);
7636}
7637
Chad Rosier17020f92014-07-23 14:57:52 +00007638SDValue
7639AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
7640 SelectionDAG &DAG,
7641 std::vector<SDNode *> *Created) const {
Haicheng Wu6a6bc752016-03-28 18:17:07 +00007642 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
7643 if (isIntDivCheap(N->getValueType(0), Attr))
7644 return SDValue(N,0); // Lower SDIV as SDIV
7645
Chad Rosier17020f92014-07-23 14:57:52 +00007646 // fold (sdiv X, pow2)
7647 EVT VT = N->getValueType(0);
7648 if ((VT != MVT::i32 && VT != MVT::i64) ||
7649 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
7650 return SDValue();
7651
7652 SDLoc DL(N);
7653 SDValue N0 = N->getOperand(0);
7654 unsigned Lg2 = Divisor.countTrailingZeros();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007655 SDValue Zero = DAG.getConstant(0, DL, VT);
7656 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
Chad Rosier17020f92014-07-23 14:57:52 +00007657
7658 // Add (N0 < 0) ? Pow2 - 1 : 0;
7659 SDValue CCVal;
7660 SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
7661 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
7662 SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
7663
7664 if (Created) {
7665 Created->push_back(Cmp.getNode());
7666 Created->push_back(Add.getNode());
7667 Created->push_back(CSel.getNode());
7668 }
7669
7670 // Divide by pow2.
7671 SDValue SRA =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007672 DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
Chad Rosier17020f92014-07-23 14:57:52 +00007673
7674 // If we're dividing by a positive value, we're done. Otherwise, we must
7675 // negate the result.
7676 if (Divisor.isNonNegative())
7677 return SRA;
7678
7679 if (Created)
7680 Created->push_back(SRA.getNode());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007681 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
Chad Rosier17020f92014-07-23 14:57:52 +00007682}
7683
Tim Northover3b0846e2014-05-24 12:50:23 +00007684static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
7685 TargetLowering::DAGCombinerInfo &DCI,
7686 const AArch64Subtarget *Subtarget) {
7687 if (DCI.isBeforeLegalizeOps())
7688 return SDValue();
7689
Chad Rosier31ee8132016-11-11 17:07:37 +00007690 // The below optimizations require a constant RHS.
7691 if (!isa<ConstantSDNode>(N->getOperand(1)))
7692 return SDValue();
7693
7694 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1));
7695 const APInt &ConstValue = C->getAPIntValue();
7696
Tim Northover3b0846e2014-05-24 12:50:23 +00007697 // Multiplication of a power of two plus/minus one can be done more
7698 // cheaply as as shift+add/sub. For now, this is true unilaterally. If
7699 // future CPUs have a cheaper MADD instruction, this may need to be
7700 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
7701 // 64-bit is 5 cycles, so this is always a win.
Haicheng Wufaee2b72016-11-15 20:16:48 +00007702 // More aggressively, some multiplications N0 * C can be lowered to
7703 // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M,
7704 // e.g. 6=3*2=(2+1)*2.
7705 // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45
7706 // which equals to (1+2)*16-(1+2).
7707 SDValue N0 = N->getOperand(0);
7708 // TrailingZeroes is used to test if the mul can be lowered to
7709 // shift+add+shift.
7710 unsigned TrailingZeroes = ConstValue.countTrailingZeros();
7711 if (TrailingZeroes) {
7712 // Conservatively do not lower to shift+add+shift if the mul might be
7713 // folded into smul or umul.
7714 if (N0->hasOneUse() && (isSignExtended(N0.getNode(), DAG) ||
7715 isZeroExtended(N0.getNode(), DAG)))
7716 return SDValue();
7717 // Conservatively do not lower to shift+add+shift if the mul might be
7718 // folded into madd or msub.
7719 if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ADD ||
7720 N->use_begin()->getOpcode() == ISD::SUB))
7721 return SDValue();
7722 }
7723 // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub
7724 // and shift+add+shift.
7725 APInt ShiftedConstValue = ConstValue.ashr(TrailingZeroes);
7726
Chad Rosierd6e85ce2016-11-11 17:49:34 +00007727 unsigned ShiftAmt, AddSubOpc;
7728 // Is the shifted value the LHS operand of the add/sub?
7729 bool ShiftValUseIsN0 = true;
7730 // Do we need to negate the result?
7731 bool NegateResult = false;
7732
Chad Rosier31ee8132016-11-11 17:07:37 +00007733 if (ConstValue.isNonNegative()) {
7734 // (mul x, 2^N + 1) => (add (shl x, N), x)
Chad Rosier31ee8132016-11-11 17:07:37 +00007735 // (mul x, 2^N - 1) => (sub (shl x, N), x)
Haicheng Wufaee2b72016-11-15 20:16:48 +00007736 // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M)
7737 APInt SCVMinus1 = ShiftedConstValue - 1;
Chad Rosier31ee8132016-11-11 17:07:37 +00007738 APInt CVPlus1 = ConstValue + 1;
Haicheng Wufaee2b72016-11-15 20:16:48 +00007739 if (SCVMinus1.isPowerOf2()) {
7740 ShiftAmt = SCVMinus1.logBase2();
Chad Rosierd6e85ce2016-11-11 17:49:34 +00007741 AddSubOpc = ISD::ADD;
7742 } else if (CVPlus1.isPowerOf2()) {
7743 ShiftAmt = CVPlus1.logBase2();
7744 AddSubOpc = ISD::SUB;
7745 } else
7746 return SDValue();
Chad Rosier31ee8132016-11-11 17:07:37 +00007747 } else {
7748 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
Chad Rosier31ee8132016-11-11 17:07:37 +00007749 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
Chad Rosierd6e85ce2016-11-11 17:49:34 +00007750 APInt CVNegPlus1 = -ConstValue + 1;
Chad Rosier31ee8132016-11-11 17:07:37 +00007751 APInt CVNegMinus1 = -ConstValue - 1;
Chad Rosierd6e85ce2016-11-11 17:49:34 +00007752 if (CVNegPlus1.isPowerOf2()) {
7753 ShiftAmt = CVNegPlus1.logBase2();
7754 AddSubOpc = ISD::SUB;
7755 ShiftValUseIsN0 = false;
7756 } else if (CVNegMinus1.isPowerOf2()) {
7757 ShiftAmt = CVNegMinus1.logBase2();
7758 AddSubOpc = ISD::ADD;
7759 NegateResult = true;
7760 } else
7761 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00007762 }
Chad Rosierd6e85ce2016-11-11 17:49:34 +00007763
7764 SDLoc DL(N);
7765 EVT VT = N->getValueType(0);
Haicheng Wufaee2b72016-11-15 20:16:48 +00007766 SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, VT, N0,
Chad Rosierd6e85ce2016-11-11 17:49:34 +00007767 DAG.getConstant(ShiftAmt, DL, MVT::i64));
7768
7769 SDValue AddSubN0 = ShiftValUseIsN0 ? ShiftedVal : N0;
7770 SDValue AddSubN1 = ShiftValUseIsN0 ? N0 : ShiftedVal;
7771 SDValue Res = DAG.getNode(AddSubOpc, DL, VT, AddSubN0, AddSubN1);
Haicheng Wufaee2b72016-11-15 20:16:48 +00007772 assert(!(NegateResult && TrailingZeroes) &&
7773 "NegateResult and TrailingZeroes cannot both be true for now.");
Chad Rosierd6e85ce2016-11-11 17:49:34 +00007774 // Negate the result.
Haicheng Wufaee2b72016-11-15 20:16:48 +00007775 if (NegateResult)
7776 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
7777 // Shift the result.
7778 if (TrailingZeroes)
7779 return DAG.getNode(ISD::SHL, DL, VT, Res,
7780 DAG.getConstant(TrailingZeroes, DL, MVT::i64));
7781 return Res;
Tim Northover3b0846e2014-05-24 12:50:23 +00007782}
7783
Jim Grosbachf7502c42014-07-18 00:40:52 +00007784static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
7785 SelectionDAG &DAG) {
7786 // Take advantage of vector comparisons producing 0 or -1 in each lane to
7787 // optimize away operation when it's from a constant.
7788 //
7789 // The general transformation is:
7790 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
7791 // AND(VECTOR_CMP(x,y), constant2)
7792 // constant2 = UNARYOP(constant)
7793
Jim Grosbach8f6f0852014-07-23 20:41:38 +00007794 // Early exit if this isn't a vector operation, the operand of the
7795 // unary operation isn't a bitwise AND, or if the sizes of the operations
7796 // aren't the same.
Jim Grosbachf7502c42014-07-18 00:40:52 +00007797 EVT VT = N->getValueType(0);
7798 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
Jim Grosbach8f6f0852014-07-23 20:41:38 +00007799 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
7800 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
Jim Grosbachf7502c42014-07-18 00:40:52 +00007801 return SDValue();
7802
Jim Grosbach724e4382014-07-23 20:41:43 +00007803 // Now check that the other operand of the AND is a constant. We could
Jim Grosbachf7502c42014-07-18 00:40:52 +00007804 // make the transformation for non-constant splats as well, but it's unclear
7805 // that would be a benefit as it would not eliminate any operations, just
7806 // perform one more step in scalar code before moving to the vector unit.
7807 if (BuildVectorSDNode *BV =
7808 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
Jim Grosbach724e4382014-07-23 20:41:43 +00007809 // Bail out if the vector isn't a constant.
7810 if (!BV->isConstant())
Jim Grosbachf7502c42014-07-18 00:40:52 +00007811 return SDValue();
7812
7813 // Everything checks out. Build up the new and improved node.
7814 SDLoc DL(N);
7815 EVT IntVT = BV->getValueType(0);
7816 // Create a new constant of the appropriate type for the transformed
7817 // DAG.
7818 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
7819 // The AND node needs bitcasts to/from an integer vector type around it.
7820 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
7821 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
7822 N->getOperand(0)->getOperand(0), MaskConst);
7823 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
7824 return Res;
7825 }
7826
7827 return SDValue();
7828}
7829
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00007830static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
7831 const AArch64Subtarget *Subtarget) {
Jim Grosbachf7502c42014-07-18 00:40:52 +00007832 // First try to optimize away the conversion when it's conditionally from
7833 // a constant. Vectors only.
Ahmed Bougacha239d6352015-08-04 00:48:02 +00007834 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
Jim Grosbachf7502c42014-07-18 00:40:52 +00007835 return Res;
7836
Tim Northover3b0846e2014-05-24 12:50:23 +00007837 EVT VT = N->getValueType(0);
7838 if (VT != MVT::f32 && VT != MVT::f64)
7839 return SDValue();
Jim Grosbachf7502c42014-07-18 00:40:52 +00007840
Tim Northover3b0846e2014-05-24 12:50:23 +00007841 // Only optimize when the source and destination types have the same width.
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00007842 if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits())
Tim Northover3b0846e2014-05-24 12:50:23 +00007843 return SDValue();
7844
7845 // If the result of an integer load is only used by an integer-to-float
7846 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
Chad Rosier1f385612015-10-02 16:42:59 +00007847 // This eliminates an "integer-to-vector-move" UOP and improves throughput.
Tim Northover3b0846e2014-05-24 12:50:23 +00007848 SDValue N0 = N->getOperand(0);
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00007849 if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Tim Northover3b0846e2014-05-24 12:50:23 +00007850 // Do not change the width of a volatile load.
7851 !cast<LoadSDNode>(N0)->isVolatile()) {
7852 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7853 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
Justin Lebar9c375812016-07-15 18:27:10 +00007854 LN0->getPointerInfo(), LN0->getAlignment(),
7855 LN0->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +00007856
7857 // Make sure successors of the original load stay after it by updating them
7858 // to use the new Chain.
7859 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
7860
7861 unsigned Opcode =
7862 (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
7863 return DAG.getNode(Opcode, SDLoc(N), VT, Load);
7864 }
7865
7866 return SDValue();
7867}
7868
Chad Rosierfa30c9b2015-10-07 17:39:18 +00007869/// Fold a floating-point multiply by power of two into floating-point to
7870/// fixed-point conversion.
7871static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
Silviu Barangafa00ba32016-08-08 13:13:57 +00007872 TargetLowering::DAGCombinerInfo &DCI,
Chad Rosierfa30c9b2015-10-07 17:39:18 +00007873 const AArch64Subtarget *Subtarget) {
7874 if (!Subtarget->hasNEON())
7875 return SDValue();
7876
7877 SDValue Op = N->getOperand(0);
Tim Northover6092de52016-03-10 23:02:21 +00007878 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
7879 Op.getOpcode() != ISD::FMUL)
Chad Rosierfa30c9b2015-10-07 17:39:18 +00007880 return SDValue();
7881
7882 SDValue ConstVec = Op->getOperand(1);
7883 if (!isa<BuildVectorSDNode>(ConstVec))
7884 return SDValue();
7885
7886 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
7887 uint32_t FloatBits = FloatTy.getSizeInBits();
7888 if (FloatBits != 32 && FloatBits != 64)
7889 return SDValue();
7890
7891 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
7892 uint32_t IntBits = IntTy.getSizeInBits();
7893 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
7894 return SDValue();
7895
7896 // Avoid conversions where iN is larger than the float (e.g., float -> i64).
7897 if (IntBits > FloatBits)
7898 return SDValue();
7899
7900 BitVector UndefElements;
7901 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
7902 int32_t Bits = IntBits == 64 ? 64 : 32;
7903 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
7904 if (C == -1 || C == 0 || C > Bits)
7905 return SDValue();
7906
7907 MVT ResTy;
7908 unsigned NumLanes = Op.getValueType().getVectorNumElements();
7909 switch (NumLanes) {
7910 default:
7911 return SDValue();
7912 case 2:
7913 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
7914 break;
7915 case 4:
Silviu Barangafa00ba32016-08-08 13:13:57 +00007916 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
Chad Rosierfa30c9b2015-10-07 17:39:18 +00007917 break;
7918 }
7919
Silviu Barangafa00ba32016-08-08 13:13:57 +00007920 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
7921 return SDValue();
7922
7923 assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) &&
7924 "Illegal vector type after legalization");
7925
Chad Rosierfa30c9b2015-10-07 17:39:18 +00007926 SDLoc DL(N);
7927 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
7928 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
7929 : Intrinsic::aarch64_neon_vcvtfp2fxu;
7930 SDValue FixConv =
7931 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
7932 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
7933 Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
7934 // We can handle smaller integers by generating an extra trunc.
7935 if (IntBits < FloatBits)
7936 FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
7937
7938 return FixConv;
7939}
7940
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00007941/// Fold a floating-point divide by power of two into fixed-point to
7942/// floating-point conversion.
7943static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
Tim Northover85cf5642016-08-26 18:52:31 +00007944 TargetLowering::DAGCombinerInfo &DCI,
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00007945 const AArch64Subtarget *Subtarget) {
7946 if (!Subtarget->hasNEON())
7947 return SDValue();
7948
7949 SDValue Op = N->getOperand(0);
7950 unsigned Opc = Op->getOpcode();
Tim Northover85cf5642016-08-26 18:52:31 +00007951 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
7952 !Op.getOperand(0).getValueType().isSimple() ||
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00007953 (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
7954 return SDValue();
7955
7956 SDValue ConstVec = N->getOperand(1);
7957 if (!isa<BuildVectorSDNode>(ConstVec))
7958 return SDValue();
7959
7960 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
7961 int32_t IntBits = IntTy.getSizeInBits();
7962 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
7963 return SDValue();
7964
7965 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
7966 int32_t FloatBits = FloatTy.getSizeInBits();
7967 if (FloatBits != 32 && FloatBits != 64)
7968 return SDValue();
7969
7970 // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
7971 if (IntBits > FloatBits)
7972 return SDValue();
7973
7974 BitVector UndefElements;
7975 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
7976 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
7977 if (C == -1 || C == 0 || C > FloatBits)
7978 return SDValue();
7979
7980 MVT ResTy;
7981 unsigned NumLanes = Op.getValueType().getVectorNumElements();
7982 switch (NumLanes) {
7983 default:
7984 return SDValue();
7985 case 2:
7986 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
7987 break;
7988 case 4:
Tim Northover85cf5642016-08-26 18:52:31 +00007989 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00007990 break;
7991 }
7992
Tim Northover85cf5642016-08-26 18:52:31 +00007993 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
7994 return SDValue();
7995
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00007996 SDLoc DL(N);
7997 SDValue ConvInput = Op.getOperand(0);
7998 bool IsSigned = Opc == ISD::SINT_TO_FP;
7999 if (IntBits < FloatBits)
8000 ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
8001 ResTy, ConvInput);
8002
8003 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
8004 : Intrinsic::aarch64_neon_vcvtfxu2fp;
8005 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
8006 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
8007 DAG.getConstant(C, DL, MVT::i32));
8008}
8009
Tim Northover3b0846e2014-05-24 12:50:23 +00008010/// An EXTR instruction is made up of two shifts, ORed together. This helper
8011/// searches for and classifies those shifts.
8012static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
8013 bool &FromHi) {
8014 if (N.getOpcode() == ISD::SHL)
8015 FromHi = false;
8016 else if (N.getOpcode() == ISD::SRL)
8017 FromHi = true;
8018 else
8019 return false;
8020
8021 if (!isa<ConstantSDNode>(N.getOperand(1)))
8022 return false;
8023
8024 ShiftAmount = N->getConstantOperandVal(1);
8025 Src = N->getOperand(0);
8026 return true;
8027}
8028
8029/// EXTR instruction extracts a contiguous chunk of bits from two existing
8030/// registers viewed as a high/low pair. This function looks for the pattern:
8031/// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an
8032/// EXTR. Can't quite be done in TableGen because the two immediates aren't
8033/// independent.
8034static SDValue tryCombineToEXTR(SDNode *N,
8035 TargetLowering::DAGCombinerInfo &DCI) {
8036 SelectionDAG &DAG = DCI.DAG;
8037 SDLoc DL(N);
8038 EVT VT = N->getValueType(0);
8039
8040 assert(N->getOpcode() == ISD::OR && "Unexpected root");
8041
8042 if (VT != MVT::i32 && VT != MVT::i64)
8043 return SDValue();
8044
8045 SDValue LHS;
8046 uint32_t ShiftLHS = 0;
8047 bool LHSFromHi = 0;
8048 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
8049 return SDValue();
8050
8051 SDValue RHS;
8052 uint32_t ShiftRHS = 0;
8053 bool RHSFromHi = 0;
8054 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
8055 return SDValue();
8056
8057 // If they're both trying to come from the high part of the register, they're
8058 // not really an EXTR.
8059 if (LHSFromHi == RHSFromHi)
8060 return SDValue();
8061
8062 if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
8063 return SDValue();
8064
8065 if (LHSFromHi) {
8066 std::swap(LHS, RHS);
8067 std::swap(ShiftLHS, ShiftRHS);
8068 }
8069
8070 return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008071 DAG.getConstant(ShiftRHS, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008072}
8073
8074static SDValue tryCombineToBSL(SDNode *N,
8075 TargetLowering::DAGCombinerInfo &DCI) {
8076 EVT VT = N->getValueType(0);
8077 SelectionDAG &DAG = DCI.DAG;
8078 SDLoc DL(N);
8079
8080 if (!VT.isVector())
8081 return SDValue();
8082
8083 SDValue N0 = N->getOperand(0);
8084 if (N0.getOpcode() != ISD::AND)
8085 return SDValue();
8086
8087 SDValue N1 = N->getOperand(1);
8088 if (N1.getOpcode() != ISD::AND)
8089 return SDValue();
8090
8091 // We only have to look for constant vectors here since the general, variable
8092 // case can be handled in TableGen.
Sanjay Patel1ed771f2016-09-14 16:37:15 +00008093 unsigned Bits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00008094 uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
8095 for (int i = 1; i >= 0; --i)
8096 for (int j = 1; j >= 0; --j) {
8097 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
8098 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
8099 if (!BVN0 || !BVN1)
8100 continue;
8101
8102 bool FoundMatch = true;
8103 for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
8104 ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
8105 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
8106 if (!CN0 || !CN1 ||
8107 CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
8108 FoundMatch = false;
8109 break;
8110 }
8111 }
8112
8113 if (FoundMatch)
8114 return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
8115 N0->getOperand(1 - i), N1->getOperand(1 - j));
8116 }
8117
8118 return SDValue();
8119}
8120
8121static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
8122 const AArch64Subtarget *Subtarget) {
8123 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
Tim Northover3b0846e2014-05-24 12:50:23 +00008124 SelectionDAG &DAG = DCI.DAG;
8125 EVT VT = N->getValueType(0);
8126
8127 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8128 return SDValue();
8129
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00008130 if (SDValue Res = tryCombineToEXTR(N, DCI))
Tim Northover3b0846e2014-05-24 12:50:23 +00008131 return Res;
8132
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00008133 if (SDValue Res = tryCombineToBSL(N, DCI))
Tim Northover3b0846e2014-05-24 12:50:23 +00008134 return Res;
8135
8136 return SDValue();
8137}
8138
Chad Rosier14aa2ad2016-05-26 19:41:33 +00008139static SDValue performSRLCombine(SDNode *N,
8140 TargetLowering::DAGCombinerInfo &DCI) {
8141 SelectionDAG &DAG = DCI.DAG;
8142 EVT VT = N->getValueType(0);
8143 if (VT != MVT::i32 && VT != MVT::i64)
8144 return SDValue();
8145
8146 // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the
8147 // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32)
8148 // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero.
8149 SDValue N0 = N->getOperand(0);
8150 if (N0.getOpcode() == ISD::BSWAP) {
8151 SDLoc DL(N);
8152 SDValue N1 = N->getOperand(1);
8153 SDValue N00 = N0.getOperand(0);
8154 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
8155 uint64_t ShiftAmt = C->getZExtValue();
8156 if (VT == MVT::i32 && ShiftAmt == 16 &&
8157 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16)))
8158 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
8159 if (VT == MVT::i64 && ShiftAmt == 32 &&
8160 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32)))
8161 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
8162 }
8163 }
8164 return SDValue();
8165}
8166
Tim Northover3b0846e2014-05-24 12:50:23 +00008167static SDValue performBitcastCombine(SDNode *N,
8168 TargetLowering::DAGCombinerInfo &DCI,
8169 SelectionDAG &DAG) {
8170 // Wait 'til after everything is legalized to try this. That way we have
8171 // legal vector types and such.
8172 if (DCI.isBeforeLegalizeOps())
8173 return SDValue();
8174
8175 // Remove extraneous bitcasts around an extract_subvector.
8176 // For example,
8177 // (v4i16 (bitconvert
8178 // (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
8179 // becomes
8180 // (extract_subvector ((v8i16 ...), (i64 4)))
8181
8182 // Only interested in 64-bit vectors as the ultimate result.
8183 EVT VT = N->getValueType(0);
8184 if (!VT.isVector())
8185 return SDValue();
8186 if (VT.getSimpleVT().getSizeInBits() != 64)
8187 return SDValue();
8188 // Is the operand an extract_subvector starting at the beginning or halfway
8189 // point of the vector? A low half may also come through as an
8190 // EXTRACT_SUBREG, so look for that, too.
8191 SDValue Op0 = N->getOperand(0);
8192 if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
8193 !(Op0->isMachineOpcode() &&
8194 Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
8195 return SDValue();
8196 uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
8197 if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
8198 if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
8199 return SDValue();
8200 } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
8201 if (idx != AArch64::dsub)
8202 return SDValue();
8203 // The dsub reference is equivalent to a lane zero subvector reference.
8204 idx = 0;
8205 }
8206 // Look through the bitcast of the input to the extract.
8207 if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
8208 return SDValue();
8209 SDValue Source = Op0->getOperand(0)->getOperand(0);
8210 // If the source type has twice the number of elements as our destination
8211 // type, we know this is an extract of the high or low half of the vector.
8212 EVT SVT = Source->getValueType(0);
8213 if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
8214 return SDValue();
8215
8216 DEBUG(dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
8217
8218 // Create the simplified form to just extract the low or high half of the
8219 // vector directly rather than bothering with the bitcasts.
8220 SDLoc dl(N);
8221 unsigned NumElements = VT.getVectorNumElements();
8222 if (idx) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008223 SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00008224 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
8225 } else {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008226 SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00008227 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
8228 Source, SubReg),
8229 0);
8230 }
8231}
8232
8233static SDValue performConcatVectorsCombine(SDNode *N,
8234 TargetLowering::DAGCombinerInfo &DCI,
8235 SelectionDAG &DAG) {
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00008236 SDLoc dl(N);
8237 EVT VT = N->getValueType(0);
8238 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
8239
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00008240 // Optimize concat_vectors of truncated vectors, where the intermediate
8241 // type is illegal, to avoid said illegality, e.g.,
8242 // (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
8243 // (v2i16 (truncate (v2i64)))))
8244 // ->
Ahmed Bougachae6bb09a2015-03-21 01:08:39 +00008245 // (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
8246 // (v4i32 (bitcast (v2i64))),
8247 // <0, 2, 4, 6>)))
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00008248 // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
8249 // on both input and result type, so we might generate worse code.
8250 // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
8251 if (N->getNumOperands() == 2 &&
8252 N0->getOpcode() == ISD::TRUNCATE &&
8253 N1->getOpcode() == ISD::TRUNCATE) {
8254 SDValue N00 = N0->getOperand(0);
8255 SDValue N10 = N1->getOperand(0);
8256 EVT N00VT = N00.getValueType();
8257
8258 if (N00VT == N10.getValueType() &&
8259 (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
8260 N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
Ahmed Bougachae6bb09a2015-03-21 01:08:39 +00008261 MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
8262 SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
8263 for (size_t i = 0; i < Mask.size(); ++i)
8264 Mask[i] = i * 2;
8265 return DAG.getNode(ISD::TRUNCATE, dl, VT,
8266 DAG.getVectorShuffle(
8267 MidVT, dl,
8268 DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
8269 DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00008270 }
8271 }
8272
Tim Northover3b0846e2014-05-24 12:50:23 +00008273 // Wait 'til after everything is legalized to try this. That way we have
8274 // legal vector types and such.
8275 if (DCI.isBeforeLegalizeOps())
8276 return SDValue();
8277
Tim Northover3b0846e2014-05-24 12:50:23 +00008278 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
8279 // splat. The indexed instructions are going to be expecting a DUPLANE64, so
8280 // canonicalise to that.
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00008281 if (N0 == N1 && VT.getVectorNumElements() == 2) {
Sanjay Patel1ed771f2016-09-14 16:37:15 +00008282 assert(VT.getScalarSizeInBits() == 64);
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00008283 return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008284 DAG.getConstant(0, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008285 }
8286
8287 // Canonicalise concat_vectors so that the right-hand vector has as few
8288 // bit-casts as possible before its real operation. The primary matching
8289 // destination for these operations will be the narrowing "2" instructions,
8290 // which depend on the operation being performed on this right-hand vector.
8291 // For example,
8292 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS))))
8293 // becomes
8294 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
8295
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00008296 if (N1->getOpcode() != ISD::BITCAST)
Tim Northover3b0846e2014-05-24 12:50:23 +00008297 return SDValue();
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00008298 SDValue RHS = N1->getOperand(0);
Tim Northover3b0846e2014-05-24 12:50:23 +00008299 MVT RHSTy = RHS.getValueType().getSimpleVT();
8300 // If the RHS is not a vector, this is not the pattern we're looking for.
8301 if (!RHSTy.isVector())
8302 return SDValue();
8303
8304 DEBUG(dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
8305
8306 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
8307 RHSTy.getVectorNumElements() * 2);
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00008308 return DAG.getNode(ISD::BITCAST, dl, VT,
8309 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
8310 DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
8311 RHS));
Tim Northover3b0846e2014-05-24 12:50:23 +00008312}
8313
8314static SDValue tryCombineFixedPointConvert(SDNode *N,
8315 TargetLowering::DAGCombinerInfo &DCI,
8316 SelectionDAG &DAG) {
8317 // Wait 'til after everything is legalized to try this. That way we have
8318 // legal vector types and such.
8319 if (DCI.isBeforeLegalizeOps())
8320 return SDValue();
8321 // Transform a scalar conversion of a value from a lane extract into a
8322 // lane extract of a vector conversion. E.g., from foo1 to foo2:
8323 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
8324 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
8325 //
8326 // The second form interacts better with instruction selection and the
8327 // register allocator to avoid cross-class register copies that aren't
8328 // coalescable due to a lane reference.
8329
8330 // Check the operand and see if it originates from a lane extract.
8331 SDValue Op1 = N->getOperand(1);
8332 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8333 // Yep, no additional predication needed. Perform the transform.
8334 SDValue IID = N->getOperand(0);
8335 SDValue Shift = N->getOperand(2);
8336 SDValue Vec = Op1.getOperand(0);
8337 SDValue Lane = Op1.getOperand(1);
8338 EVT ResTy = N->getValueType(0);
8339 EVT VecResTy;
8340 SDLoc DL(N);
8341
8342 // The vector width should be 128 bits by the time we get here, even
8343 // if it started as 64 bits (the extract_vector handling will have
8344 // done so).
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00008345 assert(Vec.getValueSizeInBits() == 128 &&
Tim Northover3b0846e2014-05-24 12:50:23 +00008346 "unexpected vector size on extract_vector_elt!");
8347 if (Vec.getValueType() == MVT::v4i32)
8348 VecResTy = MVT::v4f32;
8349 else if (Vec.getValueType() == MVT::v2i64)
8350 VecResTy = MVT::v2f64;
8351 else
Craig Topper2a30d782014-06-18 05:05:13 +00008352 llvm_unreachable("unexpected vector type!");
Tim Northover3b0846e2014-05-24 12:50:23 +00008353
8354 SDValue Convert =
8355 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
8356 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
8357 }
8358 return SDValue();
8359}
8360
8361// AArch64 high-vector "long" operations are formed by performing the non-high
8362// version on an extract_subvector of each operand which gets the high half:
8363//
8364// (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
8365//
8366// However, there are cases which don't have an extract_high explicitly, but
8367// have another operation that can be made compatible with one for free. For
8368// example:
8369//
8370// (dupv64 scalar) --> (extract_high (dup128 scalar))
8371//
8372// This routine does the actual conversion of such DUPs, once outer routines
8373// have determined that everything else is in order.
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008374// It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
8375// similarly here.
Tim Northover3b0846e2014-05-24 12:50:23 +00008376static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00008377 switch (N.getOpcode()) {
8378 case AArch64ISD::DUP:
Tim Northover3b0846e2014-05-24 12:50:23 +00008379 case AArch64ISD::DUPLANE8:
8380 case AArch64ISD::DUPLANE16:
8381 case AArch64ISD::DUPLANE32:
8382 case AArch64ISD::DUPLANE64:
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008383 case AArch64ISD::MOVI:
8384 case AArch64ISD::MOVIshift:
8385 case AArch64ISD::MOVIedit:
8386 case AArch64ISD::MOVImsl:
8387 case AArch64ISD::MVNIshift:
8388 case AArch64ISD::MVNImsl:
Tim Northover3b0846e2014-05-24 12:50:23 +00008389 break;
8390 default:
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008391 // FMOV could be supported, but isn't very useful, as it would only occur
8392 // if you passed a bitcast' floating point immediate to an eligible long
8393 // integer op (addl, smull, ...).
Tim Northover3b0846e2014-05-24 12:50:23 +00008394 return SDValue();
8395 }
8396
8397 MVT NarrowTy = N.getSimpleValueType();
8398 if (!NarrowTy.is64BitVector())
8399 return SDValue();
8400
8401 MVT ElementTy = NarrowTy.getVectorElementType();
8402 unsigned NumElems = NarrowTy.getVectorNumElements();
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008403 MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
Tim Northover3b0846e2014-05-24 12:50:23 +00008404
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008405 SDLoc dl(N);
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008406 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
8407 DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008408 DAG.getConstant(NumElems, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008409}
8410
8411static bool isEssentiallyExtractSubvector(SDValue N) {
8412 if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
8413 return true;
8414
8415 return N.getOpcode() == ISD::BITCAST &&
8416 N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
8417}
8418
8419/// \brief Helper structure to keep track of ISD::SET_CC operands.
8420struct GenericSetCCInfo {
8421 const SDValue *Opnd0;
8422 const SDValue *Opnd1;
8423 ISD::CondCode CC;
8424};
8425
8426/// \brief Helper structure to keep track of a SET_CC lowered into AArch64 code.
8427struct AArch64SetCCInfo {
8428 const SDValue *Cmp;
8429 AArch64CC::CondCode CC;
8430};
8431
8432/// \brief Helper structure to keep track of SetCC information.
8433union SetCCInfo {
8434 GenericSetCCInfo Generic;
8435 AArch64SetCCInfo AArch64;
8436};
8437
8438/// \brief Helper structure to be able to read SetCC information. If set to
8439/// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
8440/// GenericSetCCInfo.
8441struct SetCCInfoAndKind {
8442 SetCCInfo Info;
8443 bool IsAArch64;
8444};
8445
8446/// \brief Check whether or not \p Op is a SET_CC operation, either a generic or
8447/// an
8448/// AArch64 lowered one.
8449/// \p SetCCInfo is filled accordingly.
8450/// \post SetCCInfo is meanginfull only when this function returns true.
8451/// \return True when Op is a kind of SET_CC operation.
8452static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
8453 // If this is a setcc, this is straight forward.
8454 if (Op.getOpcode() == ISD::SETCC) {
8455 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
8456 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
8457 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8458 SetCCInfo.IsAArch64 = false;
8459 return true;
8460 }
8461 // Otherwise, check if this is a matching csel instruction.
8462 // In other words:
8463 // - csel 1, 0, cc
8464 // - csel 0, 1, !cc
8465 if (Op.getOpcode() != AArch64ISD::CSEL)
8466 return false;
8467 // Set the information about the operands.
8468 // TODO: we want the operands of the Cmp not the csel
8469 SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
8470 SetCCInfo.IsAArch64 = true;
8471 SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
8472 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
8473
8474 // Check that the operands matches the constraints:
8475 // (1) Both operands must be constants.
8476 // (2) One must be 1 and the other must be 0.
8477 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
8478 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8479
8480 // Check (1).
8481 if (!TValue || !FValue)
8482 return false;
8483
8484 // Check (2).
8485 if (!TValue->isOne()) {
8486 // Update the comparison when we are interested in !cc.
8487 std::swap(TValue, FValue);
8488 SetCCInfo.Info.AArch64.CC =
8489 AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
8490 }
8491 return TValue->isOne() && FValue->isNullValue();
8492}
8493
8494// Returns true if Op is setcc or zext of setcc.
8495static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
8496 if (isSetCC(Op, Info))
8497 return true;
8498 return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
8499 isSetCC(Op->getOperand(0), Info));
8500}
8501
8502// The folding we want to perform is:
8503// (add x, [zext] (setcc cc ...) )
8504// -->
8505// (csel x, (add x, 1), !cc ...)
8506//
8507// The latter will get matched to a CSINC instruction.
8508static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
8509 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
8510 SDValue LHS = Op->getOperand(0);
8511 SDValue RHS = Op->getOperand(1);
8512 SetCCInfoAndKind InfoAndKind;
8513
8514 // If neither operand is a SET_CC, give up.
8515 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
8516 std::swap(LHS, RHS);
8517 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
8518 return SDValue();
8519 }
8520
8521 // FIXME: This could be generatized to work for FP comparisons.
8522 EVT CmpVT = InfoAndKind.IsAArch64
8523 ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
8524 : InfoAndKind.Info.Generic.Opnd0->getValueType();
8525 if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
8526 return SDValue();
8527
8528 SDValue CCVal;
8529 SDValue Cmp;
8530 SDLoc dl(Op);
8531 if (InfoAndKind.IsAArch64) {
8532 CCVal = DAG.getConstant(
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008533 AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
8534 MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00008535 Cmp = *InfoAndKind.Info.AArch64.Cmp;
8536 } else
8537 Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
8538 *InfoAndKind.Info.Generic.Opnd1,
8539 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
8540 CCVal, DAG, dl);
8541
8542 EVT VT = Op->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008543 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
Tim Northover3b0846e2014-05-24 12:50:23 +00008544 return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
8545}
8546
8547// The basic add/sub long vector instructions have variants with "2" on the end
8548// which act on the high-half of their inputs. They are normally matched by
8549// patterns like:
8550//
8551// (add (zeroext (extract_high LHS)),
8552// (zeroext (extract_high RHS)))
8553// -> uaddl2 vD, vN, vM
8554//
8555// However, if one of the extracts is something like a duplicate, this
8556// instruction can still be used profitably. This function puts the DAG into a
8557// more appropriate form for those patterns to trigger.
8558static SDValue performAddSubLongCombine(SDNode *N,
8559 TargetLowering::DAGCombinerInfo &DCI,
8560 SelectionDAG &DAG) {
8561 if (DCI.isBeforeLegalizeOps())
8562 return SDValue();
8563
8564 MVT VT = N->getSimpleValueType(0);
8565 if (!VT.is128BitVector()) {
8566 if (N->getOpcode() == ISD::ADD)
8567 return performSetccAddFolding(N, DAG);
8568 return SDValue();
8569 }
8570
8571 // Make sure both branches are extended in the same way.
8572 SDValue LHS = N->getOperand(0);
8573 SDValue RHS = N->getOperand(1);
8574 if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
8575 LHS.getOpcode() != ISD::SIGN_EXTEND) ||
8576 LHS.getOpcode() != RHS.getOpcode())
8577 return SDValue();
8578
8579 unsigned ExtType = LHS.getOpcode();
8580
8581 // It's not worth doing if at least one of the inputs isn't already an
8582 // extract, but we don't know which it'll be so we have to try both.
8583 if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
8584 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
8585 if (!RHS.getNode())
8586 return SDValue();
8587
8588 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
8589 } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
8590 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
8591 if (!LHS.getNode())
8592 return SDValue();
8593
8594 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
8595 }
8596
8597 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
8598}
8599
8600// Massage DAGs which we can use the high-half "long" operations on into
8601// something isel will recognize better. E.g.
8602//
8603// (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
8604// (aarch64_neon_umull (extract_high (v2i64 vec)))
8605// (extract_high (v2i64 (dup128 scalar)))))
8606//
Hal Finkelcd8664c2015-12-11 23:11:52 +00008607static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
Tim Northover3b0846e2014-05-24 12:50:23 +00008608 TargetLowering::DAGCombinerInfo &DCI,
8609 SelectionDAG &DAG) {
8610 if (DCI.isBeforeLegalizeOps())
8611 return SDValue();
8612
Hal Finkelcd8664c2015-12-11 23:11:52 +00008613 SDValue LHS = N->getOperand(1);
8614 SDValue RHS = N->getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00008615 assert(LHS.getValueType().is64BitVector() &&
8616 RHS.getValueType().is64BitVector() &&
8617 "unexpected shape for long operation");
8618
8619 // Either node could be a DUP, but it's not worth doing both of them (you'd
8620 // just as well use the non-high version) so look for a corresponding extract
8621 // operation on the other "wing".
8622 if (isEssentiallyExtractSubvector(LHS)) {
8623 RHS = tryExtendDUPToExtractHigh(RHS, DAG);
8624 if (!RHS.getNode())
8625 return SDValue();
8626 } else if (isEssentiallyExtractSubvector(RHS)) {
8627 LHS = tryExtendDUPToExtractHigh(LHS, DAG);
8628 if (!LHS.getNode())
8629 return SDValue();
8630 }
8631
Hal Finkelcd8664c2015-12-11 23:11:52 +00008632 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
8633 N->getOperand(0), LHS, RHS);
Tim Northover3b0846e2014-05-24 12:50:23 +00008634}
8635
8636static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
8637 MVT ElemTy = N->getSimpleValueType(0).getScalarType();
8638 unsigned ElemBits = ElemTy.getSizeInBits();
8639
8640 int64_t ShiftAmount;
8641 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
8642 APInt SplatValue, SplatUndef;
8643 unsigned SplatBitSize;
8644 bool HasAnyUndefs;
8645 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
8646 HasAnyUndefs, ElemBits) ||
8647 SplatBitSize != ElemBits)
8648 return SDValue();
8649
8650 ShiftAmount = SplatValue.getSExtValue();
8651 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
8652 ShiftAmount = CVN->getSExtValue();
8653 } else
8654 return SDValue();
8655
8656 unsigned Opcode;
8657 bool IsRightShift;
8658 switch (IID) {
8659 default:
8660 llvm_unreachable("Unknown shift intrinsic");
8661 case Intrinsic::aarch64_neon_sqshl:
8662 Opcode = AArch64ISD::SQSHL_I;
8663 IsRightShift = false;
8664 break;
8665 case Intrinsic::aarch64_neon_uqshl:
8666 Opcode = AArch64ISD::UQSHL_I;
8667 IsRightShift = false;
8668 break;
8669 case Intrinsic::aarch64_neon_srshl:
8670 Opcode = AArch64ISD::SRSHR_I;
8671 IsRightShift = true;
8672 break;
8673 case Intrinsic::aarch64_neon_urshl:
8674 Opcode = AArch64ISD::URSHR_I;
8675 IsRightShift = true;
8676 break;
8677 case Intrinsic::aarch64_neon_sqshlu:
8678 Opcode = AArch64ISD::SQSHLU_I;
8679 IsRightShift = false;
8680 break;
8681 }
8682
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008683 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
8684 SDLoc dl(N);
8685 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8686 DAG.getConstant(-ShiftAmount, dl, MVT::i32));
8687 } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
8688 SDLoc dl(N);
8689 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8690 DAG.getConstant(ShiftAmount, dl, MVT::i32));
8691 }
Tim Northover3b0846e2014-05-24 12:50:23 +00008692
8693 return SDValue();
8694}
8695
8696// The CRC32[BH] instructions ignore the high bits of their data operand. Since
8697// the intrinsics must be legal and take an i32, this means there's almost
8698// certainly going to be a zext in the DAG which we can eliminate.
8699static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
8700 SDValue AndN = N->getOperand(2);
8701 if (AndN.getOpcode() != ISD::AND)
8702 return SDValue();
8703
8704 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
8705 if (!CMask || CMask->getZExtValue() != Mask)
8706 return SDValue();
8707
8708 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
8709 N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
8710}
8711
Ahmed Bougachafab58922015-03-10 20:45:38 +00008712static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
8713 SelectionDAG &DAG) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008714 SDLoc dl(N);
8715 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
8716 DAG.getNode(Opc, dl,
Ahmed Bougachafab58922015-03-10 20:45:38 +00008717 N->getOperand(1).getSimpleValueType(),
8718 N->getOperand(1)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008719 DAG.getConstant(0, dl, MVT::i64));
Ahmed Bougachafab58922015-03-10 20:45:38 +00008720}
8721
Tim Northover3b0846e2014-05-24 12:50:23 +00008722static SDValue performIntrinsicCombine(SDNode *N,
8723 TargetLowering::DAGCombinerInfo &DCI,
8724 const AArch64Subtarget *Subtarget) {
8725 SelectionDAG &DAG = DCI.DAG;
8726 unsigned IID = getIntrinsicID(N);
8727 switch (IID) {
8728 default:
8729 break;
8730 case Intrinsic::aarch64_neon_vcvtfxs2fp:
8731 case Intrinsic::aarch64_neon_vcvtfxu2fp:
8732 return tryCombineFixedPointConvert(N, DCI, DAG);
Ahmed Bougachafab58922015-03-10 20:45:38 +00008733 case Intrinsic::aarch64_neon_saddv:
8734 return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
8735 case Intrinsic::aarch64_neon_uaddv:
8736 return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
8737 case Intrinsic::aarch64_neon_sminv:
8738 return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
8739 case Intrinsic::aarch64_neon_uminv:
8740 return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
8741 case Intrinsic::aarch64_neon_smaxv:
8742 return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
8743 case Intrinsic::aarch64_neon_umaxv:
8744 return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00008745 case Intrinsic::aarch64_neon_fmax:
James Molloyedf38f02015-08-11 12:06:33 +00008746 return DAG.getNode(ISD::FMAXNAN, SDLoc(N), N->getValueType(0),
Tim Northover3b0846e2014-05-24 12:50:23 +00008747 N->getOperand(1), N->getOperand(2));
8748 case Intrinsic::aarch64_neon_fmin:
James Molloyedf38f02015-08-11 12:06:33 +00008749 return DAG.getNode(ISD::FMINNAN, SDLoc(N), N->getValueType(0),
Tim Northover3b0846e2014-05-24 12:50:23 +00008750 N->getOperand(1), N->getOperand(2));
James Molloyb7b2a1e2015-08-11 12:06:37 +00008751 case Intrinsic::aarch64_neon_fmaxnm:
8752 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
8753 N->getOperand(1), N->getOperand(2));
8754 case Intrinsic::aarch64_neon_fminnm:
8755 return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
8756 N->getOperand(1), N->getOperand(2));
Tim Northover3b0846e2014-05-24 12:50:23 +00008757 case Intrinsic::aarch64_neon_smull:
8758 case Intrinsic::aarch64_neon_umull:
8759 case Intrinsic::aarch64_neon_pmull:
8760 case Intrinsic::aarch64_neon_sqdmull:
Hal Finkelcd8664c2015-12-11 23:11:52 +00008761 return tryCombineLongOpWithDup(IID, N, DCI, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00008762 case Intrinsic::aarch64_neon_sqshl:
8763 case Intrinsic::aarch64_neon_uqshl:
8764 case Intrinsic::aarch64_neon_sqshlu:
8765 case Intrinsic::aarch64_neon_srshl:
8766 case Intrinsic::aarch64_neon_urshl:
8767 return tryCombineShiftImm(IID, N, DAG);
8768 case Intrinsic::aarch64_crc32b:
8769 case Intrinsic::aarch64_crc32cb:
8770 return tryCombineCRC32(0xff, N, DAG);
8771 case Intrinsic::aarch64_crc32h:
8772 case Intrinsic::aarch64_crc32ch:
8773 return tryCombineCRC32(0xffff, N, DAG);
8774 }
8775 return SDValue();
8776}
8777
8778static SDValue performExtendCombine(SDNode *N,
8779 TargetLowering::DAGCombinerInfo &DCI,
8780 SelectionDAG &DAG) {
8781 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
8782 // we can convert that DUP into another extract_high (of a bigger DUP), which
8783 // helps the backend to decide that an sabdl2 would be useful, saving a real
8784 // extract_high operation.
8785 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
Hal Finkelcd8664c2015-12-11 23:11:52 +00008786 N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
Tim Northover3b0846e2014-05-24 12:50:23 +00008787 SDNode *ABDNode = N->getOperand(0).getNode();
Hal Finkelcd8664c2015-12-11 23:11:52 +00008788 unsigned IID = getIntrinsicID(ABDNode);
8789 if (IID == Intrinsic::aarch64_neon_sabd ||
8790 IID == Intrinsic::aarch64_neon_uabd) {
8791 SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
8792 if (!NewABD.getNode())
8793 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00008794
Hal Finkelcd8664c2015-12-11 23:11:52 +00008795 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
8796 NewABD);
8797 }
Tim Northover3b0846e2014-05-24 12:50:23 +00008798 }
8799
8800 // This is effectively a custom type legalization for AArch64.
8801 //
8802 // Type legalization will split an extend of a small, legal, type to a larger
8803 // illegal type by first splitting the destination type, often creating
8804 // illegal source types, which then get legalized in isel-confusing ways,
8805 // leading to really terrible codegen. E.g.,
8806 // %result = v8i32 sext v8i8 %value
8807 // becomes
8808 // %losrc = extract_subreg %value, ...
8809 // %hisrc = extract_subreg %value, ...
8810 // %lo = v4i32 sext v4i8 %losrc
8811 // %hi = v4i32 sext v4i8 %hisrc
8812 // Things go rapidly downhill from there.
8813 //
8814 // For AArch64, the [sz]ext vector instructions can only go up one element
8815 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
8816 // take two instructions.
8817 //
8818 // This implies that the most efficient way to do the extend from v8i8
8819 // to two v4i32 values is to first extend the v8i8 to v8i16, then do
8820 // the normal splitting to happen for the v8i16->v8i32.
8821
8822 // This is pre-legalization to catch some cases where the default
8823 // type legalization will create ill-tempered code.
8824 if (!DCI.isBeforeLegalizeOps())
8825 return SDValue();
8826
8827 // We're only interested in cleaning things up for non-legal vector types
8828 // here. If both the source and destination are legal, things will just
8829 // work naturally without any fiddling.
Matthew Simpson13dddb02015-12-17 21:29:47 +00008830 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00008831 EVT ResVT = N->getValueType(0);
8832 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
8833 return SDValue();
8834 // If the vector type isn't a simple VT, it's beyond the scope of what
8835 // we're worried about here. Let legalization do its thing and hope for
8836 // the best.
Jim Grosbachec2b0d02014-08-28 22:08:28 +00008837 SDValue Src = N->getOperand(0);
8838 EVT SrcVT = Src->getValueType(0);
8839 if (!ResVT.isSimple() || !SrcVT.isSimple())
Tim Northover3b0846e2014-05-24 12:50:23 +00008840 return SDValue();
8841
Tim Northover3b0846e2014-05-24 12:50:23 +00008842 // If the source VT is a 64-bit vector, we can play games and get the
8843 // better results we want.
8844 if (SrcVT.getSizeInBits() != 64)
8845 return SDValue();
8846
Sanjay Patel1ed771f2016-09-14 16:37:15 +00008847 unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00008848 unsigned ElementCount = SrcVT.getVectorNumElements();
8849 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
8850 SDLoc DL(N);
8851 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
8852
8853 // Now split the rest of the operation into two halves, each with a 64
8854 // bit source.
8855 EVT LoVT, HiVT;
8856 SDValue Lo, Hi;
8857 unsigned NumElements = ResVT.getVectorNumElements();
8858 assert(!(NumElements & 1) && "Splitting vector, but not in half!");
8859 LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
8860 ResVT.getVectorElementType(), NumElements / 2);
8861
8862 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
8863 LoVT.getVectorNumElements());
8864 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008865 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008866 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008867 DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008868 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
8869 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
8870
8871 // Now combine the parts back together so we still have a single result
8872 // like the combiner expects.
8873 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
8874}
8875
Geoff Berry8301c642016-11-16 19:35:19 +00008876static SDValue splitStoreSplat(SelectionDAG &DAG, StoreSDNode &St,
8877 SDValue SplatVal, unsigned NumVecElts) {
Geoff Berrye8de67ab2016-11-14 19:59:11 +00008878 unsigned OrigAlignment = St.getAlignment();
Geoff Berry8301c642016-11-16 19:35:19 +00008879 unsigned EltOffset = SplatVal.getValueType().getSizeInBits() / 8;
Geoff Berrydef4bfa2016-11-14 19:39:00 +00008880
8881 // Create scalar stores. This is at least as good as the code sequence for a
8882 // split unaligned store which is a dup.s, ext.b, and two stores.
8883 // Most of the time the three stores should be replaced by store pair
8884 // instructions (stp).
Geoff Berrye8de67ab2016-11-14 19:59:11 +00008885 SDLoc DL(&St);
8886 SDValue BasePtr = St.getBasePtr();
Geoff Berrydef4bfa2016-11-14 19:39:00 +00008887 SDValue NewST1 =
Geoff Berrye8de67ab2016-11-14 19:59:11 +00008888 DAG.getStore(St.getChain(), DL, SplatVal, BasePtr, St.getPointerInfo(),
Geoff Berry8301c642016-11-16 19:35:19 +00008889 OrigAlignment, St.getMemOperand()->getFlags());
Geoff Berrydef4bfa2016-11-14 19:39:00 +00008890
8891 unsigned Offset = EltOffset;
8892 while (--NumVecElts) {
Geoff Berry8301c642016-11-16 19:35:19 +00008893 unsigned Alignment = MinAlign(OrigAlignment, Offset);
Geoff Berrydef4bfa2016-11-14 19:39:00 +00008894 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
8895 DAG.getConstant(Offset, DL, MVT::i64));
8896 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
Geoff Berrye8de67ab2016-11-14 19:59:11 +00008897 St.getPointerInfo(), Alignment,
8898 St.getMemOperand()->getFlags());
Geoff Berrydef4bfa2016-11-14 19:39:00 +00008899 Offset += EltOffset;
8900 }
8901 return NewST1;
8902}
8903
Geoff Berry526c5052016-11-14 19:39:04 +00008904/// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR. The
8905/// load store optimizer pass will merge them to store pair stores. This should
8906/// be better than a movi to create the vector zero followed by a vector store
8907/// if the zero constant is not re-used, since one instructions and one register
8908/// live range will be removed.
8909///
8910/// For example, the final generated code should be:
8911///
8912/// stp xzr, xzr, [x0]
8913///
8914/// instead of:
8915///
8916/// movi v0.2d, #0
8917/// str q0, [x0]
8918///
Geoff Berrye8de67ab2016-11-14 19:59:11 +00008919static SDValue replaceZeroVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
8920 SDValue StVal = St.getValue();
Geoff Berry526c5052016-11-14 19:39:04 +00008921 EVT VT = StVal.getValueType();
8922
Geoff Berry8301c642016-11-16 19:35:19 +00008923 // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or
8924 // 2, 3 or 4 i32 elements.
Geoff Berry526c5052016-11-14 19:39:04 +00008925 int NumVecElts = VT.getVectorNumElements();
Geoff Berry8301c642016-11-16 19:35:19 +00008926 if (!(((NumVecElts == 2 || NumVecElts == 3) &&
8927 VT.getVectorElementType().getSizeInBits() == 64) ||
8928 ((NumVecElts == 2 || NumVecElts == 3 || NumVecElts == 4) &&
8929 VT.getVectorElementType().getSizeInBits() == 32)))
Geoff Berry526c5052016-11-14 19:39:04 +00008930 return SDValue();
8931
8932 if (StVal.getOpcode() != ISD::BUILD_VECTOR)
8933 return SDValue();
8934
8935 // If the zero constant has more than one use then the vector store could be
8936 // better since the constant mov will be amortized and stp q instructions
8937 // should be able to be formed.
8938 if (!StVal.hasOneUse())
8939 return SDValue();
8940
8941 // If the immediate offset of the address operand is too large for the stp
8942 // instruction, then bail out.
Geoff Berrye8de67ab2016-11-14 19:59:11 +00008943 if (DAG.isBaseWithConstantOffset(St.getBasePtr())) {
8944 int64_t Offset = St.getBasePtr()->getConstantOperandVal(1);
Geoff Berry526c5052016-11-14 19:39:04 +00008945 if (Offset < -512 || Offset > 504)
8946 return SDValue();
8947 }
8948
8949 for (int I = 0; I < NumVecElts; ++I) {
8950 SDValue EltVal = StVal.getOperand(I);
Geoff Berry8301c642016-11-16 19:35:19 +00008951 if (!isNullConstant(EltVal) && !isNullFPConstant(EltVal))
Geoff Berry526c5052016-11-14 19:39:04 +00008952 return SDValue();
8953 }
Geoff Berry8301c642016-11-16 19:35:19 +00008954
Geoff Berry526c5052016-11-14 19:39:04 +00008955 // Use WZR/XZR here to prevent DAGCombiner::MergeConsecutiveStores from
8956 // undoing this transformation.
Geoff Berry8301c642016-11-16 19:35:19 +00008957 SDValue SplatVal = VT.getVectorElementType().getSizeInBits() == 32
8958 ? DAG.getRegister(AArch64::WZR, MVT::i32)
8959 : DAG.getRegister(AArch64::XZR, MVT::i64);
8960 return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
Geoff Berry526c5052016-11-14 19:39:04 +00008961}
8962
Tim Northover3b0846e2014-05-24 12:50:23 +00008963/// Replace a splat of a scalar to a vector store by scalar stores of the scalar
8964/// value. The load store optimizer pass will merge them to store pair stores.
8965/// This has better performance than a splat of the scalar followed by a split
8966/// vector store. Even if the stores are not merged it is four stores vs a dup,
8967/// followed by an ext.b and two stores.
Geoff Berrye8de67ab2016-11-14 19:59:11 +00008968static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
8969 SDValue StVal = St.getValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00008970 EVT VT = StVal.getValueType();
8971
8972 // Don't replace floating point stores, they possibly won't be transformed to
8973 // stp because of the store pair suppress pass.
8974 if (VT.isFloatingPoint())
8975 return SDValue();
8976
Tim Northover3b0846e2014-05-24 12:50:23 +00008977 // We can express a splat as store pair(s) for 2 or 4 elements.
8978 unsigned NumVecElts = VT.getVectorNumElements();
8979 if (NumVecElts != 4 && NumVecElts != 2)
8980 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00008981
8982 // Check that this is a splat.
Geoff Berry25fa4992016-11-11 19:25:20 +00008983 // Make sure that each of the relevant vector element locations are inserted
8984 // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32.
8985 std::bitset<4> IndexNotInserted((1 << NumVecElts) - 1);
8986 SDValue SplatVal;
8987 for (unsigned I = 0; I < NumVecElts; ++I) {
8988 // Check for insert vector elements.
8989 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
Tim Northover3b0846e2014-05-24 12:50:23 +00008990 return SDValue();
Geoff Berry25fa4992016-11-11 19:25:20 +00008991
8992 // Check that same value is inserted at each vector element.
8993 if (I == 0)
8994 SplatVal = StVal.getOperand(1);
8995 else if (StVal.getOperand(1) != SplatVal)
Tim Northover3b0846e2014-05-24 12:50:23 +00008996 return SDValue();
Geoff Berry25fa4992016-11-11 19:25:20 +00008997
8998 // Check insert element index.
8999 ConstantSDNode *CIndex = dyn_cast<ConstantSDNode>(StVal.getOperand(2));
9000 if (!CIndex)
9001 return SDValue();
9002 uint64_t IndexVal = CIndex->getZExtValue();
9003 if (IndexVal >= NumVecElts)
9004 return SDValue();
9005 IndexNotInserted.reset(IndexVal);
9006
9007 StVal = StVal.getOperand(0);
Tim Northover3b0846e2014-05-24 12:50:23 +00009008 }
Geoff Berry25fa4992016-11-11 19:25:20 +00009009 // Check that all vector element locations were inserted to.
9010 if (IndexNotInserted.any())
9011 return SDValue();
9012
Geoff Berry8301c642016-11-16 19:35:19 +00009013 return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
Tim Northover3b0846e2014-05-24 12:50:23 +00009014}
9015
Geoff Berry8301c642016-11-16 19:35:19 +00009016static SDValue splitStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
9017 SelectionDAG &DAG,
9018 const AArch64Subtarget *Subtarget) {
Tim Northover3b0846e2014-05-24 12:50:23 +00009019 if (!DCI.isBeforeLegalize())
9020 return SDValue();
9021
9022 StoreSDNode *S = cast<StoreSDNode>(N);
9023 if (S->isVolatile())
9024 return SDValue();
9025
Geoff Berry526c5052016-11-14 19:39:04 +00009026 SDValue StVal = S->getValue();
9027 EVT VT = StVal.getValueType();
9028 if (!VT.isVector())
9029 return SDValue();
9030
9031 // If we get a splat of zeros, convert this vector store to a store of
9032 // scalars. They will be merged into store pairs of xzr thereby removing one
9033 // instruction and one register.
Geoff Berrye8de67ab2016-11-14 19:59:11 +00009034 if (SDValue ReplacedZeroSplat = replaceZeroVectorStore(DAG, *S))
Geoff Berry526c5052016-11-14 19:39:04 +00009035 return ReplacedZeroSplat;
9036
Sanjay Patelbbbf9a12015-09-25 21:49:48 +00009037 // FIXME: The logic for deciding if an unaligned store should be split should
9038 // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
9039 // a call to that function here.
9040
Matthias Braun651cff42016-06-02 18:03:53 +00009041 if (!Subtarget->isMisaligned128StoreSlow())
Tim Northover3b0846e2014-05-24 12:50:23 +00009042 return SDValue();
9043
Sanjay Patel924879a2015-08-04 15:49:57 +00009044 // Don't split at -Oz.
9045 if (DAG.getMachineFunction().getFunction()->optForMinSize())
Tim Northover3b0846e2014-05-24 12:50:23 +00009046 return SDValue();
9047
Tim Northover3b0846e2014-05-24 12:50:23 +00009048 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
9049 // those up regresses performance on micro-benchmarks and olden/bh.
Geoff Berry526c5052016-11-14 19:39:04 +00009050 if (VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
Tim Northover3b0846e2014-05-24 12:50:23 +00009051 return SDValue();
9052
9053 // Split unaligned 16B stores. They are terrible for performance.
9054 // Don't split stores with alignment of 1 or 2. Code that uses clang vector
9055 // extensions can use this to mark that it does not want splitting to happen
9056 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
9057 // eliminating alignment hazards is only 1 in 8 for alignment of 2.
9058 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
9059 S->getAlignment() <= 2)
9060 return SDValue();
9061
9062 // If we get a splat of a scalar convert this vector store to a store of
9063 // scalars. They will be merged into store pairs thereby removing two
9064 // instructions.
Geoff Berrye8de67ab2016-11-14 19:59:11 +00009065 if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, *S))
Tim Northover3b0846e2014-05-24 12:50:23 +00009066 return ReplacedSplat;
9067
9068 SDLoc DL(S);
9069 unsigned NumElts = VT.getVectorNumElements() / 2;
9070 // Split VT into two.
9071 EVT HalfVT =
9072 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
9073 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009074 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00009075 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009076 DAG.getConstant(NumElts, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00009077 SDValue BasePtr = S->getBasePtr();
9078 SDValue NewST1 =
9079 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
Justin Lebar9c375812016-07-15 18:27:10 +00009080 S->getAlignment(), S->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +00009081 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009082 DAG.getConstant(8, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00009083 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
Justin Lebar9c375812016-07-15 18:27:10 +00009084 S->getPointerInfo(), S->getAlignment(),
9085 S->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +00009086}
9087
9088/// Target-specific DAG combine function for post-increment LD1 (lane) and
9089/// post-increment LD1R.
9090static SDValue performPostLD1Combine(SDNode *N,
9091 TargetLowering::DAGCombinerInfo &DCI,
9092 bool IsLaneOp) {
9093 if (DCI.isBeforeLegalizeOps())
9094 return SDValue();
9095
9096 SelectionDAG &DAG = DCI.DAG;
9097 EVT VT = N->getValueType(0);
9098
9099 unsigned LoadIdx = IsLaneOp ? 1 : 0;
9100 SDNode *LD = N->getOperand(LoadIdx).getNode();
9101 // If it is not LOAD, can not do such combine.
9102 if (LD->getOpcode() != ISD::LOAD)
9103 return SDValue();
9104
9105 LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
9106 EVT MemVT = LoadSDN->getMemoryVT();
9107 // Check if memory operand is the same type as the vector element.
9108 if (MemVT != VT.getVectorElementType())
9109 return SDValue();
9110
9111 // Check if there are other uses. If so, do not combine as it will introduce
9112 // an extra load.
9113 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
9114 ++UI) {
9115 if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
9116 continue;
9117 if (*UI != N)
9118 return SDValue();
9119 }
9120
9121 SDValue Addr = LD->getOperand(1);
9122 SDValue Vector = N->getOperand(0);
9123 // Search for a use of the address operand that is an increment.
9124 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
9125 Addr.getNode()->use_end(); UI != UE; ++UI) {
9126 SDNode *User = *UI;
9127 if (User->getOpcode() != ISD::ADD
9128 || UI.getUse().getResNo() != Addr.getResNo())
9129 continue;
9130
9131 // Check that the add is independent of the load. Otherwise, folding it
9132 // would create a cycle.
9133 if (User->isPredecessorOf(LD) || LD->isPredecessorOf(User))
9134 continue;
9135 // Also check that add is not used in the vector operand. This would also
9136 // create a cycle.
9137 if (User->isPredecessorOf(Vector.getNode()))
9138 continue;
9139
9140 // If the increment is a constant, it must match the memory ref size.
9141 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9142 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9143 uint32_t IncVal = CInc->getZExtValue();
9144 unsigned NumBytes = VT.getScalarSizeInBits() / 8;
9145 if (IncVal != NumBytes)
9146 continue;
9147 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
9148 }
9149
Ahmed Bougacha2448ef52015-04-17 21:02:30 +00009150 // Finally, check that the vector doesn't depend on the load.
9151 // Again, this would create a cycle.
9152 // The load depending on the vector is fine, as that's the case for the
9153 // LD1*post we'll eventually generate anyway.
9154 if (LoadSDN->isPredecessorOf(Vector.getNode()))
9155 continue;
9156
Tim Northover3b0846e2014-05-24 12:50:23 +00009157 SmallVector<SDValue, 8> Ops;
9158 Ops.push_back(LD->getOperand(0)); // Chain
9159 if (IsLaneOp) {
9160 Ops.push_back(Vector); // The vector to be inserted
9161 Ops.push_back(N->getOperand(2)); // The lane to be inserted in the vector
9162 }
9163 Ops.push_back(Addr);
9164 Ops.push_back(Inc);
9165
9166 EVT Tys[3] = { VT, MVT::i64, MVT::Other };
Craig Toppere1d12942014-08-27 05:25:25 +00009167 SDVTList SDTys = DAG.getVTList(Tys);
Tim Northover3b0846e2014-05-24 12:50:23 +00009168 unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
9169 SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
9170 MemVT,
9171 LoadSDN->getMemOperand());
9172
9173 // Update the uses.
Benjamin Kramer3bc1edf2016-07-02 11:41:39 +00009174 SDValue NewResults[] = {
9175 SDValue(LD, 0), // The result of load
9176 SDValue(UpdN.getNode(), 2) // Chain
9177 };
Tim Northover3b0846e2014-05-24 12:50:23 +00009178 DCI.CombineTo(LD, NewResults);
9179 DCI.CombineTo(N, SDValue(UpdN.getNode(), 0)); // Dup/Inserted Result
9180 DCI.CombineTo(User, SDValue(UpdN.getNode(), 1)); // Write back register
9181
9182 break;
9183 }
9184 return SDValue();
9185}
9186
Tim Northover339c83e2015-11-10 00:44:23 +00009187/// Simplify \Addr given that the top byte of it is ignored by HW during
9188/// address translation.
9189static bool performTBISimplification(SDValue Addr,
9190 TargetLowering::DAGCombinerInfo &DCI,
9191 SelectionDAG &DAG) {
9192 APInt DemandedMask = APInt::getLowBitsSet(64, 56);
9193 APInt KnownZero, KnownOne;
9194 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
9195 DCI.isBeforeLegalizeOps());
9196 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9197 if (TLI.SimplifyDemandedBits(Addr, DemandedMask, KnownZero, KnownOne, TLO)) {
9198 DCI.CommitTargetLoweringOpt(TLO);
9199 return true;
9200 }
9201 return false;
9202}
9203
9204static SDValue performSTORECombine(SDNode *N,
9205 TargetLowering::DAGCombinerInfo &DCI,
9206 SelectionDAG &DAG,
9207 const AArch64Subtarget *Subtarget) {
Geoff Berry8301c642016-11-16 19:35:19 +00009208 if (SDValue Split = splitStores(N, DCI, DAG, Subtarget))
Tim Northover339c83e2015-11-10 00:44:23 +00009209 return Split;
9210
9211 if (Subtarget->supportsAddressTopByteIgnored() &&
9212 performTBISimplification(N->getOperand(2), DCI, DAG))
9213 return SDValue(N, 0);
9214
9215 return SDValue();
9216}
9217
9218 /// This function handles the log2-shuffle pattern produced by the
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009219/// LoopVectorizer for the across vector reduction. It consists of
9220/// log2(NumVectorElements) steps and, in each step, 2^(s) elements
9221/// are reduced, where s is an induction variable from 0 to
9222/// log2(NumVectorElements).
9223static SDValue tryMatchAcrossLaneShuffleForReduction(SDNode *N, SDValue OpV,
9224 unsigned Op,
9225 SelectionDAG &DAG) {
9226 EVT VTy = OpV->getOperand(0).getValueType();
9227 if (!VTy.isVector())
Chad Rosier6c36eff2015-09-03 18:13:57 +00009228 return SDValue();
9229
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009230 int NumVecElts = VTy.getVectorNumElements();
Jun Bum Lim0aace132015-10-09 14:11:25 +00009231 if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) {
9232 if (NumVecElts != 4)
9233 return SDValue();
9234 } else {
9235 if (NumVecElts != 4 && NumVecElts != 8 && NumVecElts != 16)
9236 return SDValue();
9237 }
Chad Rosier6c36eff2015-09-03 18:13:57 +00009238
9239 int NumExpectedSteps = APInt(8, NumVecElts).logBase2();
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009240 SDValue PreOp = OpV;
Chad Rosier6c36eff2015-09-03 18:13:57 +00009241 // Iterate over each step of the across vector reduction.
9242 for (int CurStep = 0; CurStep != NumExpectedSteps; ++CurStep) {
Chad Rosier6c36eff2015-09-03 18:13:57 +00009243 SDValue CurOp = PreOp.getOperand(0);
9244 SDValue Shuffle = PreOp.getOperand(1);
9245 if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE) {
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009246 // Try to swap the 1st and 2nd operand as add and min/max instructions
9247 // are commutative.
Chad Rosier6c36eff2015-09-03 18:13:57 +00009248 CurOp = PreOp.getOperand(1);
9249 Shuffle = PreOp.getOperand(0);
9250 if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE)
9251 return SDValue();
9252 }
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009253
9254 // Check if the input vector is fed by the operator we want to handle,
9255 // except the last step; the very first input vector is not necessarily
9256 // the same operator we are handling.
9257 if (CurOp.getOpcode() != Op && (CurStep != (NumExpectedSteps - 1)))
9258 return SDValue();
9259
Chad Rosier6c36eff2015-09-03 18:13:57 +00009260 // Check if it forms one step of the across vector reduction.
9261 // E.g.,
9262 // %cur = add %1, %0
9263 // %shuffle = vector_shuffle %cur, <2, 3, u, u>
9264 // %pre = add %cur, %shuffle
9265 if (Shuffle.getOperand(0) != CurOp)
9266 return SDValue();
9267
9268 int NumMaskElts = 1 << CurStep;
9269 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Shuffle)->getMask();
9270 // Check mask values in each step.
9271 // We expect the shuffle mask in each step follows a specific pattern
9272 // denoted here by the <M, U> form, where M is a sequence of integers
9273 // starting from NumMaskElts, increasing by 1, and the number integers
9274 // in M should be NumMaskElts. U is a sequence of UNDEFs and the number
9275 // of undef in U should be NumVecElts - NumMaskElts.
9276 // E.g., for <8 x i16>, mask values in each step should be :
9277 // step 0 : <1,u,u,u,u,u,u,u>
9278 // step 1 : <2,3,u,u,u,u,u,u>
9279 // step 2 : <4,5,6,7,u,u,u,u>
9280 for (int i = 0; i < NumVecElts; ++i)
9281 if ((i < NumMaskElts && Mask[i] != (NumMaskElts + i)) ||
9282 (i >= NumMaskElts && !(Mask[i] < 0)))
9283 return SDValue();
9284
9285 PreOp = CurOp;
9286 }
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009287 unsigned Opcode;
Jun Bum Lim0aace132015-10-09 14:11:25 +00009288 bool IsIntrinsic = false;
9289
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009290 switch (Op) {
9291 default:
9292 llvm_unreachable("Unexpected operator for across vector reduction");
9293 case ISD::ADD:
9294 Opcode = AArch64ISD::UADDV;
9295 break;
9296 case ISD::SMAX:
9297 Opcode = AArch64ISD::SMAXV;
9298 break;
9299 case ISD::UMAX:
9300 Opcode = AArch64ISD::UMAXV;
9301 break;
9302 case ISD::SMIN:
9303 Opcode = AArch64ISD::SMINV;
9304 break;
9305 case ISD::UMIN:
9306 Opcode = AArch64ISD::UMINV;
9307 break;
Jun Bum Lim0aace132015-10-09 14:11:25 +00009308 case ISD::FMAXNUM:
9309 Opcode = Intrinsic::aarch64_neon_fmaxnmv;
9310 IsIntrinsic = true;
9311 break;
9312 case ISD::FMINNUM:
9313 Opcode = Intrinsic::aarch64_neon_fminnmv;
9314 IsIntrinsic = true;
9315 break;
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009316 }
Chad Rosier6c36eff2015-09-03 18:13:57 +00009317 SDLoc DL(N);
Jun Bum Lim0aace132015-10-09 14:11:25 +00009318
9319 return IsIntrinsic
9320 ? DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, N->getValueType(0),
9321 DAG.getConstant(Opcode, DL, MVT::i32), PreOp)
9322 : DAG.getNode(
9323 ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0),
9324 DAG.getNode(Opcode, DL, PreOp.getSimpleValueType(), PreOp),
9325 DAG.getConstant(0, DL, MVT::i64));
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009326}
9327
9328/// Target-specific DAG combine for the across vector min/max reductions.
9329/// This function specifically handles the final clean-up step of the vector
9330/// min/max reductions produced by the LoopVectorizer. It is the log2-shuffle
9331/// pattern, which narrows down and finds the final min/max value from all
9332/// elements of the vector.
9333/// For example, for a <16 x i8> vector :
9334/// svn0 = vector_shuffle %0, undef<8,9,10,11,12,13,14,15,u,u,u,u,u,u,u,u>
9335/// %smax0 = smax %arr, svn0
9336/// %svn1 = vector_shuffle %smax0, undef<4,5,6,7,u,u,u,u,u,u,u,u,u,u,u,u>
9337/// %smax1 = smax %smax0, %svn1
9338/// %svn2 = vector_shuffle %smax1, undef<2,3,u,u,u,u,u,u,u,u,u,u,u,u,u,u>
9339/// %smax2 = smax %smax1, svn2
9340/// %svn3 = vector_shuffle %smax2, undef<1,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u>
9341/// %sc = setcc %smax2, %svn3, gt
9342/// %n0 = extract_vector_elt %sc, #0
9343/// %n1 = extract_vector_elt %smax2, #0
9344/// %n2 = extract_vector_elt $smax2, #1
9345/// %result = select %n0, %n1, n2
9346/// becomes :
9347/// %1 = smaxv %0
9348/// %result = extract_vector_elt %1, 0
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009349static SDValue
9350performAcrossLaneMinMaxReductionCombine(SDNode *N, SelectionDAG &DAG,
9351 const AArch64Subtarget *Subtarget) {
9352 if (!Subtarget->hasNEON())
9353 return SDValue();
9354
9355 SDValue N0 = N->getOperand(0);
9356 SDValue IfTrue = N->getOperand(1);
9357 SDValue IfFalse = N->getOperand(2);
9358
9359 // Check if the SELECT merges up the final result of the min/max
9360 // from a vector.
9361 if (N0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9362 IfTrue.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9363 IfFalse.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9364 return SDValue();
9365
9366 // Expect N0 is fed by SETCC.
9367 SDValue SetCC = N0.getOperand(0);
9368 EVT SetCCVT = SetCC.getValueType();
9369 if (SetCC.getOpcode() != ISD::SETCC || !SetCCVT.isVector() ||
9370 SetCCVT.getVectorElementType() != MVT::i1)
9371 return SDValue();
9372
9373 SDValue VectorOp = SetCC.getOperand(0);
9374 unsigned Op = VectorOp->getOpcode();
9375 // Check if the input vector is fed by the operator we want to handle.
Jun Bum Lim0aace132015-10-09 14:11:25 +00009376 if (Op != ISD::SMAX && Op != ISD::UMAX && Op != ISD::SMIN &&
9377 Op != ISD::UMIN && Op != ISD::FMAXNUM && Op != ISD::FMINNUM)
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009378 return SDValue();
9379
9380 EVT VTy = VectorOp.getValueType();
9381 if (!VTy.isVector())
9382 return SDValue();
9383
Jun Bum Lim0aace132015-10-09 14:11:25 +00009384 if (VTy.getSizeInBits() < 64)
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009385 return SDValue();
9386
Jun Bum Lim0aace132015-10-09 14:11:25 +00009387 EVT EltTy = VTy.getVectorElementType();
9388 if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) {
9389 if (EltTy != MVT::f32)
9390 return SDValue();
9391 } else {
9392 if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8)
9393 return SDValue();
9394 }
9395
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009396 // Check if extracting from the same vector.
9397 // For example,
9398 // %sc = setcc %vector, %svn1, gt
9399 // %n0 = extract_vector_elt %sc, #0
9400 // %n1 = extract_vector_elt %vector, #0
9401 // %n2 = extract_vector_elt $vector, #1
9402 if (!(VectorOp == IfTrue->getOperand(0) &&
9403 VectorOp == IfFalse->getOperand(0)))
9404 return SDValue();
9405
9406 // Check if the condition code is matched with the operator type.
9407 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get();
9408 if ((Op == ISD::SMAX && CC != ISD::SETGT && CC != ISD::SETGE) ||
9409 (Op == ISD::UMAX && CC != ISD::SETUGT && CC != ISD::SETUGE) ||
9410 (Op == ISD::SMIN && CC != ISD::SETLT && CC != ISD::SETLE) ||
Jun Bum Lim0aace132015-10-09 14:11:25 +00009411 (Op == ISD::UMIN && CC != ISD::SETULT && CC != ISD::SETULE) ||
9412 (Op == ISD::FMAXNUM && CC != ISD::SETOGT && CC != ISD::SETOGE &&
9413 CC != ISD::SETUGT && CC != ISD::SETUGE && CC != ISD::SETGT &&
9414 CC != ISD::SETGE) ||
9415 (Op == ISD::FMINNUM && CC != ISD::SETOLT && CC != ISD::SETOLE &&
9416 CC != ISD::SETULT && CC != ISD::SETULE && CC != ISD::SETLT &&
9417 CC != ISD::SETLE))
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009418 return SDValue();
9419
9420 // Expect to check only lane 0 from the vector SETCC.
Artyom Skrobov314ee042015-11-25 19:41:11 +00009421 if (!isNullConstant(N0.getOperand(1)))
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009422 return SDValue();
9423
9424 // Expect to extract the true value from lane 0.
Artyom Skrobov314ee042015-11-25 19:41:11 +00009425 if (!isNullConstant(IfTrue.getOperand(1)))
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009426 return SDValue();
9427
9428 // Expect to extract the false value from lane 1.
Artyom Skrobov314ee042015-11-25 19:41:11 +00009429 if (!isOneConstant(IfFalse.getOperand(1)))
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009430 return SDValue();
9431
9432 return tryMatchAcrossLaneShuffleForReduction(N, SetCC, Op, DAG);
9433}
9434
9435/// Target-specific DAG combine for the across vector add reduction.
9436/// This function specifically handles the final clean-up step of the vector
9437/// add reduction produced by the LoopVectorizer. It is the log2-shuffle
9438/// pattern, which adds all elements of a vector together.
9439/// For example, for a <4 x i32> vector :
9440/// %1 = vector_shuffle %0, <2,3,u,u>
9441/// %2 = add %0, %1
9442/// %3 = vector_shuffle %2, <1,u,u,u>
9443/// %4 = add %2, %3
9444/// %result = extract_vector_elt %4, 0
9445/// becomes :
9446/// %0 = uaddv %0
9447/// %result = extract_vector_elt %0, 0
9448static SDValue
9449performAcrossLaneAddReductionCombine(SDNode *N, SelectionDAG &DAG,
9450 const AArch64Subtarget *Subtarget) {
9451 if (!Subtarget->hasNEON())
9452 return SDValue();
9453 SDValue N0 = N->getOperand(0);
9454 SDValue N1 = N->getOperand(1);
9455
9456 // Check if the input vector is fed by the ADD.
9457 if (N0->getOpcode() != ISD::ADD)
9458 return SDValue();
9459
9460 // The vector extract idx must constant zero because we only expect the final
9461 // result of the reduction is placed in lane 0.
Artyom Skrobov314ee042015-11-25 19:41:11 +00009462 if (!isNullConstant(N1))
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009463 return SDValue();
9464
9465 EVT VTy = N0.getValueType();
9466 if (!VTy.isVector())
9467 return SDValue();
9468
9469 EVT EltTy = VTy.getVectorElementType();
9470 if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8)
9471 return SDValue();
9472
Jun Bum Lim0aace132015-10-09 14:11:25 +00009473 if (VTy.getSizeInBits() < 64)
9474 return SDValue();
9475
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009476 return tryMatchAcrossLaneShuffleForReduction(N, N0, ISD::ADD, DAG);
Chad Rosier6c36eff2015-09-03 18:13:57 +00009477}
9478
Tim Northover3b0846e2014-05-24 12:50:23 +00009479/// Target-specific DAG combine function for NEON load/store intrinsics
9480/// to merge base address updates.
9481static SDValue performNEONPostLDSTCombine(SDNode *N,
9482 TargetLowering::DAGCombinerInfo &DCI,
9483 SelectionDAG &DAG) {
9484 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9485 return SDValue();
9486
9487 unsigned AddrOpIdx = N->getNumOperands() - 1;
9488 SDValue Addr = N->getOperand(AddrOpIdx);
9489
9490 // Search for a use of the address operand that is an increment.
9491 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9492 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9493 SDNode *User = *UI;
9494 if (User->getOpcode() != ISD::ADD ||
9495 UI.getUse().getResNo() != Addr.getResNo())
9496 continue;
9497
9498 // Check that the add is independent of the load/store. Otherwise, folding
9499 // it would create a cycle.
9500 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9501 continue;
9502
9503 // Find the new opcode for the updating load/store.
9504 bool IsStore = false;
9505 bool IsLaneOp = false;
9506 bool IsDupOp = false;
9507 unsigned NewOpc = 0;
9508 unsigned NumVecs = 0;
9509 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9510 switch (IntNo) {
9511 default: llvm_unreachable("unexpected intrinsic for Neon base update");
9512 case Intrinsic::aarch64_neon_ld2: NewOpc = AArch64ISD::LD2post;
9513 NumVecs = 2; break;
9514 case Intrinsic::aarch64_neon_ld3: NewOpc = AArch64ISD::LD3post;
9515 NumVecs = 3; break;
9516 case Intrinsic::aarch64_neon_ld4: NewOpc = AArch64ISD::LD4post;
9517 NumVecs = 4; break;
9518 case Intrinsic::aarch64_neon_st2: NewOpc = AArch64ISD::ST2post;
9519 NumVecs = 2; IsStore = true; break;
9520 case Intrinsic::aarch64_neon_st3: NewOpc = AArch64ISD::ST3post;
9521 NumVecs = 3; IsStore = true; break;
9522 case Intrinsic::aarch64_neon_st4: NewOpc = AArch64ISD::ST4post;
9523 NumVecs = 4; IsStore = true; break;
9524 case Intrinsic::aarch64_neon_ld1x2: NewOpc = AArch64ISD::LD1x2post;
9525 NumVecs = 2; break;
9526 case Intrinsic::aarch64_neon_ld1x3: NewOpc = AArch64ISD::LD1x3post;
9527 NumVecs = 3; break;
9528 case Intrinsic::aarch64_neon_ld1x4: NewOpc = AArch64ISD::LD1x4post;
9529 NumVecs = 4; break;
9530 case Intrinsic::aarch64_neon_st1x2: NewOpc = AArch64ISD::ST1x2post;
9531 NumVecs = 2; IsStore = true; break;
9532 case Intrinsic::aarch64_neon_st1x3: NewOpc = AArch64ISD::ST1x3post;
9533 NumVecs = 3; IsStore = true; break;
9534 case Intrinsic::aarch64_neon_st1x4: NewOpc = AArch64ISD::ST1x4post;
9535 NumVecs = 4; IsStore = true; break;
9536 case Intrinsic::aarch64_neon_ld2r: NewOpc = AArch64ISD::LD2DUPpost;
9537 NumVecs = 2; IsDupOp = true; break;
9538 case Intrinsic::aarch64_neon_ld3r: NewOpc = AArch64ISD::LD3DUPpost;
9539 NumVecs = 3; IsDupOp = true; break;
9540 case Intrinsic::aarch64_neon_ld4r: NewOpc = AArch64ISD::LD4DUPpost;
9541 NumVecs = 4; IsDupOp = true; break;
9542 case Intrinsic::aarch64_neon_ld2lane: NewOpc = AArch64ISD::LD2LANEpost;
9543 NumVecs = 2; IsLaneOp = true; break;
9544 case Intrinsic::aarch64_neon_ld3lane: NewOpc = AArch64ISD::LD3LANEpost;
9545 NumVecs = 3; IsLaneOp = true; break;
9546 case Intrinsic::aarch64_neon_ld4lane: NewOpc = AArch64ISD::LD4LANEpost;
9547 NumVecs = 4; IsLaneOp = true; break;
9548 case Intrinsic::aarch64_neon_st2lane: NewOpc = AArch64ISD::ST2LANEpost;
9549 NumVecs = 2; IsStore = true; IsLaneOp = true; break;
9550 case Intrinsic::aarch64_neon_st3lane: NewOpc = AArch64ISD::ST3LANEpost;
9551 NumVecs = 3; IsStore = true; IsLaneOp = true; break;
9552 case Intrinsic::aarch64_neon_st4lane: NewOpc = AArch64ISD::ST4LANEpost;
9553 NumVecs = 4; IsStore = true; IsLaneOp = true; break;
9554 }
9555
9556 EVT VecTy;
9557 if (IsStore)
9558 VecTy = N->getOperand(2).getValueType();
9559 else
9560 VecTy = N->getValueType(0);
9561
9562 // If the increment is a constant, it must match the memory ref size.
9563 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9564 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9565 uint32_t IncVal = CInc->getZExtValue();
9566 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9567 if (IsLaneOp || IsDupOp)
9568 NumBytes /= VecTy.getVectorNumElements();
9569 if (IncVal != NumBytes)
9570 continue;
9571 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
9572 }
9573 SmallVector<SDValue, 8> Ops;
9574 Ops.push_back(N->getOperand(0)); // Incoming chain
9575 // Load lane and store have vector list as input.
9576 if (IsLaneOp || IsStore)
9577 for (unsigned i = 2; i < AddrOpIdx; ++i)
9578 Ops.push_back(N->getOperand(i));
9579 Ops.push_back(Addr); // Base register
9580 Ops.push_back(Inc);
9581
9582 // Return Types.
9583 EVT Tys[6];
9584 unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
9585 unsigned n;
9586 for (n = 0; n < NumResultVecs; ++n)
9587 Tys[n] = VecTy;
9588 Tys[n++] = MVT::i64; // Type of write back register
9589 Tys[n] = MVT::Other; // Type of the chain
Craig Toppere1d12942014-08-27 05:25:25 +00009590 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
Tim Northover3b0846e2014-05-24 12:50:23 +00009591
9592 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9593 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
9594 MemInt->getMemoryVT(),
9595 MemInt->getMemOperand());
9596
9597 // Update the uses.
9598 std::vector<SDValue> NewResults;
9599 for (unsigned i = 0; i < NumResultVecs; ++i) {
9600 NewResults.push_back(SDValue(UpdN.getNode(), i));
9601 }
9602 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
9603 DCI.CombineTo(N, NewResults);
9604 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9605
9606 break;
9607 }
9608 return SDValue();
9609}
9610
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009611// Checks to see if the value is the prescribed width and returns information
9612// about its extension mode.
9613static
9614bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
9615 ExtType = ISD::NON_EXTLOAD;
9616 switch(V.getNode()->getOpcode()) {
9617 default:
9618 return false;
9619 case ISD::LOAD: {
9620 LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
9621 if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
9622 || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
9623 ExtType = LoadNode->getExtensionType();
9624 return true;
9625 }
9626 return false;
9627 }
9628 case ISD::AssertSext: {
9629 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9630 if ((TypeNode->getVT() == MVT::i8 && width == 8)
9631 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9632 ExtType = ISD::SEXTLOAD;
9633 return true;
9634 }
9635 return false;
9636 }
9637 case ISD::AssertZext: {
9638 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9639 if ((TypeNode->getVT() == MVT::i8 && width == 8)
9640 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9641 ExtType = ISD::ZEXTLOAD;
9642 return true;
9643 }
9644 return false;
9645 }
9646 case ISD::Constant:
9647 case ISD::TargetConstant: {
Eric Christopher114fa1c2016-02-29 22:50:49 +00009648 return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
9649 1LL << (width - 1);
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009650 }
9651 }
9652
9653 return true;
9654}
9655
9656// This function does a whole lot of voodoo to determine if the tests are
9657// equivalent without and with a mask. Essentially what happens is that given a
9658// DAG resembling:
9659//
9660// +-------------+ +-------------+ +-------------+ +-------------+
9661// | Input | | AddConstant | | CompConstant| | CC |
9662// +-------------+ +-------------+ +-------------+ +-------------+
9663// | | | |
9664// V V | +----------+
9665// +-------------+ +----+ | |
9666// | ADD | |0xff| | |
9667// +-------------+ +----+ | |
9668// | | | |
9669// V V | |
9670// +-------------+ | |
9671// | AND | | |
9672// +-------------+ | |
9673// | | |
9674// +-----+ | |
9675// | | |
9676// V V V
9677// +-------------+
9678// | CMP |
9679// +-------------+
9680//
9681// The AND node may be safely removed for some combinations of inputs. In
9682// particular we need to take into account the extension type of the Input,
9683// the exact values of AddConstant, CompConstant, and CC, along with the nominal
9684// width of the input (this can work for any width inputs, the above graph is
9685// specific to 8 bits.
9686//
9687// The specific equations were worked out by generating output tables for each
9688// AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
9689// problem was simplified by working with 4 bit inputs, which means we only
9690// needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
9691// extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
9692// patterns present in both extensions (0,7). For every distinct set of
9693// AddConstant and CompConstants bit patterns we can consider the masked and
9694// unmasked versions to be equivalent if the result of this function is true for
9695// all 16 distinct bit patterns of for the current extension type of Input (w0).
9696//
9697// sub w8, w0, w1
9698// and w10, w8, #0x0f
9699// cmp w8, w2
9700// cset w9, AArch64CC
9701// cmp w10, w2
9702// cset w11, AArch64CC
9703// cmp w9, w11
9704// cset w0, eq
9705// ret
9706//
9707// Since the above function shows when the outputs are equivalent it defines
9708// when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
9709// would be expensive to run during compiles. The equations below were written
9710// in a test harness that confirmed they gave equivalent outputs to the above
9711// for all inputs function, so they can be used determine if the removal is
9712// legal instead.
9713//
9714// isEquivalentMaskless() is the code for testing if the AND can be removed
9715// factored out of the DAG recognition as the DAG can take several forms.
9716
David Majnemere61e4bf2016-06-21 05:10:24 +00009717static bool isEquivalentMaskless(unsigned CC, unsigned width,
9718 ISD::LoadExtType ExtType, int AddConstant,
9719 int CompConstant) {
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009720 // By being careful about our equations and only writing the in term
9721 // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
9722 // make them generally applicable to all bit widths.
David Majnemere61e4bf2016-06-21 05:10:24 +00009723 int MaxUInt = (1 << width);
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009724
9725 // For the purposes of these comparisons sign extending the type is
9726 // equivalent to zero extending the add and displacing it by half the integer
9727 // width. Provided we are careful and make sure our equations are valid over
9728 // the whole range we can just adjust the input and avoid writing equations
9729 // for sign extended inputs.
9730 if (ExtType == ISD::SEXTLOAD)
9731 AddConstant -= (1 << (width-1));
9732
9733 switch(CC) {
9734 case AArch64CC::LE:
9735 case AArch64CC::GT: {
9736 if ((AddConstant == 0) ||
9737 (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
9738 (AddConstant >= 0 && CompConstant < 0) ||
9739 (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
9740 return true;
9741 } break;
9742 case AArch64CC::LT:
9743 case AArch64CC::GE: {
9744 if ((AddConstant == 0) ||
9745 (AddConstant >= 0 && CompConstant <= 0) ||
9746 (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
9747 return true;
9748 } break;
9749 case AArch64CC::HI:
9750 case AArch64CC::LS: {
9751 if ((AddConstant >= 0 && CompConstant < 0) ||
9752 (AddConstant <= 0 && CompConstant >= -1 &&
9753 CompConstant < AddConstant + MaxUInt))
9754 return true;
9755 } break;
9756 case AArch64CC::PL:
9757 case AArch64CC::MI: {
9758 if ((AddConstant == 0) ||
9759 (AddConstant > 0 && CompConstant <= 0) ||
9760 (AddConstant < 0 && CompConstant <= AddConstant))
9761 return true;
9762 } break;
9763 case AArch64CC::LO:
9764 case AArch64CC::HS: {
9765 if ((AddConstant >= 0 && CompConstant <= 0) ||
9766 (AddConstant <= 0 && CompConstant >= 0 &&
9767 CompConstant <= AddConstant + MaxUInt))
9768 return true;
9769 } break;
9770 case AArch64CC::EQ:
9771 case AArch64CC::NE: {
9772 if ((AddConstant > 0 && CompConstant < 0) ||
9773 (AddConstant < 0 && CompConstant >= 0 &&
9774 CompConstant < AddConstant + MaxUInt) ||
9775 (AddConstant >= 0 && CompConstant >= 0 &&
9776 CompConstant >= AddConstant) ||
9777 (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
9778
9779 return true;
9780 } break;
9781 case AArch64CC::VS:
9782 case AArch64CC::VC:
9783 case AArch64CC::AL:
9784 case AArch64CC::NV:
9785 return true;
9786 case AArch64CC::Invalid:
9787 break;
9788 }
9789
9790 return false;
9791}
9792
9793static
9794SDValue performCONDCombine(SDNode *N,
9795 TargetLowering::DAGCombinerInfo &DCI,
9796 SelectionDAG &DAG, unsigned CCIndex,
9797 unsigned CmpIndex) {
9798 unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
9799 SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
9800 unsigned CondOpcode = SubsNode->getOpcode();
9801
9802 if (CondOpcode != AArch64ISD::SUBS)
9803 return SDValue();
9804
9805 // There is a SUBS feeding this condition. Is it fed by a mask we can
9806 // use?
9807
9808 SDNode *AndNode = SubsNode->getOperand(0).getNode();
9809 unsigned MaskBits = 0;
9810
9811 if (AndNode->getOpcode() != ISD::AND)
9812 return SDValue();
9813
9814 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
9815 uint32_t CNV = CN->getZExtValue();
9816 if (CNV == 255)
9817 MaskBits = 8;
9818 else if (CNV == 65535)
9819 MaskBits = 16;
9820 }
9821
9822 if (!MaskBits)
9823 return SDValue();
9824
9825 SDValue AddValue = AndNode->getOperand(0);
9826
9827 if (AddValue.getOpcode() != ISD::ADD)
9828 return SDValue();
9829
9830 // The basic dag structure is correct, grab the inputs and validate them.
9831
9832 SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
9833 SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
9834 SDValue SubsInputValue = SubsNode->getOperand(1);
9835
9836 // The mask is present and the provenance of all the values is a smaller type,
9837 // lets see if the mask is superfluous.
9838
9839 if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
9840 !isa<ConstantSDNode>(SubsInputValue.getNode()))
9841 return SDValue();
9842
9843 ISD::LoadExtType ExtType;
9844
9845 if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
9846 !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
9847 !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
9848 return SDValue();
9849
9850 if(!isEquivalentMaskless(CC, MaskBits, ExtType,
9851 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
9852 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
9853 return SDValue();
9854
9855 // The AND is not necessary, remove it.
9856
9857 SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
9858 SubsNode->getValueType(1));
9859 SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
9860
9861 SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
9862 DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
9863
9864 return SDValue(N, 0);
9865}
9866
Tim Northover3b0846e2014-05-24 12:50:23 +00009867// Optimize compare with zero and branch.
9868static SDValue performBRCONDCombine(SDNode *N,
9869 TargetLowering::DAGCombinerInfo &DCI,
9870 SelectionDAG &DAG) {
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00009871 if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3))
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009872 N = NV.getNode();
Tim Northover3b0846e2014-05-24 12:50:23 +00009873 SDValue Chain = N->getOperand(0);
9874 SDValue Dest = N->getOperand(1);
9875 SDValue CCVal = N->getOperand(2);
9876 SDValue Cmp = N->getOperand(3);
9877
9878 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
9879 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
9880 if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
9881 return SDValue();
9882
9883 unsigned CmpOpc = Cmp.getOpcode();
9884 if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
9885 return SDValue();
9886
9887 // Only attempt folding if there is only one use of the flag and no use of the
9888 // value.
9889 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
9890 return SDValue();
9891
9892 SDValue LHS = Cmp.getOperand(0);
9893 SDValue RHS = Cmp.getOperand(1);
9894
9895 assert(LHS.getValueType() == RHS.getValueType() &&
9896 "Expected the value type to be the same for both operands!");
9897 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
9898 return SDValue();
9899
Artyom Skrobov314ee042015-11-25 19:41:11 +00009900 if (isNullConstant(LHS))
Tim Northover3b0846e2014-05-24 12:50:23 +00009901 std::swap(LHS, RHS);
9902
Artyom Skrobov314ee042015-11-25 19:41:11 +00009903 if (!isNullConstant(RHS))
Tim Northover3b0846e2014-05-24 12:50:23 +00009904 return SDValue();
9905
9906 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
9907 LHS.getOpcode() == ISD::SRL)
9908 return SDValue();
9909
9910 // Fold the compare into the branch instruction.
9911 SDValue BR;
9912 if (CC == AArch64CC::EQ)
9913 BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9914 else
9915 BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9916
9917 // Do not add new nodes to DAG combiner worklist.
9918 DCI.CombineTo(N, BR, false);
9919
9920 return SDValue();
9921}
9922
Geoff Berry9e934b02016-01-04 18:55:47 +00009923// Optimize some simple tbz/tbnz cases. Returns the new operand and bit to test
9924// as well as whether the test should be inverted. This code is required to
9925// catch these cases (as opposed to standard dag combines) because
9926// AArch64ISD::TBZ is matched during legalization.
9927static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert,
9928 SelectionDAG &DAG) {
9929
9930 if (!Op->hasOneUse())
9931 return Op;
9932
9933 // We don't handle undef/constant-fold cases below, as they should have
9934 // already been taken care of (e.g. and of 0, test of undefined shifted bits,
9935 // etc.)
9936
9937 // (tbz (trunc x), b) -> (tbz x, b)
9938 // This case is just here to enable more of the below cases to be caught.
9939 if (Op->getOpcode() == ISD::TRUNCATE &&
9940 Bit < Op->getValueType(0).getSizeInBits()) {
9941 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9942 }
9943
9944 if (Op->getNumOperands() != 2)
9945 return Op;
9946
9947 auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
9948 if (!C)
9949 return Op;
9950
9951 switch (Op->getOpcode()) {
9952 default:
9953 return Op;
9954
9955 // (tbz (and x, m), b) -> (tbz x, b)
9956 case ISD::AND:
9957 if ((C->getZExtValue() >> Bit) & 1)
9958 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9959 return Op;
9960
9961 // (tbz (shl x, c), b) -> (tbz x, b-c)
9962 case ISD::SHL:
9963 if (C->getZExtValue() <= Bit &&
9964 (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
9965 Bit = Bit - C->getZExtValue();
9966 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9967 }
9968 return Op;
9969
9970 // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
9971 case ISD::SRA:
9972 Bit = Bit + C->getZExtValue();
9973 if (Bit >= Op->getValueType(0).getSizeInBits())
9974 Bit = Op->getValueType(0).getSizeInBits() - 1;
9975 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9976
9977 // (tbz (srl x, c), b) -> (tbz x, b+c)
9978 case ISD::SRL:
9979 if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
9980 Bit = Bit + C->getZExtValue();
9981 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9982 }
9983 return Op;
9984
9985 // (tbz (xor x, -1), b) -> (tbnz x, b)
9986 case ISD::XOR:
9987 if ((C->getZExtValue() >> Bit) & 1)
9988 Invert = !Invert;
9989 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9990 }
9991}
9992
9993// Optimize test single bit zero/non-zero and branch.
9994static SDValue performTBZCombine(SDNode *N,
9995 TargetLowering::DAGCombinerInfo &DCI,
9996 SelectionDAG &DAG) {
9997 unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
9998 bool Invert = false;
9999 SDValue TestSrc = N->getOperand(1);
10000 SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG);
10001
10002 if (TestSrc == NewTestSrc)
10003 return SDValue();
10004
10005 unsigned NewOpc = N->getOpcode();
10006 if (Invert) {
10007 if (NewOpc == AArch64ISD::TBZ)
10008 NewOpc = AArch64ISD::TBNZ;
10009 else {
10010 assert(NewOpc == AArch64ISD::TBNZ);
10011 NewOpc = AArch64ISD::TBZ;
10012 }
10013 }
10014
10015 SDLoc DL(N);
10016 return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc,
10017 DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3));
10018}
10019
Tim Northover3b0846e2014-05-24 12:50:23 +000010020// vselect (v1i1 setcc) ->
10021// vselect (v1iXX setcc) (XX is the size of the compared operand type)
10022// FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
10023// condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
10024// such VSELECT.
10025static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
10026 SDValue N0 = N->getOperand(0);
10027 EVT CCVT = N0.getValueType();
10028
10029 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
10030 CCVT.getVectorElementType() != MVT::i1)
10031 return SDValue();
10032
10033 EVT ResVT = N->getValueType(0);
10034 EVT CmpVT = N0.getOperand(0).getValueType();
10035 // Only combine when the result type is of the same size as the compared
10036 // operands.
10037 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
10038 return SDValue();
10039
10040 SDValue IfTrue = N->getOperand(1);
10041 SDValue IfFalse = N->getOperand(2);
10042 SDValue SetCC =
10043 DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
10044 N0.getOperand(0), N0.getOperand(1),
10045 cast<CondCodeSDNode>(N0.getOperand(2))->get());
10046 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
10047 IfTrue, IfFalse);
10048}
10049
10050/// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
10051/// the compare-mask instructions rather than going via NZCV, even if LHS and
10052/// RHS are really scalar. This replaces any scalar setcc in the above pattern
10053/// with a vector one followed by a DUP shuffle on the result.
Ahmed Bougachac004c602015-04-27 21:43:12 +000010054static SDValue performSelectCombine(SDNode *N,
10055 TargetLowering::DAGCombinerInfo &DCI) {
10056 SelectionDAG &DAG = DCI.DAG;
Tim Northover3b0846e2014-05-24 12:50:23 +000010057 SDValue N0 = N->getOperand(0);
10058 EVT ResVT = N->getValueType(0);
Tim Northover3c0915e2014-08-29 15:34:58 +000010059
Ahmed Bougachac004c602015-04-27 21:43:12 +000010060 if (N0.getOpcode() != ISD::SETCC)
Tim Northover3c0915e2014-08-29 15:34:58 +000010061 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +000010062
Ahmed Bougachac004c602015-04-27 21:43:12 +000010063 // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
10064 // scalar SetCCResultType. We also don't expect vectors, because we assume
10065 // that selects fed by vector SETCCs are canonicalized to VSELECT.
10066 assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
10067 "Scalar-SETCC feeding SELECT has unexpected result type!");
10068
Tim Northoverc1c05ae2014-08-29 13:05:18 +000010069 // If NumMaskElts == 0, the comparison is larger than select result. The
10070 // largest real NEON comparison is 64-bits per lane, which means the result is
10071 // at most 32-bits and an illegal vector. Just bail out for now.
Tim Northover3c0915e2014-08-29 15:34:58 +000010072 EVT SrcVT = N0.getOperand(0).getValueType();
Ahmed Bougachad0ce0582014-12-01 20:59:00 +000010073
10074 // Don't try to do this optimization when the setcc itself has i1 operands.
10075 // There are no legal vectors of i1, so this would be pointless.
10076 if (SrcVT == MVT::i1)
10077 return SDValue();
10078
Tim Northover3c0915e2014-08-29 15:34:58 +000010079 int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
Tim Northoverc1c05ae2014-08-29 13:05:18 +000010080 if (!ResVT.isVector() || NumMaskElts == 0)
Tim Northover3b0846e2014-05-24 12:50:23 +000010081 return SDValue();
10082
Tim Northoverc1c05ae2014-08-29 13:05:18 +000010083 SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
Tim Northover3b0846e2014-05-24 12:50:23 +000010084 EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
10085
Ahmed Bougacha89bba612015-04-27 21:01:20 +000010086 // Also bail out if the vector CCVT isn't the same size as ResVT.
10087 // This can happen if the SETCC operand size doesn't divide the ResVT size
10088 // (e.g., f64 vs v3f32).
10089 if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
10090 return SDValue();
10091
Ahmed Bougachac004c602015-04-27 21:43:12 +000010092 // Make sure we didn't create illegal types, if we're not supposed to.
10093 assert(DCI.isBeforeLegalize() ||
10094 DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
10095
Tim Northover3b0846e2014-05-24 12:50:23 +000010096 // First perform a vector comparison, where lane 0 is the one we're interested
10097 // in.
Tim Northoverc1c05ae2014-08-29 13:05:18 +000010098 SDLoc DL(N0);
Tim Northover3b0846e2014-05-24 12:50:23 +000010099 SDValue LHS =
10100 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
10101 SDValue RHS =
10102 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
10103 SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
10104
10105 // Now duplicate the comparison mask we want across all other lanes.
10106 SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
Craig Topper2bd8b4b2016-07-01 06:54:47 +000010107 SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask);
Tim Northoverc1c05ae2014-08-29 13:05:18 +000010108 Mask = DAG.getNode(ISD::BITCAST, DL,
10109 ResVT.changeVectorElementTypeToInteger(), Mask);
Tim Northover3b0846e2014-05-24 12:50:23 +000010110
10111 return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
10112}
10113
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +000010114/// Get rid of unnecessary NVCASTs (that don't change the type).
10115static SDValue performNVCASTCombine(SDNode *N) {
10116 if (N->getValueType(0) == N->getOperand(0).getValueType())
10117 return N->getOperand(0);
10118
10119 return SDValue();
10120}
10121
Tim Northover3b0846e2014-05-24 12:50:23 +000010122SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
10123 DAGCombinerInfo &DCI) const {
10124 SelectionDAG &DAG = DCI.DAG;
10125 switch (N->getOpcode()) {
10126 default:
10127 break;
10128 case ISD::ADD:
10129 case ISD::SUB:
10130 return performAddSubLongCombine(N, DCI, DAG);
10131 case ISD::XOR:
10132 return performXorCombine(N, DAG, DCI, Subtarget);
10133 case ISD::MUL:
10134 return performMulCombine(N, DAG, DCI, Subtarget);
10135 case ISD::SINT_TO_FP:
10136 case ISD::UINT_TO_FP:
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +000010137 return performIntToFpCombine(N, DAG, Subtarget);
Chad Rosierfa30c9b2015-10-07 17:39:18 +000010138 case ISD::FP_TO_SINT:
10139 case ISD::FP_TO_UINT:
Silviu Barangafa00ba32016-08-08 13:13:57 +000010140 return performFpToIntCombine(N, DAG, DCI, Subtarget);
Chad Rosier7c6ac2b2015-10-07 17:51:37 +000010141 case ISD::FDIV:
Tim Northover85cf5642016-08-26 18:52:31 +000010142 return performFDivCombine(N, DAG, DCI, Subtarget);
Tim Northover3b0846e2014-05-24 12:50:23 +000010143 case ISD::OR:
10144 return performORCombine(N, DCI, Subtarget);
Chad Rosier14aa2ad2016-05-26 19:41:33 +000010145 case ISD::SRL:
10146 return performSRLCombine(N, DCI);
Tim Northover3b0846e2014-05-24 12:50:23 +000010147 case ISD::INTRINSIC_WO_CHAIN:
10148 return performIntrinsicCombine(N, DCI, Subtarget);
10149 case ISD::ANY_EXTEND:
10150 case ISD::ZERO_EXTEND:
10151 case ISD::SIGN_EXTEND:
10152 return performExtendCombine(N, DCI, DAG);
10153 case ISD::BITCAST:
10154 return performBitcastCombine(N, DCI, DAG);
10155 case ISD::CONCAT_VECTORS:
10156 return performConcatVectorsCombine(N, DCI, DAG);
Jun Bum Lim34b9bd02015-09-14 16:19:52 +000010157 case ISD::SELECT: {
10158 SDValue RV = performSelectCombine(N, DCI);
10159 if (!RV.getNode())
10160 RV = performAcrossLaneMinMaxReductionCombine(N, DAG, Subtarget);
10161 return RV;
10162 }
Tim Northover3b0846e2014-05-24 12:50:23 +000010163 case ISD::VSELECT:
10164 return performVSelectCombine(N, DCI.DAG);
Tim Northover339c83e2015-11-10 00:44:23 +000010165 case ISD::LOAD:
10166 if (performTBISimplification(N->getOperand(1), DCI, DAG))
10167 return SDValue(N, 0);
10168 break;
Tim Northover3b0846e2014-05-24 12:50:23 +000010169 case ISD::STORE:
10170 return performSTORECombine(N, DCI, DAG, Subtarget);
10171 case AArch64ISD::BRCOND:
10172 return performBRCONDCombine(N, DCI, DAG);
Geoff Berry9e934b02016-01-04 18:55:47 +000010173 case AArch64ISD::TBNZ:
10174 case AArch64ISD::TBZ:
10175 return performTBZCombine(N, DCI, DAG);
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010176 case AArch64ISD::CSEL:
10177 return performCONDCombine(N, DCI, DAG, 2, 3);
Tim Northover3b0846e2014-05-24 12:50:23 +000010178 case AArch64ISD::DUP:
10179 return performPostLD1Combine(N, DCI, false);
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +000010180 case AArch64ISD::NVCAST:
10181 return performNVCASTCombine(N);
Tim Northover3b0846e2014-05-24 12:50:23 +000010182 case ISD::INSERT_VECTOR_ELT:
10183 return performPostLD1Combine(N, DCI, true);
Chad Rosier6c36eff2015-09-03 18:13:57 +000010184 case ISD::EXTRACT_VECTOR_ELT:
Jun Bum Lim34b9bd02015-09-14 16:19:52 +000010185 return performAcrossLaneAddReductionCombine(N, DAG, Subtarget);
Tim Northover3b0846e2014-05-24 12:50:23 +000010186 case ISD::INTRINSIC_VOID:
10187 case ISD::INTRINSIC_W_CHAIN:
10188 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10189 case Intrinsic::aarch64_neon_ld2:
10190 case Intrinsic::aarch64_neon_ld3:
10191 case Intrinsic::aarch64_neon_ld4:
10192 case Intrinsic::aarch64_neon_ld1x2:
10193 case Intrinsic::aarch64_neon_ld1x3:
10194 case Intrinsic::aarch64_neon_ld1x4:
10195 case Intrinsic::aarch64_neon_ld2lane:
10196 case Intrinsic::aarch64_neon_ld3lane:
10197 case Intrinsic::aarch64_neon_ld4lane:
10198 case Intrinsic::aarch64_neon_ld2r:
10199 case Intrinsic::aarch64_neon_ld3r:
10200 case Intrinsic::aarch64_neon_ld4r:
10201 case Intrinsic::aarch64_neon_st2:
10202 case Intrinsic::aarch64_neon_st3:
10203 case Intrinsic::aarch64_neon_st4:
10204 case Intrinsic::aarch64_neon_st1x2:
10205 case Intrinsic::aarch64_neon_st1x3:
10206 case Intrinsic::aarch64_neon_st1x4:
10207 case Intrinsic::aarch64_neon_st2lane:
10208 case Intrinsic::aarch64_neon_st3lane:
10209 case Intrinsic::aarch64_neon_st4lane:
10210 return performNEONPostLDSTCombine(N, DCI, DAG);
10211 default:
10212 break;
10213 }
10214 }
10215 return SDValue();
10216}
10217
10218// Check if the return value is used as only a return value, as otherwise
10219// we can't perform a tail-call. In particular, we need to check for
10220// target ISD nodes that are returns and any other "odd" constructs
10221// that the generic analysis code won't necessarily catch.
10222bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
10223 SDValue &Chain) const {
10224 if (N->getNumValues() != 1)
10225 return false;
10226 if (!N->hasNUsesOfValue(1, 0))
10227 return false;
10228
10229 SDValue TCChain = Chain;
10230 SDNode *Copy = *N->use_begin();
10231 if (Copy->getOpcode() == ISD::CopyToReg) {
10232 // If the copy has a glue operand, we conservatively assume it isn't safe to
10233 // perform a tail call.
10234 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
10235 MVT::Glue)
10236 return false;
10237 TCChain = Copy->getOperand(0);
10238 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
10239 return false;
10240
10241 bool HasRet = false;
10242 for (SDNode *Node : Copy->uses()) {
10243 if (Node->getOpcode() != AArch64ISD::RET_FLAG)
10244 return false;
10245 HasRet = true;
10246 }
10247
10248 if (!HasRet)
10249 return false;
10250
10251 Chain = TCChain;
10252 return true;
10253}
10254
10255// Return whether the an instruction can potentially be optimized to a tail
10256// call. This will cause the optimizers to attempt to move, or duplicate,
10257// return instructions to help enable tail call optimizations for this
10258// instruction.
10259bool AArch64TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
Eric Christopher114fa1c2016-02-29 22:50:49 +000010260 return CI->isTailCall();
Tim Northover3b0846e2014-05-24 12:50:23 +000010261}
10262
10263bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
10264 SDValue &Offset,
10265 ISD::MemIndexedMode &AM,
10266 bool &IsInc,
10267 SelectionDAG &DAG) const {
10268 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
10269 return false;
10270
10271 Base = Op->getOperand(0);
10272 // All of the indexed addressing mode instructions take a signed
10273 // 9 bit immediate offset.
10274 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
10275 int64_t RHSC = (int64_t)RHS->getZExtValue();
10276 if (RHSC >= 256 || RHSC <= -256)
10277 return false;
10278 IsInc = (Op->getOpcode() == ISD::ADD);
10279 Offset = Op->getOperand(1);
10280 return true;
10281 }
10282 return false;
10283}
10284
10285bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10286 SDValue &Offset,
10287 ISD::MemIndexedMode &AM,
10288 SelectionDAG &DAG) const {
10289 EVT VT;
10290 SDValue Ptr;
10291 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10292 VT = LD->getMemoryVT();
10293 Ptr = LD->getBasePtr();
10294 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10295 VT = ST->getMemoryVT();
10296 Ptr = ST->getBasePtr();
10297 } else
10298 return false;
10299
10300 bool IsInc;
10301 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
10302 return false;
10303 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
10304 return true;
10305}
10306
10307bool AArch64TargetLowering::getPostIndexedAddressParts(
10308 SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
10309 ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
10310 EVT VT;
10311 SDValue Ptr;
10312 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10313 VT = LD->getMemoryVT();
10314 Ptr = LD->getBasePtr();
10315 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10316 VT = ST->getMemoryVT();
10317 Ptr = ST->getBasePtr();
10318 } else
10319 return false;
10320
10321 bool IsInc;
10322 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
10323 return false;
10324 // Post-indexing updates the base, so it's not a valid transform
10325 // if that's not the same as the load's pointer.
10326 if (Ptr != Base)
10327 return false;
10328 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
10329 return true;
10330}
10331
Tim Northoverf8bfe212014-07-18 13:07:05 +000010332static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
10333 SelectionDAG &DAG) {
Tim Northoverf8bfe212014-07-18 13:07:05 +000010334 SDLoc DL(N);
10335 SDValue Op = N->getOperand(0);
Ahmed Bougacha87946322014-12-01 20:52:32 +000010336
10337 if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
10338 return;
10339
Tim Northoverf8bfe212014-07-18 13:07:05 +000010340 Op = SDValue(
10341 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
10342 DAG.getUNDEF(MVT::i32), Op,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010343 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
Tim Northoverf8bfe212014-07-18 13:07:05 +000010344 0);
10345 Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
10346 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
10347}
10348
Charlie Turner434d4592015-10-16 15:38:25 +000010349static void ReplaceReductionResults(SDNode *N,
10350 SmallVectorImpl<SDValue> &Results,
10351 SelectionDAG &DAG, unsigned InterOp,
10352 unsigned AcrossOp) {
10353 EVT LoVT, HiVT;
10354 SDValue Lo, Hi;
10355 SDLoc dl(N);
10356 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
10357 std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
10358 SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
10359 SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
10360 Results.push_back(SplitVal);
10361}
10362
Tim Northover2f32e7f2016-08-04 19:32:28 +000010363static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) {
10364 SDLoc DL(N);
10365 SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N);
10366 SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64,
10367 DAG.getNode(ISD::SRL, DL, MVT::i128, N,
10368 DAG.getConstant(64, DL, MVT::i64)));
10369 return std::make_pair(Lo, Hi);
10370}
10371
Tim Northovercdf15292016-04-14 17:03:29 +000010372static void ReplaceCMP_SWAP_128Results(SDNode *N,
10373 SmallVectorImpl<SDValue> & Results,
10374 SelectionDAG &DAG) {
10375 assert(N->getValueType(0) == MVT::i128 &&
10376 "AtomicCmpSwap on types less than 128 should be legal");
Tim Northover2f32e7f2016-08-04 19:32:28 +000010377 auto Desired = splitInt128(N->getOperand(2), DAG);
10378 auto New = splitInt128(N->getOperand(3), DAG);
10379 SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second,
10380 New.first, New.second, N->getOperand(0)};
Tim Northovercdf15292016-04-14 17:03:29 +000010381 SDNode *CmpSwap = DAG.getMachineNode(
10382 AArch64::CMP_SWAP_128, SDLoc(N),
10383 DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops);
10384
10385 MachineFunction &MF = DAG.getMachineFunction();
10386 MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1);
10387 MemOp[0] = cast<MemSDNode>(N)->getMemOperand();
10388 cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1);
10389
10390 Results.push_back(SDValue(CmpSwap, 0));
10391 Results.push_back(SDValue(CmpSwap, 1));
10392 Results.push_back(SDValue(CmpSwap, 3));
10393}
10394
Tim Northover3b0846e2014-05-24 12:50:23 +000010395void AArch64TargetLowering::ReplaceNodeResults(
10396 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
10397 switch (N->getOpcode()) {
10398 default:
10399 llvm_unreachable("Don't know how to custom expand this");
Tim Northoverf8bfe212014-07-18 13:07:05 +000010400 case ISD::BITCAST:
10401 ReplaceBITCASTResults(N, Results, DAG);
10402 return;
Charlie Turner434d4592015-10-16 15:38:25 +000010403 case AArch64ISD::SADDV:
10404 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
10405 return;
10406 case AArch64ISD::UADDV:
10407 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
10408 return;
10409 case AArch64ISD::SMINV:
10410 ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
10411 return;
10412 case AArch64ISD::UMINV:
10413 ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
10414 return;
10415 case AArch64ISD::SMAXV:
10416 ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
10417 return;
10418 case AArch64ISD::UMAXV:
10419 ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
10420 return;
Tim Northover3b0846e2014-05-24 12:50:23 +000010421 case ISD::FP_TO_UINT:
10422 case ISD::FP_TO_SINT:
10423 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
10424 // Let normal code take care of it by not adding anything to Results.
10425 return;
Tim Northovercdf15292016-04-14 17:03:29 +000010426 case ISD::ATOMIC_CMP_SWAP:
10427 ReplaceCMP_SWAP_128Results(N, Results, DAG);
10428 return;
Tim Northover3b0846e2014-05-24 12:50:23 +000010429 }
10430}
10431
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +000010432bool AArch64TargetLowering::useLoadStackGuardNode() const {
Tim Shene885d5e2016-04-19 19:40:37 +000010433 if (!Subtarget->isTargetAndroid())
10434 return true;
10435 return TargetLowering::useLoadStackGuardNode();
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +000010436}
10437
Sanjay Patel1dd15592015-07-28 23:05:48 +000010438unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
Hao Liu44e5d7a2014-11-21 06:39:58 +000010439 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
10440 // reciprocal if there are three or more FDIVs.
Sanjay Patel1dd15592015-07-28 23:05:48 +000010441 return 3;
Hao Liu44e5d7a2014-11-21 06:39:58 +000010442}
10443
Chandler Carruth9d010ff2014-07-03 00:23:43 +000010444TargetLoweringBase::LegalizeTypeAction
10445AArch64TargetLowering::getPreferredVectorAction(EVT VT) const {
10446 MVT SVT = VT.getSimpleVT();
10447 // During type legalization, we prefer to widen v1i8, v1i16, v1i32 to v8i8,
10448 // v4i16, v2i32 instead of to promote.
10449 if (SVT == MVT::v1i8 || SVT == MVT::v1i16 || SVT == MVT::v1i32
10450 || SVT == MVT::v1f32)
10451 return TypeWidenVector;
10452
10453 return TargetLoweringBase::getPreferredVectorAction(VT);
10454}
10455
Robin Morisseted3d48f2014-09-03 21:29:59 +000010456// Loads and stores less than 128-bits are already atomic; ones above that
10457// are doomed anyway, so defer to the default libcall and blame the OS when
10458// things go wrong.
10459bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
10460 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
10461 return Size == 128;
10462}
10463
10464// Loads and stores less than 128-bits are already atomic; ones above that
10465// are doomed anyway, so defer to the default libcall and blame the OS when
10466// things go wrong.
Ahmed Bougacha52468672015-09-11 17:08:28 +000010467TargetLowering::AtomicExpansionKind
10468AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
Robin Morisseted3d48f2014-09-03 21:29:59 +000010469 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
Ahmed Bougacha52468672015-09-11 17:08:28 +000010470 return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
Robin Morisseted3d48f2014-09-03 21:29:59 +000010471}
10472
10473// For the real atomic operations, we have ldxr/stxr up to 128 bits,
Ahmed Bougacha52468672015-09-11 17:08:28 +000010474TargetLowering::AtomicExpansionKind
JF Bastienf14889e2015-03-04 15:47:57 +000010475AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
Robin Morisseted3d48f2014-09-03 21:29:59 +000010476 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
Ahmed Bougacha9d677132015-09-11 17:08:17 +000010477 return Size <= 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
Robin Morisseted3d48f2014-09-03 21:29:59 +000010478}
10479
Ahmed Bougacha52468672015-09-11 17:08:28 +000010480bool AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
10481 AtomicCmpXchgInst *AI) const {
Tim Northovercdf15292016-04-14 17:03:29 +000010482 // At -O0, fast-regalloc cannot cope with the live vregs necessary to
10483 // implement cmpxchg without spilling. If the address being exchanged is also
10484 // on the stack and close enough to the spill slot, this can lead to a
10485 // situation where the monitor always gets cleared and the atomic operation
10486 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
10487 return getTargetMachine().getOptLevel() != 0;
Robin Morisset25c8e312014-09-17 00:06:58 +000010488}
10489
Tim Northover3b0846e2014-05-24 12:50:23 +000010490Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
10491 AtomicOrdering Ord) const {
10492 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10493 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
JF Bastien800f87a2016-04-06 21:19:33 +000010494 bool IsAcquire = isAcquireOrStronger(Ord);
Tim Northover3b0846e2014-05-24 12:50:23 +000010495
10496 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
10497 // intrinsic must return {i64, i64} and we have to recombine them into a
10498 // single i128 here.
10499 if (ValTy->getPrimitiveSizeInBits() == 128) {
10500 Intrinsic::ID Int =
10501 IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
10502 Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int);
10503
10504 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10505 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
10506
10507 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
10508 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
10509 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
10510 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
10511 return Builder.CreateOr(
10512 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
10513 }
10514
10515 Type *Tys[] = { Addr->getType() };
10516 Intrinsic::ID Int =
10517 IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
10518 Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int, Tys);
10519
10520 return Builder.CreateTruncOrBitCast(
10521 Builder.CreateCall(Ldxr, Addr),
10522 cast<PointerType>(Addr->getType())->getElementType());
10523}
10524
Ahmed Bougacha07a844d2015-09-22 17:21:44 +000010525void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
10526 IRBuilder<> &Builder) const {
10527 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10528 Builder.CreateCall(
10529 llvm::Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
10530}
10531
Tim Northover3b0846e2014-05-24 12:50:23 +000010532Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
10533 Value *Val, Value *Addr,
10534 AtomicOrdering Ord) const {
10535 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
JF Bastien800f87a2016-04-06 21:19:33 +000010536 bool IsRelease = isReleaseOrStronger(Ord);
Tim Northover3b0846e2014-05-24 12:50:23 +000010537
10538 // Since the intrinsics must have legal type, the i128 intrinsics take two
10539 // parameters: "i64, i64". We must marshal Val into the appropriate form
10540 // before the call.
10541 if (Val->getType()->getPrimitiveSizeInBits() == 128) {
10542 Intrinsic::ID Int =
10543 IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
10544 Function *Stxr = Intrinsic::getDeclaration(M, Int);
10545 Type *Int64Ty = Type::getInt64Ty(M->getContext());
10546
10547 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
10548 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
10549 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
David Blaikieff6409d2015-05-18 22:13:54 +000010550 return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
Tim Northover3b0846e2014-05-24 12:50:23 +000010551 }
10552
10553 Intrinsic::ID Int =
10554 IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
10555 Type *Tys[] = { Addr->getType() };
10556 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
10557
David Blaikieff6409d2015-05-18 22:13:54 +000010558 return Builder.CreateCall(Stxr,
10559 {Builder.CreateZExtOrBitCast(
10560 Val, Stxr->getFunctionType()->getParamType(0)),
10561 Addr});
Tim Northover3b0846e2014-05-24 12:50:23 +000010562}
Tim Northover3c55cca2014-11-27 21:02:42 +000010563
10564bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
10565 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
10566 return Ty->isArrayTy();
10567}
Matthias Braunaf7d7702015-07-16 20:02:37 +000010568
10569bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
10570 EVT) const {
10571 return false;
10572}
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000010573
Tim Shen00127562016-04-08 21:26:31 +000010574Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const {
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +000010575 if (!Subtarget->isTargetAndroid())
Tim Shen00127562016-04-08 21:26:31 +000010576 return TargetLowering::getIRStackGuard(IRB);
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +000010577
10578 // Android provides a fixed TLS slot for the stack cookie. See the definition
10579 // of TLS_SLOT_STACK_GUARD in
10580 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
10581 const unsigned TlsOffset = 0x28;
10582 Module *M = IRB.GetInsertBlock()->getParent()->getParent();
10583 Function *ThreadPointerFunc =
Marcin Koscielnicki3fdc2572016-04-19 20:51:05 +000010584 Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +000010585 return IRB.CreatePointerCast(
10586 IRB.CreateConstGEP1_32(IRB.CreateCall(ThreadPointerFunc), TlsOffset),
10587 Type::getInt8PtrTy(IRB.getContext())->getPointerTo(0));
10588}
10589
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000010590Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
10591 if (!Subtarget->isTargetAndroid())
10592 return TargetLowering::getSafeStackPointerLocation(IRB);
10593
10594 // Android provides a fixed TLS slot for the SafeStack pointer. See the
10595 // definition of TLS_SLOT_SAFESTACK in
10596 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
10597 const unsigned TlsOffset = 0x48;
10598 Module *M = IRB.GetInsertBlock()->getParent()->getParent();
10599 Function *ThreadPointerFunc =
Marcin Koscielnicki3fdc2572016-04-19 20:51:05 +000010600 Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000010601 return IRB.CreatePointerCast(
10602 IRB.CreateConstGEP1_32(IRB.CreateCall(ThreadPointerFunc), TlsOffset),
10603 Type::getInt8PtrTy(IRB.getContext())->getPointerTo(0));
10604}
Manman Rencbe4f942015-12-16 21:04:19 +000010605
10606void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
10607 // Update IsSplitCSR in AArch64unctionInfo.
10608 AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>();
10609 AFI->setIsSplitCSR(true);
10610}
10611
10612void AArch64TargetLowering::insertCopiesSplitCSR(
10613 MachineBasicBlock *Entry,
10614 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
10615 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
10616 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
10617 if (!IStart)
10618 return;
10619
10620 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10621 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
Manman Ren4632e8e2016-01-15 20:13:28 +000010622 MachineBasicBlock::iterator MBBI = Entry->begin();
Manman Rencbe4f942015-12-16 21:04:19 +000010623 for (const MCPhysReg *I = IStart; *I; ++I) {
10624 const TargetRegisterClass *RC = nullptr;
10625 if (AArch64::GPR64RegClass.contains(*I))
10626 RC = &AArch64::GPR64RegClass;
10627 else if (AArch64::FPR64RegClass.contains(*I))
10628 RC = &AArch64::FPR64RegClass;
10629 else
10630 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
10631
10632 unsigned NewVR = MRI->createVirtualRegister(RC);
10633 // Create copy from CSR to a virtual register.
10634 // FIXME: this currently does not emit CFI pseudo-instructions, it works
10635 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
10636 // nounwind. If we want to generalize this later, we may need to emit
10637 // CFI pseudo-instructions.
10638 assert(Entry->getParent()->getFunction()->hasFnAttribute(
10639 Attribute::NoUnwind) &&
10640 "Function should be nounwind in insertCopiesSplitCSR!");
10641 Entry->addLiveIn(*I);
Manman Ren4632e8e2016-01-15 20:13:28 +000010642 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
Manman Rencbe4f942015-12-16 21:04:19 +000010643 .addReg(*I);
10644
Manman Ren4632e8e2016-01-15 20:13:28 +000010645 // Insert the copy-back instructions right before the terminator.
Manman Rencbe4f942015-12-16 21:04:19 +000010646 for (auto *Exit : Exits)
Manman Ren4632e8e2016-01-15 20:13:28 +000010647 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
10648 TII->get(TargetOpcode::COPY), *I)
Manman Rencbe4f942015-12-16 21:04:19 +000010649 .addReg(NewVR);
10650 }
10651}
Haicheng Wu6a6bc752016-03-28 18:17:07 +000010652
10653bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeSet Attr) const {
10654 // Integer division on AArch64 is expensive. However, when aggressively
10655 // optimizing for code size, we prefer to use a div instruction, as it is
10656 // usually smaller than the alternative sequence.
10657 // The exception to this is vector division. Since AArch64 doesn't have vector
10658 // integer division, leaving the division as-is is a loss even in terms of
10659 // size, because it will have to be scalarized, while the alternative code
10660 // sequence can be performed in vector form.
10661 bool OptSize =
10662 Attr.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
10663 return OptSize && !VT.isVector();
10664}