blob: 05775a84bef9fad7f6c1f87a838d1256d9d4eaef [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
Tim Northover3b0846e2014-05-24 12:50:23 +0000516 setHasExtractBitsInsn(true);
517
Adhemerval Zanella7bc33192015-07-28 13:03:31 +0000518 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
519
Tim Northover3b0846e2014-05-24 12:50:23 +0000520 if (Subtarget->hasNEON()) {
521 // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
522 // silliness like this:
523 setOperationAction(ISD::FABS, MVT::v1f64, Expand);
524 setOperationAction(ISD::FADD, MVT::v1f64, Expand);
525 setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
526 setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
527 setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
528 setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
529 setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
530 setOperationAction(ISD::FMA, MVT::v1f64, Expand);
531 setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
532 setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
533 setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
534 setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
535 setOperationAction(ISD::FREM, MVT::v1f64, Expand);
536 setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
537 setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
538 setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
539 setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
540 setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
541 setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
542 setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
543 setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
544 setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
545 setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
546 setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
547 setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
548
549 setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
550 setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
551 setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
552 setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
553 setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
554
555 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
556
557 // AArch64 doesn't have a direct vector ->f32 conversion instructions for
558 // elements smaller than i32, so promote the input to i32 first.
559 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Promote);
560 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Promote);
561 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Promote);
562 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Promote);
Pirama Arumuga Nainarb1881532015-04-23 17:16:27 +0000563 // i8 and i16 vector elements also need promotion to i32 for v8i8 or v8i16
564 // -> v8f16 conversions.
565 setOperationAction(ISD::SINT_TO_FP, MVT::v8i8, Promote);
566 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Promote);
567 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
568 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Promote);
Tim Northover3b0846e2014-05-24 12:50:23 +0000569 // Similarly, there is no direct i32 -> f64 vector conversion instruction.
570 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
571 setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
572 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
573 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
Pirama Arumuga Nainarb1881532015-04-23 17:16:27 +0000574 // Or, direct i32 -> f16 vector conversion. Set it so custom, so the
575 // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
576 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
577 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000578
Craig Topperc5551bf2016-04-26 05:26:51 +0000579 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand);
580 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand);
581
Craig Topper3b4842b2016-04-28 01:58:21 +0000582 setOperationAction(ISD::CTTZ, MVT::v2i8, Expand);
583 setOperationAction(ISD::CTTZ, MVT::v4i16, Expand);
584 setOperationAction(ISD::CTTZ, MVT::v2i32, Expand);
585 setOperationAction(ISD::CTTZ, MVT::v1i64, Expand);
586 setOperationAction(ISD::CTTZ, MVT::v16i8, Expand);
587 setOperationAction(ISD::CTTZ, MVT::v8i16, Expand);
588 setOperationAction(ISD::CTTZ, MVT::v4i32, Expand);
589 setOperationAction(ISD::CTTZ, MVT::v2i64, Expand);
590
Tim Northover3b0846e2014-05-24 12:50:23 +0000591 // AArch64 doesn't have MUL.2d:
592 setOperationAction(ISD::MUL, MVT::v2i64, Expand);
Chad Rosierd9d0f862014-10-08 02:31:24 +0000593 // Custom handling for some quad-vector types to detect MULL.
594 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
595 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
596 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
597
Tim Northover3b0846e2014-05-24 12:50:23 +0000598 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
599 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
600 // Likewise, narrowing and extending vector loads/stores aren't handled
601 // directly.
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000602 for (MVT VT : MVT::vector_valuetypes()) {
603 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000604
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000605 setOperationAction(ISD::MULHS, VT, Expand);
606 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
607 setOperationAction(ISD::MULHU, VT, Expand);
608 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000609
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000610 setOperationAction(ISD::BSWAP, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000611
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000612 for (MVT InnerVT : MVT::vector_valuetypes()) {
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000613 setTruncStoreAction(VT, InnerVT, Expand);
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000614 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
615 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
616 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
617 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000618 }
619
620 // AArch64 has implementations of a lot of rounding-like FP operations.
Benjamin Kramer57a3d082015-03-08 16:07:39 +0000621 for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000622 setOperationAction(ISD::FFLOOR, Ty, Legal);
623 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
624 setOperationAction(ISD::FCEIL, Ty, Legal);
625 setOperationAction(ISD::FRINT, Ty, Legal);
626 setOperationAction(ISD::FTRUNC, Ty, Legal);
627 setOperationAction(ISD::FROUND, Ty, Legal);
628 }
629 }
James Molloyf089ab72014-08-06 10:42:18 +0000630
Matthias Braun651cff42016-06-02 18:03:53 +0000631 PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive();
Tim Northover3b0846e2014-05-24 12:50:23 +0000632}
633
Craig Topper18e69f42016-04-15 06:20:21 +0000634void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) {
Jiangning Liu08f4cda2014-08-29 01:31:42 +0000635 if (VT == MVT::v2f32 || VT == MVT::v4f16) {
Craig Topper18e69f42016-04-15 06:20:21 +0000636 setOperationAction(ISD::LOAD, VT, Promote);
637 AddPromotedToType(ISD::LOAD, VT, MVT::v2i32);
Tim Northover3b0846e2014-05-24 12:50:23 +0000638
Craig Topper18e69f42016-04-15 06:20:21 +0000639 setOperationAction(ISD::STORE, VT, Promote);
640 AddPromotedToType(ISD::STORE, VT, MVT::v2i32);
Jiangning Liu08f4cda2014-08-29 01:31:42 +0000641 } else if (VT == MVT::v2f64 || VT == MVT::v4f32 || VT == MVT::v8f16) {
Craig Topper18e69f42016-04-15 06:20:21 +0000642 setOperationAction(ISD::LOAD, VT, Promote);
643 AddPromotedToType(ISD::LOAD, VT, MVT::v2i64);
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::v2i64);
Tim Northover3b0846e2014-05-24 12:50:23 +0000647 }
648
649 // Mark vector float intrinsics as expand.
650 if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
Craig Topper18e69f42016-04-15 06:20:21 +0000651 setOperationAction(ISD::FSIN, VT, Expand);
652 setOperationAction(ISD::FCOS, VT, Expand);
653 setOperationAction(ISD::FPOWI, VT, Expand);
654 setOperationAction(ISD::FPOW, VT, Expand);
655 setOperationAction(ISD::FLOG, VT, Expand);
656 setOperationAction(ISD::FLOG2, VT, Expand);
657 setOperationAction(ISD::FLOG10, VT, Expand);
658 setOperationAction(ISD::FEXP, VT, Expand);
659 setOperationAction(ISD::FEXP2, VT, Expand);
Ahmed Bougachab0ae36f2015-08-04 00:42:34 +0000660
661 // But we do support custom-lowering for FCOPYSIGN.
Craig Topper18e69f42016-04-15 06:20:21 +0000662 setOperationAction(ISD::FCOPYSIGN, VT, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000663 }
664
Craig Topper18e69f42016-04-15 06:20:21 +0000665 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
666 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
667 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
668 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
669 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
670 setOperationAction(ISD::SRA, VT, Custom);
671 setOperationAction(ISD::SRL, VT, Custom);
672 setOperationAction(ISD::SHL, VT, Custom);
673 setOperationAction(ISD::AND, VT, Custom);
674 setOperationAction(ISD::OR, VT, Custom);
675 setOperationAction(ISD::SETCC, VT, Custom);
676 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000677
Craig Topper18e69f42016-04-15 06:20:21 +0000678 setOperationAction(ISD::SELECT, VT, Expand);
679 setOperationAction(ISD::SELECT_CC, VT, Expand);
680 setOperationAction(ISD::VSELECT, VT, Expand);
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000681 for (MVT InnerVT : MVT::all_valuetypes())
Craig Topper18e69f42016-04-15 06:20:21 +0000682 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000683
684 // CNT supports only B element sizes.
685 if (VT != MVT::v8i8 && VT != MVT::v16i8)
Craig Topper18e69f42016-04-15 06:20:21 +0000686 setOperationAction(ISD::CTPOP, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000687
Craig Topper18e69f42016-04-15 06:20:21 +0000688 setOperationAction(ISD::UDIV, VT, Expand);
689 setOperationAction(ISD::SDIV, VT, Expand);
690 setOperationAction(ISD::UREM, VT, Expand);
691 setOperationAction(ISD::SREM, VT, Expand);
692 setOperationAction(ISD::FREM, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000693
Craig Topper18e69f42016-04-15 06:20:21 +0000694 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
695 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000696
Hal Finkelcd8664c2015-12-11 23:11:52 +0000697 // [SU][MIN|MAX] are available for all NEON types apart from i64.
Craig Topper18e69f42016-04-15 06:20:21 +0000698 if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64)
Hal Finkelcd8664c2015-12-11 23:11:52 +0000699 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
Craig Topper18e69f42016-04-15 06:20:21 +0000700 setOperationAction(Opcode, VT, Legal);
James Molloycfb04432015-05-15 16:15:57 +0000701
James Molloy63be1982015-08-14 09:08:50 +0000702 // F[MIN|MAX][NUM|NAN] are available for all FP NEON types (not f16 though!).
703 if (VT.isFloatingPoint() && VT.getVectorElementType() != MVT::f16)
James Molloyb7b2a1e2015-08-11 12:06:37 +0000704 for (unsigned Opcode : {ISD::FMINNAN, ISD::FMAXNAN,
705 ISD::FMINNUM, ISD::FMAXNUM})
Craig Topper18e69f42016-04-15 06:20:21 +0000706 setOperationAction(Opcode, VT, Legal);
James Molloyedf38f02015-08-11 12:06:33 +0000707
Tim Northover3b0846e2014-05-24 12:50:23 +0000708 if (Subtarget->isLittleEndian()) {
709 for (unsigned im = (unsigned)ISD::PRE_INC;
710 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
Craig Topper18e69f42016-04-15 06:20:21 +0000711 setIndexedLoadAction(im, VT, Legal);
712 setIndexedStoreAction(im, VT, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000713 }
714 }
715}
716
717void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
718 addRegisterClass(VT, &AArch64::FPR64RegClass);
719 addTypeForNEON(VT, MVT::v2i32);
720}
721
722void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
723 addRegisterClass(VT, &AArch64::FPR128RegClass);
724 addTypeForNEON(VT, MVT::v4i32);
725}
726
Mehdi Amini44ede332015-07-09 02:09:04 +0000727EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
728 EVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +0000729 if (!VT.isVector())
730 return MVT::i32;
731 return VT.changeVectorElementTypeToInteger();
732}
733
734/// computeKnownBitsForTargetNode - Determine which of the bits specified in
735/// Mask are known to be either zero or one and return them in the
736/// KnownZero/KnownOne bitsets.
737void AArch64TargetLowering::computeKnownBitsForTargetNode(
738 const SDValue Op, APInt &KnownZero, APInt &KnownOne,
739 const SelectionDAG &DAG, unsigned Depth) const {
740 switch (Op.getOpcode()) {
741 default:
742 break;
743 case AArch64ISD::CSEL: {
744 APInt KnownZero2, KnownOne2;
745 DAG.computeKnownBits(Op->getOperand(0), KnownZero, KnownOne, Depth + 1);
746 DAG.computeKnownBits(Op->getOperand(1), KnownZero2, KnownOne2, Depth + 1);
747 KnownZero &= KnownZero2;
748 KnownOne &= KnownOne2;
749 break;
750 }
751 case ISD::INTRINSIC_W_CHAIN: {
Jun Bum Lim4d3c5982015-09-08 16:11:22 +0000752 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +0000753 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
754 switch (IntID) {
755 default: return;
756 case Intrinsic::aarch64_ldaxr:
757 case Intrinsic::aarch64_ldxr: {
758 unsigned BitWidth = KnownOne.getBitWidth();
759 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
760 unsigned MemBits = VT.getScalarType().getSizeInBits();
761 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
762 return;
763 }
764 }
765 break;
766 }
767 case ISD::INTRINSIC_WO_CHAIN:
768 case ISD::INTRINSIC_VOID: {
769 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
770 switch (IntNo) {
771 default:
772 break;
773 case Intrinsic::aarch64_neon_umaxv:
774 case Intrinsic::aarch64_neon_uminv: {
775 // Figure out the datatype of the vector operand. The UMINV instruction
776 // will zero extend the result, so we can mark as known zero all the
777 // bits larger than the element datatype. 32-bit or larget doesn't need
778 // this as those are legal types and will be handled by isel directly.
779 MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
780 unsigned BitWidth = KnownZero.getBitWidth();
781 if (VT == MVT::v8i8 || VT == MVT::v16i8) {
782 assert(BitWidth >= 8 && "Unexpected width!");
783 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
784 KnownZero |= Mask;
785 } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
786 assert(BitWidth >= 16 && "Unexpected width!");
787 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
788 KnownZero |= Mask;
789 }
790 break;
791 } break;
792 }
793 }
794 }
795}
796
Mehdi Aminieaabc512015-07-09 15:12:23 +0000797MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
798 EVT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +0000799 return MVT::i64;
800}
801
Akira Hatanakaf53b0402015-07-29 14:17:26 +0000802bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
803 unsigned AddrSpace,
804 unsigned Align,
805 bool *Fast) const {
806 if (Subtarget->requiresStrictAlign())
807 return false;
Sanjay Patelbbbf9a12015-09-25 21:49:48 +0000808
Sanjay Patelbbbf9a12015-09-25 21:49:48 +0000809 if (Fast) {
Matthias Braun651cff42016-06-02 18:03:53 +0000810 // Some CPUs are fine with unaligned stores except for 128-bit ones.
811 *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 ||
Sanjay Patelbbbf9a12015-09-25 21:49:48 +0000812 // See comments in performSTORECombine() for more details about
813 // these conditions.
814
815 // Code that uses clang vector extensions can mark that it
816 // wants unaligned accesses to be treated as fast by
817 // underspecifying alignment to be 1 or 2.
818 Align <= 2 ||
819
820 // Disregard v2i64. Memcpy lowering produces those and splitting
821 // them regresses performance on micro-benchmarks and olden/bh.
822 VT == MVT::v2i64;
823 }
Akira Hatanakaf53b0402015-07-29 14:17:26 +0000824 return true;
825}
826
Tim Northover3b0846e2014-05-24 12:50:23 +0000827FastISel *
828AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
829 const TargetLibraryInfo *libInfo) const {
830 return AArch64::createFastISel(funcInfo, libInfo);
831}
832
833const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
Matthias Braund04893f2015-05-07 21:33:59 +0000834 switch ((AArch64ISD::NodeType)Opcode) {
835 case AArch64ISD::FIRST_NUMBER: break;
Tim Northover3b0846e2014-05-24 12:50:23 +0000836 case AArch64ISD::CALL: return "AArch64ISD::CALL";
837 case AArch64ISD::ADRP: return "AArch64ISD::ADRP";
838 case AArch64ISD::ADDlow: return "AArch64ISD::ADDlow";
839 case AArch64ISD::LOADgot: return "AArch64ISD::LOADgot";
840 case AArch64ISD::RET_FLAG: return "AArch64ISD::RET_FLAG";
841 case AArch64ISD::BRCOND: return "AArch64ISD::BRCOND";
842 case AArch64ISD::CSEL: return "AArch64ISD::CSEL";
843 case AArch64ISD::FCSEL: return "AArch64ISD::FCSEL";
844 case AArch64ISD::CSINV: return "AArch64ISD::CSINV";
845 case AArch64ISD::CSNEG: return "AArch64ISD::CSNEG";
846 case AArch64ISD::CSINC: return "AArch64ISD::CSINC";
847 case AArch64ISD::THREAD_POINTER: return "AArch64ISD::THREAD_POINTER";
Kristof Beylsaea84612015-03-04 09:12:08 +0000848 case AArch64ISD::TLSDESC_CALLSEQ: return "AArch64ISD::TLSDESC_CALLSEQ";
Tim Northover3b0846e2014-05-24 12:50:23 +0000849 case AArch64ISD::ADC: return "AArch64ISD::ADC";
850 case AArch64ISD::SBC: return "AArch64ISD::SBC";
851 case AArch64ISD::ADDS: return "AArch64ISD::ADDS";
852 case AArch64ISD::SUBS: return "AArch64ISD::SUBS";
853 case AArch64ISD::ADCS: return "AArch64ISD::ADCS";
854 case AArch64ISD::SBCS: return "AArch64ISD::SBCS";
855 case AArch64ISD::ANDS: return "AArch64ISD::ANDS";
Matthias Braunaf7d7702015-07-16 20:02:37 +0000856 case AArch64ISD::CCMP: return "AArch64ISD::CCMP";
857 case AArch64ISD::CCMN: return "AArch64ISD::CCMN";
858 case AArch64ISD::FCCMP: return "AArch64ISD::FCCMP";
Tim Northover3b0846e2014-05-24 12:50:23 +0000859 case AArch64ISD::FCMP: return "AArch64ISD::FCMP";
Tim Northover3b0846e2014-05-24 12:50:23 +0000860 case AArch64ISD::DUP: return "AArch64ISD::DUP";
861 case AArch64ISD::DUPLANE8: return "AArch64ISD::DUPLANE8";
862 case AArch64ISD::DUPLANE16: return "AArch64ISD::DUPLANE16";
863 case AArch64ISD::DUPLANE32: return "AArch64ISD::DUPLANE32";
864 case AArch64ISD::DUPLANE64: return "AArch64ISD::DUPLANE64";
865 case AArch64ISD::MOVI: return "AArch64ISD::MOVI";
866 case AArch64ISD::MOVIshift: return "AArch64ISD::MOVIshift";
867 case AArch64ISD::MOVIedit: return "AArch64ISD::MOVIedit";
868 case AArch64ISD::MOVImsl: return "AArch64ISD::MOVImsl";
869 case AArch64ISD::FMOV: return "AArch64ISD::FMOV";
870 case AArch64ISD::MVNIshift: return "AArch64ISD::MVNIshift";
871 case AArch64ISD::MVNImsl: return "AArch64ISD::MVNImsl";
872 case AArch64ISD::BICi: return "AArch64ISD::BICi";
873 case AArch64ISD::ORRi: return "AArch64ISD::ORRi";
874 case AArch64ISD::BSL: return "AArch64ISD::BSL";
875 case AArch64ISD::NEG: return "AArch64ISD::NEG";
876 case AArch64ISD::EXTR: return "AArch64ISD::EXTR";
877 case AArch64ISD::ZIP1: return "AArch64ISD::ZIP1";
878 case AArch64ISD::ZIP2: return "AArch64ISD::ZIP2";
879 case AArch64ISD::UZP1: return "AArch64ISD::UZP1";
880 case AArch64ISD::UZP2: return "AArch64ISD::UZP2";
881 case AArch64ISD::TRN1: return "AArch64ISD::TRN1";
882 case AArch64ISD::TRN2: return "AArch64ISD::TRN2";
883 case AArch64ISD::REV16: return "AArch64ISD::REV16";
884 case AArch64ISD::REV32: return "AArch64ISD::REV32";
885 case AArch64ISD::REV64: return "AArch64ISD::REV64";
886 case AArch64ISD::EXT: return "AArch64ISD::EXT";
887 case AArch64ISD::VSHL: return "AArch64ISD::VSHL";
888 case AArch64ISD::VLSHR: return "AArch64ISD::VLSHR";
889 case AArch64ISD::VASHR: return "AArch64ISD::VASHR";
890 case AArch64ISD::CMEQ: return "AArch64ISD::CMEQ";
891 case AArch64ISD::CMGE: return "AArch64ISD::CMGE";
892 case AArch64ISD::CMGT: return "AArch64ISD::CMGT";
893 case AArch64ISD::CMHI: return "AArch64ISD::CMHI";
894 case AArch64ISD::CMHS: return "AArch64ISD::CMHS";
895 case AArch64ISD::FCMEQ: return "AArch64ISD::FCMEQ";
896 case AArch64ISD::FCMGE: return "AArch64ISD::FCMGE";
897 case AArch64ISD::FCMGT: return "AArch64ISD::FCMGT";
898 case AArch64ISD::CMEQz: return "AArch64ISD::CMEQz";
899 case AArch64ISD::CMGEz: return "AArch64ISD::CMGEz";
900 case AArch64ISD::CMGTz: return "AArch64ISD::CMGTz";
901 case AArch64ISD::CMLEz: return "AArch64ISD::CMLEz";
902 case AArch64ISD::CMLTz: return "AArch64ISD::CMLTz";
903 case AArch64ISD::FCMEQz: return "AArch64ISD::FCMEQz";
904 case AArch64ISD::FCMGEz: return "AArch64ISD::FCMGEz";
905 case AArch64ISD::FCMGTz: return "AArch64ISD::FCMGTz";
906 case AArch64ISD::FCMLEz: return "AArch64ISD::FCMLEz";
907 case AArch64ISD::FCMLTz: return "AArch64ISD::FCMLTz";
Ahmed Bougachafab58922015-03-10 20:45:38 +0000908 case AArch64ISD::SADDV: return "AArch64ISD::SADDV";
909 case AArch64ISD::UADDV: return "AArch64ISD::UADDV";
910 case AArch64ISD::SMINV: return "AArch64ISD::SMINV";
911 case AArch64ISD::UMINV: return "AArch64ISD::UMINV";
912 case AArch64ISD::SMAXV: return "AArch64ISD::SMAXV";
913 case AArch64ISD::UMAXV: return "AArch64ISD::UMAXV";
Tim Northover3b0846e2014-05-24 12:50:23 +0000914 case AArch64ISD::NOT: return "AArch64ISD::NOT";
915 case AArch64ISD::BIT: return "AArch64ISD::BIT";
916 case AArch64ISD::CBZ: return "AArch64ISD::CBZ";
917 case AArch64ISD::CBNZ: return "AArch64ISD::CBNZ";
918 case AArch64ISD::TBZ: return "AArch64ISD::TBZ";
919 case AArch64ISD::TBNZ: return "AArch64ISD::TBNZ";
920 case AArch64ISD::TC_RETURN: return "AArch64ISD::TC_RETURN";
Matthias Braund04893f2015-05-07 21:33:59 +0000921 case AArch64ISD::PREFETCH: return "AArch64ISD::PREFETCH";
Tim Northover3b0846e2014-05-24 12:50:23 +0000922 case AArch64ISD::SITOF: return "AArch64ISD::SITOF";
923 case AArch64ISD::UITOF: return "AArch64ISD::UITOF";
Asiri Rathnayake530b3ed2014-10-01 09:59:45 +0000924 case AArch64ISD::NVCAST: return "AArch64ISD::NVCAST";
Tim Northover3b0846e2014-05-24 12:50:23 +0000925 case AArch64ISD::SQSHL_I: return "AArch64ISD::SQSHL_I";
926 case AArch64ISD::UQSHL_I: return "AArch64ISD::UQSHL_I";
927 case AArch64ISD::SRSHR_I: return "AArch64ISD::SRSHR_I";
928 case AArch64ISD::URSHR_I: return "AArch64ISD::URSHR_I";
929 case AArch64ISD::SQSHLU_I: return "AArch64ISD::SQSHLU_I";
930 case AArch64ISD::WrapperLarge: return "AArch64ISD::WrapperLarge";
931 case AArch64ISD::LD2post: return "AArch64ISD::LD2post";
932 case AArch64ISD::LD3post: return "AArch64ISD::LD3post";
933 case AArch64ISD::LD4post: return "AArch64ISD::LD4post";
934 case AArch64ISD::ST2post: return "AArch64ISD::ST2post";
935 case AArch64ISD::ST3post: return "AArch64ISD::ST3post";
936 case AArch64ISD::ST4post: return "AArch64ISD::ST4post";
937 case AArch64ISD::LD1x2post: return "AArch64ISD::LD1x2post";
938 case AArch64ISD::LD1x3post: return "AArch64ISD::LD1x3post";
939 case AArch64ISD::LD1x4post: return "AArch64ISD::LD1x4post";
940 case AArch64ISD::ST1x2post: return "AArch64ISD::ST1x2post";
941 case AArch64ISD::ST1x3post: return "AArch64ISD::ST1x3post";
942 case AArch64ISD::ST1x4post: return "AArch64ISD::ST1x4post";
943 case AArch64ISD::LD1DUPpost: return "AArch64ISD::LD1DUPpost";
944 case AArch64ISD::LD2DUPpost: return "AArch64ISD::LD2DUPpost";
945 case AArch64ISD::LD3DUPpost: return "AArch64ISD::LD3DUPpost";
946 case AArch64ISD::LD4DUPpost: return "AArch64ISD::LD4DUPpost";
947 case AArch64ISD::LD1LANEpost: return "AArch64ISD::LD1LANEpost";
948 case AArch64ISD::LD2LANEpost: return "AArch64ISD::LD2LANEpost";
949 case AArch64ISD::LD3LANEpost: return "AArch64ISD::LD3LANEpost";
950 case AArch64ISD::LD4LANEpost: return "AArch64ISD::LD4LANEpost";
951 case AArch64ISD::ST2LANEpost: return "AArch64ISD::ST2LANEpost";
952 case AArch64ISD::ST3LANEpost: return "AArch64ISD::ST3LANEpost";
953 case AArch64ISD::ST4LANEpost: return "AArch64ISD::ST4LANEpost";
Chad Rosierd9d0f862014-10-08 02:31:24 +0000954 case AArch64ISD::SMULL: return "AArch64ISD::SMULL";
955 case AArch64ISD::UMULL: return "AArch64ISD::UMULL";
Evandro Menezesbcb95cd2016-05-04 20:18:27 +0000956 case AArch64ISD::FRSQRTE: return "AArch64ISD::FRSQRTE";
957 case AArch64ISD::FRECPE: return "AArch64ISD::FRECPE";
Tim Northover3b0846e2014-05-24 12:50:23 +0000958 }
Matthias Braund04893f2015-05-07 21:33:59 +0000959 return nullptr;
Tim Northover3b0846e2014-05-24 12:50:23 +0000960}
961
962MachineBasicBlock *
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +0000963AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI,
Tim Northover3b0846e2014-05-24 12:50:23 +0000964 MachineBasicBlock *MBB) const {
965 // We materialise the F128CSEL pseudo-instruction as some control flow and a
966 // phi node:
967
968 // OrigBB:
969 // [... previous instrs leading to comparison ...]
970 // b.ne TrueBB
971 // b EndBB
972 // TrueBB:
973 // ; Fallthrough
974 // EndBB:
975 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
976
Tim Northover3b0846e2014-05-24 12:50:23 +0000977 MachineFunction *MF = MBB->getParent();
Eric Christopher905f12d2015-01-29 00:19:42 +0000978 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +0000979 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +0000980 DebugLoc DL = MI.getDebugLoc();
Duncan P. N. Exon Smithd3b9df02015-10-13 20:02:15 +0000981 MachineFunction::iterator It = ++MBB->getIterator();
Tim Northover3b0846e2014-05-24 12:50:23 +0000982
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +0000983 unsigned DestReg = MI.getOperand(0).getReg();
984 unsigned IfTrueReg = MI.getOperand(1).getReg();
985 unsigned IfFalseReg = MI.getOperand(2).getReg();
986 unsigned CondCode = MI.getOperand(3).getImm();
987 bool NZCVKilled = MI.getOperand(4).isKill();
Tim Northover3b0846e2014-05-24 12:50:23 +0000988
989 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
990 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
991 MF->insert(It, TrueBB);
992 MF->insert(It, EndBB);
993
994 // Transfer rest of current basic-block to EndBB
995 EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
996 MBB->end());
997 EndBB->transferSuccessorsAndUpdatePHIs(MBB);
998
999 BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
1000 BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
1001 MBB->addSuccessor(TrueBB);
1002 MBB->addSuccessor(EndBB);
1003
1004 // TrueBB falls through to the end.
1005 TrueBB->addSuccessor(EndBB);
1006
1007 if (!NZCVKilled) {
1008 TrueBB->addLiveIn(AArch64::NZCV);
1009 EndBB->addLiveIn(AArch64::NZCV);
1010 }
1011
1012 BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
1013 .addReg(IfTrueReg)
1014 .addMBB(TrueBB)
1015 .addReg(IfFalseReg)
1016 .addMBB(MBB);
1017
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001018 MI.eraseFromParent();
Tim Northover3b0846e2014-05-24 12:50:23 +00001019 return EndBB;
1020}
1021
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001022MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter(
1023 MachineInstr &MI, MachineBasicBlock *BB) const {
1024 switch (MI.getOpcode()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001025 default:
1026#ifndef NDEBUG
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001027 MI.dump();
Tim Northover3b0846e2014-05-24 12:50:23 +00001028#endif
Craig Topper35b2f752014-06-19 06:10:58 +00001029 llvm_unreachable("Unexpected instruction for custom inserter!");
Tim Northover3b0846e2014-05-24 12:50:23 +00001030
1031 case AArch64::F128CSEL:
1032 return EmitF128CSEL(MI, BB);
1033
1034 case TargetOpcode::STACKMAP:
1035 case TargetOpcode::PATCHPOINT:
1036 return emitPatchPoint(MI, BB);
1037 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001038}
1039
1040//===----------------------------------------------------------------------===//
1041// AArch64 Lowering private implementation.
1042//===----------------------------------------------------------------------===//
1043
1044//===----------------------------------------------------------------------===//
1045// Lowering Code
1046//===----------------------------------------------------------------------===//
1047
1048/// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1049/// CC
1050static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1051 switch (CC) {
1052 default:
1053 llvm_unreachable("Unknown condition code!");
1054 case ISD::SETNE:
1055 return AArch64CC::NE;
1056 case ISD::SETEQ:
1057 return AArch64CC::EQ;
1058 case ISD::SETGT:
1059 return AArch64CC::GT;
1060 case ISD::SETGE:
1061 return AArch64CC::GE;
1062 case ISD::SETLT:
1063 return AArch64CC::LT;
1064 case ISD::SETLE:
1065 return AArch64CC::LE;
1066 case ISD::SETUGT:
1067 return AArch64CC::HI;
1068 case ISD::SETUGE:
1069 return AArch64CC::HS;
1070 case ISD::SETULT:
1071 return AArch64CC::LO;
1072 case ISD::SETULE:
1073 return AArch64CC::LS;
1074 }
1075}
1076
1077/// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1078static void changeFPCCToAArch64CC(ISD::CondCode CC,
1079 AArch64CC::CondCode &CondCode,
1080 AArch64CC::CondCode &CondCode2) {
1081 CondCode2 = AArch64CC::AL;
1082 switch (CC) {
1083 default:
1084 llvm_unreachable("Unknown FP condition!");
1085 case ISD::SETEQ:
1086 case ISD::SETOEQ:
1087 CondCode = AArch64CC::EQ;
1088 break;
1089 case ISD::SETGT:
1090 case ISD::SETOGT:
1091 CondCode = AArch64CC::GT;
1092 break;
1093 case ISD::SETGE:
1094 case ISD::SETOGE:
1095 CondCode = AArch64CC::GE;
1096 break;
1097 case ISD::SETOLT:
1098 CondCode = AArch64CC::MI;
1099 break;
1100 case ISD::SETOLE:
1101 CondCode = AArch64CC::LS;
1102 break;
1103 case ISD::SETONE:
1104 CondCode = AArch64CC::MI;
1105 CondCode2 = AArch64CC::GT;
1106 break;
1107 case ISD::SETO:
1108 CondCode = AArch64CC::VC;
1109 break;
1110 case ISD::SETUO:
1111 CondCode = AArch64CC::VS;
1112 break;
1113 case ISD::SETUEQ:
1114 CondCode = AArch64CC::EQ;
1115 CondCode2 = AArch64CC::VS;
1116 break;
1117 case ISD::SETUGT:
1118 CondCode = AArch64CC::HI;
1119 break;
1120 case ISD::SETUGE:
1121 CondCode = AArch64CC::PL;
1122 break;
1123 case ISD::SETLT:
1124 case ISD::SETULT:
1125 CondCode = AArch64CC::LT;
1126 break;
1127 case ISD::SETLE:
1128 case ISD::SETULE:
1129 CondCode = AArch64CC::LE;
1130 break;
1131 case ISD::SETNE:
1132 case ISD::SETUNE:
1133 CondCode = AArch64CC::NE;
1134 break;
1135 }
1136}
1137
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001138/// Convert a DAG fp condition code to an AArch64 CC.
1139/// This differs from changeFPCCToAArch64CC in that it returns cond codes that
1140/// should be AND'ed instead of OR'ed.
1141static void changeFPCCToANDAArch64CC(ISD::CondCode CC,
1142 AArch64CC::CondCode &CondCode,
1143 AArch64CC::CondCode &CondCode2) {
1144 CondCode2 = AArch64CC::AL;
1145 switch (CC) {
1146 default:
1147 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1148 assert(CondCode2 == AArch64CC::AL);
1149 break;
1150 case ISD::SETONE:
1151 // (a one b)
1152 // == ((a olt b) || (a ogt b))
1153 // == ((a ord b) && (a une b))
1154 CondCode = AArch64CC::VC;
1155 CondCode2 = AArch64CC::NE;
1156 break;
1157 case ISD::SETUEQ:
1158 // (a ueq b)
1159 // == ((a uno b) || (a oeq b))
1160 // == ((a ule b) && (a uge b))
1161 CondCode = AArch64CC::PL;
1162 CondCode2 = AArch64CC::LE;
1163 break;
1164 }
1165}
1166
Tim Northover3b0846e2014-05-24 12:50:23 +00001167/// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1168/// CC usable with the vector instructions. Fewer operations are available
1169/// without a real NZCV register, so we have to use less efficient combinations
1170/// to get the same effect.
1171static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1172 AArch64CC::CondCode &CondCode,
1173 AArch64CC::CondCode &CondCode2,
1174 bool &Invert) {
1175 Invert = false;
1176 switch (CC) {
1177 default:
1178 // Mostly the scalar mappings work fine.
1179 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1180 break;
1181 case ISD::SETUO:
Justin Bognerb03fd122016-08-17 05:10:15 +00001182 Invert = true;
1183 LLVM_FALLTHROUGH;
Tim Northover3b0846e2014-05-24 12:50:23 +00001184 case ISD::SETO:
1185 CondCode = AArch64CC::MI;
1186 CondCode2 = AArch64CC::GE;
1187 break;
1188 case ISD::SETUEQ:
1189 case ISD::SETULT:
1190 case ISD::SETULE:
1191 case ISD::SETUGT:
1192 case ISD::SETUGE:
1193 // All of the compare-mask comparisons are ordered, but we can switch
1194 // between the two by a double inversion. E.g. ULE == !OGT.
1195 Invert = true;
1196 changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1197 break;
1198 }
1199}
1200
1201static bool isLegalArithImmed(uint64_t C) {
1202 // Matches AArch64DAGToDAGISel::SelectArithImmed().
1203 return (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1204}
1205
1206static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00001207 const SDLoc &dl, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001208 EVT VT = LHS.getValueType();
1209
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001210 if (VT.isFloatingPoint()) {
1211 assert(VT != MVT::f128);
1212 if (VT == MVT::f16) {
1213 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
1214 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
Weiming Zhao095c2712016-05-11 01:26:32 +00001215 VT = MVT::f32;
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001216 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001217 return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001218 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001219
1220 // The CMP instruction is just an alias for SUBS, and representing it as
1221 // SUBS means that it's possible to get CSE with subtract operations.
1222 // A later phase can perform the optimization of setting the destination
1223 // register to WZR/XZR if it ends up being unused.
1224 unsigned Opcode = AArch64ISD::SUBS;
1225
Artyom Skrobov314ee042015-11-25 19:41:11 +00001226 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001227 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1228 // We'd like to combine a (CMP op1, (sub 0, op2) into a CMN instruction on
1229 // the grounds that "op1 - (-op2) == op1 + op2". However, the C and V flags
1230 // can be set differently by this operation. It comes down to whether
1231 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1232 // everything is fine. If not then the optimization is wrong. Thus general
1233 // comparisons are only valid if op2 != 0.
1234
1235 // So, finally, the only LLVM-native comparisons that don't mention C and V
1236 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1237 // the absence of information about op2.
1238 Opcode = AArch64ISD::ADDS;
1239 RHS = RHS.getOperand(1);
Artyom Skrobov314ee042015-11-25 19:41:11 +00001240 } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001241 !isUnsignedIntSetCC(CC)) {
1242 // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1243 // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1244 // of the signed comparisons.
1245 Opcode = AArch64ISD::ANDS;
1246 RHS = LHS.getOperand(1);
1247 LHS = LHS.getOperand(0);
1248 }
1249
Matthias Braunaf7d7702015-07-16 20:02:37 +00001250 return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
Tim Northover3b0846e2014-05-24 12:50:23 +00001251 .getValue(1);
1252}
1253
Matthias Braunaf7d7702015-07-16 20:02:37 +00001254/// \defgroup AArch64CCMP CMP;CCMP matching
1255///
1256/// These functions deal with the formation of CMP;CCMP;... sequences.
1257/// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1258/// a comparison. They set the NZCV flags to a predefined value if their
1259/// predicate is false. This allows to express arbitrary conjunctions, for
1260/// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B))))"
1261/// expressed as:
1262/// cmp A
1263/// ccmp B, inv(CB), CA
1264/// check for CB flags
1265///
1266/// In general we can create code for arbitrary "... (and (and A B) C)"
1267/// sequences. We can also implement some "or" expressions, because "(or A B)"
1268/// is equivalent to "not (and (not A) (not B))" and we can implement some
1269/// negation operations:
1270/// We can negate the results of a single comparison by inverting the flags
1271/// used when the predicate fails and inverting the flags tested in the next
1272/// instruction; We can also negate the results of the whole previous
1273/// conditional compare sequence by inverting the flags tested in the next
1274/// instruction. However there is no way to negate the result of a partial
1275/// sequence.
1276///
1277/// Therefore on encountering an "or" expression we can negate the subtree on
1278/// one side and have to be able to push the negate to the leafs of the subtree
1279/// on the other side (see also the comments in code). As complete example:
1280/// "or (or (setCA (cmp A)) (setCB (cmp B)))
1281/// (and (setCC (cmp C)) (setCD (cmp D)))"
1282/// is transformed to
1283/// "not (and (not (and (setCC (cmp C)) (setCC (cmp D))))
1284/// (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1285/// and implemented as:
1286/// cmp C
1287/// ccmp D, inv(CD), CC
1288/// ccmp A, CA, inv(CD)
1289/// ccmp B, CB, inv(CA)
1290/// check for CB flags
1291/// A counterexample is "or (and A B) (and C D)" which cannot be implemented
1292/// by conditional compare sequences.
1293/// @{
1294
Geoff Berrye41c2df2015-07-20 22:03:52 +00001295/// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001296static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1297 ISD::CondCode CC, SDValue CCOp,
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001298 AArch64CC::CondCode Predicate,
1299 AArch64CC::CondCode OutCC,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00001300 const SDLoc &DL, SelectionDAG &DAG) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001301 unsigned Opcode = 0;
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001302 if (LHS.getValueType().isFloatingPoint()) {
1303 assert(LHS.getValueType() != MVT::f128);
1304 if (LHS.getValueType() == MVT::f16) {
1305 LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS);
1306 RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS);
1307 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001308 Opcode = AArch64ISD::FCCMP;
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001309 } else if (RHS.getOpcode() == ISD::SUB) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001310 SDValue SubOp0 = RHS.getOperand(0);
Artyom Skrobov314ee042015-11-25 19:41:11 +00001311 if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
Matthias Braunfd13c142016-01-23 04:05:16 +00001312 // See emitComparison() on why we can only do this for SETEQ and SETNE.
1313 Opcode = AArch64ISD::CCMN;
1314 RHS = RHS.getOperand(1);
1315 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001316 }
1317 if (Opcode == 0)
1318 Opcode = AArch64ISD::CCMP;
1319
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001320 SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC);
1321 AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1322 unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001323 SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1324 return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1325}
1326
1327/// Returns true if @p Val is a tree of AND/OR/SETCC operations.
1328/// CanPushNegate is set to true if we can push a negate operation through
1329/// the tree in a was that we are left with AND operations and negate operations
1330/// at the leafs only. i.e. "not (or (or x y) z)" can be changed to
1331/// "and (and (not x) (not y)) (not z)"; "not (or (and x y) z)" cannot be
1332/// brought into such a form.
Matthias Braunfdef49b2016-01-23 04:05:22 +00001333static bool isConjunctionDisjunctionTree(const SDValue Val, bool &CanNegate,
Matthias Braunaf7d7702015-07-16 20:02:37 +00001334 unsigned Depth = 0) {
1335 if (!Val.hasOneUse())
1336 return false;
1337 unsigned Opcode = Val->getOpcode();
1338 if (Opcode == ISD::SETCC) {
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001339 if (Val->getOperand(0).getValueType() == MVT::f128)
1340 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001341 CanNegate = true;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001342 return true;
1343 }
Matthias Braun985bdf92016-01-23 04:05:18 +00001344 // Protect against exponential runtime and stack overflow.
1345 if (Depth > 6)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001346 return false;
1347 if (Opcode == ISD::AND || Opcode == ISD::OR) {
1348 SDValue O0 = Val->getOperand(0);
1349 SDValue O1 = Val->getOperand(1);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001350 bool CanNegateL;
1351 if (!isConjunctionDisjunctionTree(O0, CanNegateL, Depth+1))
Matthias Braunaf7d7702015-07-16 20:02:37 +00001352 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001353 bool CanNegateR;
1354 if (!isConjunctionDisjunctionTree(O1, CanNegateR, Depth+1))
Matthias Braunaf7d7702015-07-16 20:02:37 +00001355 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001356
1357 if (Opcode == ISD::OR) {
1358 // For an OR expression we need to be able to negate at least one side or
1359 // we cannot do the transformation at all.
1360 if (!CanNegateL && !CanNegateR)
1361 return false;
1362 // We can however change a (not (or x y)) to (and (not x) (not y)) if we
1363 // can negate the x and y subtrees.
1364 CanNegate = CanNegateL && CanNegateR;
1365 } else {
1366 // If the operands are OR expressions then we finally need to negate their
1367 // outputs, we can only do that for the operand with emitted last by
1368 // negating OutCC, not for both operands.
1369 bool NeedsNegOutL = O0->getOpcode() == ISD::OR;
1370 bool NeedsNegOutR = O1->getOpcode() == ISD::OR;
1371 if (NeedsNegOutL && NeedsNegOutR)
1372 return false;
1373 // We cannot negate an AND operation (it would become an OR),
1374 CanNegate = false;
1375 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001376 return true;
1377 }
1378 return false;
1379}
1380
1381/// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1382/// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1383/// Tries to transform the given i1 producing node @p Val to a series compare
1384/// and conditional compare operations. @returns an NZCV flags producing node
1385/// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1386/// transformation was not possible.
1387/// On recursive invocations @p PushNegate may be set to true to have negation
1388/// effects pushed to the tree leafs; @p Predicate is an NZCV flag predicate
1389/// for the comparisons in the current subtree; @p Depth limits the search
1390/// depth to avoid stack overflow.
Matthias Braunfdef49b2016-01-23 04:05:22 +00001391static SDValue emitConjunctionDisjunctionTreeRec(SelectionDAG &DAG, SDValue Val,
1392 AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp,
1393 AArch64CC::CondCode Predicate) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001394 // We're at a tree leaf, produce a conditional comparison operation.
1395 unsigned Opcode = Val->getOpcode();
1396 if (Opcode == ISD::SETCC) {
1397 SDValue LHS = Val->getOperand(0);
1398 SDValue RHS = Val->getOperand(1);
1399 ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1400 bool isInteger = LHS.getValueType().isInteger();
Matthias Braunfdef49b2016-01-23 04:05:22 +00001401 if (Negate)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001402 CC = getSetCCInverse(CC, isInteger);
1403 SDLoc DL(Val);
1404 // Determine OutCC and handle FP special case.
1405 if (isInteger) {
1406 OutCC = changeIntCCToAArch64CC(CC);
1407 } else {
1408 assert(LHS.getValueType().isFloatingPoint());
1409 AArch64CC::CondCode ExtraCC;
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001410 changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
1411 // Some floating point conditions can't be tested with a single condition
1412 // code. Construct an additional comparison in this case.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001413 if (ExtraCC != AArch64CC::AL) {
1414 SDValue ExtraCmp;
1415 if (!CCOp.getNode())
1416 ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001417 else
1418 ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate,
1419 ExtraCC, DL, DAG);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001420 CCOp = ExtraCmp;
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001421 Predicate = ExtraCC;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001422 }
1423 }
1424
1425 // Produce a normal comparison if we are first in the chain
Matthias Braunfdef49b2016-01-23 04:05:22 +00001426 if (!CCOp)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001427 return emitComparison(LHS, RHS, CC, DL, DAG);
1428 // Otherwise produce a ccmp.
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001429 return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL,
Matthias Braunaf7d7702015-07-16 20:02:37 +00001430 DAG);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001431 }
Junmo Park3ca3e192016-01-25 10:17:17 +00001432 assert((Opcode == ISD::AND || (Opcode == ISD::OR && Val->hasOneUse())) &&
1433 "Valid conjunction/disjunction tree");
Matthias Braunaf7d7702015-07-16 20:02:37 +00001434
1435 // Check if both sides can be transformed.
1436 SDValue LHS = Val->getOperand(0);
1437 SDValue RHS = Val->getOperand(1);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001438
Matthias Braunfdef49b2016-01-23 04:05:22 +00001439 // In case of an OR we need to negate our operands and the result.
1440 // (A v B) <=> not(not(A) ^ not(B))
1441 bool NegateOpsAndResult = Opcode == ISD::OR;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001442 // We can negate the results of all previous operations by inverting the
Matthias Braunfdef49b2016-01-23 04:05:22 +00001443 // predicate flags giving us a free negation for one side. The other side
1444 // must be negatable by itself.
1445 if (NegateOpsAndResult) {
1446 // See which side we can negate.
1447 bool CanNegateL;
1448 bool isValidL = isConjunctionDisjunctionTree(LHS, CanNegateL);
1449 assert(isValidL && "Valid conjunction/disjunction tree");
1450 (void)isValidL;
1451
1452#ifndef NDEBUG
1453 bool CanNegateR;
1454 bool isValidR = isConjunctionDisjunctionTree(RHS, CanNegateR);
1455 assert(isValidR && "Valid conjunction/disjunction tree");
1456 assert((CanNegateL || CanNegateR) && "Valid conjunction/disjunction tree");
1457#endif
1458
1459 // Order the side which we cannot negate to RHS so we can emit it first.
1460 if (!CanNegateL)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001461 std::swap(LHS, RHS);
Matthias Braun46e56392015-08-20 23:33:34 +00001462 } else {
1463 bool NeedsNegOutL = LHS->getOpcode() == ISD::OR;
Matthias Braun327bca72016-01-23 06:49:29 +00001464 assert((!NeedsNegOutL || RHS->getOpcode() != ISD::OR) &&
Matthias Braunfdef49b2016-01-23 04:05:22 +00001465 "Valid conjunction/disjunction tree");
Matthias Braun46e56392015-08-20 23:33:34 +00001466 // Order the side where we need to negate the output flags to RHS so it
1467 // gets emitted first.
1468 if (NeedsNegOutL)
1469 std::swap(LHS, RHS);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001470 }
1471
1472 // Emit RHS. If we want to negate the tree we only need to push a negate
1473 // through if we are already in a PushNegate case, otherwise we can negate
1474 // the "flags to test" afterwards.
1475 AArch64CC::CondCode RHSCC;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001476 SDValue CmpR = emitConjunctionDisjunctionTreeRec(DAG, RHS, RHSCC, Negate,
1477 CCOp, Predicate);
1478 if (NegateOpsAndResult && !Negate)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001479 RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001480 // Emit LHS. We may need to negate it.
1481 SDValue CmpL = emitConjunctionDisjunctionTreeRec(DAG, LHS, OutCC,
1482 NegateOpsAndResult, CmpR,
1483 RHSCC);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001484 // If we transformed an OR to and AND then we have to negate the result
Matthias Braunfdef49b2016-01-23 04:05:22 +00001485 // (or absorb the Negate parameter).
1486 if (NegateOpsAndResult && !Negate)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001487 OutCC = AArch64CC::getInvertedCondCode(OutCC);
1488 return CmpL;
1489}
1490
Matthias Braunfdef49b2016-01-23 04:05:22 +00001491/// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1492/// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1493/// \see emitConjunctionDisjunctionTreeRec().
1494static SDValue emitConjunctionDisjunctionTree(SelectionDAG &DAG, SDValue Val,
1495 AArch64CC::CondCode &OutCC) {
1496 bool CanNegate;
1497 if (!isConjunctionDisjunctionTree(Val, CanNegate))
1498 return SDValue();
1499
1500 return emitConjunctionDisjunctionTreeRec(DAG, Val, OutCC, false, SDValue(),
1501 AArch64CC::AL);
1502}
1503
Matthias Braunaf7d7702015-07-16 20:02:37 +00001504/// @}
1505
Tim Northover3b0846e2014-05-24 12:50:23 +00001506static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00001507 SDValue &AArch64cc, SelectionDAG &DAG,
1508 const SDLoc &dl) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001509 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1510 EVT VT = RHS.getValueType();
1511 uint64_t C = RHSC->getZExtValue();
1512 if (!isLegalArithImmed(C)) {
1513 // Constant does not fit, try adjusting it by one?
1514 switch (CC) {
1515 default:
1516 break;
1517 case ISD::SETLT:
1518 case ISD::SETGE:
1519 if ((VT == MVT::i32 && C != 0x80000000 &&
1520 isLegalArithImmed((uint32_t)(C - 1))) ||
1521 (VT == MVT::i64 && C != 0x80000000ULL &&
1522 isLegalArithImmed(C - 1ULL))) {
1523 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1524 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001525 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001526 }
1527 break;
1528 case ISD::SETULT:
1529 case ISD::SETUGE:
1530 if ((VT == MVT::i32 && C != 0 &&
1531 isLegalArithImmed((uint32_t)(C - 1))) ||
1532 (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1533 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1534 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001535 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001536 }
1537 break;
1538 case ISD::SETLE:
1539 case ISD::SETGT:
Oliver Stannard269a275c2014-11-03 15:28:40 +00001540 if ((VT == MVT::i32 && C != INT32_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001541 isLegalArithImmed((uint32_t)(C + 1))) ||
Oliver Stannard269a275c2014-11-03 15:28:40 +00001542 (VT == MVT::i64 && C != INT64_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001543 isLegalArithImmed(C + 1ULL))) {
1544 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1545 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001546 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001547 }
1548 break;
1549 case ISD::SETULE:
1550 case ISD::SETUGT:
Oliver Stannard269a275c2014-11-03 15:28:40 +00001551 if ((VT == MVT::i32 && C != UINT32_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001552 isLegalArithImmed((uint32_t)(C + 1))) ||
Oliver Stannard269a275c2014-11-03 15:28:40 +00001553 (VT == MVT::i64 && C != UINT64_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001554 isLegalArithImmed(C + 1ULL))) {
1555 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1556 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001557 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001558 }
1559 break;
1560 }
1561 }
1562 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001563 SDValue Cmp;
1564 AArch64CC::CondCode AArch64CC;
David Xuee978202014-08-28 04:59:53 +00001565 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001566 const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
1567
1568 // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
1569 // For the i8 operand, the largest immediate is 255, so this can be easily
1570 // encoded in the compare instruction. For the i16 operand, however, the
1571 // largest immediate cannot be encoded in the compare.
1572 // Therefore, use a sign extending load and cmn to avoid materializing the
1573 // -1 constant. For example,
1574 // movz w1, #65535
1575 // ldrh w0, [x0, #0]
1576 // cmp w0, w1
1577 // >
1578 // ldrsh w0, [x0, #0]
1579 // cmn w0, #1
1580 // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
1581 // if and only if (sext LHS) == (sext RHS). The checks are in place to
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001582 // ensure both the LHS and RHS are truly zero extended and to make sure the
Matthias Braunaf7d7702015-07-16 20:02:37 +00001583 // transformation is profitable.
1584 if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
1585 cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
1586 cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
1587 LHS.getNode()->hasNUsesOfValue(1, 0)) {
1588 int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
1589 if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
1590 SDValue SExt =
1591 DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
1592 DAG.getValueType(MVT::i16));
1593 Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
1594 RHS.getValueType()),
1595 CC, dl, DAG);
1596 AArch64CC = changeIntCCToAArch64CC(CC);
1597 }
1598 }
1599
1600 if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
1601 if ((Cmp = emitConjunctionDisjunctionTree(DAG, LHS, AArch64CC))) {
1602 if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
1603 AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
David Xuee978202014-08-28 04:59:53 +00001604 }
1605 }
1606 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001607
1608 if (!Cmp) {
1609 Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
1610 AArch64CC = changeIntCCToAArch64CC(CC);
1611 }
1612 AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
Tim Northover3b0846e2014-05-24 12:50:23 +00001613 return Cmp;
1614}
1615
1616static std::pair<SDValue, SDValue>
1617getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
1618 assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
1619 "Unsupported value type");
1620 SDValue Value, Overflow;
1621 SDLoc DL(Op);
1622 SDValue LHS = Op.getOperand(0);
1623 SDValue RHS = Op.getOperand(1);
1624 unsigned Opc = 0;
1625 switch (Op.getOpcode()) {
1626 default:
1627 llvm_unreachable("Unknown overflow instruction!");
1628 case ISD::SADDO:
1629 Opc = AArch64ISD::ADDS;
1630 CC = AArch64CC::VS;
1631 break;
1632 case ISD::UADDO:
1633 Opc = AArch64ISD::ADDS;
1634 CC = AArch64CC::HS;
1635 break;
1636 case ISD::SSUBO:
1637 Opc = AArch64ISD::SUBS;
1638 CC = AArch64CC::VS;
1639 break;
1640 case ISD::USUBO:
1641 Opc = AArch64ISD::SUBS;
1642 CC = AArch64CC::LO;
1643 break;
1644 // Multiply needs a little bit extra work.
1645 case ISD::SMULO:
1646 case ISD::UMULO: {
1647 CC = AArch64CC::NE;
David Blaikie186d2cb2015-03-24 16:24:01 +00001648 bool IsSigned = Op.getOpcode() == ISD::SMULO;
Tim Northover3b0846e2014-05-24 12:50:23 +00001649 if (Op.getValueType() == MVT::i32) {
1650 unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1651 // For a 32 bit multiply with overflow check we want the instruction
1652 // selector to generate a widening multiply (SMADDL/UMADDL). For that we
1653 // need to generate the following pattern:
1654 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
1655 LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
1656 RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
1657 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1658 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001659 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001660 // On AArch64 the upper 32 bits are always zero extended for a 32 bit
1661 // operation. We need to clear out the upper 32 bits, because we used a
1662 // widening multiply that wrote all 64 bits. In the end this should be a
1663 // noop.
1664 Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
1665 if (IsSigned) {
1666 // The signed overflow check requires more than just a simple check for
1667 // any bit set in the upper 32 bits of the result. These bits could be
1668 // just the sign bits of a negative number. To perform the overflow
1669 // check we have to arithmetic shift right the 32nd bit of the result by
1670 // 31 bits. Then we compare the result to the upper 32 bits.
1671 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001672 DAG.getConstant(32, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001673 UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
1674 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001675 DAG.getConstant(31, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001676 // It is important that LowerBits is last, otherwise the arithmetic
1677 // shift will not be folded into the compare (SUBS).
1678 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
1679 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1680 .getValue(1);
1681 } else {
1682 // The overflow check for unsigned multiply is easy. We only need to
1683 // check if any of the upper 32 bits are set. This can be done with a
1684 // CMP (shifted register). For that we need to generate the following
1685 // pattern:
1686 // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
1687 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001688 DAG.getConstant(32, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001689 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1690 Overflow =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001691 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1692 DAG.getConstant(0, DL, MVT::i64),
Tim Northover3b0846e2014-05-24 12:50:23 +00001693 UpperBits).getValue(1);
1694 }
1695 break;
1696 }
1697 assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
1698 // For the 64 bit multiply
1699 Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1700 if (IsSigned) {
1701 SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
1702 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001703 DAG.getConstant(63, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001704 // It is important that LowerBits is last, otherwise the arithmetic
1705 // shift will not be folded into the compare (SUBS).
1706 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1707 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1708 .getValue(1);
1709 } else {
1710 SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
1711 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1712 Overflow =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001713 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1714 DAG.getConstant(0, DL, MVT::i64),
Tim Northover3b0846e2014-05-24 12:50:23 +00001715 UpperBits).getValue(1);
1716 }
1717 break;
1718 }
1719 } // switch (...)
1720
1721 if (Opc) {
1722 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
1723
1724 // Emit the AArch64 operation with overflow check.
1725 Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
1726 Overflow = Value.getValue(1);
1727 }
1728 return std::make_pair(Value, Overflow);
1729}
1730
1731SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
1732 RTLIB::Libcall Call) const {
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00001733 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
Craig Topper8fe40e02015-10-22 17:05:00 +00001734 return makeLibCall(DAG, Call, MVT::f128, Ops, false, SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00001735}
1736
1737static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
1738 SDValue Sel = Op.getOperand(0);
1739 SDValue Other = Op.getOperand(1);
1740
1741 // If neither operand is a SELECT_CC, give up.
1742 if (Sel.getOpcode() != ISD::SELECT_CC)
1743 std::swap(Sel, Other);
1744 if (Sel.getOpcode() != ISD::SELECT_CC)
1745 return Op;
1746
1747 // The folding we want to perform is:
1748 // (xor x, (select_cc a, b, cc, 0, -1) )
1749 // -->
1750 // (csel x, (xor x, -1), cc ...)
1751 //
1752 // The latter will get matched to a CSINV instruction.
1753
1754 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
1755 SDValue LHS = Sel.getOperand(0);
1756 SDValue RHS = Sel.getOperand(1);
1757 SDValue TVal = Sel.getOperand(2);
1758 SDValue FVal = Sel.getOperand(3);
1759 SDLoc dl(Sel);
1760
1761 // FIXME: This could be generalized to non-integer comparisons.
1762 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
1763 return Op;
1764
1765 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
1766 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
1767
Eric Christopher572e03a2015-06-19 01:53:21 +00001768 // The values aren't constants, this isn't the pattern we're looking for.
Tim Northover3b0846e2014-05-24 12:50:23 +00001769 if (!CFVal || !CTVal)
1770 return Op;
1771
1772 // We can commute the SELECT_CC by inverting the condition. This
1773 // might be needed to make this fit into a CSINV pattern.
1774 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
1775 std::swap(TVal, FVal);
1776 std::swap(CTVal, CFVal);
1777 CC = ISD::getSetCCInverse(CC, true);
1778 }
1779
1780 // If the constants line up, perform the transform!
1781 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
1782 SDValue CCVal;
1783 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
1784
1785 FVal = Other;
1786 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001787 DAG.getConstant(-1ULL, dl, Other.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00001788
1789 return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
1790 CCVal, Cmp);
1791 }
1792
1793 return Op;
1794}
1795
1796static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
1797 EVT VT = Op.getValueType();
1798
1799 // Let legalize expand this if it isn't a legal type yet.
1800 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
1801 return SDValue();
1802
1803 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
1804
1805 unsigned Opc;
1806 bool ExtraOp = false;
1807 switch (Op.getOpcode()) {
1808 default:
Craig Topper2a30d782014-06-18 05:05:13 +00001809 llvm_unreachable("Invalid code");
Tim Northover3b0846e2014-05-24 12:50:23 +00001810 case ISD::ADDC:
1811 Opc = AArch64ISD::ADDS;
1812 break;
1813 case ISD::SUBC:
1814 Opc = AArch64ISD::SUBS;
1815 break;
1816 case ISD::ADDE:
1817 Opc = AArch64ISD::ADCS;
1818 ExtraOp = true;
1819 break;
1820 case ISD::SUBE:
1821 Opc = AArch64ISD::SBCS;
1822 ExtraOp = true;
1823 break;
1824 }
1825
1826 if (!ExtraOp)
1827 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
1828 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
1829 Op.getOperand(2));
1830}
1831
1832static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
1833 // Let legalize expand this if it isn't a legal type yet.
1834 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
1835 return SDValue();
1836
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001837 SDLoc dl(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00001838 AArch64CC::CondCode CC;
1839 // The actual operation that sets the overflow or carry flag.
1840 SDValue Value, Overflow;
1841 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
1842
1843 // We use 0 and 1 as false and true values.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001844 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
1845 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00001846
1847 // We use an inverted condition, because the conditional select is inverted
1848 // too. This will allow it to be selected to a single instruction:
1849 // CSINC Wd, WZR, WZR, invert(cond).
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001850 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
1851 Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
Tim Northover3b0846e2014-05-24 12:50:23 +00001852 CCVal, Overflow);
1853
1854 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001855 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
Tim Northover3b0846e2014-05-24 12:50:23 +00001856}
1857
1858// Prefetch operands are:
1859// 1: Address to prefetch
1860// 2: bool isWrite
1861// 3: int locality (0 = no locality ... 3 = extreme locality)
1862// 4: bool isDataCache
1863static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
1864 SDLoc DL(Op);
1865 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
1866 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
Yi Konge56de692014-08-05 12:46:47 +00001867 unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00001868
1869 bool IsStream = !Locality;
1870 // When the locality number is set
1871 if (Locality) {
1872 // The front-end should have filtered out the out-of-range values
1873 assert(Locality <= 3 && "Prefetch locality out-of-range");
1874 // The locality degree is the opposite of the cache speed.
1875 // Put the number the other way around.
1876 // The encoding starts at 0 for level 1
1877 Locality = 3 - Locality;
1878 }
1879
1880 // built the mask value encoding the expected behavior.
1881 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit
Yi Konge56de692014-08-05 12:46:47 +00001882 (!IsData << 3) | // IsDataCache bit
Tim Northover3b0846e2014-05-24 12:50:23 +00001883 (Locality << 1) | // Cache level bits
1884 (unsigned)IsStream; // Stream bit
1885 return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001886 DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00001887}
1888
1889SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
1890 SelectionDAG &DAG) const {
1891 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
1892
1893 RTLIB::Libcall LC;
1894 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
1895
1896 return LowerF128Call(Op, DAG, LC);
1897}
1898
1899SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
1900 SelectionDAG &DAG) const {
1901 if (Op.getOperand(0).getValueType() != MVT::f128) {
1902 // It's legal except when f128 is involved
1903 return Op;
1904 }
1905
1906 RTLIB::Libcall LC;
1907 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
1908
1909 // FP_ROUND node has a second operand indicating whether it is known to be
1910 // precise. That doesn't take part in the LibCall so we can't directly use
1911 // LowerF128Call.
1912 SDValue SrcVal = Op.getOperand(0);
Craig Topper8fe40e02015-10-22 17:05:00 +00001913 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
1914 SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00001915}
1916
1917static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
1918 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1919 // Any additional optimization in this function should be recorded
1920 // in the cost tables.
1921 EVT InVT = Op.getOperand(0).getValueType();
1922 EVT VT = Op.getValueType();
Pirama Arumuga Nainar1317d5f2015-12-10 17:16:49 +00001923 unsigned NumElts = InVT.getVectorNumElements();
1924
1925 // f16 vectors are promoted to f32 before a conversion.
1926 if (InVT.getVectorElementType() == MVT::f16) {
1927 MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
1928 SDLoc dl(Op);
1929 return DAG.getNode(
1930 Op.getOpcode(), dl, Op.getValueType(),
1931 DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
1932 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001933
Tim Northoverdbecc3b2014-06-15 09:27:15 +00001934 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001935 SDLoc dl(Op);
1936 SDValue Cv =
1937 DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
1938 Op.getOperand(0));
1939 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
Tim Northoverdbecc3b2014-06-15 09:27:15 +00001940 }
1941
1942 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001943 SDLoc dl(Op);
Oliver Stannard89d15422014-08-27 16:16:04 +00001944 MVT ExtVT =
1945 MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
1946 VT.getVectorNumElements());
1947 SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
Tim Northover3b0846e2014-05-24 12:50:23 +00001948 return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
1949 }
1950
1951 // Type changing conversions are illegal.
Tim Northoverdbecc3b2014-06-15 09:27:15 +00001952 return Op;
Tim Northover3b0846e2014-05-24 12:50:23 +00001953}
1954
1955SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
1956 SelectionDAG &DAG) const {
1957 if (Op.getOperand(0).getValueType().isVector())
1958 return LowerVectorFP_TO_INT(Op, DAG);
1959
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00001960 // f16 conversions are promoted to f32.
1961 if (Op.getOperand(0).getValueType() == MVT::f16) {
1962 SDLoc dl(Op);
1963 return DAG.getNode(
1964 Op.getOpcode(), dl, Op.getValueType(),
1965 DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
1966 }
1967
Tim Northover3b0846e2014-05-24 12:50:23 +00001968 if (Op.getOperand(0).getValueType() != MVT::f128) {
1969 // It's legal except when f128 is involved
1970 return Op;
1971 }
1972
1973 RTLIB::Libcall LC;
1974 if (Op.getOpcode() == ISD::FP_TO_SINT)
1975 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
1976 else
1977 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
1978
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00001979 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
Craig Topper8fe40e02015-10-22 17:05:00 +00001980 return makeLibCall(DAG, LC, Op.getValueType(), Ops, false, SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00001981}
1982
1983static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
1984 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1985 // Any additional optimization in this function should be recorded
1986 // in the cost tables.
1987 EVT VT = Op.getValueType();
1988 SDLoc dl(Op);
1989 SDValue In = Op.getOperand(0);
1990 EVT InVT = In.getValueType();
1991
Tim Northoveref0d7602014-06-15 09:27:06 +00001992 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
1993 MVT CastVT =
1994 MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
1995 InVT.getVectorNumElements());
1996 In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001997 return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
Tim Northover3b0846e2014-05-24 12:50:23 +00001998 }
1999
Tim Northoveref0d7602014-06-15 09:27:06 +00002000 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2001 unsigned CastOpc =
2002 Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2003 EVT CastVT = VT.changeVectorElementTypeToInteger();
2004 In = DAG.getNode(CastOpc, dl, CastVT, In);
2005 return DAG.getNode(Op.getOpcode(), dl, VT, In);
Tim Northover3b0846e2014-05-24 12:50:23 +00002006 }
2007
Tim Northoveref0d7602014-06-15 09:27:06 +00002008 return Op;
Tim Northover3b0846e2014-05-24 12:50:23 +00002009}
2010
2011SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
2012 SelectionDAG &DAG) const {
2013 if (Op.getValueType().isVector())
2014 return LowerVectorINT_TO_FP(Op, DAG);
2015
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00002016 // f16 conversions are promoted to f32.
2017 if (Op.getValueType() == MVT::f16) {
2018 SDLoc dl(Op);
2019 return DAG.getNode(
2020 ISD::FP_ROUND, dl, MVT::f16,
2021 DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002022 DAG.getIntPtrConstant(0, dl));
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00002023 }
2024
Tim Northover3b0846e2014-05-24 12:50:23 +00002025 // i128 conversions are libcalls.
2026 if (Op.getOperand(0).getValueType() == MVT::i128)
2027 return SDValue();
2028
2029 // Other conversions are legal, unless it's to the completely software-based
2030 // fp128.
2031 if (Op.getValueType() != MVT::f128)
2032 return Op;
2033
2034 RTLIB::Libcall LC;
2035 if (Op.getOpcode() == ISD::SINT_TO_FP)
2036 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2037 else
2038 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2039
2040 return LowerF128Call(Op, DAG, LC);
2041}
2042
2043SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
2044 SelectionDAG &DAG) const {
2045 // For iOS, we want to call an alternative entry point: __sincos_stret,
2046 // which returns the values in two S / D registers.
2047 SDLoc dl(Op);
2048 SDValue Arg = Op.getOperand(0);
2049 EVT ArgVT = Arg.getValueType();
2050 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2051
2052 ArgListTy Args;
2053 ArgListEntry Entry;
2054
2055 Entry.Node = Arg;
2056 Entry.Ty = ArgTy;
2057 Entry.isSExt = false;
2058 Entry.isZExt = false;
2059 Args.push_back(Entry);
2060
2061 const char *LibcallName =
2062 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
Mehdi Amini44ede332015-07-09 02:09:04 +00002063 SDValue Callee =
2064 DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00002065
Reid Kleckner343c3952014-11-20 23:51:47 +00002066 StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
Tim Northover3b0846e2014-05-24 12:50:23 +00002067 TargetLowering::CallLoweringInfo CLI(DAG);
2068 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
Krzysztof Parzyszeke116d5002016-06-22 12:54:25 +00002069 .setCallee(CallingConv::Fast, RetTy, Callee, std::move(Args));
Tim Northover3b0846e2014-05-24 12:50:23 +00002070
2071 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2072 return CallResult.first;
2073}
2074
Tim Northoverf8bfe212014-07-18 13:07:05 +00002075static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
2076 if (Op.getValueType() != MVT::f16)
2077 return SDValue();
2078
2079 assert(Op.getOperand(0).getValueType() == MVT::i16);
2080 SDLoc DL(Op);
2081
2082 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
2083 Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
2084 return SDValue(
2085 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002086 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
Tim Northoverf8bfe212014-07-18 13:07:05 +00002087 0);
2088}
2089
Chad Rosierd9d0f862014-10-08 02:31:24 +00002090static EVT getExtensionTo64Bits(const EVT &OrigVT) {
2091 if (OrigVT.getSizeInBits() >= 64)
2092 return OrigVT;
2093
2094 assert(OrigVT.isSimple() && "Expecting a simple value type");
2095
2096 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
2097 switch (OrigSimpleTy) {
2098 default: llvm_unreachable("Unexpected Vector Type");
2099 case MVT::v2i8:
2100 case MVT::v2i16:
2101 return MVT::v2i32;
2102 case MVT::v4i8:
2103 return MVT::v4i16;
2104 }
2105}
2106
2107static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2108 const EVT &OrigTy,
2109 const EVT &ExtTy,
2110 unsigned ExtOpcode) {
2111 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2112 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2113 // 64-bits we need to insert a new extension so that it will be 64-bits.
2114 assert(ExtTy.is128BitVector() && "Unexpected extension size");
2115 if (OrigTy.getSizeInBits() >= 64)
2116 return N;
2117
2118 // Must extend size to at least 64 bits to be used as an operand for VMULL.
2119 EVT NewVT = getExtensionTo64Bits(OrigTy);
2120
2121 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2122}
2123
2124static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2125 bool isSigned) {
2126 EVT VT = N->getValueType(0);
2127
2128 if (N->getOpcode() != ISD::BUILD_VECTOR)
2129 return false;
2130
Pete Cooper3af9a252015-06-26 18:17:36 +00002131 for (const SDValue &Elt : N->op_values()) {
Chad Rosierd9d0f862014-10-08 02:31:24 +00002132 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
2133 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
2134 unsigned HalfSize = EltSize / 2;
2135 if (isSigned) {
2136 if (!isIntN(HalfSize, C->getSExtValue()))
2137 return false;
2138 } else {
2139 if (!isUIntN(HalfSize, C->getZExtValue()))
2140 return false;
2141 }
2142 continue;
2143 }
2144 return false;
2145 }
2146
2147 return true;
2148}
2149
2150static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2151 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2152 return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2153 N->getOperand(0)->getValueType(0),
2154 N->getValueType(0),
2155 N->getOpcode());
2156
2157 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2158 EVT VT = N->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002159 SDLoc dl(N);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002160 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
2161 unsigned NumElts = VT.getVectorNumElements();
2162 MVT TruncVT = MVT::getIntegerVT(EltSize);
2163 SmallVector<SDValue, 8> Ops;
2164 for (unsigned i = 0; i != NumElts; ++i) {
2165 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2166 const APInt &CInt = C->getAPIntValue();
2167 // Element types smaller than 32 bits are not legal, so use i32 elements.
2168 // The values are implicitly truncated so sext vs. zext doesn't matter.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002169 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
Chad Rosierd9d0f862014-10-08 02:31:24 +00002170 }
Ahmed Bougacha128f8732016-04-26 21:15:30 +00002171 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002172}
2173
2174static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
2175 if (N->getOpcode() == ISD::SIGN_EXTEND)
2176 return true;
2177 if (isExtendedBUILD_VECTOR(N, DAG, true))
2178 return true;
2179 return false;
2180}
2181
2182static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
2183 if (N->getOpcode() == ISD::ZERO_EXTEND)
2184 return true;
2185 if (isExtendedBUILD_VECTOR(N, DAG, false))
2186 return true;
2187 return false;
2188}
2189
2190static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2191 unsigned Opcode = N->getOpcode();
2192 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2193 SDNode *N0 = N->getOperand(0).getNode();
2194 SDNode *N1 = N->getOperand(1).getNode();
2195 return N0->hasOneUse() && N1->hasOneUse() &&
2196 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2197 }
2198 return false;
2199}
2200
2201static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2202 unsigned Opcode = N->getOpcode();
2203 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2204 SDNode *N0 = N->getOperand(0).getNode();
2205 SDNode *N1 = N->getOperand(1).getNode();
2206 return N0->hasOneUse() && N1->hasOneUse() &&
2207 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2208 }
2209 return false;
2210}
2211
2212static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2213 // Multiplications are only custom-lowered for 128-bit vectors so that
2214 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
2215 EVT VT = Op.getValueType();
2216 assert(VT.is128BitVector() && VT.isInteger() &&
2217 "unexpected type for custom-lowering ISD::MUL");
2218 SDNode *N0 = Op.getOperand(0).getNode();
2219 SDNode *N1 = Op.getOperand(1).getNode();
2220 unsigned NewOpc = 0;
2221 bool isMLA = false;
2222 bool isN0SExt = isSignExtended(N0, DAG);
2223 bool isN1SExt = isSignExtended(N1, DAG);
2224 if (isN0SExt && isN1SExt)
2225 NewOpc = AArch64ISD::SMULL;
2226 else {
2227 bool isN0ZExt = isZeroExtended(N0, DAG);
2228 bool isN1ZExt = isZeroExtended(N1, DAG);
2229 if (isN0ZExt && isN1ZExt)
2230 NewOpc = AArch64ISD::UMULL;
2231 else if (isN1SExt || isN1ZExt) {
2232 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2233 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2234 if (isN1SExt && isAddSubSExt(N0, DAG)) {
2235 NewOpc = AArch64ISD::SMULL;
2236 isMLA = true;
2237 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2238 NewOpc = AArch64ISD::UMULL;
2239 isMLA = true;
2240 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2241 std::swap(N0, N1);
2242 NewOpc = AArch64ISD::UMULL;
2243 isMLA = true;
2244 }
2245 }
2246
2247 if (!NewOpc) {
2248 if (VT == MVT::v2i64)
2249 // Fall through to expand this. It is not legal.
2250 return SDValue();
2251 else
2252 // Other vector multiplications are legal.
2253 return Op;
2254 }
2255 }
2256
2257 // Legalize to a S/UMULL instruction
2258 SDLoc DL(Op);
2259 SDValue Op0;
2260 SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2261 if (!isMLA) {
2262 Op0 = skipExtensionForVectorMULL(N0, DAG);
2263 assert(Op0.getValueType().is64BitVector() &&
2264 Op1.getValueType().is64BitVector() &&
2265 "unexpected types for extended operands to VMULL");
2266 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2267 }
2268 // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2269 // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2270 // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2271 SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2272 SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2273 EVT Op1VT = Op1.getValueType();
2274 return DAG.getNode(N0->getOpcode(), DL, VT,
2275 DAG.getNode(NewOpc, DL, VT,
2276 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2277 DAG.getNode(NewOpc, DL, VT,
2278 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2279}
Tim Northoverf8bfe212014-07-18 13:07:05 +00002280
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002281SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2282 SelectionDAG &DAG) const {
2283 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2284 SDLoc dl(Op);
2285 switch (IntNo) {
2286 default: return SDValue(); // Don't custom lower most intrinsics.
Marcin Koscielnicki3fdc2572016-04-19 20:51:05 +00002287 case Intrinsic::thread_pointer: {
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002288 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2289 return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
2290 }
Silviu Barangadb1ddb32015-08-26 11:11:14 +00002291 case Intrinsic::aarch64_neon_smax:
2292 return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
2293 Op.getOperand(1), Op.getOperand(2));
2294 case Intrinsic::aarch64_neon_umax:
2295 return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
2296 Op.getOperand(1), Op.getOperand(2));
2297 case Intrinsic::aarch64_neon_smin:
2298 return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
2299 Op.getOperand(1), Op.getOperand(2));
2300 case Intrinsic::aarch64_neon_umin:
2301 return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
2302 Op.getOperand(1), Op.getOperand(2));
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002303 }
2304}
2305
Tim Northover3b0846e2014-05-24 12:50:23 +00002306SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
2307 SelectionDAG &DAG) const {
2308 switch (Op.getOpcode()) {
2309 default:
2310 llvm_unreachable("unimplemented operand");
2311 return SDValue();
Tim Northoverf8bfe212014-07-18 13:07:05 +00002312 case ISD::BITCAST:
2313 return LowerBITCAST(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002314 case ISD::GlobalAddress:
2315 return LowerGlobalAddress(Op, DAG);
2316 case ISD::GlobalTLSAddress:
2317 return LowerGlobalTLSAddress(Op, DAG);
2318 case ISD::SETCC:
2319 return LowerSETCC(Op, DAG);
2320 case ISD::BR_CC:
2321 return LowerBR_CC(Op, DAG);
2322 case ISD::SELECT:
2323 return LowerSELECT(Op, DAG);
2324 case ISD::SELECT_CC:
2325 return LowerSELECT_CC(Op, DAG);
2326 case ISD::JumpTable:
2327 return LowerJumpTable(Op, DAG);
2328 case ISD::ConstantPool:
2329 return LowerConstantPool(Op, DAG);
2330 case ISD::BlockAddress:
2331 return LowerBlockAddress(Op, DAG);
2332 case ISD::VASTART:
2333 return LowerVASTART(Op, DAG);
2334 case ISD::VACOPY:
2335 return LowerVACOPY(Op, DAG);
2336 case ISD::VAARG:
2337 return LowerVAARG(Op, DAG);
2338 case ISD::ADDC:
2339 case ISD::ADDE:
2340 case ISD::SUBC:
2341 case ISD::SUBE:
2342 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
2343 case ISD::SADDO:
2344 case ISD::UADDO:
2345 case ISD::SSUBO:
2346 case ISD::USUBO:
2347 case ISD::SMULO:
2348 case ISD::UMULO:
2349 return LowerXALUO(Op, DAG);
2350 case ISD::FADD:
2351 return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
2352 case ISD::FSUB:
2353 return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
2354 case ISD::FMUL:
2355 return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
2356 case ISD::FDIV:
2357 return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
2358 case ISD::FP_ROUND:
2359 return LowerFP_ROUND(Op, DAG);
2360 case ISD::FP_EXTEND:
2361 return LowerFP_EXTEND(Op, DAG);
2362 case ISD::FRAMEADDR:
2363 return LowerFRAMEADDR(Op, DAG);
2364 case ISD::RETURNADDR:
2365 return LowerRETURNADDR(Op, DAG);
2366 case ISD::INSERT_VECTOR_ELT:
2367 return LowerINSERT_VECTOR_ELT(Op, DAG);
2368 case ISD::EXTRACT_VECTOR_ELT:
2369 return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2370 case ISD::BUILD_VECTOR:
2371 return LowerBUILD_VECTOR(Op, DAG);
2372 case ISD::VECTOR_SHUFFLE:
2373 return LowerVECTOR_SHUFFLE(Op, DAG);
2374 case ISD::EXTRACT_SUBVECTOR:
2375 return LowerEXTRACT_SUBVECTOR(Op, DAG);
2376 case ISD::SRA:
2377 case ISD::SRL:
2378 case ISD::SHL:
2379 return LowerVectorSRA_SRL_SHL(Op, DAG);
2380 case ISD::SHL_PARTS:
2381 return LowerShiftLeftParts(Op, DAG);
2382 case ISD::SRL_PARTS:
2383 case ISD::SRA_PARTS:
2384 return LowerShiftRightParts(Op, DAG);
2385 case ISD::CTPOP:
2386 return LowerCTPOP(Op, DAG);
2387 case ISD::FCOPYSIGN:
2388 return LowerFCOPYSIGN(Op, DAG);
2389 case ISD::AND:
Balaram Makamd4acd7e2016-07-05 20:24:05 +00002390 return LowerVectorAND(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002391 case ISD::OR:
Balaram Makamd4acd7e2016-07-05 20:24:05 +00002392 return LowerVectorOR(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002393 case ISD::XOR:
2394 return LowerXOR(Op, DAG);
2395 case ISD::PREFETCH:
2396 return LowerPREFETCH(Op, DAG);
2397 case ISD::SINT_TO_FP:
2398 case ISD::UINT_TO_FP:
2399 return LowerINT_TO_FP(Op, DAG);
2400 case ISD::FP_TO_SINT:
2401 case ISD::FP_TO_UINT:
2402 return LowerFP_TO_INT(Op, DAG);
2403 case ISD::FSINCOS:
2404 return LowerFSINCOS(Op, DAG);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002405 case ISD::MUL:
2406 return LowerMUL(Op, DAG);
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002407 case ISD::INTRINSIC_WO_CHAIN:
2408 return LowerINTRINSIC_WO_CHAIN(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002409 }
2410}
2411
Tim Northover3b0846e2014-05-24 12:50:23 +00002412//===----------------------------------------------------------------------===//
2413// Calling Convention Implementation
2414//===----------------------------------------------------------------------===//
2415
2416#include "AArch64GenCallingConv.inc"
2417
Robin Morisset039781e2014-08-29 21:53:01 +00002418/// Selects the correct CCAssignFn for a given CallingConvention value.
Tim Northover3b0846e2014-05-24 12:50:23 +00002419CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2420 bool IsVarArg) const {
2421 switch (CC) {
2422 default:
2423 llvm_unreachable("Unsupported calling convention.");
2424 case CallingConv::WebKit_JS:
2425 return CC_AArch64_WebKit_JS;
Greg Fitzgeraldfa78d082015-01-19 17:40:05 +00002426 case CallingConv::GHC:
2427 return CC_AArch64_GHC;
Tim Northover3b0846e2014-05-24 12:50:23 +00002428 case CallingConv::C:
2429 case CallingConv::Fast:
Roman Levenstein2792b3f2016-03-10 04:35:09 +00002430 case CallingConv::PreserveMost:
Manman Ren2828c572016-03-18 23:38:49 +00002431 case CallingConv::CXX_FAST_TLS:
Tim Northover3b0846e2014-05-24 12:50:23 +00002432 if (!Subtarget->isTargetDarwin())
2433 return CC_AArch64_AAPCS;
2434 return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
2435 }
2436}
2437
Tim Northover406024a2016-08-10 21:44:01 +00002438CCAssignFn *
2439AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const {
2440 return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
2441 : RetCC_AArch64_AAPCS;
2442}
2443
Tim Northover3b0846e2014-05-24 12:50:23 +00002444SDValue AArch64TargetLowering::LowerFormalArguments(
2445 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00002446 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2447 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00002448 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braun941a7052016-07-28 18:40:00 +00002449 MachineFrameInfo &MFI = MF.getFrameInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00002450
2451 // Assign locations to all of the incoming arguments.
2452 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002453 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2454 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002455
2456 // At this point, Ins[].VT may already be promoted to i32. To correctly
2457 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2458 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2459 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
2460 // we use a special version of AnalyzeFormalArguments to pass in ValVT and
2461 // LocVT.
2462 unsigned NumArgs = Ins.size();
2463 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2464 unsigned CurArgIdx = 0;
2465 for (unsigned i = 0; i != NumArgs; ++i) {
2466 MVT ValVT = Ins[i].VT;
Andrew Trick05938a52015-02-16 18:10:47 +00002467 if (Ins[i].isOrigArg()) {
2468 std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
2469 CurArgIdx = Ins[i].getOrigArgIndex();
Tim Northover3b0846e2014-05-24 12:50:23 +00002470
Andrew Trick05938a52015-02-16 18:10:47 +00002471 // Get type of the original argument.
Mehdi Amini44ede332015-07-09 02:09:04 +00002472 EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
2473 /*AllowUnknown*/ true);
Andrew Trick05938a52015-02-16 18:10:47 +00002474 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
2475 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2476 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2477 ValVT = MVT::i8;
2478 else if (ActualMVT == MVT::i16)
2479 ValVT = MVT::i16;
2480 }
Tim Northover3b0846e2014-05-24 12:50:23 +00002481 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2482 bool Res =
Tim Northover47e003c2014-05-26 17:21:53 +00002483 AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00002484 assert(!Res && "Call operand has unhandled type");
2485 (void)Res;
2486 }
2487 assert(ArgLocs.size() == Ins.size());
2488 SmallVector<SDValue, 16> ArgValues;
2489 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2490 CCValAssign &VA = ArgLocs[i];
2491
2492 if (Ins[i].Flags.isByVal()) {
2493 // Byval is used for HFAs in the PCS, but the system should work in a
2494 // non-compliant manner for larger structs.
Mehdi Amini44ede332015-07-09 02:09:04 +00002495 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00002496 int Size = Ins[i].Flags.getByValSize();
2497 unsigned NumRegs = (Size + 7) / 8;
2498
2499 // FIXME: This works on big-endian for composite byvals, which are the common
2500 // case. It should also work for fundamental types too.
2501 unsigned FrameIdx =
Matthias Braun941a7052016-07-28 18:40:00 +00002502 MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
Mehdi Amini44ede332015-07-09 02:09:04 +00002503 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00002504 InVals.push_back(FrameIdxN);
2505
2506 continue;
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002507 }
Junmo Park3b8c7152016-01-05 09:36:47 +00002508
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002509 if (VA.isRegLoc()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00002510 // Arguments stored in registers.
2511 EVT RegVT = VA.getLocVT();
2512
2513 SDValue ArgValue;
2514 const TargetRegisterClass *RC;
2515
2516 if (RegVT == MVT::i32)
2517 RC = &AArch64::GPR32RegClass;
2518 else if (RegVT == MVT::i64)
2519 RC = &AArch64::GPR64RegClass;
Oliver Stannard6eda6ff2014-07-11 13:33:46 +00002520 else if (RegVT == MVT::f16)
2521 RC = &AArch64::FPR16RegClass;
Tim Northover3b0846e2014-05-24 12:50:23 +00002522 else if (RegVT == MVT::f32)
2523 RC = &AArch64::FPR32RegClass;
2524 else if (RegVT == MVT::f64 || RegVT.is64BitVector())
2525 RC = &AArch64::FPR64RegClass;
2526 else if (RegVT == MVT::f128 || RegVT.is128BitVector())
2527 RC = &AArch64::FPR128RegClass;
2528 else
2529 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2530
2531 // Transform the arguments in physical registers into virtual ones.
2532 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2533 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2534
2535 // If this is an 8, 16 or 32-bit value, it is really passed promoted
2536 // to 64 bits. Insert an assert[sz]ext to capture this, then
2537 // truncate to the right size.
2538 switch (VA.getLocInfo()) {
2539 default:
2540 llvm_unreachable("Unknown loc info!");
2541 case CCValAssign::Full:
2542 break;
2543 case CCValAssign::BCvt:
2544 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
2545 break;
Tim Northover47e003c2014-05-26 17:21:53 +00002546 case CCValAssign::AExt:
Tim Northover3b0846e2014-05-24 12:50:23 +00002547 case CCValAssign::SExt:
Tim Northover3b0846e2014-05-24 12:50:23 +00002548 case CCValAssign::ZExt:
Tim Northover47e003c2014-05-26 17:21:53 +00002549 // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
2550 // nodes after our lowering.
2551 assert(RegVT == Ins[i].VT && "incorrect register location selected");
Tim Northover3b0846e2014-05-24 12:50:23 +00002552 break;
2553 }
2554
2555 InVals.push_back(ArgValue);
2556
2557 } else { // VA.isRegLoc()
2558 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
2559 unsigned ArgOffset = VA.getLocMemOffset();
Amara Emerson82da7d02014-08-15 14:29:57 +00002560 unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
Tim Northover3b0846e2014-05-24 12:50:23 +00002561
2562 uint32_t BEAlign = 0;
Tim Northover293d4142014-12-03 17:49:26 +00002563 if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
2564 !Ins[i].Flags.isInConsecutiveRegs())
Tim Northover3b0846e2014-05-24 12:50:23 +00002565 BEAlign = 8 - ArgSize;
2566
Matthias Braun941a7052016-07-28 18:40:00 +00002567 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
Tim Northover3b0846e2014-05-24 12:50:23 +00002568
2569 // Create load nodes to retrieve arguments from the stack.
Mehdi Amini44ede332015-07-09 02:09:04 +00002570 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00002571 SDValue ArgValue;
2572
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002573 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
Tim Northover47e003c2014-05-26 17:21:53 +00002574 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002575 MVT MemVT = VA.getValVT();
2576
Tim Northover47e003c2014-05-26 17:21:53 +00002577 switch (VA.getLocInfo()) {
2578 default:
2579 break;
Tim Northover6890add2014-06-03 13:54:53 +00002580 case CCValAssign::BCvt:
2581 MemVT = VA.getLocVT();
2582 break;
Tim Northover47e003c2014-05-26 17:21:53 +00002583 case CCValAssign::SExt:
2584 ExtType = ISD::SEXTLOAD;
2585 break;
2586 case CCValAssign::ZExt:
2587 ExtType = ISD::ZEXTLOAD;
2588 break;
2589 case CCValAssign::AExt:
2590 ExtType = ISD::EXTLOAD;
2591 break;
Tim Northover3b0846e2014-05-24 12:50:23 +00002592 }
2593
Alex Lorenze40c8a22015-08-11 23:09:45 +00002594 ArgValue = DAG.getExtLoad(
2595 ExtType, DL, VA.getLocVT(), Chain, FIN,
2596 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
Justin Lebar9c375812016-07-15 18:27:10 +00002597 MemVT);
Tim Northover47e003c2014-05-26 17:21:53 +00002598
Tim Northover3b0846e2014-05-24 12:50:23 +00002599 InVals.push_back(ArgValue);
2600 }
2601 }
2602
2603 // varargs
Matthias Braundff243e2016-04-12 02:16:13 +00002604 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Tim Northover3b0846e2014-05-24 12:50:23 +00002605 if (isVarArg) {
2606 if (!Subtarget->isTargetDarwin()) {
2607 // The AAPCS variadic function ABI is identical to the non-variadic
2608 // one. As a result there may be more arguments in registers and we should
2609 // save them for future reference.
2610 saveVarArgRegisters(CCInfo, DAG, DL, Chain);
2611 }
2612
Tim Northover3b0846e2014-05-24 12:50:23 +00002613 // This will point to the next argument passed via stack.
2614 unsigned StackOffset = CCInfo.getNextStackOffset();
2615 // We currently pass all varargs at 8-byte alignment.
2616 StackOffset = ((StackOffset + 7) & ~7);
Matthias Braun941a7052016-07-28 18:40:00 +00002617 FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true));
Tim Northover3b0846e2014-05-24 12:50:23 +00002618 }
2619
Tim Northover3b0846e2014-05-24 12:50:23 +00002620 unsigned StackArgSize = CCInfo.getNextStackOffset();
2621 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2622 if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
2623 // This is a non-standard ABI so by fiat I say we're allowed to make full
2624 // use of the stack area to be popped, which must be aligned to 16 bytes in
2625 // any case:
Rui Ueyamada00f2f2016-01-14 21:06:47 +00002626 StackArgSize = alignTo(StackArgSize, 16);
Tim Northover3b0846e2014-05-24 12:50:23 +00002627
2628 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
2629 // a multiple of 16.
2630 FuncInfo->setArgumentStackToRestore(StackArgSize);
2631
2632 // This realignment carries over to the available bytes below. Our own
2633 // callers will guarantee the space is free by giving an aligned value to
2634 // CALLSEQ_START.
2635 }
2636 // Even if we're not expected to free up the space, it's useful to know how
2637 // much is there while considering tail calls (because we can reuse it).
2638 FuncInfo->setBytesInStackArgArea(StackArgSize);
2639
2640 return Chain;
2641}
2642
2643void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00002644 SelectionDAG &DAG,
2645 const SDLoc &DL,
Tim Northover3b0846e2014-05-24 12:50:23 +00002646 SDValue &Chain) const {
2647 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braun941a7052016-07-28 18:40:00 +00002648 MachineFrameInfo &MFI = MF.getFrameInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00002649 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Mehdi Amini44ede332015-07-09 02:09:04 +00002650 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00002651
2652 SmallVector<SDValue, 8> MemOps;
2653
2654 static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
2655 AArch64::X3, AArch64::X4, AArch64::X5,
2656 AArch64::X6, AArch64::X7 };
2657 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
Tim Northover3b6b7ca2015-02-21 02:11:17 +00002658 unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
Tim Northover3b0846e2014-05-24 12:50:23 +00002659
2660 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
2661 int GPRIdx = 0;
2662 if (GPRSaveSize != 0) {
Matthias Braun941a7052016-07-28 18:40:00 +00002663 GPRIdx = MFI.CreateStackObject(GPRSaveSize, 8, false);
Tim Northover3b0846e2014-05-24 12:50:23 +00002664
Mehdi Amini44ede332015-07-09 02:09:04 +00002665 SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00002666
2667 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
2668 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
2669 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
Alex Lorenze40c8a22015-08-11 23:09:45 +00002670 SDValue Store = DAG.getStore(
2671 Val.getValue(1), DL, Val, FIN,
Justin Lebar9c375812016-07-15 18:27:10 +00002672 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00002673 MemOps.push_back(Store);
Mehdi Amini44ede332015-07-09 02:09:04 +00002674 FIN =
2675 DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00002676 }
2677 }
2678 FuncInfo->setVarArgsGPRIndex(GPRIdx);
2679 FuncInfo->setVarArgsGPRSize(GPRSaveSize);
2680
2681 if (Subtarget->hasFPARMv8()) {
2682 static const MCPhysReg FPRArgRegs[] = {
2683 AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
2684 AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
2685 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
Tim Northover3b6b7ca2015-02-21 02:11:17 +00002686 unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
Tim Northover3b0846e2014-05-24 12:50:23 +00002687
2688 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
2689 int FPRIdx = 0;
2690 if (FPRSaveSize != 0) {
Matthias Braun941a7052016-07-28 18:40:00 +00002691 FPRIdx = MFI.CreateStackObject(FPRSaveSize, 16, false);
Tim Northover3b0846e2014-05-24 12:50:23 +00002692
Mehdi Amini44ede332015-07-09 02:09:04 +00002693 SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00002694
2695 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
2696 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
2697 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
2698
Alex Lorenze40c8a22015-08-11 23:09:45 +00002699 SDValue Store = DAG.getStore(
2700 Val.getValue(1), DL, Val, FIN,
Justin Lebar9c375812016-07-15 18:27:10 +00002701 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16));
Tim Northover3b0846e2014-05-24 12:50:23 +00002702 MemOps.push_back(Store);
Mehdi Amini44ede332015-07-09 02:09:04 +00002703 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
2704 DAG.getConstant(16, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00002705 }
2706 }
2707 FuncInfo->setVarArgsFPRIndex(FPRIdx);
2708 FuncInfo->setVarArgsFPRSize(FPRSaveSize);
2709 }
2710
2711 if (!MemOps.empty()) {
2712 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
2713 }
2714}
2715
2716/// LowerCallResult - Lower the result values of a call into the
2717/// appropriate copies out of appropriate physical registers.
2718SDValue AArch64TargetLowering::LowerCallResult(
2719 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00002720 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2721 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
Tim Northover3b0846e2014-05-24 12:50:23 +00002722 SDValue ThisVal) const {
2723 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
2724 ? RetCC_AArch64_WebKit_JS
2725 : RetCC_AArch64_AAPCS;
2726 // Assign locations to each value returned by this call.
2727 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002728 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2729 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002730 CCInfo.AnalyzeCallResult(Ins, RetCC);
2731
2732 // Copy all of the result registers out of their specified physreg.
2733 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2734 CCValAssign VA = RVLocs[i];
2735
2736 // Pass 'this' value directly from the argument to return value, to avoid
2737 // reg unit interference
David Majnemer5d261272016-07-20 04:13:01 +00002738 if (i == 0 && isThisReturn) {
Tim Northover3b0846e2014-05-24 12:50:23 +00002739 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
2740 "unexpected return calling convention register assignment");
2741 InVals.push_back(ThisVal);
2742 continue;
2743 }
2744
2745 SDValue Val =
2746 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2747 Chain = Val.getValue(1);
2748 InFlag = Val.getValue(2);
2749
2750 switch (VA.getLocInfo()) {
2751 default:
2752 llvm_unreachable("Unknown loc info!");
2753 case CCValAssign::Full:
2754 break;
2755 case CCValAssign::BCvt:
2756 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2757 break;
2758 }
2759
2760 InVals.push_back(Val);
2761 }
2762
2763 return Chain;
2764}
2765
2766bool AArch64TargetLowering::isEligibleForTailCallOptimization(
2767 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
Tim Northover3b0846e2014-05-24 12:50:23 +00002768 const SmallVectorImpl<ISD::OutputArg> &Outs,
2769 const SmallVectorImpl<SDValue> &OutVals,
2770 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2771 // For CallingConv::C this function knows whether the ABI needs
2772 // changing. That's not true for other conventions so they will have to opt in
2773 // manually.
2774 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
2775 return false;
2776
Matthias Braun8d414362016-03-30 22:46:04 +00002777 MachineFunction &MF = DAG.getMachineFunction();
Tim Northover3b0846e2014-05-24 12:50:23 +00002778 const Function *CallerF = MF.getFunction();
2779 CallingConv::ID CallerCC = CallerF->getCallingConv();
2780 bool CCMatch = CallerCC == CalleeCC;
2781
2782 // Byval parameters hand the function a pointer directly into the stack area
2783 // we want to reuse during a tail call. Working around this *is* possible (see
2784 // X86) but less efficient and uglier in LowerCall.
2785 for (Function::const_arg_iterator i = CallerF->arg_begin(),
2786 e = CallerF->arg_end();
2787 i != e; ++i)
2788 if (i->hasByValAttr())
2789 return false;
2790
2791 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
Eric Christopher114fa1c2016-02-29 22:50:49 +00002792 return IsTailCallConvention(CalleeCC) && CCMatch;
Tim Northover3b0846e2014-05-24 12:50:23 +00002793 }
2794
Oliver Stannard12993dd2014-08-18 12:42:15 +00002795 // Externally-defined functions with weak linkage should not be
2796 // tail-called on AArch64 when the OS does not support dynamic
2797 // pre-emption of symbols, as the AAELF spec requires normal calls
2798 // to undefined weak functions to be replaced with a NOP or jump to the
2799 // next instruction. The behaviour of branch instructions in this
2800 // situation (as used for tail calls) is implementation-defined, so we
2801 // cannot rely on the linker replacing the tail call with a return.
2802 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2803 const GlobalValue *GV = G->getGlobal();
Daniel Sandersc81f4502015-06-16 15:44:21 +00002804 const Triple &TT = getTargetMachine().getTargetTriple();
Saleem Abdulrasool67f72992015-01-03 21:35:00 +00002805 if (GV->hasExternalWeakLinkage() &&
2806 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
Oliver Stannard12993dd2014-08-18 12:42:15 +00002807 return false;
2808 }
2809
Tim Northover3b0846e2014-05-24 12:50:23 +00002810 // Now we search for cases where we can use a tail call without changing the
2811 // ABI. Sibcall is used in some places (particularly gcc) to refer to this
2812 // concept.
2813
2814 // I want anyone implementing a new calling convention to think long and hard
2815 // about this assert.
2816 assert((!isVarArg || CalleeCC == CallingConv::C) &&
2817 "Unexpected variadic calling convention");
2818
Matthias Braun8d414362016-03-30 22:46:04 +00002819 LLVMContext &C = *DAG.getContext();
Tim Northover3b0846e2014-05-24 12:50:23 +00002820 if (isVarArg && !Outs.empty()) {
2821 // At least two cases here: if caller is fastcc then we can't have any
2822 // memory arguments (we'd be expected to clean up the stack afterwards). If
2823 // caller is C then we could potentially use its argument area.
2824
2825 // FIXME: for now we take the most conservative of these in both cases:
2826 // disallow all variadic memory operands.
2827 SmallVector<CCValAssign, 16> ArgLocs;
Matthias Braun8d414362016-03-30 22:46:04 +00002828 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
Tim Northover3b0846e2014-05-24 12:50:23 +00002829
2830 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
Pete Cooper7be8f8f2015-08-03 19:04:32 +00002831 for (const CCValAssign &ArgLoc : ArgLocs)
2832 if (!ArgLoc.isRegLoc())
Tim Northover3b0846e2014-05-24 12:50:23 +00002833 return false;
2834 }
2835
Matthias Braun8d414362016-03-30 22:46:04 +00002836 // Check that the call results are passed in the same way.
2837 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
2838 CCAssignFnForCall(CalleeCC, isVarArg),
2839 CCAssignFnForCall(CallerCC, isVarArg)))
2840 return false;
Matthias Braun870c34f2016-04-04 18:56:13 +00002841 // The callee has to preserve all registers the caller needs to preserve.
Matthias Braun74a0bd32016-04-13 21:43:16 +00002842 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
2843 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
Matthias Braun870c34f2016-04-04 18:56:13 +00002844 if (!CCMatch) {
Matthias Braun74a0bd32016-04-13 21:43:16 +00002845 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2846 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
Matthias Braun870c34f2016-04-04 18:56:13 +00002847 return false;
2848 }
Tim Northover3b0846e2014-05-24 12:50:23 +00002849
2850 // Nothing more to check if the callee is taking no arguments
2851 if (Outs.empty())
2852 return true;
2853
2854 SmallVector<CCValAssign, 16> ArgLocs;
Matthias Braun8d414362016-03-30 22:46:04 +00002855 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
Tim Northover3b0846e2014-05-24 12:50:23 +00002856
2857 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2858
2859 const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2860
Matthias Braun74a0bd32016-04-13 21:43:16 +00002861 // If the stack arguments for this call do not fit into our own save area then
2862 // the call cannot be made tail.
2863 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2864 return false;
2865
Matthias Braun46b0f032016-04-14 01:10:42 +00002866 const MachineRegisterInfo &MRI = MF.getRegInfo();
2867 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
2868 return false;
Matthias Braun74a0bd32016-04-13 21:43:16 +00002869
2870 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +00002871}
2872
2873SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
2874 SelectionDAG &DAG,
Matthias Braun941a7052016-07-28 18:40:00 +00002875 MachineFrameInfo &MFI,
Tim Northover3b0846e2014-05-24 12:50:23 +00002876 int ClobberedFI) const {
2877 SmallVector<SDValue, 8> ArgChains;
Matthias Braun941a7052016-07-28 18:40:00 +00002878 int64_t FirstByte = MFI.getObjectOffset(ClobberedFI);
2879 int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1;
Tim Northover3b0846e2014-05-24 12:50:23 +00002880
2881 // Include the original chain at the beginning of the list. When this is
2882 // used by target LowerCall hooks, this helps legalize find the
2883 // CALLSEQ_BEGIN node.
2884 ArgChains.push_back(Chain);
2885
2886 // Add a chain value for each stack argument corresponding
2887 for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
2888 UE = DAG.getEntryNode().getNode()->use_end();
2889 U != UE; ++U)
2890 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
2891 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
2892 if (FI->getIndex() < 0) {
Matthias Braun941a7052016-07-28 18:40:00 +00002893 int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex());
Tim Northover3b0846e2014-05-24 12:50:23 +00002894 int64_t InLastByte = InFirstByte;
Matthias Braun941a7052016-07-28 18:40:00 +00002895 InLastByte += MFI.getObjectSize(FI->getIndex()) - 1;
Tim Northover3b0846e2014-05-24 12:50:23 +00002896
2897 if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
2898 (FirstByte <= InFirstByte && InFirstByte <= LastByte))
2899 ArgChains.push_back(SDValue(L, 1));
2900 }
2901
2902 // Build a tokenfactor for all the chains.
2903 return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
2904}
2905
2906bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
2907 bool TailCallOpt) const {
2908 return CallCC == CallingConv::Fast && TailCallOpt;
2909}
2910
2911bool AArch64TargetLowering::IsTailCallConvention(CallingConv::ID CallCC) const {
Roman Levenstein2792b3f2016-03-10 04:35:09 +00002912 return CallCC == CallingConv::Fast ||
2913 CallCC == CallingConv::PreserveMost;
Tim Northover3b0846e2014-05-24 12:50:23 +00002914}
2915
2916/// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
2917/// and add input and output parameter nodes.
2918SDValue
2919AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
2920 SmallVectorImpl<SDValue> &InVals) const {
2921 SelectionDAG &DAG = CLI.DAG;
2922 SDLoc &DL = CLI.DL;
2923 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2924 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2925 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2926 SDValue Chain = CLI.Chain;
2927 SDValue Callee = CLI.Callee;
2928 bool &IsTailCall = CLI.IsTailCall;
2929 CallingConv::ID CallConv = CLI.CallConv;
2930 bool IsVarArg = CLI.IsVarArg;
2931
2932 MachineFunction &MF = DAG.getMachineFunction();
Tim Northover3b0846e2014-05-24 12:50:23 +00002933 bool IsThisReturn = false;
2934
2935 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2936 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2937 bool IsSibCall = false;
2938
2939 if (IsTailCall) {
2940 // Check if it's really possible to do a tail call.
2941 IsTailCall = isEligibleForTailCallOptimization(
Matthias Brauncc7fba42016-04-01 02:49:17 +00002942 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002943 if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
2944 report_fatal_error("failed to perform tail call elimination on a call "
2945 "site marked musttail");
2946
2947 // A sibling call is one where we're under the usual C ABI and not planning
2948 // to change that but can still do a tail call:
2949 if (!TailCallOpt && IsTailCall)
2950 IsSibCall = true;
2951
2952 if (IsTailCall)
2953 ++NumTailCalls;
2954 }
2955
2956 // Analyze operands of the call, assigning locations to each operand.
2957 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002958 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
2959 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002960
2961 if (IsVarArg) {
2962 // Handle fixed and variable vector arguments differently.
2963 // Variable vector arguments always go into memory.
2964 unsigned NumArgs = Outs.size();
2965
2966 for (unsigned i = 0; i != NumArgs; ++i) {
2967 MVT ArgVT = Outs[i].VT;
2968 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2969 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
2970 /*IsVarArg=*/ !Outs[i].IsFixed);
2971 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
2972 assert(!Res && "Call operand has unhandled type");
2973 (void)Res;
2974 }
2975 } else {
2976 // At this point, Outs[].VT may already be promoted to i32. To correctly
2977 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2978 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2979 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
2980 // we use a special version of AnalyzeCallOperands to pass in ValVT and
2981 // LocVT.
2982 unsigned NumArgs = Outs.size();
2983 for (unsigned i = 0; i != NumArgs; ++i) {
2984 MVT ValVT = Outs[i].VT;
2985 // Get type of the original argument.
Mehdi Amini44ede332015-07-09 02:09:04 +00002986 EVT ActualVT = getValueType(DAG.getDataLayout(),
2987 CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
Tim Northover3b0846e2014-05-24 12:50:23 +00002988 /*AllowUnknown*/ true);
2989 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
2990 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2991 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
Tim Northover3b0846e2014-05-24 12:50:23 +00002992 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
Tim Northover47e003c2014-05-26 17:21:53 +00002993 ValVT = MVT::i8;
Tim Northover3b0846e2014-05-24 12:50:23 +00002994 else if (ActualMVT == MVT::i16)
Tim Northover47e003c2014-05-26 17:21:53 +00002995 ValVT = MVT::i16;
Tim Northover3b0846e2014-05-24 12:50:23 +00002996
2997 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
Tim Northover47e003c2014-05-26 17:21:53 +00002998 bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00002999 assert(!Res && "Call operand has unhandled type");
3000 (void)Res;
3001 }
3002 }
3003
3004 // Get a count of how many bytes are to be pushed on the stack.
3005 unsigned NumBytes = CCInfo.getNextStackOffset();
3006
3007 if (IsSibCall) {
3008 // Since we're not changing the ABI to make this a tail call, the memory
3009 // operands are already available in the caller's incoming argument space.
3010 NumBytes = 0;
3011 }
3012
3013 // FPDiff is the byte offset of the call's argument area from the callee's.
3014 // Stores to callee stack arguments will be placed in FixedStackSlots offset
3015 // by this amount for a tail call. In a sibling call it must be 0 because the
3016 // caller will deallocate the entire stack and the callee still expects its
3017 // arguments to begin at SP+0. Completely unused for non-tail calls.
3018 int FPDiff = 0;
3019
3020 if (IsTailCall && !IsSibCall) {
3021 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
3022
3023 // Since callee will pop argument stack as a tail call, we must keep the
3024 // popped size 16-byte aligned.
Rui Ueyamada00f2f2016-01-14 21:06:47 +00003025 NumBytes = alignTo(NumBytes, 16);
Tim Northover3b0846e2014-05-24 12:50:23 +00003026
3027 // FPDiff will be negative if this tail call requires more space than we
3028 // would automatically have in our incoming argument space. Positive if we
3029 // can actually shrink the stack.
3030 FPDiff = NumReusableBytes - NumBytes;
3031
3032 // The stack pointer must be 16-byte aligned at all times it's used for a
3033 // memory operation, which in practice means at *all* times and in
3034 // particular across call boundaries. Therefore our own arguments started at
3035 // a 16-byte aligned SP and the delta applied for the tail call should
3036 // satisfy the same constraint.
3037 assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
3038 }
3039
3040 // Adjust the stack pointer for the new arguments...
3041 // These operations are automatically eliminated by the prolog/epilog pass
3042 if (!IsSibCall)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003043 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, DL,
3044 true),
3045 DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003046
Mehdi Amini44ede332015-07-09 02:09:04 +00003047 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
3048 getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00003049
3050 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3051 SmallVector<SDValue, 8> MemOpChains;
Mehdi Amini44ede332015-07-09 02:09:04 +00003052 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003053
3054 // Walk the register/memloc assignments, inserting copies/loads.
3055 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
3056 ++i, ++realArgIdx) {
3057 CCValAssign &VA = ArgLocs[i];
3058 SDValue Arg = OutVals[realArgIdx];
3059 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
3060
3061 // Promote the value if needed.
3062 switch (VA.getLocInfo()) {
3063 default:
3064 llvm_unreachable("Unknown loc info!");
3065 case CCValAssign::Full:
3066 break;
3067 case CCValAssign::SExt:
3068 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3069 break;
3070 case CCValAssign::ZExt:
3071 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3072 break;
3073 case CCValAssign::AExt:
Tim Northover68ae5032014-05-26 17:22:07 +00003074 if (Outs[realArgIdx].ArgVT == MVT::i1) {
3075 // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
3076 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3077 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
3078 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003079 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3080 break;
3081 case CCValAssign::BCvt:
3082 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3083 break;
3084 case CCValAssign::FPExt:
3085 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3086 break;
3087 }
3088
3089 if (VA.isRegLoc()) {
3090 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i64) {
3091 assert(VA.getLocVT() == MVT::i64 &&
3092 "unexpected calling convention register assignment");
3093 assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
3094 "unexpected use of 'returned'");
3095 IsThisReturn = true;
3096 }
3097 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3098 } else {
3099 assert(VA.isMemLoc());
3100
3101 SDValue DstAddr;
3102 MachinePointerInfo DstInfo;
3103
3104 // FIXME: This works on big-endian for composite byvals, which are the
3105 // common case. It should also work for fundamental types too.
3106 uint32_t BEAlign = 0;
3107 unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
Amara Emerson82da7d02014-08-15 14:29:57 +00003108 : VA.getValVT().getSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00003109 OpSize = (OpSize + 7) / 8;
Tim Northover293d4142014-12-03 17:49:26 +00003110 if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
3111 !Flags.isInConsecutiveRegs()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003112 if (OpSize < 8)
3113 BEAlign = 8 - OpSize;
3114 }
3115 unsigned LocMemOffset = VA.getLocMemOffset();
3116 int32_t Offset = LocMemOffset + BEAlign;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003117 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
Mehdi Amini44ede332015-07-09 02:09:04 +00003118 PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
Tim Northover3b0846e2014-05-24 12:50:23 +00003119
3120 if (IsTailCall) {
3121 Offset = Offset + FPDiff;
Matthias Braun941a7052016-07-28 18:40:00 +00003122 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
Tim Northover3b0846e2014-05-24 12:50:23 +00003123
Mehdi Amini44ede332015-07-09 02:09:04 +00003124 DstAddr = DAG.getFrameIndex(FI, PtrVT);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003125 DstInfo =
3126 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
Tim Northover3b0846e2014-05-24 12:50:23 +00003127
3128 // Make sure any stack arguments overlapping with where we're storing
3129 // are loaded before this eventual operation. Otherwise they'll be
3130 // clobbered.
3131 Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
3132 } else {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003133 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003134
Mehdi Amini44ede332015-07-09 02:09:04 +00003135 DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003136 DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
3137 LocMemOffset);
Tim Northover3b0846e2014-05-24 12:50:23 +00003138 }
3139
3140 if (Outs[i].Flags.isByVal()) {
3141 SDValue SizeNode =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003142 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00003143 SDValue Cpy = DAG.getMemcpy(
3144 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
Krzysztof Parzyszeka46c36b2015-04-13 17:16:45 +00003145 /*isVol = */ false, /*AlwaysInline = */ false,
3146 /*isTailCall = */ false,
3147 DstInfo, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00003148
3149 MemOpChains.push_back(Cpy);
3150 } else {
3151 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
3152 // promoted to a legal register type i32, we should truncate Arg back to
3153 // i1/i8/i16.
Tim Northover6890add2014-06-03 13:54:53 +00003154 if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
3155 VA.getValVT() == MVT::i16)
3156 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
Tim Northover3b0846e2014-05-24 12:50:23 +00003157
Justin Lebar9c375812016-07-15 18:27:10 +00003158 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00003159 MemOpChains.push_back(Store);
3160 }
3161 }
3162 }
3163
3164 if (!MemOpChains.empty())
3165 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3166
3167 // Build a sequence of copy-to-reg nodes chained together with token chain
3168 // and flag operands which copy the outgoing args into the appropriate regs.
3169 SDValue InFlag;
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003170 for (auto &RegToPass : RegsToPass) {
3171 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3172 RegToPass.second, InFlag);
Tim Northover3b0846e2014-05-24 12:50:23 +00003173 InFlag = Chain.getValue(1);
3174 }
3175
3176 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3177 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3178 // node so that legalize doesn't hack it.
3179 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3180 Subtarget->isTargetMachO()) {
3181 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3182 const GlobalValue *GV = G->getGlobal();
3183 bool InternalLinkage = GV->hasInternalLinkage();
3184 if (InternalLinkage)
Mehdi Amini44ede332015-07-09 02:09:04 +00003185 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00003186 else {
Mehdi Amini44ede332015-07-09 02:09:04 +00003187 Callee =
3188 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT);
3189 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
Tim Northover3b0846e2014-05-24 12:50:23 +00003190 }
3191 } else if (ExternalSymbolSDNode *S =
3192 dyn_cast<ExternalSymbolSDNode>(Callee)) {
3193 const char *Sym = S->getSymbol();
Mehdi Amini44ede332015-07-09 02:09:04 +00003194 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
3195 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
Tim Northover3b0846e2014-05-24 12:50:23 +00003196 }
3197 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3198 const GlobalValue *GV = G->getGlobal();
Mehdi Amini44ede332015-07-09 02:09:04 +00003199 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00003200 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3201 const char *Sym = S->getSymbol();
Mehdi Amini44ede332015-07-09 02:09:04 +00003202 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00003203 }
3204
3205 // We don't usually want to end the call-sequence here because we would tidy
3206 // the frame up *after* the call, however in the ABI-changing tail-call case
3207 // we've carefully laid out the parameters so that when sp is reset they'll be
3208 // in the correct location.
3209 if (IsTailCall && !IsSibCall) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003210 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3211 DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003212 InFlag = Chain.getValue(1);
3213 }
3214
3215 std::vector<SDValue> Ops;
3216 Ops.push_back(Chain);
3217 Ops.push_back(Callee);
3218
3219 if (IsTailCall) {
3220 // Each tail call may have to adjust the stack by a different amount, so
3221 // this information must travel along with the operation for eventual
3222 // consumption by emitEpilogue.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003223 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00003224 }
3225
3226 // Add argument registers to the end of the list so that they are known live
3227 // into the call.
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003228 for (auto &RegToPass : RegsToPass)
3229 Ops.push_back(DAG.getRegister(RegToPass.first,
3230 RegToPass.second.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00003231
3232 // Add a register mask operand representing the call-preserved registers.
3233 const uint32_t *Mask;
Eric Christopher905f12d2015-01-29 00:19:42 +00003234 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00003235 if (IsThisReturn) {
3236 // For 'this' returns, use the X0-preserving mask if applicable
Eric Christopher9deb75d2015-03-11 22:42:13 +00003237 Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003238 if (!Mask) {
3239 IsThisReturn = false;
Eric Christopher9deb75d2015-03-11 22:42:13 +00003240 Mask = TRI->getCallPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003241 }
3242 } else
Eric Christopher9deb75d2015-03-11 22:42:13 +00003243 Mask = TRI->getCallPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003244
3245 assert(Mask && "Missing call preserved mask for calling convention");
3246 Ops.push_back(DAG.getRegisterMask(Mask));
3247
3248 if (InFlag.getNode())
3249 Ops.push_back(InFlag);
3250
3251 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3252
3253 // If we're doing a tall call, use a TC_RETURN here rather than an
3254 // actual call instruction.
Arnold Schwaighoferf54b73d2015-05-08 23:52:00 +00003255 if (IsTailCall) {
Matthias Braun941a7052016-07-28 18:40:00 +00003256 MF.getFrameInfo().setHasTailCall();
Tim Northover3b0846e2014-05-24 12:50:23 +00003257 return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
Arnold Schwaighoferf54b73d2015-05-08 23:52:00 +00003258 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003259
3260 // Returns a chain and a flag for retval copy to use.
3261 Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
3262 InFlag = Chain.getValue(1);
3263
Rui Ueyamada00f2f2016-01-14 21:06:47 +00003264 uint64_t CalleePopBytes =
3265 DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00003266
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003267 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3268 DAG.getIntPtrConstant(CalleePopBytes, DL, true),
Tim Northover3b0846e2014-05-24 12:50:23 +00003269 InFlag, DL);
3270 if (!Ins.empty())
3271 InFlag = Chain.getValue(1);
3272
3273 // Handle result values, copying them out of physregs into vregs that we
3274 // return.
3275 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3276 InVals, IsThisReturn,
3277 IsThisReturn ? OutVals[0] : SDValue());
3278}
3279
3280bool AArch64TargetLowering::CanLowerReturn(
3281 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
3282 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
3283 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3284 ? RetCC_AArch64_WebKit_JS
3285 : RetCC_AArch64_AAPCS;
3286 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003287 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
Tim Northover3b0846e2014-05-24 12:50:23 +00003288 return CCInfo.CheckReturn(Outs, RetCC);
3289}
3290
3291SDValue
3292AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3293 bool isVarArg,
3294 const SmallVectorImpl<ISD::OutputArg> &Outs,
3295 const SmallVectorImpl<SDValue> &OutVals,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003296 const SDLoc &DL, SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00003297 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3298 ? RetCC_AArch64_WebKit_JS
3299 : RetCC_AArch64_AAPCS;
3300 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003301 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3302 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00003303 CCInfo.AnalyzeReturn(Outs, RetCC);
3304
3305 // Copy the result values into the output registers.
3306 SDValue Flag;
3307 SmallVector<SDValue, 4> RetOps(1, Chain);
3308 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
3309 ++i, ++realRVLocIdx) {
3310 CCValAssign &VA = RVLocs[i];
3311 assert(VA.isRegLoc() && "Can only return in registers!");
3312 SDValue Arg = OutVals[realRVLocIdx];
3313
3314 switch (VA.getLocInfo()) {
3315 default:
3316 llvm_unreachable("Unknown loc info!");
3317 case CCValAssign::Full:
Tim Northover68ae5032014-05-26 17:22:07 +00003318 if (Outs[i].ArgVT == MVT::i1) {
3319 // AAPCS requires i1 to be zero-extended to i8 by the producer of the
3320 // value. This is strictly redundant on Darwin (which uses "zeroext
3321 // i1"), but will be optimised out before ISel.
3322 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3323 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3324 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003325 break;
3326 case CCValAssign::BCvt:
3327 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3328 break;
3329 }
3330
3331 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
3332 Flag = Chain.getValue(1);
3333 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3334 }
Manman Rencbe4f942015-12-16 21:04:19 +00003335 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3336 const MCPhysReg *I =
3337 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
3338 if (I) {
3339 for (; *I; ++I) {
3340 if (AArch64::GPR64RegClass.contains(*I))
3341 RetOps.push_back(DAG.getRegister(*I, MVT::i64));
3342 else if (AArch64::FPR64RegClass.contains(*I))
3343 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
3344 else
3345 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
3346 }
3347 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003348
3349 RetOps[0] = Chain; // Update chain.
3350
3351 // Add the flag if we have it.
3352 if (Flag.getNode())
3353 RetOps.push_back(Flag);
3354
3355 return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
3356}
3357
3358//===----------------------------------------------------------------------===//
3359// Other Lowering Code
3360//===----------------------------------------------------------------------===//
3361
3362SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
3363 SelectionDAG &DAG) const {
Mehdi Amini44ede332015-07-09 02:09:04 +00003364 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003365 SDLoc DL(Op);
Asiri Rathnayake369c0302014-09-10 13:54:38 +00003366 const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
3367 const GlobalValue *GV = GN->getGlobal();
Tim Northover3b0846e2014-05-24 12:50:23 +00003368 unsigned char OpFlags =
3369 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
3370
3371 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
3372 "unexpected offset in global node");
3373
3374 // This also catched the large code model case for Darwin.
3375 if ((OpFlags & AArch64II::MO_GOT) != 0) {
3376 SDValue GotAddr = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
3377 // FIXME: Once remat is capable of dealing with instructions with register
3378 // operands, expand this into two nodes instead of using a wrapper node.
3379 return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
3380 }
3381
3382 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
3383 const unsigned char MO_NC = AArch64II::MO_NC;
3384 return DAG.getNode(
3385 AArch64ISD::WrapperLarge, DL, PtrVT,
3386 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G3),
3387 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
3388 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
3389 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
3390 } else {
3391 // Use ADRP/ADD or ADRP/LDR for everything else: the small model on ELF and
3392 // the only correct model on Darwin.
3393 SDValue Hi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
3394 OpFlags | AArch64II::MO_PAGE);
3395 unsigned char LoFlags = OpFlags | AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
3396 SDValue Lo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, LoFlags);
3397
3398 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3399 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3400 }
3401}
3402
3403/// \brief Convert a TLS address reference into the correct sequence of loads
3404/// and calls to compute the variable's address (for Darwin, currently) and
3405/// return an SDValue containing the final node.
3406
3407/// Darwin only has one TLS scheme which must be capable of dealing with the
3408/// fully general situation, in the worst case. This means:
3409/// + "extern __thread" declaration.
3410/// + Defined in a possibly unknown dynamic library.
3411///
3412/// The general system is that each __thread variable has a [3 x i64] descriptor
3413/// which contains information used by the runtime to calculate the address. The
3414/// only part of this the compiler needs to know about is the first xword, which
3415/// contains a function pointer that must be called with the address of the
3416/// entire descriptor in "x0".
3417///
3418/// Since this descriptor may be in a different unit, in general even the
3419/// descriptor must be accessed via an indirect load. The "ideal" code sequence
3420/// is:
3421/// adrp x0, _var@TLVPPAGE
3422/// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor
3423/// ldr x1, [x0] ; x1 contains 1st entry of descriptor,
3424/// ; the function pointer
3425/// blr x1 ; Uses descriptor address in x0
3426/// ; Address of _var is now in x0.
3427///
3428/// If the address of _var's descriptor *is* known to the linker, then it can
3429/// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
3430/// a slight efficiency gain.
3431SDValue
3432AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
3433 SelectionDAG &DAG) const {
3434 assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
3435
3436 SDLoc DL(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00003437 MVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003438 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3439
3440 SDValue TLVPAddr =
3441 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3442 SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
3443
3444 // The first entry in the descriptor is a function pointer that we must call
3445 // to obtain the address of the variable.
3446 SDValue Chain = DAG.getEntryNode();
3447 SDValue FuncTLVGet =
Alex Lorenze40c8a22015-08-11 23:09:45 +00003448 DAG.getLoad(MVT::i64, DL, Chain, DescAddr,
Justin Lebar9c375812016-07-15 18:27:10 +00003449 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
3450 /* Alignment = */ 8, MachineMemOperand::MONonTemporal |
3451 MachineMemOperand::MOInvariant);
Tim Northover3b0846e2014-05-24 12:50:23 +00003452 Chain = FuncTLVGet.getValue(1);
3453
Matthias Braun941a7052016-07-28 18:40:00 +00003454 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
3455 MFI.setAdjustsStack(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00003456
3457 // TLS calls preserve all registers except those that absolutely must be
3458 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
3459 // silly).
Eric Christopher6c901622015-01-28 03:51:33 +00003460 const uint32_t *Mask =
Eric Christopher905f12d2015-01-29 00:19:42 +00003461 Subtarget->getRegisterInfo()->getTLSCallPreservedMask();
Tim Northover3b0846e2014-05-24 12:50:23 +00003462
3463 // Finally, we can make the call. This is just a degenerate version of a
3464 // normal AArch64 call node: x0 takes the address of the descriptor, and
3465 // returns the address of the variable in this thread.
3466 Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
3467 Chain =
3468 DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3469 Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
3470 DAG.getRegisterMask(Mask), Chain.getValue(1));
3471 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
3472}
3473
3474/// When accessing thread-local variables under either the general-dynamic or
3475/// local-dynamic system, we make a "TLS-descriptor" call. The variable will
3476/// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
Kristof Beylsaea84612015-03-04 09:12:08 +00003477/// is a function pointer to carry out the resolution.
Tim Northover3b0846e2014-05-24 12:50:23 +00003478///
Kristof Beylsaea84612015-03-04 09:12:08 +00003479/// The sequence is:
3480/// adrp x0, :tlsdesc:var
3481/// ldr x1, [x0, #:tlsdesc_lo12:var]
3482/// add x0, x0, #:tlsdesc_lo12:var
3483/// .tlsdesccall var
3484/// blr x1
3485/// (TPIDR_EL0 offset now in x0)
Tim Northover3b0846e2014-05-24 12:50:23 +00003486///
Kristof Beylsaea84612015-03-04 09:12:08 +00003487/// The above sequence must be produced unscheduled, to enable the linker to
3488/// optimize/relax this sequence.
3489/// Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
3490/// above sequence, and expanded really late in the compilation flow, to ensure
3491/// the sequence is produced as per above.
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003492SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr,
3493 const SDLoc &DL,
Kristof Beylsaea84612015-03-04 09:12:08 +00003494 SelectionDAG &DAG) const {
Mehdi Amini44ede332015-07-09 02:09:04 +00003495 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003496
Kristof Beylsaea84612015-03-04 09:12:08 +00003497 SDValue Chain = DAG.getEntryNode();
Tim Northover3b0846e2014-05-24 12:50:23 +00003498 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
Kristof Beylsaea84612015-03-04 09:12:08 +00003499
Benjamin Kramer3bc1edf2016-07-02 11:41:39 +00003500 Chain =
3501 DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr});
Kristof Beylsaea84612015-03-04 09:12:08 +00003502 SDValue Glue = Chain.getValue(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00003503
3504 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
3505}
3506
3507SDValue
3508AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
3509 SelectionDAG &DAG) const {
3510 assert(Subtarget->isTargetELF() && "This function expects an ELF target");
3511 assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
3512 "ELF TLS only supported in small memory model");
Kristof Beylsaea84612015-03-04 09:12:08 +00003513 // Different choices can be made for the maximum size of the TLS area for a
3514 // module. For the small address model, the default TLS size is 16MiB and the
3515 // maximum TLS size is 4GiB.
3516 // FIXME: add -mtls-size command line option and make it control the 16MiB
3517 // vs. 4GiB code sequence generation.
Tim Northover3b0846e2014-05-24 12:50:23 +00003518 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3519
3520 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
Chih-Hung Hsieh1e859582015-07-28 16:24:05 +00003521
3522 if (DAG.getTarget().Options.EmulatedTLS)
3523 return LowerToTLSEmulatedModel(GA, DAG);
3524
Kristof Beylsaea84612015-03-04 09:12:08 +00003525 if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
3526 if (Model == TLSModel::LocalDynamic)
3527 Model = TLSModel::GeneralDynamic;
3528 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003529
3530 SDValue TPOff;
Mehdi Amini44ede332015-07-09 02:09:04 +00003531 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003532 SDLoc DL(Op);
3533 const GlobalValue *GV = GA->getGlobal();
3534
3535 SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
3536
3537 if (Model == TLSModel::LocalExec) {
3538 SDValue HiVar = DAG.getTargetGlobalAddress(
Kristof Beylsaea84612015-03-04 09:12:08 +00003539 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
Tim Northover3b0846e2014-05-24 12:50:23 +00003540 SDValue LoVar = DAG.getTargetGlobalAddress(
3541 GV, DL, PtrVT, 0,
Kristof Beylsaea84612015-03-04 09:12:08 +00003542 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
Tim Northover3b0846e2014-05-24 12:50:23 +00003543
Kristof Beylsaea84612015-03-04 09:12:08 +00003544 SDValue TPWithOff_lo =
3545 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003546 HiVar,
3547 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003548 0);
3549 SDValue TPWithOff =
3550 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003551 LoVar,
3552 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003553 0);
3554 return TPWithOff;
Tim Northover3b0846e2014-05-24 12:50:23 +00003555 } else if (Model == TLSModel::InitialExec) {
3556 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3557 TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
3558 } else if (Model == TLSModel::LocalDynamic) {
3559 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
3560 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
3561 // the beginning of the module's TLS region, followed by a DTPREL offset
3562 // calculation.
3563
3564 // These accesses will need deduplicating if there's more than one.
3565 AArch64FunctionInfo *MFI =
3566 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
3567 MFI->incNumLocalDynamicTLSAccesses();
3568
Tim Northover3b0846e2014-05-24 12:50:23 +00003569 // The call needs a relocation too for linker relaxation. It doesn't make
3570 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3571 // the address.
3572 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
3573 AArch64II::MO_TLS);
3574
3575 // Now we can calculate the offset from TPIDR_EL0 to this module's
3576 // thread-local area.
Kristof Beylsaea84612015-03-04 09:12:08 +00003577 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00003578
3579 // Now use :dtprel_whatever: operations to calculate this variable's offset
3580 // in its thread-storage area.
3581 SDValue HiVar = DAG.getTargetGlobalAddress(
Kristof Beylsaea84612015-03-04 09:12:08 +00003582 GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
Tim Northover3b0846e2014-05-24 12:50:23 +00003583 SDValue LoVar = DAG.getTargetGlobalAddress(
3584 GV, DL, MVT::i64, 0,
Tim Northover3b0846e2014-05-24 12:50:23 +00003585 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3586
Kristof Beylsaea84612015-03-04 09:12:08 +00003587 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003588 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003589 0);
3590 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003591 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003592 0);
3593 } else if (Model == TLSModel::GeneralDynamic) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003594 // The call needs a relocation too for linker relaxation. It doesn't make
3595 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3596 // the address.
3597 SDValue SymAddr =
3598 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3599
3600 // Finally we can make a call to calculate the offset from tpidr_el0.
Kristof Beylsaea84612015-03-04 09:12:08 +00003601 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00003602 } else
3603 llvm_unreachable("Unsupported ELF TLS access model");
3604
3605 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
3606}
3607
3608SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
3609 SelectionDAG &DAG) const {
3610 if (Subtarget->isTargetDarwin())
3611 return LowerDarwinGlobalTLSAddress(Op, DAG);
3612 else if (Subtarget->isTargetELF())
3613 return LowerELFGlobalTLSAddress(Op, DAG);
3614
3615 llvm_unreachable("Unexpected platform trying to use TLS");
3616}
3617SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3618 SDValue Chain = Op.getOperand(0);
3619 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3620 SDValue LHS = Op.getOperand(2);
3621 SDValue RHS = Op.getOperand(3);
3622 SDValue Dest = Op.getOperand(4);
3623 SDLoc dl(Op);
3624
3625 // Handle f128 first, since lowering it will result in comparing the return
3626 // value of a libcall against zero, which is just what the rest of LowerBR_CC
3627 // is expecting to deal with.
3628 if (LHS.getValueType() == MVT::f128) {
3629 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3630
3631 // If softenSetCCOperands returned a scalar, we need to compare the result
3632 // against zero to select between true and false values.
3633 if (!RHS.getNode()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003634 RHS = DAG.getConstant(0, dl, LHS.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00003635 CC = ISD::SETNE;
3636 }
3637 }
3638
3639 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
3640 // instruction.
3641 unsigned Opc = LHS.getOpcode();
Artyom Skrobov314ee042015-11-25 19:41:11 +00003642 if (LHS.getResNo() == 1 && isOneConstant(RHS) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00003643 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3644 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
3645 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
3646 "Unexpected condition code.");
3647 // Only lower legal XALUO ops.
3648 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
3649 return SDValue();
3650
3651 // The actual operation with overflow check.
3652 AArch64CC::CondCode OFCC;
3653 SDValue Value, Overflow;
3654 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
3655
3656 if (CC == ISD::SETNE)
3657 OFCC = getInvertedCondCode(OFCC);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003658 SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003659
Ahmed Bougachadf956a22015-02-06 23:15:39 +00003660 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3661 Overflow);
Tim Northover3b0846e2014-05-24 12:50:23 +00003662 }
3663
3664 if (LHS.getValueType().isInteger()) {
3665 assert((LHS.getValueType() == RHS.getValueType()) &&
3666 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3667
3668 // If the RHS of the comparison is zero, we can potentially fold this
3669 // to a specialized branch.
3670 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
3671 if (RHSC && RHSC->getZExtValue() == 0) {
3672 if (CC == ISD::SETEQ) {
3673 // See if we can use a TBZ to fold in an AND as well.
3674 // TBZ has a smaller branch displacement than CBZ. If the offset is
3675 // out of bounds, a late MI-layer pass rewrites branches.
3676 // 403.gcc is an example that hits this case.
3677 if (LHS.getOpcode() == ISD::AND &&
3678 isa<ConstantSDNode>(LHS.getOperand(1)) &&
3679 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3680 SDValue Test = LHS.getOperand(0);
3681 uint64_t Mask = LHS.getConstantOperandVal(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00003682 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003683 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3684 Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00003685 }
3686
3687 return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
3688 } else if (CC == ISD::SETNE) {
3689 // See if we can use a TBZ to fold in an AND as well.
3690 // TBZ has a smaller branch displacement than CBZ. If the offset is
3691 // out of bounds, a late MI-layer pass rewrites branches.
3692 // 403.gcc is an example that hits this case.
3693 if (LHS.getOpcode() == ISD::AND &&
3694 isa<ConstantSDNode>(LHS.getOperand(1)) &&
3695 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3696 SDValue Test = LHS.getOperand(0);
3697 uint64_t Mask = LHS.getConstantOperandVal(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00003698 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003699 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3700 Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00003701 }
3702
3703 return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
Chad Rosier579c02c2014-08-01 14:48:56 +00003704 } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
3705 // Don't combine AND since emitComparison converts the AND to an ANDS
3706 // (a.k.a. TST) and the test in the test bit and branch instruction
3707 // becomes redundant. This would also increase register pressure.
3708 uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
3709 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003710 DAG.getConstant(Mask, dl, MVT::i64), Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00003711 }
3712 }
Chad Rosier579c02c2014-08-01 14:48:56 +00003713 if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
3714 LHS.getOpcode() != ISD::AND) {
3715 // Don't combine AND since emitComparison converts the AND to an ANDS
3716 // (a.k.a. TST) and the test in the test bit and branch instruction
3717 // becomes redundant. This would also increase register pressure.
3718 uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
3719 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003720 DAG.getConstant(Mask, dl, MVT::i64), Dest);
Chad Rosier579c02c2014-08-01 14:48:56 +00003721 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003722
3723 SDValue CCVal;
3724 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3725 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3726 Cmp);
3727 }
3728
3729 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3730
3731 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
3732 // clean. Some of them require two branches to implement.
3733 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3734 AArch64CC::CondCode CC1, CC2;
3735 changeFPCCToAArch64CC(CC, CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003736 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003737 SDValue BR1 =
3738 DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
3739 if (CC2 != AArch64CC::AL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003740 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003741 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
3742 Cmp);
3743 }
3744
3745 return BR1;
3746}
3747
3748SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
3749 SelectionDAG &DAG) const {
3750 EVT VT = Op.getValueType();
3751 SDLoc DL(Op);
3752
3753 SDValue In1 = Op.getOperand(0);
3754 SDValue In2 = Op.getOperand(1);
3755 EVT SrcVT = In2.getValueType();
Ahmed Bougacha2a97b1b2015-08-13 01:13:56 +00003756
3757 if (SrcVT.bitsLT(VT))
3758 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
3759 else if (SrcVT.bitsGT(VT))
3760 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
Tim Northover3b0846e2014-05-24 12:50:23 +00003761
3762 EVT VecVT;
3763 EVT EltVT;
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00003764 uint64_t EltMask;
3765 SDValue VecVal1, VecVal2;
Tim Northover3b0846e2014-05-24 12:50:23 +00003766 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
3767 EltVT = MVT::i32;
Ahmed Bougachab0ae36f2015-08-04 00:42:34 +00003768 VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00003769 EltMask = 0x80000000ULL;
Tim Northover3b0846e2014-05-24 12:50:23 +00003770
3771 if (!VT.isVector()) {
3772 VecVal1 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3773 DAG.getUNDEF(VecVT), In1);
3774 VecVal2 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3775 DAG.getUNDEF(VecVT), In2);
3776 } else {
3777 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3778 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3779 }
3780 } else if (VT == MVT::f64 || VT == MVT::v2f64) {
3781 EltVT = MVT::i64;
3782 VecVT = MVT::v2i64;
3783
Eric Christopher572e03a2015-06-19 01:53:21 +00003784 // We want to materialize a mask with the high bit set, but the AdvSIMD
Tim Northover3b0846e2014-05-24 12:50:23 +00003785 // immediate moves cannot materialize that in a single instruction for
3786 // 64-bit elements. Instead, materialize zero and then negate it.
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00003787 EltMask = 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00003788
3789 if (!VT.isVector()) {
3790 VecVal1 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3791 DAG.getUNDEF(VecVT), In1);
3792 VecVal2 = DAG.getTargetInsertSubreg(AArch64::dsub, 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 {
3799 llvm_unreachable("Invalid type for copysign!");
3800 }
3801
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003802 SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00003803
3804 // If we couldn't materialize the mask above, then the mask vector will be
3805 // the zero vector, and we need to negate it here.
3806 if (VT == MVT::f64 || VT == MVT::v2f64) {
3807 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
3808 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
3809 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
3810 }
3811
3812 SDValue Sel =
3813 DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
3814
3815 if (VT == MVT::f32)
3816 return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
3817 else if (VT == MVT::f64)
3818 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
3819 else
3820 return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
3821}
3822
3823SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
Duncan P. N. Exon Smith003bb7d2015-02-14 02:09:06 +00003824 if (DAG.getMachineFunction().getFunction()->hasFnAttribute(
3825 Attribute::NoImplicitFloat))
Tim Northover3b0846e2014-05-24 12:50:23 +00003826 return SDValue();
3827
Weiming Zhao7a2d1562014-11-19 00:29:14 +00003828 if (!Subtarget->hasNEON())
3829 return SDValue();
3830
Tim Northover3b0846e2014-05-24 12:50:23 +00003831 // While there is no integer popcount instruction, it can
3832 // be more efficiently lowered to the following sequence that uses
3833 // AdvSIMD registers/instructions as long as the copies to/from
3834 // the AdvSIMD registers are cheap.
3835 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd
3836 // CNT V0.8B, V0.8B // 8xbyte pop-counts
3837 // ADDV B0, V0.8B // sum 8xbyte pop-counts
3838 // UMOV X0, V0.B[0] // copy byte result back to integer reg
3839 SDValue Val = Op.getOperand(0);
3840 SDLoc DL(Op);
3841 EVT VT = Op.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00003842
Hao Liue0335d72015-01-30 02:13:53 +00003843 if (VT == MVT::i32)
3844 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
3845 Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
Tim Northover3b0846e2014-05-24 12:50:23 +00003846
Hao Liue0335d72015-01-30 02:13:53 +00003847 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
Tim Northover3b0846e2014-05-24 12:50:23 +00003848 SDValue UaddLV = DAG.getNode(
3849 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003850 DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
Tim Northover3b0846e2014-05-24 12:50:23 +00003851
3852 if (VT == MVT::i64)
3853 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
3854 return UaddLV;
3855}
3856
3857SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3858
3859 if (Op.getValueType().isVector())
3860 return LowerVSETCC(Op, DAG);
3861
3862 SDValue LHS = Op.getOperand(0);
3863 SDValue RHS = Op.getOperand(1);
3864 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3865 SDLoc dl(Op);
3866
3867 // We chose ZeroOrOneBooleanContents, so use zero and one.
3868 EVT VT = Op.getValueType();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003869 SDValue TVal = DAG.getConstant(1, dl, VT);
3870 SDValue FVal = DAG.getConstant(0, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00003871
3872 // Handle f128 first, since one possible outcome is a normal integer
3873 // comparison which gets picked up by the next if statement.
3874 if (LHS.getValueType() == MVT::f128) {
3875 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3876
3877 // If softenSetCCOperands returned a scalar, use it.
3878 if (!RHS.getNode()) {
3879 assert(LHS.getValueType() == Op.getValueType() &&
3880 "Unexpected setcc expansion!");
3881 return LHS;
3882 }
3883 }
3884
3885 if (LHS.getValueType().isInteger()) {
3886 SDValue CCVal;
3887 SDValue Cmp =
3888 getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
3889
3890 // Note that we inverted the condition above, so we reverse the order of
3891 // the true and false operands here. This will allow the setcc to be
3892 // matched to a single CSINC instruction.
3893 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
3894 }
3895
3896 // Now we know we're dealing with FP values.
3897 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3898
3899 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
3900 // and do the comparison.
3901 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3902
3903 AArch64CC::CondCode CC1, CC2;
3904 changeFPCCToAArch64CC(CC, CC1, CC2);
3905 if (CC2 == AArch64CC::AL) {
3906 changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003907 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003908
3909 // Note that we inverted the condition above, so we reverse the order of
3910 // the true and false operands here. This will allow the setcc to be
3911 // matched to a single CSINC instruction.
3912 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
3913 } else {
3914 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
3915 // totally clean. Some of them require two CSELs to implement. As is in
3916 // this case, we emit the first CSEL and then emit a second using the output
3917 // of the first as the RHS. We're effectively OR'ing the two CC's together.
3918
3919 // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003920 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003921 SDValue CS1 =
3922 DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3923
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003924 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003925 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3926 }
3927}
3928
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00003929SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
3930 SDValue RHS, SDValue TVal,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003931 SDValue FVal, const SDLoc &dl,
Tim Northover3b0846e2014-05-24 12:50:23 +00003932 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00003933 // Handle f128 first, because it will result in a comparison of some RTLIB
3934 // call result against zero.
3935 if (LHS.getValueType() == MVT::f128) {
3936 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3937
3938 // If softenSetCCOperands returned a scalar, we need to compare the result
3939 // against zero to select between true and false values.
3940 if (!RHS.getNode()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003941 RHS = DAG.getConstant(0, dl, LHS.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00003942 CC = ISD::SETNE;
3943 }
3944 }
3945
Ahmed Bougacha88ddeae2015-11-17 16:45:40 +00003946 // Also handle f16, for which we need to do a f32 comparison.
3947 if (LHS.getValueType() == MVT::f16) {
3948 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
3949 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
3950 }
3951
3952 // Next, handle integers.
Tim Northover3b0846e2014-05-24 12:50:23 +00003953 if (LHS.getValueType().isInteger()) {
3954 assert((LHS.getValueType() == RHS.getValueType()) &&
3955 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3956
3957 unsigned Opcode = AArch64ISD::CSEL;
3958
3959 // If both the TVal and the FVal are constants, see if we can swap them in
3960 // order to for a CSINV or CSINC out of them.
3961 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
3962 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
3963
3964 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
3965 std::swap(TVal, FVal);
3966 std::swap(CTVal, CFVal);
3967 CC = ISD::getSetCCInverse(CC, true);
3968 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
3969 std::swap(TVal, FVal);
3970 std::swap(CTVal, CFVal);
3971 CC = ISD::getSetCCInverse(CC, true);
3972 } else if (TVal.getOpcode() == ISD::XOR) {
3973 // If TVal is a NOT we want to swap TVal and FVal so that we can match
3974 // with a CSINV rather than a CSEL.
Artyom Skrobov314ee042015-11-25 19:41:11 +00003975 if (isAllOnesConstant(TVal.getOperand(1))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003976 std::swap(TVal, FVal);
3977 std::swap(CTVal, CFVal);
3978 CC = ISD::getSetCCInverse(CC, true);
3979 }
3980 } else if (TVal.getOpcode() == ISD::SUB) {
3981 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
3982 // that we can match with a CSNEG rather than a CSEL.
Artyom Skrobov314ee042015-11-25 19:41:11 +00003983 if (isNullConstant(TVal.getOperand(0))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003984 std::swap(TVal, FVal);
3985 std::swap(CTVal, CFVal);
3986 CC = ISD::getSetCCInverse(CC, true);
3987 }
3988 } else if (CTVal && CFVal) {
3989 const int64_t TrueVal = CTVal->getSExtValue();
3990 const int64_t FalseVal = CFVal->getSExtValue();
3991 bool Swap = false;
3992
3993 // If both TVal and FVal are constants, see if FVal is the
3994 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
3995 // instead of a CSEL in that case.
3996 if (TrueVal == ~FalseVal) {
3997 Opcode = AArch64ISD::CSINV;
3998 } else if (TrueVal == -FalseVal) {
3999 Opcode = AArch64ISD::CSNEG;
4000 } else if (TVal.getValueType() == MVT::i32) {
4001 // If our operands are only 32-bit wide, make sure we use 32-bit
4002 // arithmetic for the check whether we can use CSINC. This ensures that
4003 // the addition in the check will wrap around properly in case there is
4004 // an overflow (which would not be the case if we do the check with
4005 // 64-bit arithmetic).
4006 const uint32_t TrueVal32 = CTVal->getZExtValue();
4007 const uint32_t FalseVal32 = CFVal->getZExtValue();
4008
4009 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
4010 Opcode = AArch64ISD::CSINC;
4011
4012 if (TrueVal32 > FalseVal32) {
4013 Swap = true;
4014 }
4015 }
4016 // 64-bit check whether we can use CSINC.
4017 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
4018 Opcode = AArch64ISD::CSINC;
4019
4020 if (TrueVal > FalseVal) {
4021 Swap = true;
4022 }
4023 }
4024
4025 // Swap TVal and FVal if necessary.
4026 if (Swap) {
4027 std::swap(TVal, FVal);
4028 std::swap(CTVal, CFVal);
4029 CC = ISD::getSetCCInverse(CC, true);
4030 }
4031
4032 if (Opcode != AArch64ISD::CSEL) {
4033 // Drop FVal since we can get its value by simply inverting/negating
4034 // TVal.
4035 FVal = TVal;
4036 }
4037 }
4038
4039 SDValue CCVal;
4040 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
4041
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004042 EVT VT = TVal.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00004043 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
4044 }
4045
4046 // Now we know we're dealing with FP values.
4047 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
4048 assert(LHS.getValueType() == RHS.getValueType());
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004049 EVT VT = TVal.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00004050 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
4051
4052 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4053 // clean. Some of them require two CSELs to implement.
4054 AArch64CC::CondCode CC1, CC2;
4055 changeFPCCToAArch64CC(CC, CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004056 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004057 SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4058
4059 // If we need a second CSEL, emit it, using the output of the first as the
4060 // RHS. We're effectively OR'ing the two CC's together.
4061 if (CC2 != AArch64CC::AL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004062 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004063 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4064 }
4065
4066 // Otherwise, return the output of the first CSEL.
4067 return CS1;
4068}
4069
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004070SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
4071 SelectionDAG &DAG) const {
4072 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4073 SDValue LHS = Op.getOperand(0);
4074 SDValue RHS = Op.getOperand(1);
4075 SDValue TVal = Op.getOperand(2);
4076 SDValue FVal = Op.getOperand(3);
4077 SDLoc DL(Op);
4078 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4079}
4080
4081SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
4082 SelectionDAG &DAG) const {
4083 SDValue CCVal = Op->getOperand(0);
4084 SDValue TVal = Op->getOperand(1);
4085 SDValue FVal = Op->getOperand(2);
4086 SDLoc DL(Op);
4087
4088 unsigned Opc = CCVal.getOpcode();
4089 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
4090 // instruction.
4091 if (CCVal.getResNo() == 1 &&
4092 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4093 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
4094 // Only lower legal XALUO ops.
4095 if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
4096 return SDValue();
4097
4098 AArch64CC::CondCode OFCC;
4099 SDValue Value, Overflow;
4100 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004101 SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004102
4103 return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
4104 CCVal, Overflow);
4105 }
4106
4107 // Lower it the same way as we would lower a SELECT_CC node.
4108 ISD::CondCode CC;
4109 SDValue LHS, RHS;
4110 if (CCVal.getOpcode() == ISD::SETCC) {
4111 LHS = CCVal.getOperand(0);
4112 RHS = CCVal.getOperand(1);
4113 CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
4114 } else {
4115 LHS = CCVal;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004116 RHS = DAG.getConstant(0, DL, CCVal.getValueType());
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004117 CC = ISD::SETNE;
4118 }
4119 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4120}
4121
Tim Northover3b0846e2014-05-24 12:50:23 +00004122SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
4123 SelectionDAG &DAG) const {
4124 // Jump table entries as PC relative offsets. No additional tweaking
4125 // is necessary here. Just get the address of the jump table.
4126 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00004127 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004128 SDLoc DL(Op);
4129
4130 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4131 !Subtarget->isTargetMachO()) {
4132 const unsigned char MO_NC = AArch64II::MO_NC;
4133 return DAG.getNode(
4134 AArch64ISD::WrapperLarge, DL, PtrVT,
4135 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G3),
4136 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G2 | MO_NC),
4137 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G1 | MO_NC),
4138 DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4139 AArch64II::MO_G0 | MO_NC));
4140 }
4141
4142 SDValue Hi =
4143 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_PAGE);
4144 SDValue Lo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4145 AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4146 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4147 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4148}
4149
4150SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
4151 SelectionDAG &DAG) const {
4152 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00004153 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004154 SDLoc DL(Op);
4155
4156 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4157 // Use the GOT for the large code model on iOS.
4158 if (Subtarget->isTargetMachO()) {
4159 SDValue GotAddr = DAG.getTargetConstantPool(
4160 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4161 AArch64II::MO_GOT);
4162 return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
4163 }
4164
4165 const unsigned char MO_NC = AArch64II::MO_NC;
4166 return DAG.getNode(
4167 AArch64ISD::WrapperLarge, DL, PtrVT,
4168 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4169 CP->getOffset(), AArch64II::MO_G3),
4170 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4171 CP->getOffset(), AArch64II::MO_G2 | MO_NC),
4172 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4173 CP->getOffset(), AArch64II::MO_G1 | MO_NC),
4174 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4175 CP->getOffset(), AArch64II::MO_G0 | MO_NC));
4176 } else {
4177 // Use ADRP/ADD or ADRP/LDR for everything else: the small memory model on
4178 // ELF, the only valid one on Darwin.
4179 SDValue Hi =
4180 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4181 CP->getOffset(), AArch64II::MO_PAGE);
4182 SDValue Lo = DAG.getTargetConstantPool(
4183 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4184 AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4185
4186 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4187 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4188 }
4189}
4190
4191SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
4192 SelectionDAG &DAG) const {
4193 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
Mehdi Amini44ede332015-07-09 02:09:04 +00004194 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004195 SDLoc DL(Op);
4196 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4197 !Subtarget->isTargetMachO()) {
4198 const unsigned char MO_NC = AArch64II::MO_NC;
4199 return DAG.getNode(
4200 AArch64ISD::WrapperLarge, DL, PtrVT,
4201 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G3),
4202 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
4203 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
4204 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
4205 } else {
4206 SDValue Hi = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGE);
4207 SDValue Lo = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGEOFF |
4208 AArch64II::MO_NC);
4209 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4210 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4211 }
4212}
4213
4214SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
4215 SelectionDAG &DAG) const {
4216 AArch64FunctionInfo *FuncInfo =
4217 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4218
4219 SDLoc DL(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00004220 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
4221 getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00004222 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4223 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
Justin Lebar9c375812016-07-15 18:27:10 +00004224 MachinePointerInfo(SV));
Tim Northover3b0846e2014-05-24 12:50:23 +00004225}
4226
4227SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
4228 SelectionDAG &DAG) const {
4229 // The layout of the va_list struct is specified in the AArch64 Procedure Call
4230 // Standard, section B.3.
4231 MachineFunction &MF = DAG.getMachineFunction();
4232 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Mehdi Amini44ede332015-07-09 02:09:04 +00004233 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004234 SDLoc DL(Op);
4235
4236 SDValue Chain = Op.getOperand(0);
4237 SDValue VAList = Op.getOperand(1);
4238 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4239 SmallVector<SDValue, 4> MemOps;
4240
4241 // void *__stack at offset 0
Mehdi Amini44ede332015-07-09 02:09:04 +00004242 SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004243 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
Justin Lebar9c375812016-07-15 18:27:10 +00004244 MachinePointerInfo(SV), /* Alignment = */ 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00004245
4246 // void *__gr_top at offset 8
4247 int GPRSize = FuncInfo->getVarArgsGPRSize();
4248 if (GPRSize > 0) {
4249 SDValue GRTop, GRTopAddr;
4250
Mehdi Amini44ede332015-07-09 02:09:04 +00004251 GRTopAddr =
4252 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004253
Mehdi Amini44ede332015-07-09 02:09:04 +00004254 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
4255 GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
4256 DAG.getConstant(GPRSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004257
4258 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
Justin Lebar9c375812016-07-15 18:27:10 +00004259 MachinePointerInfo(SV, 8),
4260 /* Alignment = */ 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00004261 }
4262
4263 // void *__vr_top at offset 16
4264 int FPRSize = FuncInfo->getVarArgsFPRSize();
4265 if (FPRSize > 0) {
4266 SDValue VRTop, VRTopAddr;
Mehdi Amini44ede332015-07-09 02:09:04 +00004267 VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4268 DAG.getConstant(16, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004269
Mehdi Amini44ede332015-07-09 02:09:04 +00004270 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
4271 VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
4272 DAG.getConstant(FPRSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004273
4274 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
Justin Lebar9c375812016-07-15 18:27:10 +00004275 MachinePointerInfo(SV, 16),
4276 /* Alignment = */ 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00004277 }
4278
4279 // int __gr_offs at offset 24
Mehdi Amini44ede332015-07-09 02:09:04 +00004280 SDValue GROffsAddr =
4281 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
Justin Lebar9c375812016-07-15 18:27:10 +00004282 MemOps.push_back(DAG.getStore(
4283 Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32), GROffsAddr,
4284 MachinePointerInfo(SV, 24), /* Alignment = */ 4));
Tim Northover3b0846e2014-05-24 12:50:23 +00004285
4286 // int __vr_offs at offset 28
Mehdi Amini44ede332015-07-09 02:09:04 +00004287 SDValue VROffsAddr =
4288 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
Justin Lebar9c375812016-07-15 18:27:10 +00004289 MemOps.push_back(DAG.getStore(
4290 Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32), VROffsAddr,
4291 MachinePointerInfo(SV, 28), /* Alignment = */ 4));
Tim Northover3b0846e2014-05-24 12:50:23 +00004292
4293 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
4294}
4295
4296SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
4297 SelectionDAG &DAG) const {
4298 return Subtarget->isTargetDarwin() ? LowerDarwin_VASTART(Op, DAG)
4299 : LowerAAPCS_VASTART(Op, DAG);
4300}
4301
4302SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
4303 SelectionDAG &DAG) const {
4304 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
4305 // pointer.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004306 SDLoc DL(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00004307 unsigned VaListSize = Subtarget->isTargetDarwin() ? 8 : 32;
4308 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4309 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4310
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004311 return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1),
4312 Op.getOperand(2),
4313 DAG.getConstant(VaListSize, DL, MVT::i32),
Krzysztof Parzyszeka46c36b2015-04-13 17:16:45 +00004314 8, false, false, false, MachinePointerInfo(DestSV),
Tim Northover3b0846e2014-05-24 12:50:23 +00004315 MachinePointerInfo(SrcSV));
4316}
4317
4318SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
4319 assert(Subtarget->isTargetDarwin() &&
4320 "automatic va_arg instruction only works on Darwin");
4321
4322 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4323 EVT VT = Op.getValueType();
4324 SDLoc DL(Op);
4325 SDValue Chain = Op.getOperand(0);
4326 SDValue Addr = Op.getOperand(1);
4327 unsigned Align = Op.getConstantOperandVal(3);
Mehdi Amini44ede332015-07-09 02:09:04 +00004328 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004329
Justin Lebar9c375812016-07-15 18:27:10 +00004330 SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V));
Tim Northover3b0846e2014-05-24 12:50:23 +00004331 Chain = VAList.getValue(1);
4332
4333 if (Align > 8) {
4334 assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
Mehdi Amini44ede332015-07-09 02:09:04 +00004335 VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4336 DAG.getConstant(Align - 1, DL, PtrVT));
4337 VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
4338 DAG.getConstant(-(int64_t)Align, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004339 }
4340
4341 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
Mehdi Amini44ede332015-07-09 02:09:04 +00004342 uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
Tim Northover3b0846e2014-05-24 12:50:23 +00004343
4344 // Scalar integer and FP values smaller than 64 bits are implicitly extended
4345 // up to 64 bits. At the very least, we have to increase the striding of the
4346 // vaargs list to match this, and for FP values we need to introduce
4347 // FP_ROUND nodes as well.
4348 if (VT.isInteger() && !VT.isVector())
4349 ArgSize = 8;
4350 bool NeedFPTrunc = false;
4351 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
4352 ArgSize = 8;
4353 NeedFPTrunc = true;
4354 }
4355
4356 // Increment the pointer, VAList, to the next vaarg
Mehdi Amini44ede332015-07-09 02:09:04 +00004357 SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4358 DAG.getConstant(ArgSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004359 // Store the incremented VAList to the legalized pointer
Justin Lebar9c375812016-07-15 18:27:10 +00004360 SDValue APStore =
4361 DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V));
Tim Northover3b0846e2014-05-24 12:50:23 +00004362
4363 // Load the actual argument out of the pointer VAList
4364 if (NeedFPTrunc) {
4365 // Load the value as an f64.
Justin Lebar9c375812016-07-15 18:27:10 +00004366 SDValue WideFP =
4367 DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00004368 // Round the value down to an f32.
4369 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004370 DAG.getIntPtrConstant(1, DL));
Tim Northover3b0846e2014-05-24 12:50:23 +00004371 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
4372 // Merge the rounded value with the chain output of the load.
4373 return DAG.getMergeValues(Ops, DL);
4374 }
4375
Justin Lebar9c375812016-07-15 18:27:10 +00004376 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00004377}
4378
4379SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
4380 SelectionDAG &DAG) const {
Matthias Braun941a7052016-07-28 18:40:00 +00004381 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
4382 MFI.setFrameAddressIsTaken(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00004383
4384 EVT VT = Op.getValueType();
4385 SDLoc DL(Op);
4386 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4387 SDValue FrameAddr =
4388 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
4389 while (Depth--)
4390 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
Justin Lebar9c375812016-07-15 18:27:10 +00004391 MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00004392 return FrameAddr;
4393}
4394
4395// FIXME? Maybe this could be a TableGen attribute on some registers and
4396// this table could be generated automatically from RegInfo.
Pat Gavlina717f252015-07-09 17:40:29 +00004397unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT,
4398 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004399 unsigned Reg = StringSwitch<unsigned>(RegName)
4400 .Case("sp", AArch64::SP)
4401 .Default(0);
4402 if (Reg)
4403 return Reg;
Luke Cheeseman85fd06d2015-06-01 12:02:47 +00004404 report_fatal_error(Twine("Invalid register name \""
4405 + StringRef(RegName) + "\"."));
Tim Northover3b0846e2014-05-24 12:50:23 +00004406}
4407
4408SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
4409 SelectionDAG &DAG) const {
4410 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braun941a7052016-07-28 18:40:00 +00004411 MachineFrameInfo &MFI = MF.getFrameInfo();
4412 MFI.setReturnAddressIsTaken(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00004413
4414 EVT VT = Op.getValueType();
4415 SDLoc DL(Op);
4416 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4417 if (Depth) {
4418 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
Mehdi Amini44ede332015-07-09 02:09:04 +00004419 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00004420 return DAG.getLoad(VT, DL, DAG.getEntryNode(),
4421 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
Justin Lebar9c375812016-07-15 18:27:10 +00004422 MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00004423 }
4424
4425 // Return LR, which contains the return address. Mark it an implicit live-in.
4426 unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
4427 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4428}
4429
4430/// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4431/// i64 values and take a 2 x i64 value to shift plus a shift amount.
4432SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
4433 SelectionDAG &DAG) const {
4434 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4435 EVT VT = Op.getValueType();
4436 unsigned VTBits = VT.getSizeInBits();
4437 SDLoc dl(Op);
4438 SDValue ShOpLo = Op.getOperand(0);
4439 SDValue ShOpHi = Op.getOperand(1);
4440 SDValue ShAmt = Op.getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00004441 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4442
4443 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4444
4445 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004446 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
Tim Northoverf3be9d52015-12-02 00:33:54 +00004447 SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4448
4449 // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
4450 // is "undef". We wanted 0, so CSEL it directly.
4451 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
4452 ISD::SETEQ, dl, DAG);
4453 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
4454 HiBitsForLo =
4455 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
4456 HiBitsForLo, CCVal, Cmp);
4457
Tim Northover3b0846e2014-05-24 12:50:23 +00004458 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004459 DAG.getConstant(VTBits, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00004460
Tim Northoverf3be9d52015-12-02 00:33:54 +00004461 SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4462 SDValue LoForNormalShift =
4463 DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
Tim Northover3b0846e2014-05-24 12:50:23 +00004464
Tim Northoverf3be9d52015-12-02 00:33:54 +00004465 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
4466 dl, DAG);
4467 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4468 SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4469 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
4470 LoForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00004471
4472 // AArch64 shifts larger than the register width are wrapped rather than
4473 // clamped, so we can't just emit "hi >> x".
Tim Northoverf3be9d52015-12-02 00:33:54 +00004474 SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4475 SDValue HiForBigShift =
4476 Opc == ISD::SRA
4477 ? DAG.getNode(Opc, dl, VT, ShOpHi,
4478 DAG.getConstant(VTBits - 1, dl, MVT::i64))
4479 : DAG.getConstant(0, dl, VT);
4480 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
4481 HiForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00004482
4483 SDValue Ops[2] = { Lo, Hi };
4484 return DAG.getMergeValues(Ops, dl);
4485}
4486
Tim Northoverf3be9d52015-12-02 00:33:54 +00004487
Tim Northover3b0846e2014-05-24 12:50:23 +00004488/// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4489/// i64 values and take a 2 x i64 value to shift plus a shift amount.
4490SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
Tim Northoverf3be9d52015-12-02 00:33:54 +00004491 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004492 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4493 EVT VT = Op.getValueType();
4494 unsigned VTBits = VT.getSizeInBits();
4495 SDLoc dl(Op);
4496 SDValue ShOpLo = Op.getOperand(0);
4497 SDValue ShOpHi = Op.getOperand(1);
4498 SDValue ShAmt = Op.getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00004499
4500 assert(Op.getOpcode() == ISD::SHL_PARTS);
4501 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004502 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
Tim Northoverf3be9d52015-12-02 00:33:54 +00004503 SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4504
4505 // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
4506 // is "undef". We wanted 0, so CSEL it directly.
4507 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
4508 ISD::SETEQ, dl, DAG);
4509 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
4510 LoBitsForHi =
4511 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
4512 LoBitsForHi, CCVal, Cmp);
4513
Tim Northover3b0846e2014-05-24 12:50:23 +00004514 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004515 DAG.getConstant(VTBits, dl, MVT::i64));
Tim Northoverf3be9d52015-12-02 00:33:54 +00004516 SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4517 SDValue HiForNormalShift =
4518 DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
Tim Northover3b0846e2014-05-24 12:50:23 +00004519
Tim Northoverf3be9d52015-12-02 00:33:54 +00004520 SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
Tim Northover3b0846e2014-05-24 12:50:23 +00004521
Tim Northoverf3be9d52015-12-02 00:33:54 +00004522 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
4523 dl, DAG);
4524 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4525 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
4526 HiForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00004527
4528 // AArch64 shifts of larger than register sizes are wrapped rather than
4529 // clamped, so we can't just emit "lo << a" if a is too big.
Tim Northoverf3be9d52015-12-02 00:33:54 +00004530 SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
4531 SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4532 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
4533 LoForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00004534
4535 SDValue Ops[2] = { Lo, Hi };
4536 return DAG.getMergeValues(Ops, dl);
4537}
4538
4539bool AArch64TargetLowering::isOffsetFoldingLegal(
4540 const GlobalAddressSDNode *GA) const {
4541 // The AArch64 target doesn't support folding offsets into global addresses.
4542 return false;
4543}
4544
4545bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4546 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
4547 // FIXME: We should be able to handle f128 as well with a clever lowering.
4548 if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32))
4549 return true;
4550
4551 if (VT == MVT::f64)
4552 return AArch64_AM::getFP64Imm(Imm) != -1;
4553 else if (VT == MVT::f32)
4554 return AArch64_AM::getFP32Imm(Imm) != -1;
4555 return false;
4556}
4557
4558//===----------------------------------------------------------------------===//
4559// AArch64 Optimization Hooks
4560//===----------------------------------------------------------------------===//
4561
Evandro Menezesbcb95cd2016-05-04 20:18:27 +00004562/// getEstimate - Return the appropriate estimate DAG for either the reciprocal
4563/// or the reciprocal square root.
4564static SDValue getEstimate(const AArch64Subtarget &ST,
4565 const AArch64TargetLowering::DAGCombinerInfo &DCI, unsigned Opcode,
4566 const SDValue &Operand, unsigned &ExtraSteps) {
4567 if (!ST.hasNEON())
4568 return SDValue();
4569
4570 EVT VT = Operand.getValueType();
Evandro Menezes238fa762016-07-19 22:31:11 +00004571 if (VT != MVT::f64 && VT != MVT::v1f64 && VT != MVT::v2f64 &&
4572 VT != MVT::f32 && VT != MVT::v1f32 &&
4573 VT != MVT::v2f32 && VT != MVT::v4f32 &&
4574 (!ST.hasFullFP16() ||
4575 (VT != MVT::f16 && VT != MVT::v4f16 && VT != MVT::v8f16)))
4576 return SDValue();
Evandro Menezesbcb95cd2016-05-04 20:18:27 +00004577
4578 std::string RecipOp;
4579 RecipOp = Opcode == (AArch64ISD::FRECPE) ? "div": "sqrt";
4580 RecipOp = ((VT.isVector()) ? "vec-": "") + RecipOp;
4581 RecipOp += (VT.getScalarType() == MVT::f64) ? "d": "f";
4582
4583 TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
4584 if (!Recips.isEnabled(RecipOp))
4585 return SDValue();
4586
4587 ExtraSteps = Recips.getRefinementSteps(RecipOp);
4588 return DCI.DAG.getNode(Opcode, SDLoc(Operand), VT, Operand);
4589}
4590
4591SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand,
4592 DAGCombinerInfo &DCI, unsigned &ExtraSteps) const {
4593 return getEstimate(*Subtarget, DCI, AArch64ISD::FRECPE, Operand, ExtraSteps);
4594}
4595
4596SDValue AArch64TargetLowering::getRsqrtEstimate(SDValue Operand,
4597 DAGCombinerInfo &DCI, unsigned &ExtraSteps, bool &UseOneConst) const {
4598 UseOneConst = true;
4599 return getEstimate(*Subtarget, DCI, AArch64ISD::FRSQRTE, Operand, ExtraSteps);
4600}
4601
Tim Northover3b0846e2014-05-24 12:50:23 +00004602//===----------------------------------------------------------------------===//
4603// AArch64 Inline Assembly Support
4604//===----------------------------------------------------------------------===//
4605
4606// Table of Constraints
4607// TODO: This is the current set of constraints supported by ARM for the
4608// compiler, not all of them may make sense, e.g. S may be difficult to support.
4609//
4610// r - A general register
4611// w - An FP/SIMD register of some size in the range v0-v31
4612// x - An FP/SIMD register of some size in the range v0-v15
4613// I - Constant that can be used with an ADD instruction
4614// J - Constant that can be used with a SUB instruction
4615// K - Constant that can be used with a 32-bit logical instruction
4616// L - Constant that can be used with a 64-bit logical instruction
4617// M - Constant that can be used as a 32-bit MOV immediate
4618// N - Constant that can be used as a 64-bit MOV immediate
4619// Q - A memory reference with base register and no offset
4620// S - A symbolic address
4621// Y - Floating point constant zero
4622// Z - Integer constant zero
4623//
4624// Note that general register operands will be output using their 64-bit x
4625// register name, whatever the size of the variable, unless the asm operand
4626// is prefixed by the %w modifier. Floating-point and SIMD register operands
4627// will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
4628// %q modifier.
Silviu Barangaf60be282016-05-09 11:10:44 +00004629const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
4630 // At this point, we have to lower this constraint to something else, so we
4631 // lower it to an "r" or "w". However, by doing this we will force the result
4632 // to be in register, while the X constraint is much more permissive.
4633 //
4634 // Although we are correct (we are free to emit anything, without
4635 // constraints), we might break use cases that would expect us to be more
4636 // efficient and emit something else.
4637 if (!Subtarget->hasFPARMv8())
4638 return "r";
4639
4640 if (ConstraintVT.isFloatingPoint())
4641 return "w";
4642
4643 if (ConstraintVT.isVector() &&
4644 (ConstraintVT.getSizeInBits() == 64 ||
4645 ConstraintVT.getSizeInBits() == 128))
4646 return "w";
4647
4648 return "r";
4649}
Tim Northover3b0846e2014-05-24 12:50:23 +00004650
4651/// getConstraintType - Given a constraint letter, return the type of
4652/// constraint it is for this target.
4653AArch64TargetLowering::ConstraintType
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00004654AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004655 if (Constraint.size() == 1) {
4656 switch (Constraint[0]) {
4657 default:
4658 break;
4659 case 'z':
4660 return C_Other;
4661 case 'x':
4662 case 'w':
4663 return C_RegisterClass;
4664 // An address with a single base register. Due to the way we
4665 // currently handle addresses it is the same as 'r'.
4666 case 'Q':
4667 return C_Memory;
4668 }
4669 }
4670 return TargetLowering::getConstraintType(Constraint);
4671}
4672
4673/// Examine constraint type and operand type and determine a weight value.
4674/// This object must already have been set up with the operand type
4675/// and the current alternative constraint selected.
4676TargetLowering::ConstraintWeight
4677AArch64TargetLowering::getSingleConstraintMatchWeight(
4678 AsmOperandInfo &info, const char *constraint) const {
4679 ConstraintWeight weight = CW_Invalid;
4680 Value *CallOperandVal = info.CallOperandVal;
4681 // If we don't have a value, we can't do a match,
4682 // but allow it at the lowest weight.
4683 if (!CallOperandVal)
4684 return CW_Default;
4685 Type *type = CallOperandVal->getType();
4686 // Look at the constraint type.
4687 switch (*constraint) {
4688 default:
4689 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
4690 break;
4691 case 'x':
4692 case 'w':
4693 if (type->isFloatingPointTy() || type->isVectorTy())
4694 weight = CW_Register;
4695 break;
4696 case 'z':
4697 weight = CW_Constant;
4698 break;
4699 }
4700 return weight;
4701}
4702
4703std::pair<unsigned, const TargetRegisterClass *>
4704AArch64TargetLowering::getRegForInlineAsmConstraint(
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00004705 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004706 if (Constraint.size() == 1) {
4707 switch (Constraint[0]) {
4708 case 'r':
4709 if (VT.getSizeInBits() == 64)
4710 return std::make_pair(0U, &AArch64::GPR64commonRegClass);
4711 return std::make_pair(0U, &AArch64::GPR32commonRegClass);
4712 case 'w':
Akira Hatanakab8d28732016-07-21 21:39:05 +00004713 if (VT.getSizeInBits() == 32)
Tim Northover3b0846e2014-05-24 12:50:23 +00004714 return std::make_pair(0U, &AArch64::FPR32RegClass);
4715 if (VT.getSizeInBits() == 64)
4716 return std::make_pair(0U, &AArch64::FPR64RegClass);
4717 if (VT.getSizeInBits() == 128)
4718 return std::make_pair(0U, &AArch64::FPR128RegClass);
4719 break;
4720 // The instructions that this constraint is designed for can
4721 // only take 128-bit registers so just use that regclass.
4722 case 'x':
4723 if (VT.getSizeInBits() == 128)
4724 return std::make_pair(0U, &AArch64::FPR128_loRegClass);
4725 break;
4726 }
4727 }
4728 if (StringRef("{cc}").equals_lower(Constraint))
4729 return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
4730
4731 // Use the default implementation in TargetLowering to convert the register
4732 // constraint into a member of a register class.
4733 std::pair<unsigned, const TargetRegisterClass *> Res;
Eric Christopher11e4df72015-02-26 22:38:43 +00004734 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004735
4736 // Not found as a standard register?
4737 if (!Res.second) {
4738 unsigned Size = Constraint.size();
4739 if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
4740 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00004741 int RegNo;
4742 bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
4743 if (!Failed && RegNo >= 0 && RegNo <= 31) {
Tim Northover9508a702016-05-10 22:26:45 +00004744 // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size.
Tim Northover3b0846e2014-05-24 12:50:23 +00004745 // By default we'll emit v0-v31 for this unless there's a modifier where
4746 // we'll emit the correct register as well.
Tim Northover9508a702016-05-10 22:26:45 +00004747 if (VT != MVT::Other && VT.getSizeInBits() == 64) {
4748 Res.first = AArch64::FPR64RegClass.getRegister(RegNo);
4749 Res.second = &AArch64::FPR64RegClass;
4750 } else {
4751 Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
4752 Res.second = &AArch64::FPR128RegClass;
4753 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004754 }
4755 }
4756 }
4757
4758 return Res;
4759}
4760
4761/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
4762/// vector. If it is invalid, don't add anything to Ops.
4763void AArch64TargetLowering::LowerAsmOperandForConstraint(
4764 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
4765 SelectionDAG &DAG) const {
4766 SDValue Result;
4767
4768 // Currently only support length 1 constraints.
4769 if (Constraint.length() != 1)
4770 return;
4771
4772 char ConstraintLetter = Constraint[0];
4773 switch (ConstraintLetter) {
4774 default:
4775 break;
4776
4777 // This set of constraints deal with valid constants for various instructions.
4778 // Validate and return a target constant for them if we can.
4779 case 'z': {
4780 // 'z' maps to xzr or wzr so it needs an input of 0.
Artyom Skrobov314ee042015-11-25 19:41:11 +00004781 if (!isNullConstant(Op))
Tim Northover3b0846e2014-05-24 12:50:23 +00004782 return;
4783
4784 if (Op.getValueType() == MVT::i64)
4785 Result = DAG.getRegister(AArch64::XZR, MVT::i64);
4786 else
4787 Result = DAG.getRegister(AArch64::WZR, MVT::i32);
4788 break;
4789 }
4790
4791 case 'I':
4792 case 'J':
4793 case 'K':
4794 case 'L':
4795 case 'M':
4796 case 'N':
4797 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4798 if (!C)
4799 return;
4800
4801 // Grab the value and do some validation.
4802 uint64_t CVal = C->getZExtValue();
4803 switch (ConstraintLetter) {
4804 // The I constraint applies only to simple ADD or SUB immediate operands:
4805 // i.e. 0 to 4095 with optional shift by 12
4806 // The J constraint applies only to ADD or SUB immediates that would be
4807 // valid when negated, i.e. if [an add pattern] were to be output as a SUB
4808 // instruction [or vice versa], in other words -1 to -4095 with optional
4809 // left shift by 12.
4810 case 'I':
4811 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
4812 break;
4813 return;
4814 case 'J': {
4815 uint64_t NVal = -C->getSExtValue();
Tim Northover2c46beb2014-07-27 07:10:29 +00004816 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
4817 CVal = C->getSExtValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00004818 break;
Tim Northover2c46beb2014-07-27 07:10:29 +00004819 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004820 return;
4821 }
4822 // The K and L constraints apply *only* to logical immediates, including
4823 // what used to be the MOVI alias for ORR (though the MOVI alias has now
4824 // been removed and MOV should be used). So these constraints have to
4825 // distinguish between bit patterns that are valid 32-bit or 64-bit
4826 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
4827 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
4828 // versa.
4829 case 'K':
4830 if (AArch64_AM::isLogicalImmediate(CVal, 32))
4831 break;
4832 return;
4833 case 'L':
4834 if (AArch64_AM::isLogicalImmediate(CVal, 64))
4835 break;
4836 return;
4837 // The M and N constraints are a superset of K and L respectively, for use
4838 // with the MOV (immediate) alias. As well as the logical immediates they
4839 // also match 32 or 64-bit immediates that can be loaded either using a
4840 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
4841 // (M) or 64-bit 0x1234000000000000 (N) etc.
4842 // As a note some of this code is liberally stolen from the asm parser.
4843 case 'M': {
4844 if (!isUInt<32>(CVal))
4845 return;
4846 if (AArch64_AM::isLogicalImmediate(CVal, 32))
4847 break;
4848 if ((CVal & 0xFFFF) == CVal)
4849 break;
4850 if ((CVal & 0xFFFF0000ULL) == CVal)
4851 break;
4852 uint64_t NCVal = ~(uint32_t)CVal;
4853 if ((NCVal & 0xFFFFULL) == NCVal)
4854 break;
4855 if ((NCVal & 0xFFFF0000ULL) == NCVal)
4856 break;
4857 return;
4858 }
4859 case 'N': {
4860 if (AArch64_AM::isLogicalImmediate(CVal, 64))
4861 break;
4862 if ((CVal & 0xFFFFULL) == CVal)
4863 break;
4864 if ((CVal & 0xFFFF0000ULL) == CVal)
4865 break;
4866 if ((CVal & 0xFFFF00000000ULL) == CVal)
4867 break;
4868 if ((CVal & 0xFFFF000000000000ULL) == CVal)
4869 break;
4870 uint64_t NCVal = ~CVal;
4871 if ((NCVal & 0xFFFFULL) == NCVal)
4872 break;
4873 if ((NCVal & 0xFFFF0000ULL) == NCVal)
4874 break;
4875 if ((NCVal & 0xFFFF00000000ULL) == NCVal)
4876 break;
4877 if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
4878 break;
4879 return;
4880 }
4881 default:
4882 return;
4883 }
4884
4885 // All assembler immediates are 64-bit integers.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004886 Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00004887 break;
4888 }
4889
4890 if (Result.getNode()) {
4891 Ops.push_back(Result);
4892 return;
4893 }
4894
4895 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
4896}
4897
4898//===----------------------------------------------------------------------===//
4899// AArch64 Advanced SIMD Support
4900//===----------------------------------------------------------------------===//
4901
4902/// WidenVector - Given a value in the V64 register class, produce the
4903/// equivalent value in the V128 register class.
4904static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
4905 EVT VT = V64Reg.getValueType();
4906 unsigned NarrowSize = VT.getVectorNumElements();
4907 MVT EltTy = VT.getVectorElementType().getSimpleVT();
4908 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
4909 SDLoc DL(V64Reg);
4910
4911 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004912 V64Reg, DAG.getConstant(0, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00004913}
4914
4915/// getExtFactor - Determine the adjustment factor for the position when
4916/// generating an "extract from vector registers" instruction.
4917static unsigned getExtFactor(SDValue &V) {
4918 EVT EltType = V.getValueType().getVectorElementType();
4919 return EltType.getSizeInBits() / 8;
4920}
4921
4922/// NarrowVector - Given a value in the V128 register class, produce the
4923/// equivalent value in the V64 register class.
4924static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
4925 EVT VT = V128Reg.getValueType();
4926 unsigned WideSize = VT.getVectorNumElements();
4927 MVT EltTy = VT.getVectorElementType().getSimpleVT();
4928 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
4929 SDLoc DL(V128Reg);
4930
4931 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
4932}
4933
4934// Gather data to see if the operation can be modelled as a
4935// shuffle in combination with VEXTs.
4936SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
4937 SelectionDAG &DAG) const {
Kevin Qinf0ec9af2014-06-18 05:54:42 +00004938 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
Tim Northover3b0846e2014-05-24 12:50:23 +00004939 SDLoc dl(Op);
4940 EVT VT = Op.getValueType();
4941 unsigned NumElts = VT.getVectorNumElements();
4942
Tim Northover7324e842014-07-24 15:39:55 +00004943 struct ShuffleSourceInfo {
4944 SDValue Vec;
4945 unsigned MinElt;
4946 unsigned MaxElt;
Tim Northover3b0846e2014-05-24 12:50:23 +00004947
Tim Northover7324e842014-07-24 15:39:55 +00004948 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
4949 // be compatible with the shuffle we intend to construct. As a result
4950 // ShuffleVec will be some sliding window into the original Vec.
4951 SDValue ShuffleVec;
4952
4953 // Code should guarantee that element i in Vec starts at element "WindowBase
4954 // + i * WindowScale in ShuffleVec".
4955 int WindowBase;
4956 int WindowScale;
4957
4958 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
4959 ShuffleSourceInfo(SDValue Vec)
4960 : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
4961 WindowScale(1) {}
4962 };
4963
4964 // First gather all vectors used as an immediate source for this BUILD_VECTOR
4965 // node.
4966 SmallVector<ShuffleSourceInfo, 2> Sources;
Tim Northover3b0846e2014-05-24 12:50:23 +00004967 for (unsigned i = 0; i < NumElts; ++i) {
4968 SDValue V = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00004969 if (V.isUndef())
Tim Northover3b0846e2014-05-24 12:50:23 +00004970 continue;
Ahmed Bougachadfc77352016-01-14 02:12:30 +00004971 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4972 !isa<ConstantSDNode>(V.getOperand(1))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004973 // A shuffle can only come from building a vector from various
Ahmed Bougachadfc77352016-01-14 02:12:30 +00004974 // elements of other vectors, provided their indices are constant.
Tim Northover3b0846e2014-05-24 12:50:23 +00004975 return SDValue();
4976 }
4977
Tim Northover7324e842014-07-24 15:39:55 +00004978 // Add this element source to the list if it's not already there.
Tim Northover3b0846e2014-05-24 12:50:23 +00004979 SDValue SourceVec = V.getOperand(0);
David Majnemer0d955d02016-08-11 22:21:41 +00004980 auto Source = find(Sources, SourceVec);
Tim Northover7324e842014-07-24 15:39:55 +00004981 if (Source == Sources.end())
James Molloyf497d552014-10-17 17:06:31 +00004982 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
Tim Northover3b0846e2014-05-24 12:50:23 +00004983
Tim Northover7324e842014-07-24 15:39:55 +00004984 // Update the minimum and maximum lane number seen.
4985 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4986 Source->MinElt = std::min(Source->MinElt, EltNo);
4987 Source->MaxElt = std::max(Source->MaxElt, EltNo);
Tim Northover3b0846e2014-05-24 12:50:23 +00004988 }
4989
4990 // Currently only do something sane when at most two source vectors
Tim Northover7324e842014-07-24 15:39:55 +00004991 // are involved.
4992 if (Sources.size() > 2)
Tim Northover3b0846e2014-05-24 12:50:23 +00004993 return SDValue();
4994
Kevin Qin9a2a2c52014-07-24 02:05:42 +00004995 // Find out the smallest element size among result and two sources, and use
4996 // it as element size to build the shuffle_vector.
4997 EVT SmallestEltTy = VT.getVectorElementType();
Tim Northover7324e842014-07-24 15:39:55 +00004998 for (auto &Source : Sources) {
4999 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00005000 if (SrcEltTy.bitsLT(SmallestEltTy)) {
5001 SmallestEltTy = SrcEltTy;
5002 }
5003 }
5004 unsigned ResMultiplier =
5005 VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00005006 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
5007 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
Tim Northover3b0846e2014-05-24 12:50:23 +00005008
Tim Northover7324e842014-07-24 15:39:55 +00005009 // If the source vector is too wide or too narrow, we may nevertheless be able
5010 // to construct a compatible shuffle either by concatenating it with UNDEF or
5011 // extracting a suitable range of elements.
5012 for (auto &Src : Sources) {
5013 EVT SrcVT = Src.ShuffleVec.getValueType();
Kevin Qinf0ec9af2014-06-18 05:54:42 +00005014
Tim Northover7324e842014-07-24 15:39:55 +00005015 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
Tim Northover3b0846e2014-05-24 12:50:23 +00005016 continue;
Tim Northover7324e842014-07-24 15:39:55 +00005017
5018 // This stage of the search produces a source with the same element type as
5019 // the original, but with a total width matching the BUILD_VECTOR output.
5020 EVT EltVT = SrcVT.getVectorElementType();
James Molloyf497d552014-10-17 17:06:31 +00005021 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
5022 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
Tim Northover7324e842014-07-24 15:39:55 +00005023
5024 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
5025 assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00005026 // We can pad out the smaller vector for free, so if it's part of a
5027 // shuffle...
Tim Northover7324e842014-07-24 15:39:55 +00005028 Src.ShuffleVec =
5029 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
5030 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00005031 continue;
5032 }
5033
Tim Northover7324e842014-07-24 15:39:55 +00005034 assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00005035
James Molloyf497d552014-10-17 17:06:31 +00005036 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005037 // Span too large for a VEXT to cope
5038 return SDValue();
5039 }
5040
James Molloyf497d552014-10-17 17:06:31 +00005041 if (Src.MinElt >= NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005042 // The extraction can just take the second half
Tim Northover7324e842014-07-24 15:39:55 +00005043 Src.ShuffleVec =
5044 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005045 DAG.getConstant(NumSrcElts, dl, MVT::i64));
James Molloyf497d552014-10-17 17:06:31 +00005046 Src.WindowBase = -NumSrcElts;
5047 } else if (Src.MaxElt < NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005048 // The extraction can just take the first half
Tim Northover5e84fe32014-12-06 00:33:37 +00005049 Src.ShuffleVec =
5050 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005051 DAG.getConstant(0, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005052 } else {
5053 // An actual VEXT is needed
Tim Northover5e84fe32014-12-06 00:33:37 +00005054 SDValue VEXTSrc1 =
5055 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005056 DAG.getConstant(0, dl, MVT::i64));
Tim Northover7324e842014-07-24 15:39:55 +00005057 SDValue VEXTSrc2 =
5058 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005059 DAG.getConstant(NumSrcElts, dl, MVT::i64));
Tim Northover7324e842014-07-24 15:39:55 +00005060 unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
5061
5062 Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005063 VEXTSrc2,
5064 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover7324e842014-07-24 15:39:55 +00005065 Src.WindowBase = -Src.MinElt;
Tim Northover3b0846e2014-05-24 12:50:23 +00005066 }
5067 }
5068
Tim Northover7324e842014-07-24 15:39:55 +00005069 // Another possible incompatibility occurs from the vector element types. We
5070 // can fix this by bitcasting the source vectors to the same type we intend
5071 // for the shuffle.
5072 for (auto &Src : Sources) {
5073 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
5074 if (SrcEltTy == SmallestEltTy)
5075 continue;
5076 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
5077 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
5078 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
5079 Src.WindowBase *= Src.WindowScale;
5080 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005081
Tim Northover7324e842014-07-24 15:39:55 +00005082 // Final sanity check before we try to actually produce a shuffle.
5083 DEBUG(
5084 for (auto Src : Sources)
5085 assert(Src.ShuffleVec.getValueType() == ShuffleVT);
5086 );
5087
5088 // The stars all align, our next step is to produce the mask for the shuffle.
5089 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
5090 int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00005091 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005092 SDValue Entry = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00005093 if (Entry.isUndef())
Tim Northover7324e842014-07-24 15:39:55 +00005094 continue;
Tim Northover3b0846e2014-05-24 12:50:23 +00005095
David Majnemer0d955d02016-08-11 22:21:41 +00005096 auto Src = find(Sources, Entry.getOperand(0));
Tim Northover7324e842014-07-24 15:39:55 +00005097 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
5098
5099 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
5100 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
5101 // segment.
5102 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
5103 int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
5104 VT.getVectorElementType().getSizeInBits());
5105 int LanesDefined = BitsDefined / BitsPerShuffleLane;
5106
5107 // This source is expected to fill ResMultiplier lanes of the final shuffle,
5108 // starting at the appropriate offset.
5109 int *LaneMask = &Mask[i * ResMultiplier];
5110
5111 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
5112 ExtractBase += NumElts * (Src - Sources.begin());
5113 for (int j = 0; j < LanesDefined; ++j)
5114 LaneMask[j] = ExtractBase + j;
Tim Northover3b0846e2014-05-24 12:50:23 +00005115 }
5116
5117 // Final check before we try to produce nonsense...
Tim Northover7324e842014-07-24 15:39:55 +00005118 if (!isShuffleMaskLegal(Mask, ShuffleVT))
5119 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00005120
Tim Northover7324e842014-07-24 15:39:55 +00005121 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
5122 for (unsigned i = 0; i < Sources.size(); ++i)
5123 ShuffleOps[i] = Sources[i].ShuffleVec;
5124
5125 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
Craig Topper2bd8b4b2016-07-01 06:54:47 +00005126 ShuffleOps[1], Mask);
Tim Northover7324e842014-07-24 15:39:55 +00005127 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
Tim Northover3b0846e2014-05-24 12:50:23 +00005128}
5129
5130// check if an EXT instruction can handle the shuffle mask when the
5131// vector sources of the shuffle are the same.
5132static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
5133 unsigned NumElts = VT.getVectorNumElements();
5134
5135 // Assume that the first shuffle index is not UNDEF. Fail if it is.
5136 if (M[0] < 0)
5137 return false;
5138
5139 Imm = M[0];
5140
5141 // If this is a VEXT shuffle, the immediate value is the index of the first
5142 // element. The other shuffle indices must be the successive elements after
5143 // the first one.
5144 unsigned ExpectedElt = Imm;
5145 for (unsigned i = 1; i < NumElts; ++i) {
5146 // Increment the expected index. If it wraps around, just follow it
5147 // back to index zero and keep going.
5148 ++ExpectedElt;
5149 if (ExpectedElt == NumElts)
5150 ExpectedElt = 0;
5151
5152 if (M[i] < 0)
5153 continue; // ignore UNDEF indices
5154 if (ExpectedElt != static_cast<unsigned>(M[i]))
5155 return false;
5156 }
5157
5158 return true;
5159}
5160
5161// check if an EXT instruction can handle the shuffle mask when the
5162// vector sources of the shuffle are different.
5163static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
5164 unsigned &Imm) {
5165 // Look for the first non-undef element.
David Majnemer562e8292016-08-12 00:18:03 +00005166 const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; });
Tim Northover3b0846e2014-05-24 12:50:23 +00005167
5168 // Benefit form APInt to handle overflow when calculating expected element.
5169 unsigned NumElts = VT.getVectorNumElements();
5170 unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
5171 APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
5172 // The following shuffle indices must be the successive elements after the
5173 // first real element.
5174 const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
5175 [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
5176 if (FirstWrongElt != M.end())
5177 return false;
5178
5179 // The index of an EXT is the first element if it is not UNDEF.
5180 // Watch out for the beginning UNDEFs. The EXT index should be the expected
Junmo Park3b8c7152016-01-05 09:36:47 +00005181 // value of the first element. E.g.
Tim Northover3b0846e2014-05-24 12:50:23 +00005182 // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
5183 // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
5184 // ExpectedElt is the last mask index plus 1.
5185 Imm = ExpectedElt.getZExtValue();
5186
5187 // There are two difference cases requiring to reverse input vectors.
5188 // For example, for vector <4 x i32> we have the following cases,
5189 // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
5190 // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
5191 // For both cases, we finally use mask <5, 6, 7, 0>, which requires
5192 // to reverse two input vectors.
5193 if (Imm < NumElts)
5194 ReverseEXT = true;
5195 else
5196 Imm -= NumElts;
5197
5198 return true;
5199}
5200
5201/// isREVMask - Check if a vector shuffle corresponds to a REV
5202/// instruction with the specified blocksize. (The order of the elements
5203/// within each block of the vector is reversed.)
5204static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5205 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
5206 "Only possible block sizes for REV are: 16, 32, 64");
5207
5208 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5209 if (EltSz == 64)
5210 return false;
5211
5212 unsigned NumElts = VT.getVectorNumElements();
5213 unsigned BlockElts = M[0] + 1;
5214 // If the first shuffle index is UNDEF, be optimistic.
5215 if (M[0] < 0)
5216 BlockElts = BlockSize / EltSz;
5217
5218 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5219 return false;
5220
5221 for (unsigned i = 0; i < NumElts; ++i) {
5222 if (M[i] < 0)
5223 continue; // ignore UNDEF indices
5224 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
5225 return false;
5226 }
5227
5228 return true;
5229}
5230
5231static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5232 unsigned NumElts = VT.getVectorNumElements();
5233 WhichResult = (M[0] == 0 ? 0 : 1);
5234 unsigned Idx = WhichResult * NumElts / 2;
5235 for (unsigned i = 0; i != NumElts; i += 2) {
5236 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5237 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
5238 return false;
5239 Idx += 1;
5240 }
5241
5242 return true;
5243}
5244
5245static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5246 unsigned NumElts = VT.getVectorNumElements();
5247 WhichResult = (M[0] == 0 ? 0 : 1);
5248 for (unsigned i = 0; i != NumElts; ++i) {
5249 if (M[i] < 0)
5250 continue; // ignore UNDEF indices
5251 if ((unsigned)M[i] != 2 * i + WhichResult)
5252 return false;
5253 }
5254
5255 return true;
5256}
5257
5258static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5259 unsigned NumElts = VT.getVectorNumElements();
5260 WhichResult = (M[0] == 0 ? 0 : 1);
5261 for (unsigned i = 0; i < NumElts; i += 2) {
5262 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5263 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
5264 return false;
5265 }
5266 return true;
5267}
5268
5269/// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
5270/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5271/// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5272static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5273 unsigned NumElts = VT.getVectorNumElements();
5274 WhichResult = (M[0] == 0 ? 0 : 1);
5275 unsigned Idx = WhichResult * NumElts / 2;
5276 for (unsigned i = 0; i != NumElts; i += 2) {
5277 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5278 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
5279 return false;
5280 Idx += 1;
5281 }
5282
5283 return true;
5284}
5285
5286/// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
5287/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5288/// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5289static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5290 unsigned Half = VT.getVectorNumElements() / 2;
5291 WhichResult = (M[0] == 0 ? 0 : 1);
5292 for (unsigned j = 0; j != 2; ++j) {
5293 unsigned Idx = WhichResult;
5294 for (unsigned i = 0; i != Half; ++i) {
5295 int MIdx = M[i + j * Half];
5296 if (MIdx >= 0 && (unsigned)MIdx != Idx)
5297 return false;
5298 Idx += 2;
5299 }
5300 }
5301
5302 return true;
5303}
5304
5305/// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
5306/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5307/// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5308static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5309 unsigned NumElts = VT.getVectorNumElements();
5310 WhichResult = (M[0] == 0 ? 0 : 1);
5311 for (unsigned i = 0; i < NumElts; i += 2) {
5312 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5313 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
5314 return false;
5315 }
5316 return true;
5317}
5318
5319static bool isINSMask(ArrayRef<int> M, int NumInputElements,
5320 bool &DstIsLeft, int &Anomaly) {
5321 if (M.size() != static_cast<size_t>(NumInputElements))
5322 return false;
5323
5324 int NumLHSMatch = 0, NumRHSMatch = 0;
5325 int LastLHSMismatch = -1, LastRHSMismatch = -1;
5326
5327 for (int i = 0; i < NumInputElements; ++i) {
5328 if (M[i] == -1) {
5329 ++NumLHSMatch;
5330 ++NumRHSMatch;
5331 continue;
5332 }
5333
5334 if (M[i] == i)
5335 ++NumLHSMatch;
5336 else
5337 LastLHSMismatch = i;
5338
5339 if (M[i] == i + NumInputElements)
5340 ++NumRHSMatch;
5341 else
5342 LastRHSMismatch = i;
5343 }
5344
5345 if (NumLHSMatch == NumInputElements - 1) {
5346 DstIsLeft = true;
5347 Anomaly = LastLHSMismatch;
5348 return true;
5349 } else if (NumRHSMatch == NumInputElements - 1) {
5350 DstIsLeft = false;
5351 Anomaly = LastRHSMismatch;
5352 return true;
5353 }
5354
5355 return false;
5356}
5357
5358static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
5359 if (VT.getSizeInBits() != 128)
5360 return false;
5361
5362 unsigned NumElts = VT.getVectorNumElements();
5363
5364 for (int I = 0, E = NumElts / 2; I != E; I++) {
5365 if (Mask[I] != I)
5366 return false;
5367 }
5368
5369 int Offset = NumElts / 2;
5370 for (int I = NumElts / 2, E = NumElts; I != E; I++) {
5371 if (Mask[I] != I + SplitLHS * Offset)
5372 return false;
5373 }
5374
5375 return true;
5376}
5377
5378static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
5379 SDLoc DL(Op);
5380 EVT VT = Op.getValueType();
5381 SDValue V0 = Op.getOperand(0);
5382 SDValue V1 = Op.getOperand(1);
5383 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
5384
5385 if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
5386 VT.getVectorElementType() != V1.getValueType().getVectorElementType())
5387 return SDValue();
5388
5389 bool SplitV0 = V0.getValueType().getSizeInBits() == 128;
5390
5391 if (!isConcatMask(Mask, VT, SplitV0))
5392 return SDValue();
5393
5394 EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
5395 VT.getVectorNumElements() / 2);
5396 if (SplitV0) {
5397 V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005398 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005399 }
5400 if (V1.getValueType().getSizeInBits() == 128) {
5401 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005402 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005403 }
5404 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
5405}
5406
5407/// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5408/// the specified operations to build the shuffle.
5409static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5410 SDValue RHS, SelectionDAG &DAG,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00005411 const SDLoc &dl) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005412 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5413 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
5414 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
5415
5416 enum {
5417 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5418 OP_VREV,
5419 OP_VDUP0,
5420 OP_VDUP1,
5421 OP_VDUP2,
5422 OP_VDUP3,
5423 OP_VEXT1,
5424 OP_VEXT2,
5425 OP_VEXT3,
5426 OP_VUZPL, // VUZP, left result
5427 OP_VUZPR, // VUZP, right result
5428 OP_VZIPL, // VZIP, left result
5429 OP_VZIPR, // VZIP, right result
5430 OP_VTRNL, // VTRN, left result
5431 OP_VTRNR // VTRN, right result
5432 };
5433
5434 if (OpNum == OP_COPY) {
5435 if (LHSID == (1 * 9 + 2) * 9 + 3)
5436 return LHS;
5437 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
5438 return RHS;
5439 }
5440
5441 SDValue OpLHS, OpRHS;
5442 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5443 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5444 EVT VT = OpLHS.getValueType();
5445
5446 switch (OpNum) {
5447 default:
5448 llvm_unreachable("Unknown shuffle opcode!");
5449 case OP_VREV:
5450 // VREV divides the vector in half and swaps within the half.
5451 if (VT.getVectorElementType() == MVT::i32 ||
5452 VT.getVectorElementType() == MVT::f32)
5453 return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
5454 // vrev <4 x i16> -> REV32
Oliver Stannard89d15422014-08-27 16:16:04 +00005455 if (VT.getVectorElementType() == MVT::i16 ||
5456 VT.getVectorElementType() == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00005457 return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
5458 // vrev <4 x i8> -> REV16
5459 assert(VT.getVectorElementType() == MVT::i8);
5460 return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
5461 case OP_VDUP0:
5462 case OP_VDUP1:
5463 case OP_VDUP2:
5464 case OP_VDUP3: {
5465 EVT EltTy = VT.getVectorElementType();
5466 unsigned Opcode;
5467 if (EltTy == MVT::i8)
5468 Opcode = AArch64ISD::DUPLANE8;
Ahmed Bougacha941420d2015-04-16 23:57:07 +00005469 else if (EltTy == MVT::i16 || EltTy == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00005470 Opcode = AArch64ISD::DUPLANE16;
5471 else if (EltTy == MVT::i32 || EltTy == MVT::f32)
5472 Opcode = AArch64ISD::DUPLANE32;
5473 else if (EltTy == MVT::i64 || EltTy == MVT::f64)
5474 Opcode = AArch64ISD::DUPLANE64;
5475 else
5476 llvm_unreachable("Invalid vector element type?");
5477
5478 if (VT.getSizeInBits() == 64)
5479 OpLHS = WidenVector(OpLHS, DAG);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005480 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00005481 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
5482 }
5483 case OP_VEXT1:
5484 case OP_VEXT2:
5485 case OP_VEXT3: {
5486 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
5487 return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005488 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005489 }
5490 case OP_VUZPL:
5491 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
5492 OpRHS);
5493 case OP_VUZPR:
5494 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
5495 OpRHS);
5496 case OP_VZIPL:
5497 return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
5498 OpRHS);
5499 case OP_VZIPR:
5500 return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
5501 OpRHS);
5502 case OP_VTRNL:
5503 return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
5504 OpRHS);
5505 case OP_VTRNR:
5506 return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
5507 OpRHS);
5508 }
5509}
5510
5511static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
5512 SelectionDAG &DAG) {
5513 // Check to see if we can use the TBL instruction.
5514 SDValue V1 = Op.getOperand(0);
5515 SDValue V2 = Op.getOperand(1);
5516 SDLoc DL(Op);
5517
5518 EVT EltVT = Op.getValueType().getVectorElementType();
5519 unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
5520
5521 SmallVector<SDValue, 8> TBLMask;
5522 for (int Val : ShuffleMask) {
5523 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
5524 unsigned Offset = Byte + Val * BytesPerElt;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005525 TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005526 }
5527 }
5528
5529 MVT IndexVT = MVT::v8i8;
5530 unsigned IndexLen = 8;
5531 if (Op.getValueType().getSizeInBits() == 128) {
5532 IndexVT = MVT::v16i8;
5533 IndexLen = 16;
5534 }
5535
5536 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
5537 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
5538
5539 SDValue Shuffle;
Sanjay Patel57195842016-03-14 17:28:46 +00005540 if (V2.getNode()->isUndef()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005541 if (IndexLen == 8)
5542 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
5543 Shuffle = DAG.getNode(
5544 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005545 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00005546 DAG.getBuildVector(IndexVT, DL,
5547 makeArrayRef(TBLMask.data(), IndexLen)));
Tim Northover3b0846e2014-05-24 12:50:23 +00005548 } else {
5549 if (IndexLen == 8) {
5550 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
5551 Shuffle = DAG.getNode(
5552 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005553 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00005554 DAG.getBuildVector(IndexVT, DL,
5555 makeArrayRef(TBLMask.data(), IndexLen)));
Tim Northover3b0846e2014-05-24 12:50:23 +00005556 } else {
5557 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
5558 // cannot currently represent the register constraints on the input
5559 // table registers.
5560 // Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00005561 // DAG.getBuildVector(IndexVT, DL, &TBLMask[0],
5562 // IndexLen));
Tim Northover3b0846e2014-05-24 12:50:23 +00005563 Shuffle = DAG.getNode(
5564 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00005565 DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst,
5566 V2Cst, DAG.getBuildVector(IndexVT, DL,
5567 makeArrayRef(TBLMask.data(), IndexLen)));
Tim Northover3b0846e2014-05-24 12:50:23 +00005568 }
5569 }
5570 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
5571}
5572
5573static unsigned getDUPLANEOp(EVT EltType) {
5574 if (EltType == MVT::i8)
5575 return AArch64ISD::DUPLANE8;
Oliver Stannard89d15422014-08-27 16:16:04 +00005576 if (EltType == MVT::i16 || EltType == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00005577 return AArch64ISD::DUPLANE16;
5578 if (EltType == MVT::i32 || EltType == MVT::f32)
5579 return AArch64ISD::DUPLANE32;
5580 if (EltType == MVT::i64 || EltType == MVT::f64)
5581 return AArch64ISD::DUPLANE64;
5582
5583 llvm_unreachable("Invalid vector element type?");
5584}
5585
5586SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5587 SelectionDAG &DAG) const {
5588 SDLoc dl(Op);
5589 EVT VT = Op.getValueType();
5590
5591 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5592
5593 // Convert shuffles that are directly supported on NEON to target-specific
5594 // DAG nodes, instead of keeping them as shuffles and matching them again
5595 // during code selection. This is more efficient and avoids the possibility
5596 // of inconsistencies between legalization and selection.
5597 ArrayRef<int> ShuffleMask = SVN->getMask();
5598
5599 SDValue V1 = Op.getOperand(0);
5600 SDValue V2 = Op.getOperand(1);
5601
Craig Topperbc56e3b2016-06-30 04:38:51 +00005602 if (SVN->isSplat()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005603 int Lane = SVN->getSplatIndex();
5604 // If this is undef splat, generate it via "just" vdup, if possible.
5605 if (Lane == -1)
5606 Lane = 0;
5607
5608 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
5609 return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
5610 V1.getOperand(0));
5611 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
5612 // constant. If so, we can just reference the lane's definition directly.
5613 if (V1.getOpcode() == ISD::BUILD_VECTOR &&
5614 !isa<ConstantSDNode>(V1.getOperand(Lane)))
5615 return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
5616
5617 // Otherwise, duplicate from the lane of the input vector.
5618 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
5619
5620 // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
5621 // to make a vector of the same size as this SHUFFLE. We can ignore the
5622 // extract entirely, and canonicalise the concat using WidenVector.
5623 if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
5624 Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
5625 V1 = V1.getOperand(0);
5626 } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
5627 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
5628 Lane -= Idx * VT.getVectorNumElements() / 2;
5629 V1 = WidenVector(V1.getOperand(Idx), DAG);
5630 } else if (VT.getSizeInBits() == 64)
5631 V1 = WidenVector(V1, DAG);
5632
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005633 return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005634 }
5635
5636 if (isREVMask(ShuffleMask, VT, 64))
5637 return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
5638 if (isREVMask(ShuffleMask, VT, 32))
5639 return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
5640 if (isREVMask(ShuffleMask, VT, 16))
5641 return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
5642
5643 bool ReverseEXT = false;
5644 unsigned Imm;
5645 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
5646 if (ReverseEXT)
5647 std::swap(V1, V2);
5648 Imm *= getExtFactor(V1);
5649 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005650 DAG.getConstant(Imm, dl, MVT::i32));
Sanjay Patel57195842016-03-14 17:28:46 +00005651 } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005652 Imm *= getExtFactor(V1);
5653 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005654 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005655 }
5656
5657 unsigned WhichResult;
5658 if (isZIPMask(ShuffleMask, VT, WhichResult)) {
5659 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5660 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5661 }
5662 if (isUZPMask(ShuffleMask, VT, WhichResult)) {
5663 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5664 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5665 }
5666 if (isTRNMask(ShuffleMask, VT, WhichResult)) {
5667 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5668 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5669 }
5670
5671 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5672 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5673 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5674 }
5675 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5676 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5677 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5678 }
5679 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5680 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5681 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5682 }
5683
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00005684 if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00005685 return Concat;
5686
5687 bool DstIsLeft;
5688 int Anomaly;
5689 int NumInputElements = V1.getValueType().getVectorNumElements();
5690 if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
5691 SDValue DstVec = DstIsLeft ? V1 : V2;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005692 SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00005693
5694 SDValue SrcVec = V1;
5695 int SrcLane = ShuffleMask[Anomaly];
5696 if (SrcLane >= NumInputElements) {
5697 SrcVec = V2;
5698 SrcLane -= VT.getVectorNumElements();
5699 }
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005700 SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00005701
5702 EVT ScalarVT = VT.getVectorElementType();
Oliver Stannard89d15422014-08-27 16:16:04 +00005703
5704 if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00005705 ScalarVT = MVT::i32;
5706
5707 return DAG.getNode(
5708 ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5709 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
5710 DstLaneV);
5711 }
5712
5713 // If the shuffle is not directly supported and it has 4 elements, use
5714 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5715 unsigned NumElts = VT.getVectorNumElements();
5716 if (NumElts == 4) {
5717 unsigned PFIndexes[4];
5718 for (unsigned i = 0; i != 4; ++i) {
5719 if (ShuffleMask[i] < 0)
5720 PFIndexes[i] = 8;
5721 else
5722 PFIndexes[i] = ShuffleMask[i];
5723 }
5724
5725 // Compute the index in the perfect shuffle table.
5726 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
5727 PFIndexes[2] * 9 + PFIndexes[3];
5728 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5729 unsigned Cost = (PFEntry >> 30);
5730
5731 if (Cost <= 4)
5732 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5733 }
5734
5735 return GenerateTBL(Op, ShuffleMask, DAG);
5736}
5737
5738static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
5739 APInt &UndefBits) {
5740 EVT VT = BVN->getValueType(0);
5741 APInt SplatBits, SplatUndef;
5742 unsigned SplatBitSize;
5743 bool HasAnyUndefs;
5744 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5745 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
5746
5747 for (unsigned i = 0; i < NumSplats; ++i) {
5748 CnstBits <<= SplatBitSize;
5749 UndefBits <<= SplatBitSize;
5750 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
5751 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
5752 }
5753
5754 return true;
5755 }
5756
5757 return false;
5758}
5759
5760SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op,
5761 SelectionDAG &DAG) const {
5762 BuildVectorSDNode *BVN =
5763 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5764 SDValue LHS = Op.getOperand(0);
5765 SDLoc dl(Op);
5766 EVT VT = Op.getValueType();
5767
5768 if (!BVN)
5769 return Op;
5770
5771 APInt CnstBits(VT.getSizeInBits(), 0);
5772 APInt UndefBits(VT.getSizeInBits(), 0);
5773 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5774 // We only have BIC vector immediate instruction, which is and-not.
5775 CnstBits = ~CnstBits;
5776
5777 // We make use of a little bit of goto ickiness in order to avoid having to
5778 // duplicate the immediate matching logic for the undef toggled case.
5779 bool SecondTry = false;
5780 AttemptModImm:
5781
5782 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5783 CnstBits = CnstBits.zextOrTrunc(64);
5784 uint64_t CnstVal = CnstBits.getZExtValue();
5785
5786 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5787 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5788 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5789 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005790 DAG.getConstant(CnstVal, dl, MVT::i32),
5791 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005792 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005793 }
5794
5795 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5796 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5797 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5798 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005799 DAG.getConstant(CnstVal, dl, MVT::i32),
5800 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005801 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005802 }
5803
5804 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5805 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5806 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5807 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005808 DAG.getConstant(CnstVal, dl, MVT::i32),
5809 DAG.getConstant(16, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005810 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005811 }
5812
5813 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5814 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5815 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5816 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005817 DAG.getConstant(CnstVal, dl, MVT::i32),
5818 DAG.getConstant(24, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005819 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005820 }
5821
5822 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5823 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5824 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5825 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005826 DAG.getConstant(CnstVal, dl, MVT::i32),
5827 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005828 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005829 }
5830
5831 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5832 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5833 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5834 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005835 DAG.getConstant(CnstVal, dl, MVT::i32),
5836 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005837 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005838 }
5839 }
5840
5841 if (SecondTry)
5842 goto FailedModImm;
5843 SecondTry = true;
5844 CnstBits = ~UndefBits;
5845 goto AttemptModImm;
5846 }
5847
5848// We can always fall back to a non-immediate AND.
5849FailedModImm:
5850 return Op;
5851}
5852
5853// Specialized code to quickly find if PotentialBVec is a BuildVector that
5854// consists of only the same constant int value, returned in reference arg
5855// ConstVal
5856static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
5857 uint64_t &ConstVal) {
5858 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
5859 if (!Bvec)
5860 return false;
5861 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
5862 if (!FirstElt)
5863 return false;
5864 EVT VT = Bvec->getValueType(0);
5865 unsigned NumElts = VT.getVectorNumElements();
5866 for (unsigned i = 1; i < NumElts; ++i)
5867 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
5868 return false;
5869 ConstVal = FirstElt->getZExtValue();
5870 return true;
5871}
5872
5873static unsigned getIntrinsicID(const SDNode *N) {
5874 unsigned Opcode = N->getOpcode();
5875 switch (Opcode) {
5876 default:
5877 return Intrinsic::not_intrinsic;
5878 case ISD::INTRINSIC_WO_CHAIN: {
5879 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
5880 if (IID < Intrinsic::num_intrinsics)
5881 return IID;
5882 return Intrinsic::not_intrinsic;
5883 }
5884 }
5885}
5886
5887// Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
5888// to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
5889// BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
5890// Also, logical shift right -> sri, with the same structure.
5891static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
5892 EVT VT = N->getValueType(0);
5893
5894 if (!VT.isVector())
5895 return SDValue();
5896
5897 SDLoc DL(N);
5898
5899 // Is the first op an AND?
5900 const SDValue And = N->getOperand(0);
5901 if (And.getOpcode() != ISD::AND)
5902 return SDValue();
5903
5904 // Is the second op an shl or lshr?
5905 SDValue Shift = N->getOperand(1);
5906 // This will have been turned into: AArch64ISD::VSHL vector, #shift
5907 // or AArch64ISD::VLSHR vector, #shift
5908 unsigned ShiftOpc = Shift.getOpcode();
5909 if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
5910 return SDValue();
5911 bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
5912
5913 // Is the shift amount constant?
5914 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
5915 if (!C2node)
5916 return SDValue();
5917
5918 // Is the and mask vector all constant?
5919 uint64_t C1;
5920 if (!isAllConstantBuildVector(And.getOperand(1), C1))
5921 return SDValue();
5922
5923 // Is C1 == ~C2, taking into account how much one can shift elements of a
5924 // particular size?
5925 uint64_t C2 = C2node->getZExtValue();
5926 unsigned ElemSizeInBits = VT.getVectorElementType().getSizeInBits();
5927 if (C2 > ElemSizeInBits)
5928 return SDValue();
5929 unsigned ElemMask = (1 << ElemSizeInBits) - 1;
5930 if ((C1 & ElemMask) != (~C2 & ElemMask))
5931 return SDValue();
5932
5933 SDValue X = And.getOperand(0);
5934 SDValue Y = Shift.getOperand(0);
5935
5936 unsigned Intrin =
5937 IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
5938 SDValue ResultSLI =
5939 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005940 DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
5941 Shift.getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00005942
5943 DEBUG(dbgs() << "aarch64-lower: transformed: \n");
5944 DEBUG(N->dump(&DAG));
5945 DEBUG(dbgs() << "into: \n");
5946 DEBUG(ResultSLI->dump(&DAG));
5947
5948 ++NumShiftInserts;
5949 return ResultSLI;
5950}
5951
5952SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
5953 SelectionDAG &DAG) const {
5954 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
5955 if (EnableAArch64SlrGeneration) {
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00005956 if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00005957 return Res;
5958 }
5959
5960 BuildVectorSDNode *BVN =
5961 dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
5962 SDValue LHS = Op.getOperand(1);
5963 SDLoc dl(Op);
5964 EVT VT = Op.getValueType();
5965
5966 // OR commutes, so try swapping the operands.
5967 if (!BVN) {
5968 LHS = Op.getOperand(0);
5969 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5970 }
5971 if (!BVN)
5972 return Op;
5973
5974 APInt CnstBits(VT.getSizeInBits(), 0);
5975 APInt UndefBits(VT.getSizeInBits(), 0);
5976 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5977 // We make use of a little bit of goto ickiness in order to avoid having to
5978 // duplicate the immediate matching logic for the undef toggled case.
5979 bool SecondTry = false;
5980 AttemptModImm:
5981
5982 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5983 CnstBits = CnstBits.zextOrTrunc(64);
5984 uint64_t CnstVal = CnstBits.getZExtValue();
5985
5986 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5987 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5988 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5989 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005990 DAG.getConstant(CnstVal, dl, MVT::i32),
5991 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005992 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005993 }
5994
5995 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5996 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5997 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5998 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005999 DAG.getConstant(CnstVal, dl, MVT::i32),
6000 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00006001 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006002 }
6003
6004 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6005 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6006 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6007 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006008 DAG.getConstant(CnstVal, dl, MVT::i32),
6009 DAG.getConstant(16, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00006010 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006011 }
6012
6013 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6014 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6015 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6016 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006017 DAG.getConstant(CnstVal, dl, MVT::i32),
6018 DAG.getConstant(24, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00006019 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006020 }
6021
6022 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6023 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6024 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6025 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006026 DAG.getConstant(CnstVal, dl, MVT::i32),
6027 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00006028 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006029 }
6030
6031 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6032 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6033 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6034 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006035 DAG.getConstant(CnstVal, dl, MVT::i32),
6036 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00006037 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006038 }
6039 }
6040
6041 if (SecondTry)
6042 goto FailedModImm;
6043 SecondTry = true;
6044 CnstBits = UndefBits;
6045 goto AttemptModImm;
6046 }
6047
6048// We can always fall back to a non-immediate OR.
6049FailedModImm:
6050 return Op;
6051}
6052
Kevin Qin4473c192014-07-07 02:45:40 +00006053// Normalize the operands of BUILD_VECTOR. The value of constant operands will
6054// be truncated to fit element width.
6055static SDValue NormalizeBuildVector(SDValue Op,
6056 SelectionDAG &DAG) {
6057 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
Tim Northover3b0846e2014-05-24 12:50:23 +00006058 SDLoc dl(Op);
6059 EVT VT = Op.getValueType();
Kevin Qin4473c192014-07-07 02:45:40 +00006060 EVT EltTy= VT.getVectorElementType();
6061
6062 if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
6063 return Op;
6064
6065 SmallVector<SDValue, 16> Ops;
Pete Cooper7be8f8f2015-08-03 19:04:32 +00006066 for (SDValue Lane : Op->ops()) {
6067 if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
Kevin Qin4473c192014-07-07 02:45:40 +00006068 APInt LowBits(EltTy.getSizeInBits(),
Pete Cooper7be8f8f2015-08-03 19:04:32 +00006069 CstLane->getZExtValue());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006070 Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
Kevin Qin4473c192014-07-07 02:45:40 +00006071 }
6072 Ops.push_back(Lane);
6073 }
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006074 return DAG.getBuildVector(VT, dl, Ops);
Kevin Qin4473c192014-07-07 02:45:40 +00006075}
6076
6077SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
6078 SelectionDAG &DAG) const {
6079 SDLoc dl(Op);
6080 EVT VT = Op.getValueType();
6081 Op = NormalizeBuildVector(Op, DAG);
6082 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
Tim Northover3b0846e2014-05-24 12:50:23 +00006083
6084 APInt CnstBits(VT.getSizeInBits(), 0);
6085 APInt UndefBits(VT.getSizeInBits(), 0);
6086 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
6087 // We make use of a little bit of goto ickiness in order to avoid having to
6088 // duplicate the immediate matching logic for the undef toggled case.
6089 bool SecondTry = false;
6090 AttemptModImm:
6091
6092 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
6093 CnstBits = CnstBits.zextOrTrunc(64);
6094 uint64_t CnstVal = CnstBits.getZExtValue();
6095
6096 // Certain magic vector constants (used to express things like NOT
6097 // and NEG) are passed through unmodified. This allows codegen patterns
6098 // for these operations to match. Special-purpose patterns will lower
6099 // these immediates to MOVIs if it proves necessary.
6100 if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL))
6101 return Op;
6102
6103 // The many faces of MOVI...
6104 if (AArch64_AM::isAdvSIMDModImmType10(CnstVal)) {
6105 CnstVal = AArch64_AM::encodeAdvSIMDModImmType10(CnstVal);
6106 if (VT.getSizeInBits() == 128) {
6107 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::v2i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006108 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006109 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006110 }
6111
6112 // Support the V64 version via subregister insertion.
6113 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::f64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006114 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006115 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006116 }
6117
6118 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6119 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6120 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6121 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006122 DAG.getConstant(CnstVal, dl, MVT::i32),
6123 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006124 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006125 }
6126
6127 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6128 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6129 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6130 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006131 DAG.getConstant(CnstVal, dl, MVT::i32),
6132 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006133 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006134 }
6135
6136 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6137 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6138 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6139 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006140 DAG.getConstant(CnstVal, dl, MVT::i32),
6141 DAG.getConstant(16, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006142 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006143 }
6144
6145 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6146 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6147 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6148 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006149 DAG.getConstant(CnstVal, dl, MVT::i32),
6150 DAG.getConstant(24, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006151 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006152 }
6153
6154 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6155 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6156 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6157 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006158 DAG.getConstant(CnstVal, dl, MVT::i32),
6159 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006160 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006161 }
6162
6163 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6164 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6165 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6166 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006167 DAG.getConstant(CnstVal, dl, MVT::i32),
6168 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006169 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006170 }
6171
6172 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6173 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6174 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6175 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006176 DAG.getConstant(CnstVal, dl, MVT::i32),
6177 DAG.getConstant(264, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006178 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006179 }
6180
6181 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6182 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6183 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6184 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006185 DAG.getConstant(CnstVal, dl, MVT::i32),
6186 DAG.getConstant(272, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006187 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006188 }
6189
6190 if (AArch64_AM::isAdvSIMDModImmType9(CnstVal)) {
6191 CnstVal = AArch64_AM::encodeAdvSIMDModImmType9(CnstVal);
6192 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
6193 SDValue Mov = DAG.getNode(AArch64ISD::MOVI, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006194 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006195 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006196 }
6197
6198 // The few faces of FMOV...
6199 if (AArch64_AM::isAdvSIMDModImmType11(CnstVal)) {
6200 CnstVal = AArch64_AM::encodeAdvSIMDModImmType11(CnstVal);
6201 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32;
6202 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006203 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006204 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006205 }
6206
6207 if (AArch64_AM::isAdvSIMDModImmType12(CnstVal) &&
6208 VT.getSizeInBits() == 128) {
6209 CnstVal = AArch64_AM::encodeAdvSIMDModImmType12(CnstVal);
6210 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MVT::v2f64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006211 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006212 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006213 }
6214
6215 // The many faces of MVNI...
6216 CnstVal = ~CnstVal;
6217 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6218 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6219 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6220 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006221 DAG.getConstant(CnstVal, dl, MVT::i32),
6222 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006223 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006224 }
6225
6226 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6227 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6228 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6229 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006230 DAG.getConstant(CnstVal, dl, MVT::i32),
6231 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006232 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006233 }
6234
6235 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6236 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6237 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6238 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006239 DAG.getConstant(CnstVal, dl, MVT::i32),
6240 DAG.getConstant(16, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006241 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006242 }
6243
6244 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6245 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6246 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6247 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006248 DAG.getConstant(CnstVal, dl, MVT::i32),
6249 DAG.getConstant(24, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006250 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006251 }
6252
6253 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6254 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6255 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6256 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006257 DAG.getConstant(CnstVal, dl, MVT::i32),
6258 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006259 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006260 }
6261
6262 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6263 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6264 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6265 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006266 DAG.getConstant(CnstVal, dl, MVT::i32),
6267 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006268 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006269 }
6270
6271 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6272 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6273 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6274 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006275 DAG.getConstant(CnstVal, dl, MVT::i32),
6276 DAG.getConstant(264, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006277 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006278 }
6279
6280 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6281 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6282 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6283 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006284 DAG.getConstant(CnstVal, dl, MVT::i32),
6285 DAG.getConstant(272, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006286 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006287 }
6288 }
6289
6290 if (SecondTry)
6291 goto FailedModImm;
6292 SecondTry = true;
6293 CnstBits = UndefBits;
6294 goto AttemptModImm;
6295 }
6296FailedModImm:
6297
6298 // Scan through the operands to find some interesting properties we can
6299 // exploit:
6300 // 1) If only one value is used, we can use a DUP, or
6301 // 2) if only the low element is not undef, we can just insert that, or
6302 // 3) if only one constant value is used (w/ some non-constant lanes),
6303 // we can splat the constant value into the whole vector then fill
6304 // in the non-constant lanes.
6305 // 4) FIXME: If different constant values are used, but we can intelligently
6306 // select the values we'll be overwriting for the non-constant
6307 // lanes such that we can directly materialize the vector
6308 // some other way (MOVI, e.g.), we can be sneaky.
6309 unsigned NumElts = VT.getVectorNumElements();
6310 bool isOnlyLowElement = true;
6311 bool usesOnlyOneValue = true;
6312 bool usesOnlyOneConstantValue = true;
6313 bool isConstant = true;
6314 unsigned NumConstantLanes = 0;
6315 SDValue Value;
6316 SDValue ConstantValue;
6317 for (unsigned i = 0; i < NumElts; ++i) {
6318 SDValue V = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00006319 if (V.isUndef())
Tim Northover3b0846e2014-05-24 12:50:23 +00006320 continue;
6321 if (i > 0)
6322 isOnlyLowElement = false;
6323 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6324 isConstant = false;
6325
6326 if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
6327 ++NumConstantLanes;
6328 if (!ConstantValue.getNode())
6329 ConstantValue = V;
6330 else if (ConstantValue != V)
6331 usesOnlyOneConstantValue = false;
6332 }
6333
6334 if (!Value.getNode())
6335 Value = V;
6336 else if (V != Value)
6337 usesOnlyOneValue = false;
6338 }
6339
6340 if (!Value.getNode())
6341 return DAG.getUNDEF(VT);
6342
6343 if (isOnlyLowElement)
6344 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
6345
6346 // Use DUP for non-constant splats. For f32 constant splats, reduce to
6347 // i32 and try again.
6348 if (usesOnlyOneValue) {
6349 if (!isConstant) {
6350 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6351 Value.getValueType() != VT)
6352 return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
6353
6354 // This is actually a DUPLANExx operation, which keeps everything vectory.
6355
6356 // DUPLANE works on 128-bit vectors, widen it if necessary.
6357 SDValue Lane = Value.getOperand(1);
6358 Value = Value.getOperand(0);
6359 if (Value.getValueType().getSizeInBits() == 64)
6360 Value = WidenVector(Value, DAG);
6361
6362 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
6363 return DAG.getNode(Opcode, dl, VT, Value, Lane);
6364 }
6365
6366 if (VT.getVectorElementType().isFloatingPoint()) {
6367 SmallVector<SDValue, 8> Ops;
Pirama Arumuga Nainar12aeefc2015-03-17 23:10:29 +00006368 EVT EltTy = VT.getVectorElementType();
6369 assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
6370 "Unsupported floating-point vector type");
6371 MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00006372 for (unsigned i = 0; i < NumElts; ++i)
6373 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
6374 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006375 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
Tim Northover3b0846e2014-05-24 12:50:23 +00006376 Val = LowerBUILD_VECTOR(Val, DAG);
6377 if (Val.getNode())
6378 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6379 }
6380 }
6381
6382 // If there was only one constant value used and for more than one lane,
6383 // start by splatting that value, then replace the non-constant lanes. This
6384 // is better than the default, which will perform a separate initialization
6385 // for each lane.
6386 if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
6387 SDValue Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
6388 // Now insert the non-constant lanes.
6389 for (unsigned i = 0; i < NumElts; ++i) {
6390 SDValue V = Op.getOperand(i);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006391 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006392 if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) {
6393 // Note that type legalization likely mucked about with the VT of the
6394 // source operand, so we may have to convert it here before inserting.
6395 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
6396 }
6397 }
6398 return Val;
6399 }
6400
6401 // If all elements are constants and the case above didn't get hit, fall back
6402 // to the default expansion, which will generate a load from the constant
6403 // pool.
6404 if (isConstant)
6405 return SDValue();
6406
6407 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6408 if (NumElts >= 4) {
Ahmed Bougacha239d6352015-08-04 00:48:02 +00006409 if (SDValue shuffle = ReconstructShuffle(Op, DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00006410 return shuffle;
6411 }
6412
6413 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6414 // know the default expansion would otherwise fall back on something even
6415 // worse. For a vector with one or two non-undef values, that's
6416 // scalar_to_vector for the elements followed by a shuffle (provided the
6417 // shuffle is valid for the target) and materialization element by element
6418 // on the stack followed by a load for everything else.
6419 if (!isConstant && !usesOnlyOneValue) {
6420 SDValue Vec = DAG.getUNDEF(VT);
6421 SDValue Op0 = Op.getOperand(0);
6422 unsigned ElemSize = VT.getVectorElementType().getSizeInBits();
6423 unsigned i = 0;
6424 // For 32 and 64 bit types, use INSERT_SUBREG for lane zero to
6425 // a) Avoid a RMW dependency on the full vector register, and
6426 // b) Allow the register coalescer to fold away the copy if the
6427 // value is already in an S or D register.
Matthias Braun0acbd082015-08-31 18:25:15 +00006428 // Do not do this for UNDEF/LOAD nodes because we have better patterns
6429 // for those avoiding the SCALAR_TO_VECTOR/BUILD_VECTOR.
Sanjay Patel75068522016-03-14 18:09:43 +00006430 if (!Op0.isUndef() && Op0.getOpcode() != ISD::LOAD &&
Matthias Braun0acbd082015-08-31 18:25:15 +00006431 (ElemSize == 32 || ElemSize == 64)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006432 unsigned SubIdx = ElemSize == 32 ? AArch64::ssub : AArch64::dsub;
6433 MachineSDNode *N =
6434 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl, VT, Vec, Op0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006435 DAG.getTargetConstant(SubIdx, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006436 Vec = SDValue(N, 0);
6437 ++i;
6438 }
6439 for (; i < NumElts; ++i) {
6440 SDValue V = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00006441 if (V.isUndef())
Tim Northover3b0846e2014-05-24 12:50:23 +00006442 continue;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006443 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006444 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6445 }
6446 return Vec;
6447 }
6448
6449 // Just use the default expansion. We failed to find a better alternative.
6450 return SDValue();
6451}
6452
6453SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
6454 SelectionDAG &DAG) const {
6455 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
6456
Tim Northovere4b8e132014-07-15 10:00:26 +00006457 // Check for non-constant or out of range lane.
6458 EVT VT = Op.getOperand(0).getValueType();
6459 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
6460 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
Tim Northover3b0846e2014-05-24 12:50:23 +00006461 return SDValue();
6462
Tim Northover3b0846e2014-05-24 12:50:23 +00006463
6464 // Insertion/extraction are legal for V128 types.
6465 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
Oliver Stannard89d15422014-08-27 16:16:04 +00006466 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6467 VT == MVT::v8f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006468 return Op;
6469
6470 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
Oliver Stannard89d15422014-08-27 16:16:04 +00006471 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006472 return SDValue();
6473
6474 // For V64 types, we perform insertion by expanding the value
6475 // to a V128 type and perform the insertion on that.
6476 SDLoc DL(Op);
6477 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6478 EVT WideTy = WideVec.getValueType();
6479
6480 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
6481 Op.getOperand(1), Op.getOperand(2));
6482 // Re-narrow the resultant vector.
6483 return NarrowVector(Node, DAG);
6484}
6485
6486SDValue
6487AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6488 SelectionDAG &DAG) const {
6489 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
6490
Tim Northovere4b8e132014-07-15 10:00:26 +00006491 // Check for non-constant or out of range lane.
6492 EVT VT = Op.getOperand(0).getValueType();
6493 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6494 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
Tim Northover3b0846e2014-05-24 12:50:23 +00006495 return SDValue();
6496
Tim Northover3b0846e2014-05-24 12:50:23 +00006497
6498 // Insertion/extraction are legal for V128 types.
6499 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
Oliver Stannard89d15422014-08-27 16:16:04 +00006500 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6501 VT == MVT::v8f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006502 return Op;
6503
6504 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
Oliver Stannard89d15422014-08-27 16:16:04 +00006505 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006506 return SDValue();
6507
6508 // For V64 types, we perform extraction by expanding the value
6509 // to a V128 type and perform the extraction on that.
6510 SDLoc DL(Op);
6511 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6512 EVT WideTy = WideVec.getValueType();
6513
6514 EVT ExtrTy = WideTy.getVectorElementType();
6515 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
6516 ExtrTy = MVT::i32;
6517
6518 // For extractions, we just return the result directly.
6519 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
6520 Op.getOperand(1));
6521}
6522
6523SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
6524 SelectionDAG &DAG) const {
6525 EVT VT = Op.getOperand(0).getValueType();
6526 SDLoc dl(Op);
6527 // Just in case...
6528 if (!VT.isVector())
6529 return SDValue();
6530
6531 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6532 if (!Cst)
6533 return SDValue();
6534 unsigned Val = Cst->getZExtValue();
6535
6536 unsigned Size = Op.getValueType().getSizeInBits();
Charlie Turner7b7b06f2015-11-09 12:45:11 +00006537
6538 // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
6539 if (Val == 0)
6540 return Op;
6541
Tim Northover3b0846e2014-05-24 12:50:23 +00006542 // If this is extracting the upper 64-bits of a 128-bit vector, we match
6543 // that directly.
6544 if (Size == 64 && Val * VT.getVectorElementType().getSizeInBits() == 64)
6545 return Op;
6546
6547 return SDValue();
6548}
6549
6550bool AArch64TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
6551 EVT VT) const {
6552 if (VT.getVectorNumElements() == 4 &&
6553 (VT.is128BitVector() || VT.is64BitVector())) {
6554 unsigned PFIndexes[4];
6555 for (unsigned i = 0; i != 4; ++i) {
6556 if (M[i] < 0)
6557 PFIndexes[i] = 8;
6558 else
6559 PFIndexes[i] = M[i];
6560 }
6561
6562 // Compute the index in the perfect shuffle table.
6563 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6564 PFIndexes[2] * 9 + PFIndexes[3];
6565 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6566 unsigned Cost = (PFEntry >> 30);
6567
6568 if (Cost <= 4)
6569 return true;
6570 }
6571
6572 bool DummyBool;
6573 int DummyInt;
6574 unsigned DummyUnsigned;
6575
6576 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
6577 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
6578 isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
6579 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
6580 isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
6581 isZIPMask(M, VT, DummyUnsigned) ||
6582 isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
6583 isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
6584 isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
6585 isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
6586 isConcatMask(M, VT, VT.getSizeInBits() == 128));
6587}
6588
6589/// getVShiftImm - Check if this is a valid build_vector for the immediate
6590/// operand of a vector shift operation, where all the elements of the
6591/// build_vector must have the same constant integer value.
6592static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
6593 // Ignore bit_converts.
6594 while (Op.getOpcode() == ISD::BITCAST)
6595 Op = Op.getOperand(0);
6596 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6597 APInt SplatBits, SplatUndef;
6598 unsigned SplatBitSize;
6599 bool HasAnyUndefs;
6600 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
6601 HasAnyUndefs, ElementBits) ||
6602 SplatBitSize > ElementBits)
6603 return false;
6604 Cnt = SplatBits.getSExtValue();
6605 return true;
6606}
6607
6608/// isVShiftLImm - Check if this is a valid build_vector for the immediate
6609/// operand of a vector shift left operation. That value must be in the range:
6610/// 0 <= Value < ElementBits for a left shift; or
6611/// 0 <= Value <= ElementBits for a long left shift.
6612static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
6613 assert(VT.isVector() && "vector shift count is not a vector type");
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00006614 int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00006615 if (!getVShiftImm(Op, ElementBits, Cnt))
6616 return false;
6617 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
6618}
6619
6620/// isVShiftRImm - Check if this is a valid build_vector for the immediate
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00006621/// operand of a vector shift right operation. The value must be in the range:
6622/// 1 <= Value <= ElementBits for a right shift; or
6623static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006624 assert(VT.isVector() && "vector shift count is not a vector type");
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00006625 int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00006626 if (!getVShiftImm(Op, ElementBits, Cnt))
6627 return false;
Tim Northover3b0846e2014-05-24 12:50:23 +00006628 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
6629}
6630
6631SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
6632 SelectionDAG &DAG) const {
6633 EVT VT = Op.getValueType();
6634 SDLoc DL(Op);
6635 int64_t Cnt;
6636
6637 if (!Op.getOperand(1).getValueType().isVector())
6638 return Op;
6639 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6640
6641 switch (Op.getOpcode()) {
6642 default:
6643 llvm_unreachable("unexpected shift opcode");
6644
6645 case ISD::SHL:
6646 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006647 return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
6648 DAG.getConstant(Cnt, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006649 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006650 DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
6651 MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00006652 Op.getOperand(0), Op.getOperand(1));
6653 case ISD::SRA:
6654 case ISD::SRL:
6655 // Right shift immediate
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00006656 if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006657 unsigned Opc =
6658 (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006659 return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
6660 DAG.getConstant(Cnt, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006661 }
6662
6663 // Right shift register. Note, there is not a shift right register
6664 // instruction, but the shift left register instruction takes a signed
6665 // value, where negative numbers specify a right shift.
6666 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
6667 : Intrinsic::aarch64_neon_ushl;
6668 // negate the shift amount
6669 SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
6670 SDValue NegShiftLeft =
6671 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006672 DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
6673 NegShift);
Tim Northover3b0846e2014-05-24 12:50:23 +00006674 return NegShiftLeft;
6675 }
6676
6677 return SDValue();
6678}
6679
6680static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
6681 AArch64CC::CondCode CC, bool NoNans, EVT VT,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00006682 const SDLoc &dl, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006683 EVT SrcVT = LHS.getValueType();
Tim Northover45aa89c2015-02-08 00:50:47 +00006684 assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
6685 "function only supposed to emit natural comparisons");
Tim Northover3b0846e2014-05-24 12:50:23 +00006686
6687 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
6688 APInt CnstBits(VT.getSizeInBits(), 0);
6689 APInt UndefBits(VT.getSizeInBits(), 0);
6690 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
6691 bool IsZero = IsCnst && (CnstBits == 0);
6692
6693 if (SrcVT.getVectorElementType().isFloatingPoint()) {
6694 switch (CC) {
6695 default:
6696 return SDValue();
6697 case AArch64CC::NE: {
6698 SDValue Fcmeq;
6699 if (IsZero)
6700 Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6701 else
6702 Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6703 return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
6704 }
6705 case AArch64CC::EQ:
6706 if (IsZero)
6707 return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6708 return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6709 case AArch64CC::GE:
6710 if (IsZero)
6711 return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
6712 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
6713 case AArch64CC::GT:
6714 if (IsZero)
6715 return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
6716 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
6717 case AArch64CC::LS:
6718 if (IsZero)
6719 return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
6720 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
6721 case AArch64CC::LT:
6722 if (!NoNans)
6723 return SDValue();
Justin Bognerb03fd122016-08-17 05:10:15 +00006724 // If we ignore NaNs then we can use to the MI implementation.
6725 LLVM_FALLTHROUGH;
Tim Northover3b0846e2014-05-24 12:50:23 +00006726 case AArch64CC::MI:
6727 if (IsZero)
6728 return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
6729 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
6730 }
6731 }
6732
6733 switch (CC) {
6734 default:
6735 return SDValue();
6736 case AArch64CC::NE: {
6737 SDValue Cmeq;
6738 if (IsZero)
6739 Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6740 else
6741 Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6742 return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
6743 }
6744 case AArch64CC::EQ:
6745 if (IsZero)
6746 return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6747 return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6748 case AArch64CC::GE:
6749 if (IsZero)
6750 return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
6751 return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
6752 case AArch64CC::GT:
6753 if (IsZero)
6754 return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
6755 return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
6756 case AArch64CC::LE:
6757 if (IsZero)
6758 return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
6759 return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
6760 case AArch64CC::LS:
6761 return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
6762 case AArch64CC::LO:
6763 return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
6764 case AArch64CC::LT:
6765 if (IsZero)
6766 return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
6767 return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
6768 case AArch64CC::HI:
6769 return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
6770 case AArch64CC::HS:
6771 return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
6772 }
6773}
6774
6775SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
6776 SelectionDAG &DAG) const {
6777 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6778 SDValue LHS = Op.getOperand(0);
6779 SDValue RHS = Op.getOperand(1);
Tim Northover45aa89c2015-02-08 00:50:47 +00006780 EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
Tim Northover3b0846e2014-05-24 12:50:23 +00006781 SDLoc dl(Op);
6782
6783 if (LHS.getValueType().getVectorElementType().isInteger()) {
6784 assert(LHS.getValueType() == RHS.getValueType());
6785 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
Tim Northover45aa89c2015-02-08 00:50:47 +00006786 SDValue Cmp =
6787 EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
6788 return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00006789 }
6790
Pirama Arumuga Nainar71e9a2a2016-01-22 01:16:57 +00006791 if (LHS.getValueType().getVectorElementType() == MVT::f16)
6792 return SDValue();
6793
Tim Northover3b0846e2014-05-24 12:50:23 +00006794 assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
6795 LHS.getValueType().getVectorElementType() == MVT::f64);
6796
6797 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
6798 // clean. Some of them require two branches to implement.
6799 AArch64CC::CondCode CC1, CC2;
6800 bool ShouldInvert;
6801 changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
6802
6803 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
6804 SDValue Cmp =
Tim Northover45aa89c2015-02-08 00:50:47 +00006805 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00006806 if (!Cmp.getNode())
6807 return SDValue();
6808
6809 if (CC2 != AArch64CC::AL) {
6810 SDValue Cmp2 =
Tim Northover45aa89c2015-02-08 00:50:47 +00006811 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00006812 if (!Cmp2.getNode())
6813 return SDValue();
6814
Tim Northover45aa89c2015-02-08 00:50:47 +00006815 Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
Tim Northover3b0846e2014-05-24 12:50:23 +00006816 }
6817
Tim Northover45aa89c2015-02-08 00:50:47 +00006818 Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
6819
Tim Northover3b0846e2014-05-24 12:50:23 +00006820 if (ShouldInvert)
6821 return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
6822
6823 return Cmp;
6824}
6825
6826/// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
6827/// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
6828/// specified in the intrinsic calls.
6829bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
6830 const CallInst &I,
6831 unsigned Intrinsic) const {
Mehdi Aminia749f2a2015-07-09 02:09:52 +00006832 auto &DL = I.getModule()->getDataLayout();
Tim Northover3b0846e2014-05-24 12:50:23 +00006833 switch (Intrinsic) {
6834 case Intrinsic::aarch64_neon_ld2:
6835 case Intrinsic::aarch64_neon_ld3:
6836 case Intrinsic::aarch64_neon_ld4:
6837 case Intrinsic::aarch64_neon_ld1x2:
6838 case Intrinsic::aarch64_neon_ld1x3:
6839 case Intrinsic::aarch64_neon_ld1x4:
6840 case Intrinsic::aarch64_neon_ld2lane:
6841 case Intrinsic::aarch64_neon_ld3lane:
6842 case Intrinsic::aarch64_neon_ld4lane:
6843 case Intrinsic::aarch64_neon_ld2r:
6844 case Intrinsic::aarch64_neon_ld3r:
6845 case Intrinsic::aarch64_neon_ld4r: {
6846 Info.opc = ISD::INTRINSIC_W_CHAIN;
6847 // Conservatively set memVT to the entire set of vectors loaded.
Ahmed Bougacha97564c32015-12-09 01:19:50 +00006848 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00006849 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6850 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6851 Info.offset = 0;
6852 Info.align = 0;
6853 Info.vol = false; // volatile loads with NEON intrinsics not supported
6854 Info.readMem = true;
6855 Info.writeMem = false;
6856 return true;
6857 }
6858 case Intrinsic::aarch64_neon_st2:
6859 case Intrinsic::aarch64_neon_st3:
6860 case Intrinsic::aarch64_neon_st4:
6861 case Intrinsic::aarch64_neon_st1x2:
6862 case Intrinsic::aarch64_neon_st1x3:
6863 case Intrinsic::aarch64_neon_st1x4:
6864 case Intrinsic::aarch64_neon_st2lane:
6865 case Intrinsic::aarch64_neon_st3lane:
6866 case Intrinsic::aarch64_neon_st4lane: {
6867 Info.opc = ISD::INTRINSIC_VOID;
6868 // Conservatively set memVT to the entire set of vectors stored.
6869 unsigned NumElts = 0;
6870 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
6871 Type *ArgTy = I.getArgOperand(ArgI)->getType();
6872 if (!ArgTy->isVectorTy())
6873 break;
Ahmed Bougacha97564c32015-12-09 01:19:50 +00006874 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00006875 }
6876 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6877 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6878 Info.offset = 0;
6879 Info.align = 0;
6880 Info.vol = false; // volatile stores with NEON intrinsics not supported
6881 Info.readMem = false;
6882 Info.writeMem = true;
6883 return true;
6884 }
6885 case Intrinsic::aarch64_ldaxr:
6886 case Intrinsic::aarch64_ldxr: {
6887 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
6888 Info.opc = ISD::INTRINSIC_W_CHAIN;
6889 Info.memVT = MVT::getVT(PtrTy->getElementType());
6890 Info.ptrVal = I.getArgOperand(0);
6891 Info.offset = 0;
Mehdi Aminia749f2a2015-07-09 02:09:52 +00006892 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
Tim Northover3b0846e2014-05-24 12:50:23 +00006893 Info.vol = true;
6894 Info.readMem = true;
6895 Info.writeMem = false;
6896 return true;
6897 }
6898 case Intrinsic::aarch64_stlxr:
6899 case Intrinsic::aarch64_stxr: {
6900 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
6901 Info.opc = ISD::INTRINSIC_W_CHAIN;
6902 Info.memVT = MVT::getVT(PtrTy->getElementType());
6903 Info.ptrVal = I.getArgOperand(1);
6904 Info.offset = 0;
Mehdi Aminia749f2a2015-07-09 02:09:52 +00006905 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
Tim Northover3b0846e2014-05-24 12:50:23 +00006906 Info.vol = true;
6907 Info.readMem = false;
6908 Info.writeMem = true;
6909 return true;
6910 }
6911 case Intrinsic::aarch64_ldaxp:
6912 case Intrinsic::aarch64_ldxp: {
6913 Info.opc = ISD::INTRINSIC_W_CHAIN;
6914 Info.memVT = MVT::i128;
6915 Info.ptrVal = I.getArgOperand(0);
6916 Info.offset = 0;
6917 Info.align = 16;
6918 Info.vol = true;
6919 Info.readMem = true;
6920 Info.writeMem = false;
6921 return true;
6922 }
6923 case Intrinsic::aarch64_stlxp:
6924 case Intrinsic::aarch64_stxp: {
6925 Info.opc = ISD::INTRINSIC_W_CHAIN;
6926 Info.memVT = MVT::i128;
6927 Info.ptrVal = I.getArgOperand(2);
6928 Info.offset = 0;
6929 Info.align = 16;
6930 Info.vol = true;
6931 Info.readMem = false;
6932 Info.writeMem = true;
6933 return true;
6934 }
6935 default:
6936 break;
6937 }
6938
6939 return false;
6940}
6941
6942// Truncations from 64-bit GPR to 32-bit GPR is free.
6943bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
6944 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6945 return false;
6946 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6947 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00006948 return NumBits1 > NumBits2;
Tim Northover3b0846e2014-05-24 12:50:23 +00006949}
6950bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
Hao Liu40914502014-05-29 09:19:07 +00006951 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00006952 return false;
6953 unsigned NumBits1 = VT1.getSizeInBits();
6954 unsigned NumBits2 = VT2.getSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00006955 return NumBits1 > NumBits2;
Tim Northover3b0846e2014-05-24 12:50:23 +00006956}
6957
Chad Rosier54390052015-02-23 19:15:16 +00006958/// Check if it is profitable to hoist instruction in then/else to if.
6959/// Not profitable if I and it's user can form a FMA instruction
6960/// because we prefer FMSUB/FMADD.
6961bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
6962 if (I->getOpcode() != Instruction::FMul)
6963 return true;
6964
6965 if (I->getNumUses() != 1)
6966 return true;
6967
6968 Instruction *User = I->user_back();
6969
6970 if (User &&
6971 !(User->getOpcode() == Instruction::FSub ||
6972 User->getOpcode() == Instruction::FAdd))
6973 return true;
6974
6975 const TargetOptions &Options = getTargetMachine().Options;
Mehdi Amini44ede332015-07-09 02:09:04 +00006976 const DataLayout &DL = I->getModule()->getDataLayout();
6977 EVT VT = getValueType(DL, User->getOperand(0)->getType());
Chad Rosier54390052015-02-23 19:15:16 +00006978
Eric Christopher114fa1c2016-02-29 22:50:49 +00006979 return !(isFMAFasterThanFMulAndFAdd(VT) &&
6980 isOperationLegalOrCustom(ISD::FMA, VT) &&
6981 (Options.AllowFPOpFusion == FPOpFusion::Fast ||
6982 Options.UnsafeFPMath));
Chad Rosier54390052015-02-23 19:15:16 +00006983}
6984
Tim Northover3b0846e2014-05-24 12:50:23 +00006985// All 32-bit GPR operations implicitly zero the high-half of the corresponding
6986// 64-bit GPR.
6987bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
6988 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6989 return false;
6990 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6991 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00006992 return NumBits1 == 32 && NumBits2 == 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00006993}
6994bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
Hao Liu40914502014-05-29 09:19:07 +00006995 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00006996 return false;
6997 unsigned NumBits1 = VT1.getSizeInBits();
6998 unsigned NumBits2 = VT2.getSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00006999 return NumBits1 == 32 && NumBits2 == 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00007000}
7001
7002bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
7003 EVT VT1 = Val.getValueType();
7004 if (isZExtFree(VT1, VT2)) {
7005 return true;
7006 }
7007
7008 if (Val.getOpcode() != ISD::LOAD)
7009 return false;
7010
7011 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
Hao Liu40914502014-05-29 09:19:07 +00007012 return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
7013 VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
7014 VT1.getSizeInBits() <= 32);
Tim Northover3b0846e2014-05-24 12:50:23 +00007015}
7016
Quentin Colombet6843ac42015-03-31 20:52:32 +00007017bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
7018 if (isa<FPExtInst>(Ext))
7019 return false;
7020
7021 // Vector types are next free.
7022 if (Ext->getType()->isVectorTy())
7023 return false;
7024
7025 for (const Use &U : Ext->uses()) {
7026 // The extension is free if we can fold it with a left shift in an
7027 // addressing mode or an arithmetic operation: add, sub, and cmp.
7028
7029 // Is there a shift?
7030 const Instruction *Instr = cast<Instruction>(U.getUser());
7031
7032 // Is this a constant shift?
7033 switch (Instr->getOpcode()) {
7034 case Instruction::Shl:
7035 if (!isa<ConstantInt>(Instr->getOperand(1)))
7036 return false;
7037 break;
7038 case Instruction::GetElementPtr: {
7039 gep_type_iterator GTI = gep_type_begin(Instr);
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007040 auto &DL = Ext->getModule()->getDataLayout();
Quentin Colombet6843ac42015-03-31 20:52:32 +00007041 std::advance(GTI, U.getOperandNo());
7042 Type *IdxTy = *GTI;
7043 // This extension will end up with a shift because of the scaling factor.
7044 // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
7045 // Get the shift amount based on the scaling factor:
7046 // log2(sizeof(IdxTy)) - log2(8).
7047 uint64_t ShiftAmt =
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007048 countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3;
Quentin Colombet6843ac42015-03-31 20:52:32 +00007049 // Is the constant foldable in the shift of the addressing mode?
7050 // I.e., shift amount is between 1 and 4 inclusive.
7051 if (ShiftAmt == 0 || ShiftAmt > 4)
7052 return false;
7053 break;
7054 }
7055 case Instruction::Trunc:
7056 // Check if this is a noop.
7057 // trunc(sext ty1 to ty2) to ty1.
7058 if (Instr->getType() == Ext->getOperand(0)->getType())
7059 continue;
7060 // FALL THROUGH.
7061 default:
7062 return false;
7063 }
7064
7065 // At this point we can use the bfm family, so this extension is free
7066 // for that use.
7067 }
7068 return true;
7069}
7070
Tim Northover3b0846e2014-05-24 12:50:23 +00007071bool AArch64TargetLowering::hasPairedLoad(Type *LoadedType,
7072 unsigned &RequiredAligment) const {
7073 if (!LoadedType->isIntegerTy() && !LoadedType->isFloatTy())
7074 return false;
7075 // Cyclone supports unaligned accesses.
7076 RequiredAligment = 0;
7077 unsigned NumBits = LoadedType->getPrimitiveSizeInBits();
7078 return NumBits == 32 || NumBits == 64;
7079}
7080
7081bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
7082 unsigned &RequiredAligment) const {
7083 if (!LoadedType.isSimple() ||
7084 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
7085 return false;
7086 // Cyclone supports unaligned accesses.
7087 RequiredAligment = 0;
7088 unsigned NumBits = LoadedType.getSizeInBits();
7089 return NumBits == 32 || NumBits == 64;
7090}
7091
Hao Liu7ec8ee32015-06-26 02:32:07 +00007092/// \brief Lower an interleaved load into a ldN intrinsic.
7093///
7094/// E.g. Lower an interleaved load (Factor = 2):
7095/// %wide.vec = load <8 x i32>, <8 x i32>* %ptr
7096/// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
7097/// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
7098///
7099/// Into:
7100/// %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
7101/// %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
7102/// %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
7103bool AArch64TargetLowering::lowerInterleavedLoad(
7104 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
7105 ArrayRef<unsigned> Indices, unsigned Factor) const {
7106 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7107 "Invalid interleave factor");
7108 assert(!Shuffles.empty() && "Empty shufflevector input");
7109 assert(Shuffles.size() == Indices.size() &&
7110 "Unmatched number of shufflevectors and indices");
7111
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007112 const DataLayout &DL = LI->getModule()->getDataLayout();
Hao Liu7ec8ee32015-06-26 02:32:07 +00007113
7114 VectorType *VecTy = Shuffles[0]->getType();
Ahmed Bougacha97564c32015-12-09 01:19:50 +00007115 unsigned VecSize = DL.getTypeSizeInBits(VecTy);
Hao Liu7ec8ee32015-06-26 02:32:07 +00007116
Jeroen Ketemaaebca092015-10-07 14:53:29 +00007117 // Skip if we do not have NEON and skip illegal vector types.
7118 if (!Subtarget->hasNEON() || (VecSize != 64 && VecSize != 128))
Hao Liu7ec8ee32015-06-26 02:32:07 +00007119 return false;
7120
7121 // A pointer vector can not be the return type of the ldN intrinsics. Need to
7122 // load integer vectors first and then convert to pointer vectors.
7123 Type *EltTy = VecTy->getVectorElementType();
7124 if (EltTy->isPointerTy())
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007125 VecTy =
7126 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
Hao Liu7ec8ee32015-06-26 02:32:07 +00007127
7128 Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
7129 Type *Tys[2] = {VecTy, PtrTy};
7130 static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
7131 Intrinsic::aarch64_neon_ld3,
7132 Intrinsic::aarch64_neon_ld4};
7133 Function *LdNFunc =
7134 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
7135
7136 IRBuilder<> Builder(LI);
7137 Value *Ptr = Builder.CreateBitCast(LI->getPointerOperand(), PtrTy);
7138
7139 CallInst *LdN = Builder.CreateCall(LdNFunc, Ptr, "ldN");
7140
7141 // Replace uses of each shufflevector with the corresponding vector loaded
7142 // by ldN.
7143 for (unsigned i = 0; i < Shuffles.size(); i++) {
7144 ShuffleVectorInst *SVI = Shuffles[i];
7145 unsigned Index = Indices[i];
7146
7147 Value *SubVec = Builder.CreateExtractValue(LdN, Index);
7148
7149 // Convert the integer vector to pointer vector if the element is pointer.
7150 if (EltTy->isPointerTy())
7151 SubVec = Builder.CreateIntToPtr(SubVec, SVI->getType());
7152
7153 SVI->replaceAllUsesWith(SubVec);
7154 }
7155
7156 return true;
7157}
7158
7159/// \brief Get a mask consisting of sequential integers starting from \p Start.
7160///
7161/// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
7162static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
7163 unsigned NumElts) {
7164 SmallVector<Constant *, 16> Mask;
7165 for (unsigned i = 0; i < NumElts; i++)
7166 Mask.push_back(Builder.getInt32(Start + i));
7167
7168 return ConstantVector::get(Mask);
7169}
7170
7171/// \brief Lower an interleaved store into a stN intrinsic.
7172///
7173/// E.g. Lower an interleaved store (Factor = 3):
7174/// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
7175/// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
7176/// store <12 x i32> %i.vec, <12 x i32>* %ptr
7177///
7178/// Into:
7179/// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
7180/// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
7181/// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
7182/// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
7183///
7184/// Note that the new shufflevectors will be removed and we'll only generate one
7185/// st3 instruction in CodeGen.
7186bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
7187 ShuffleVectorInst *SVI,
7188 unsigned Factor) const {
7189 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7190 "Invalid interleave factor");
7191
7192 VectorType *VecTy = SVI->getType();
7193 assert(VecTy->getVectorNumElements() % Factor == 0 &&
7194 "Invalid interleaved store");
7195
7196 unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
7197 Type *EltTy = VecTy->getVectorElementType();
7198 VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
7199
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007200 const DataLayout &DL = SI->getModule()->getDataLayout();
Ahmed Bougacha97564c32015-12-09 01:19:50 +00007201 unsigned SubVecSize = DL.getTypeSizeInBits(SubVecTy);
Hao Liu7ec8ee32015-06-26 02:32:07 +00007202
Jeroen Ketemaaebca092015-10-07 14:53:29 +00007203 // Skip if we do not have NEON and skip illegal vector types.
7204 if (!Subtarget->hasNEON() || (SubVecSize != 64 && SubVecSize != 128))
Hao Liu7ec8ee32015-06-26 02:32:07 +00007205 return false;
7206
7207 Value *Op0 = SVI->getOperand(0);
7208 Value *Op1 = SVI->getOperand(1);
7209 IRBuilder<> Builder(SI);
7210
7211 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
7212 // vectors to integer vectors.
7213 if (EltTy->isPointerTy()) {
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007214 Type *IntTy = DL.getIntPtrType(EltTy);
Hao Liu7ec8ee32015-06-26 02:32:07 +00007215 unsigned NumOpElts =
7216 dyn_cast<VectorType>(Op0->getType())->getVectorNumElements();
7217
7218 // Convert to the corresponding integer vector.
7219 Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
7220 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
7221 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
7222
7223 SubVecTy = VectorType::get(IntTy, NumSubElts);
7224 }
7225
7226 Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
7227 Type *Tys[2] = {SubVecTy, PtrTy};
7228 static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
7229 Intrinsic::aarch64_neon_st3,
7230 Intrinsic::aarch64_neon_st4};
7231 Function *StNFunc =
7232 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
7233
7234 SmallVector<Value *, 5> Ops;
7235
7236 // Split the shufflevector operands into sub vectors for the new stN call.
7237 for (unsigned i = 0; i < Factor; i++)
7238 Ops.push_back(Builder.CreateShuffleVector(
7239 Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
7240
7241 Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), PtrTy));
7242 Builder.CreateCall(StNFunc, Ops);
7243 return true;
7244}
7245
Tim Northover3b0846e2014-05-24 12:50:23 +00007246static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
7247 unsigned AlignCheck) {
7248 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
7249 (DstAlign == 0 || DstAlign % AlignCheck == 0));
7250}
7251
7252EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
7253 unsigned SrcAlign, bool IsMemset,
7254 bool ZeroMemset,
7255 bool MemcpyStrSrc,
7256 MachineFunction &MF) const {
7257 // Don't use AdvSIMD to implement 16-byte memset. It would have taken one
7258 // instruction to materialize the v2i64 zero and one store (with restrictive
7259 // addressing mode). Just do two i64 store of zero-registers.
7260 bool Fast;
7261 const Function *F = MF.getFunction();
7262 if (Subtarget->hasFPARMv8() && !IsMemset && Size >= 16 &&
Duncan P. N. Exon Smith003bb7d2015-02-14 02:09:06 +00007263 !F->hasFnAttribute(Attribute::NoImplicitFloat) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00007264 (memOpAlign(SrcAlign, DstAlign, 16) ||
Matt Arsenault6f2a5262014-07-27 17:46:40 +00007265 (allowsMisalignedMemoryAccesses(MVT::f128, 0, 1, &Fast) && Fast)))
Tim Northover3b0846e2014-05-24 12:50:23 +00007266 return MVT::f128;
7267
Lang Hames90333852015-04-09 03:40:33 +00007268 if (Size >= 8 &&
7269 (memOpAlign(SrcAlign, DstAlign, 8) ||
7270 (allowsMisalignedMemoryAccesses(MVT::i64, 0, 1, &Fast) && Fast)))
7271 return MVT::i64;
7272
7273 if (Size >= 4 &&
7274 (memOpAlign(SrcAlign, DstAlign, 4) ||
7275 (allowsMisalignedMemoryAccesses(MVT::i32, 0, 1, &Fast) && Fast)))
Lang Hames522bf132015-04-09 05:34:57 +00007276 return MVT::i32;
Lang Hames90333852015-04-09 03:40:33 +00007277
7278 return MVT::Other;
Tim Northover3b0846e2014-05-24 12:50:23 +00007279}
7280
7281// 12-bit optionally shifted immediates are legal for adds.
7282bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
Geoff Berry486f49c2016-06-07 16:48:43 +00007283 // Avoid UB for INT64_MIN.
7284 if (Immed == std::numeric_limits<int64_t>::min())
7285 return false;
7286 // Same encoding for add/sub, just flip the sign.
7287 Immed = std::abs(Immed);
Eric Christopher114fa1c2016-02-29 22:50:49 +00007288 return ((Immed >> 12) == 0 || ((Immed & 0xfff) == 0 && Immed >> 24 == 0));
Tim Northover3b0846e2014-05-24 12:50:23 +00007289}
7290
7291// Integer comparisons are implemented with ADDS/SUBS, so the range of valid
7292// immediates is the same as for an add or a sub.
7293bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00007294 return isLegalAddImmediate(Immed);
7295}
7296
7297/// isLegalAddressingMode - Return true if the addressing mode represented
7298/// by AM is legal for this target, for a load/store of the specified type.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00007299bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
7300 const AddrMode &AM, Type *Ty,
Matt Arsenaultbd7d80a2015-06-01 05:31:59 +00007301 unsigned AS) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00007302 // AArch64 has five basic addressing modes:
7303 // reg
7304 // reg + 9-bit signed offset
7305 // reg + SIZE_IN_BYTES * 12-bit unsigned offset
7306 // reg1 + reg2
7307 // reg + SIZE_IN_BYTES * reg
7308
7309 // No global is ever allowed as a base.
7310 if (AM.BaseGV)
7311 return false;
7312
7313 // No reg+reg+imm addressing.
7314 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
7315 return false;
7316
7317 // check reg + imm case:
7318 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
7319 uint64_t NumBytes = 0;
7320 if (Ty->isSized()) {
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00007321 uint64_t NumBits = DL.getTypeSizeInBits(Ty);
Tim Northover3b0846e2014-05-24 12:50:23 +00007322 NumBytes = NumBits / 8;
7323 if (!isPowerOf2_64(NumBits))
7324 NumBytes = 0;
7325 }
7326
7327 if (!AM.Scale) {
7328 int64_t Offset = AM.BaseOffs;
7329
7330 // 9-bit signed offset
7331 if (Offset >= -(1LL << 9) && Offset <= (1LL << 9) - 1)
7332 return true;
7333
7334 // 12-bit unsigned offset
7335 unsigned shift = Log2_64(NumBytes);
7336 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
7337 // Must be a multiple of NumBytes (NumBytes is a power of 2)
7338 (Offset >> shift) << shift == Offset)
7339 return true;
7340 return false;
7341 }
7342
7343 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
7344
Eric Christopher114fa1c2016-02-29 22:50:49 +00007345 return !AM.Scale || AM.Scale == 1 ||
7346 (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes);
Tim Northover3b0846e2014-05-24 12:50:23 +00007347}
7348
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00007349int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
7350 const AddrMode &AM, Type *Ty,
Matt Arsenaultbd7d80a2015-06-01 05:31:59 +00007351 unsigned AS) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00007352 // Scaling factors are not free at all.
7353 // Operands | Rt Latency
7354 // -------------------------------------------
7355 // Rt, [Xn, Xm] | 4
7356 // -------------------------------------------
7357 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5
7358 // Rt, [Xn, Wm, <extend> #imm] |
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00007359 if (isLegalAddressingMode(DL, AM, Ty, AS))
Tim Northover3b0846e2014-05-24 12:50:23 +00007360 // Scale represents reg2 * scale, thus account for 1 if
7361 // it is not equal to 0 or 1.
7362 return AM.Scale != 0 && AM.Scale != 1;
7363 return -1;
7364}
7365
7366bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
7367 VT = VT.getScalarType();
7368
7369 if (!VT.isSimple())
7370 return false;
7371
7372 switch (VT.getSimpleVT().SimpleTy) {
7373 case MVT::f32:
7374 case MVT::f64:
7375 return true;
7376 default:
7377 break;
7378 }
7379
7380 return false;
7381}
7382
7383const MCPhysReg *
7384AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
7385 // LR is a callee-save register, but we must treat it as clobbered by any call
7386 // site. Hence we include LR in the scratch registers, which are in turn added
7387 // as implicit-defs for stackmaps and patchpoints.
7388 static const MCPhysReg ScratchRegs[] = {
7389 AArch64::X16, AArch64::X17, AArch64::LR, 0
7390 };
7391 return ScratchRegs;
7392}
7393
7394bool
7395AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N) const {
7396 EVT VT = N->getValueType(0);
7397 // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
7398 // it with shift to let it be lowered to UBFX.
7399 if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
7400 isa<ConstantSDNode>(N->getOperand(1))) {
7401 uint64_t TruncMask = N->getConstantOperandVal(1);
7402 if (isMask_64(TruncMask) &&
7403 N->getOperand(0).getOpcode() == ISD::SRL &&
7404 isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
7405 return false;
7406 }
7407 return true;
7408}
7409
7410bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
7411 Type *Ty) const {
7412 assert(Ty->isIntegerTy());
7413
7414 unsigned BitSize = Ty->getPrimitiveSizeInBits();
7415 if (BitSize == 0)
7416 return false;
7417
7418 int64_t Val = Imm.getSExtValue();
7419 if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
7420 return true;
7421
7422 if ((int64_t)Val < 0)
7423 Val = ~Val;
7424 if (BitSize == 32)
7425 Val &= (1LL << 32) - 1;
7426
7427 unsigned LZ = countLeadingZeros((uint64_t)Val);
7428 unsigned Shift = (63 - LZ) / 16;
7429 // MOVZ is free so return true for one or fewer MOVK.
David Blaikie186d2cb2015-03-24 16:24:01 +00007430 return Shift < 3;
Tim Northover3b0846e2014-05-24 12:50:23 +00007431}
7432
Sanjay Pateld6cb4ec2016-03-03 15:56:08 +00007433/// Turn vector tests of the signbit in the form of:
7434/// xor (sra X, elt_size(X)-1), -1
7435/// into:
7436/// cmge X, X, #0
7437static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
7438 const AArch64Subtarget *Subtarget) {
7439 EVT VT = N->getValueType(0);
7440 if (!Subtarget->hasNEON() || !VT.isVector())
7441 return SDValue();
7442
7443 // There must be a shift right algebraic before the xor, and the xor must be a
7444 // 'not' operation.
7445 SDValue Shift = N->getOperand(0);
7446 SDValue Ones = N->getOperand(1);
7447 if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() ||
7448 !ISD::isBuildVectorAllOnes(Ones.getNode()))
7449 return SDValue();
7450
7451 // The shift should be smearing the sign bit across each vector element.
7452 auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
7453 EVT ShiftEltTy = Shift.getValueType().getVectorElementType();
7454 if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1)
7455 return SDValue();
7456
7457 return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0));
7458}
7459
Tim Northover3b0846e2014-05-24 12:50:23 +00007460// Generate SUBS and CSEL for integer abs.
7461static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
7462 EVT VT = N->getValueType(0);
7463
7464 SDValue N0 = N->getOperand(0);
7465 SDValue N1 = N->getOperand(1);
7466 SDLoc DL(N);
7467
7468 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
7469 // and change it to SUB and CSEL.
7470 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
7471 N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
7472 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
7473 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
7474 if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007475 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
Tim Northover3b0846e2014-05-24 12:50:23 +00007476 N0.getOperand(0));
7477 // Generate SUBS & CSEL.
7478 SDValue Cmp =
7479 DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007480 N0.getOperand(0), DAG.getConstant(0, DL, VT));
Tim Northover3b0846e2014-05-24 12:50:23 +00007481 return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007482 DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00007483 SDValue(Cmp.getNode(), 1));
7484 }
7485 return SDValue();
7486}
7487
Tim Northover3b0846e2014-05-24 12:50:23 +00007488static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
7489 TargetLowering::DAGCombinerInfo &DCI,
7490 const AArch64Subtarget *Subtarget) {
7491 if (DCI.isBeforeLegalizeOps())
7492 return SDValue();
7493
Sanjay Pateld6cb4ec2016-03-03 15:56:08 +00007494 if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget))
7495 return Cmp;
7496
Tim Northover3b0846e2014-05-24 12:50:23 +00007497 return performIntegerAbsCombine(N, DAG);
7498}
7499
Chad Rosier17020f92014-07-23 14:57:52 +00007500SDValue
7501AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
7502 SelectionDAG &DAG,
7503 std::vector<SDNode *> *Created) const {
Haicheng Wu6a6bc752016-03-28 18:17:07 +00007504 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
7505 if (isIntDivCheap(N->getValueType(0), Attr))
7506 return SDValue(N,0); // Lower SDIV as SDIV
7507
Chad Rosier17020f92014-07-23 14:57:52 +00007508 // fold (sdiv X, pow2)
7509 EVT VT = N->getValueType(0);
7510 if ((VT != MVT::i32 && VT != MVT::i64) ||
7511 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
7512 return SDValue();
7513
7514 SDLoc DL(N);
7515 SDValue N0 = N->getOperand(0);
7516 unsigned Lg2 = Divisor.countTrailingZeros();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007517 SDValue Zero = DAG.getConstant(0, DL, VT);
7518 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
Chad Rosier17020f92014-07-23 14:57:52 +00007519
7520 // Add (N0 < 0) ? Pow2 - 1 : 0;
7521 SDValue CCVal;
7522 SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
7523 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
7524 SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
7525
7526 if (Created) {
7527 Created->push_back(Cmp.getNode());
7528 Created->push_back(Add.getNode());
7529 Created->push_back(CSel.getNode());
7530 }
7531
7532 // Divide by pow2.
7533 SDValue SRA =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007534 DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
Chad Rosier17020f92014-07-23 14:57:52 +00007535
7536 // If we're dividing by a positive value, we're done. Otherwise, we must
7537 // negate the result.
7538 if (Divisor.isNonNegative())
7539 return SRA;
7540
7541 if (Created)
7542 Created->push_back(SRA.getNode());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007543 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
Chad Rosier17020f92014-07-23 14:57:52 +00007544}
7545
Tim Northover3b0846e2014-05-24 12:50:23 +00007546static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
7547 TargetLowering::DAGCombinerInfo &DCI,
7548 const AArch64Subtarget *Subtarget) {
7549 if (DCI.isBeforeLegalizeOps())
7550 return SDValue();
7551
7552 // Multiplication of a power of two plus/minus one can be done more
7553 // cheaply as as shift+add/sub. For now, this is true unilaterally. If
7554 // future CPUs have a cheaper MADD instruction, this may need to be
7555 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
7556 // 64-bit is 5 cycles, so this is always a win.
7557 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
Benjamin Kramer46e38f32016-06-08 10:01:20 +00007558 const APInt &Value = C->getAPIntValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00007559 EVT VT = N->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007560 SDLoc DL(N);
Chad Rosiere6b87612014-06-30 14:51:14 +00007561 if (Value.isNonNegative()) {
7562 // (mul x, 2^N + 1) => (add (shl x, N), x)
7563 APInt VM1 = Value - 1;
7564 if (VM1.isPowerOf2()) {
7565 SDValue ShiftedVal =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007566 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7567 DAG.getConstant(VM1.logBase2(), DL, MVT::i64));
7568 return DAG.getNode(ISD::ADD, DL, VT, ShiftedVal,
Chad Rosiere6b87612014-06-30 14:51:14 +00007569 N->getOperand(0));
7570 }
7571 // (mul x, 2^N - 1) => (sub (shl x, N), x)
7572 APInt VP1 = Value + 1;
7573 if (VP1.isPowerOf2()) {
7574 SDValue ShiftedVal =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007575 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7576 DAG.getConstant(VP1.logBase2(), DL, MVT::i64));
7577 return DAG.getNode(ISD::SUB, DL, VT, ShiftedVal,
Chad Rosiere6b87612014-06-30 14:51:14 +00007578 N->getOperand(0));
7579 }
7580 } else {
Chad Rosier8e38f302015-03-03 17:31:01 +00007581 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7582 APInt VNP1 = -Value + 1;
7583 if (VNP1.isPowerOf2()) {
7584 SDValue ShiftedVal =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007585 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7586 DAG.getConstant(VNP1.logBase2(), DL, MVT::i64));
7587 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0),
Chad Rosier8e38f302015-03-03 17:31:01 +00007588 ShiftedVal);
7589 }
Chad Rosiere6b87612014-06-30 14:51:14 +00007590 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7591 APInt VNM1 = -Value - 1;
7592 if (VNM1.isPowerOf2()) {
7593 SDValue ShiftedVal =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007594 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7595 DAG.getConstant(VNM1.logBase2(), DL, MVT::i64));
Chad Rosiere6b87612014-06-30 14:51:14 +00007596 SDValue Add =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007597 DAG.getNode(ISD::ADD, DL, VT, ShiftedVal, N->getOperand(0));
7598 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Add);
Chad Rosiere6b87612014-06-30 14:51:14 +00007599 }
Chad Rosierd96e9f12014-06-09 01:25:51 +00007600 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007601 }
7602 return SDValue();
7603}
7604
Jim Grosbachf7502c42014-07-18 00:40:52 +00007605static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
7606 SelectionDAG &DAG) {
7607 // Take advantage of vector comparisons producing 0 or -1 in each lane to
7608 // optimize away operation when it's from a constant.
7609 //
7610 // The general transformation is:
7611 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
7612 // AND(VECTOR_CMP(x,y), constant2)
7613 // constant2 = UNARYOP(constant)
7614
Jim Grosbach8f6f0852014-07-23 20:41:38 +00007615 // Early exit if this isn't a vector operation, the operand of the
7616 // unary operation isn't a bitwise AND, or if the sizes of the operations
7617 // aren't the same.
Jim Grosbachf7502c42014-07-18 00:40:52 +00007618 EVT VT = N->getValueType(0);
7619 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
Jim Grosbach8f6f0852014-07-23 20:41:38 +00007620 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
7621 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
Jim Grosbachf7502c42014-07-18 00:40:52 +00007622 return SDValue();
7623
Jim Grosbach724e4382014-07-23 20:41:43 +00007624 // Now check that the other operand of the AND is a constant. We could
Jim Grosbachf7502c42014-07-18 00:40:52 +00007625 // make the transformation for non-constant splats as well, but it's unclear
7626 // that would be a benefit as it would not eliminate any operations, just
7627 // perform one more step in scalar code before moving to the vector unit.
7628 if (BuildVectorSDNode *BV =
7629 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
Jim Grosbach724e4382014-07-23 20:41:43 +00007630 // Bail out if the vector isn't a constant.
7631 if (!BV->isConstant())
Jim Grosbachf7502c42014-07-18 00:40:52 +00007632 return SDValue();
7633
7634 // Everything checks out. Build up the new and improved node.
7635 SDLoc DL(N);
7636 EVT IntVT = BV->getValueType(0);
7637 // Create a new constant of the appropriate type for the transformed
7638 // DAG.
7639 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
7640 // The AND node needs bitcasts to/from an integer vector type around it.
7641 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
7642 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
7643 N->getOperand(0)->getOperand(0), MaskConst);
7644 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
7645 return Res;
7646 }
7647
7648 return SDValue();
7649}
7650
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00007651static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
7652 const AArch64Subtarget *Subtarget) {
Jim Grosbachf7502c42014-07-18 00:40:52 +00007653 // First try to optimize away the conversion when it's conditionally from
7654 // a constant. Vectors only.
Ahmed Bougacha239d6352015-08-04 00:48:02 +00007655 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
Jim Grosbachf7502c42014-07-18 00:40:52 +00007656 return Res;
7657
Tim Northover3b0846e2014-05-24 12:50:23 +00007658 EVT VT = N->getValueType(0);
7659 if (VT != MVT::f32 && VT != MVT::f64)
7660 return SDValue();
Jim Grosbachf7502c42014-07-18 00:40:52 +00007661
Tim Northover3b0846e2014-05-24 12:50:23 +00007662 // Only optimize when the source and destination types have the same width.
7663 if (VT.getSizeInBits() != N->getOperand(0).getValueType().getSizeInBits())
7664 return SDValue();
7665
7666 // If the result of an integer load is only used by an integer-to-float
7667 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
Chad Rosier1f385612015-10-02 16:42:59 +00007668 // This eliminates an "integer-to-vector-move" UOP and improves throughput.
Tim Northover3b0846e2014-05-24 12:50:23 +00007669 SDValue N0 = N->getOperand(0);
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00007670 if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Tim Northover3b0846e2014-05-24 12:50:23 +00007671 // Do not change the width of a volatile load.
7672 !cast<LoadSDNode>(N0)->isVolatile()) {
7673 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7674 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
Justin Lebar9c375812016-07-15 18:27:10 +00007675 LN0->getPointerInfo(), LN0->getAlignment(),
7676 LN0->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +00007677
7678 // Make sure successors of the original load stay after it by updating them
7679 // to use the new Chain.
7680 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
7681
7682 unsigned Opcode =
7683 (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
7684 return DAG.getNode(Opcode, SDLoc(N), VT, Load);
7685 }
7686
7687 return SDValue();
7688}
7689
Chad Rosierfa30c9b2015-10-07 17:39:18 +00007690/// Fold a floating-point multiply by power of two into floating-point to
7691/// fixed-point conversion.
7692static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
Silviu Barangafa00ba32016-08-08 13:13:57 +00007693 TargetLowering::DAGCombinerInfo &DCI,
Chad Rosierfa30c9b2015-10-07 17:39:18 +00007694 const AArch64Subtarget *Subtarget) {
7695 if (!Subtarget->hasNEON())
7696 return SDValue();
7697
7698 SDValue Op = N->getOperand(0);
Tim Northover6092de52016-03-10 23:02:21 +00007699 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
7700 Op.getOpcode() != ISD::FMUL)
Chad Rosierfa30c9b2015-10-07 17:39:18 +00007701 return SDValue();
7702
7703 SDValue ConstVec = Op->getOperand(1);
7704 if (!isa<BuildVectorSDNode>(ConstVec))
7705 return SDValue();
7706
7707 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
7708 uint32_t FloatBits = FloatTy.getSizeInBits();
7709 if (FloatBits != 32 && FloatBits != 64)
7710 return SDValue();
7711
7712 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
7713 uint32_t IntBits = IntTy.getSizeInBits();
7714 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
7715 return SDValue();
7716
7717 // Avoid conversions where iN is larger than the float (e.g., float -> i64).
7718 if (IntBits > FloatBits)
7719 return SDValue();
7720
7721 BitVector UndefElements;
7722 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
7723 int32_t Bits = IntBits == 64 ? 64 : 32;
7724 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
7725 if (C == -1 || C == 0 || C > Bits)
7726 return SDValue();
7727
7728 MVT ResTy;
7729 unsigned NumLanes = Op.getValueType().getVectorNumElements();
7730 switch (NumLanes) {
7731 default:
7732 return SDValue();
7733 case 2:
7734 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
7735 break;
7736 case 4:
Silviu Barangafa00ba32016-08-08 13:13:57 +00007737 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
Chad Rosierfa30c9b2015-10-07 17:39:18 +00007738 break;
7739 }
7740
Silviu Barangafa00ba32016-08-08 13:13:57 +00007741 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
7742 return SDValue();
7743
7744 assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) &&
7745 "Illegal vector type after legalization");
7746
Chad Rosierfa30c9b2015-10-07 17:39:18 +00007747 SDLoc DL(N);
7748 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
7749 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
7750 : Intrinsic::aarch64_neon_vcvtfp2fxu;
7751 SDValue FixConv =
7752 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
7753 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
7754 Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
7755 // We can handle smaller integers by generating an extra trunc.
7756 if (IntBits < FloatBits)
7757 FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
7758
7759 return FixConv;
7760}
7761
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00007762/// Fold a floating-point divide by power of two into fixed-point to
7763/// floating-point conversion.
7764static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
7765 const AArch64Subtarget *Subtarget) {
7766 if (!Subtarget->hasNEON())
7767 return SDValue();
7768
7769 SDValue Op = N->getOperand(0);
7770 unsigned Opc = Op->getOpcode();
7771 if (!Op.getValueType().isVector() ||
7772 (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
7773 return SDValue();
7774
7775 SDValue ConstVec = N->getOperand(1);
7776 if (!isa<BuildVectorSDNode>(ConstVec))
7777 return SDValue();
7778
7779 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
7780 int32_t IntBits = IntTy.getSizeInBits();
7781 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
7782 return SDValue();
7783
7784 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
7785 int32_t FloatBits = FloatTy.getSizeInBits();
7786 if (FloatBits != 32 && FloatBits != 64)
7787 return SDValue();
7788
7789 // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
7790 if (IntBits > FloatBits)
7791 return SDValue();
7792
7793 BitVector UndefElements;
7794 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
7795 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
7796 if (C == -1 || C == 0 || C > FloatBits)
7797 return SDValue();
7798
7799 MVT ResTy;
7800 unsigned NumLanes = Op.getValueType().getVectorNumElements();
7801 switch (NumLanes) {
7802 default:
7803 return SDValue();
7804 case 2:
7805 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
7806 break;
7807 case 4:
7808 ResTy = MVT::v4i32;
7809 break;
7810 }
7811
7812 SDLoc DL(N);
7813 SDValue ConvInput = Op.getOperand(0);
7814 bool IsSigned = Opc == ISD::SINT_TO_FP;
7815 if (IntBits < FloatBits)
7816 ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
7817 ResTy, ConvInput);
7818
7819 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
7820 : Intrinsic::aarch64_neon_vcvtfxu2fp;
7821 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
7822 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
7823 DAG.getConstant(C, DL, MVT::i32));
7824}
7825
Tim Northover3b0846e2014-05-24 12:50:23 +00007826/// An EXTR instruction is made up of two shifts, ORed together. This helper
7827/// searches for and classifies those shifts.
7828static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
7829 bool &FromHi) {
7830 if (N.getOpcode() == ISD::SHL)
7831 FromHi = false;
7832 else if (N.getOpcode() == ISD::SRL)
7833 FromHi = true;
7834 else
7835 return false;
7836
7837 if (!isa<ConstantSDNode>(N.getOperand(1)))
7838 return false;
7839
7840 ShiftAmount = N->getConstantOperandVal(1);
7841 Src = N->getOperand(0);
7842 return true;
7843}
7844
7845/// EXTR instruction extracts a contiguous chunk of bits from two existing
7846/// registers viewed as a high/low pair. This function looks for the pattern:
7847/// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an
7848/// EXTR. Can't quite be done in TableGen because the two immediates aren't
7849/// independent.
7850static SDValue tryCombineToEXTR(SDNode *N,
7851 TargetLowering::DAGCombinerInfo &DCI) {
7852 SelectionDAG &DAG = DCI.DAG;
7853 SDLoc DL(N);
7854 EVT VT = N->getValueType(0);
7855
7856 assert(N->getOpcode() == ISD::OR && "Unexpected root");
7857
7858 if (VT != MVT::i32 && VT != MVT::i64)
7859 return SDValue();
7860
7861 SDValue LHS;
7862 uint32_t ShiftLHS = 0;
7863 bool LHSFromHi = 0;
7864 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
7865 return SDValue();
7866
7867 SDValue RHS;
7868 uint32_t ShiftRHS = 0;
7869 bool RHSFromHi = 0;
7870 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
7871 return SDValue();
7872
7873 // If they're both trying to come from the high part of the register, they're
7874 // not really an EXTR.
7875 if (LHSFromHi == RHSFromHi)
7876 return SDValue();
7877
7878 if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
7879 return SDValue();
7880
7881 if (LHSFromHi) {
7882 std::swap(LHS, RHS);
7883 std::swap(ShiftLHS, ShiftRHS);
7884 }
7885
7886 return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007887 DAG.getConstant(ShiftRHS, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00007888}
7889
7890static SDValue tryCombineToBSL(SDNode *N,
7891 TargetLowering::DAGCombinerInfo &DCI) {
7892 EVT VT = N->getValueType(0);
7893 SelectionDAG &DAG = DCI.DAG;
7894 SDLoc DL(N);
7895
7896 if (!VT.isVector())
7897 return SDValue();
7898
7899 SDValue N0 = N->getOperand(0);
7900 if (N0.getOpcode() != ISD::AND)
7901 return SDValue();
7902
7903 SDValue N1 = N->getOperand(1);
7904 if (N1.getOpcode() != ISD::AND)
7905 return SDValue();
7906
7907 // We only have to look for constant vectors here since the general, variable
7908 // case can be handled in TableGen.
7909 unsigned Bits = VT.getVectorElementType().getSizeInBits();
7910 uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
7911 for (int i = 1; i >= 0; --i)
7912 for (int j = 1; j >= 0; --j) {
7913 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
7914 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
7915 if (!BVN0 || !BVN1)
7916 continue;
7917
7918 bool FoundMatch = true;
7919 for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
7920 ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
7921 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
7922 if (!CN0 || !CN1 ||
7923 CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
7924 FoundMatch = false;
7925 break;
7926 }
7927 }
7928
7929 if (FoundMatch)
7930 return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
7931 N0->getOperand(1 - i), N1->getOperand(1 - j));
7932 }
7933
7934 return SDValue();
7935}
7936
7937static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
7938 const AArch64Subtarget *Subtarget) {
7939 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
Tim Northover3b0846e2014-05-24 12:50:23 +00007940 SelectionDAG &DAG = DCI.DAG;
7941 EVT VT = N->getValueType(0);
7942
7943 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7944 return SDValue();
7945
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00007946 if (SDValue Res = tryCombineToEXTR(N, DCI))
Tim Northover3b0846e2014-05-24 12:50:23 +00007947 return Res;
7948
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00007949 if (SDValue Res = tryCombineToBSL(N, DCI))
Tim Northover3b0846e2014-05-24 12:50:23 +00007950 return Res;
7951
7952 return SDValue();
7953}
7954
Chad Rosier14aa2ad2016-05-26 19:41:33 +00007955static SDValue performSRLCombine(SDNode *N,
7956 TargetLowering::DAGCombinerInfo &DCI) {
7957 SelectionDAG &DAG = DCI.DAG;
7958 EVT VT = N->getValueType(0);
7959 if (VT != MVT::i32 && VT != MVT::i64)
7960 return SDValue();
7961
7962 // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the
7963 // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32)
7964 // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero.
7965 SDValue N0 = N->getOperand(0);
7966 if (N0.getOpcode() == ISD::BSWAP) {
7967 SDLoc DL(N);
7968 SDValue N1 = N->getOperand(1);
7969 SDValue N00 = N0.getOperand(0);
7970 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
7971 uint64_t ShiftAmt = C->getZExtValue();
7972 if (VT == MVT::i32 && ShiftAmt == 16 &&
7973 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16)))
7974 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
7975 if (VT == MVT::i64 && ShiftAmt == 32 &&
7976 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32)))
7977 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
7978 }
7979 }
7980 return SDValue();
7981}
7982
Tim Northover3b0846e2014-05-24 12:50:23 +00007983static SDValue performBitcastCombine(SDNode *N,
7984 TargetLowering::DAGCombinerInfo &DCI,
7985 SelectionDAG &DAG) {
7986 // Wait 'til after everything is legalized to try this. That way we have
7987 // legal vector types and such.
7988 if (DCI.isBeforeLegalizeOps())
7989 return SDValue();
7990
7991 // Remove extraneous bitcasts around an extract_subvector.
7992 // For example,
7993 // (v4i16 (bitconvert
7994 // (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
7995 // becomes
7996 // (extract_subvector ((v8i16 ...), (i64 4)))
7997
7998 // Only interested in 64-bit vectors as the ultimate result.
7999 EVT VT = N->getValueType(0);
8000 if (!VT.isVector())
8001 return SDValue();
8002 if (VT.getSimpleVT().getSizeInBits() != 64)
8003 return SDValue();
8004 // Is the operand an extract_subvector starting at the beginning or halfway
8005 // point of the vector? A low half may also come through as an
8006 // EXTRACT_SUBREG, so look for that, too.
8007 SDValue Op0 = N->getOperand(0);
8008 if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
8009 !(Op0->isMachineOpcode() &&
8010 Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
8011 return SDValue();
8012 uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
8013 if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
8014 if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
8015 return SDValue();
8016 } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
8017 if (idx != AArch64::dsub)
8018 return SDValue();
8019 // The dsub reference is equivalent to a lane zero subvector reference.
8020 idx = 0;
8021 }
8022 // Look through the bitcast of the input to the extract.
8023 if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
8024 return SDValue();
8025 SDValue Source = Op0->getOperand(0)->getOperand(0);
8026 // If the source type has twice the number of elements as our destination
8027 // type, we know this is an extract of the high or low half of the vector.
8028 EVT SVT = Source->getValueType(0);
8029 if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
8030 return SDValue();
8031
8032 DEBUG(dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
8033
8034 // Create the simplified form to just extract the low or high half of the
8035 // vector directly rather than bothering with the bitcasts.
8036 SDLoc dl(N);
8037 unsigned NumElements = VT.getVectorNumElements();
8038 if (idx) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008039 SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00008040 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
8041 } else {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008042 SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00008043 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
8044 Source, SubReg),
8045 0);
8046 }
8047}
8048
8049static SDValue performConcatVectorsCombine(SDNode *N,
8050 TargetLowering::DAGCombinerInfo &DCI,
8051 SelectionDAG &DAG) {
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00008052 SDLoc dl(N);
8053 EVT VT = N->getValueType(0);
8054 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
8055
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00008056 // Optimize concat_vectors of truncated vectors, where the intermediate
8057 // type is illegal, to avoid said illegality, e.g.,
8058 // (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
8059 // (v2i16 (truncate (v2i64)))))
8060 // ->
Ahmed Bougachae6bb09a2015-03-21 01:08:39 +00008061 // (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
8062 // (v4i32 (bitcast (v2i64))),
8063 // <0, 2, 4, 6>)))
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00008064 // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
8065 // on both input and result type, so we might generate worse code.
8066 // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
8067 if (N->getNumOperands() == 2 &&
8068 N0->getOpcode() == ISD::TRUNCATE &&
8069 N1->getOpcode() == ISD::TRUNCATE) {
8070 SDValue N00 = N0->getOperand(0);
8071 SDValue N10 = N1->getOperand(0);
8072 EVT N00VT = N00.getValueType();
8073
8074 if (N00VT == N10.getValueType() &&
8075 (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
8076 N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
Ahmed Bougachae6bb09a2015-03-21 01:08:39 +00008077 MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
8078 SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
8079 for (size_t i = 0; i < Mask.size(); ++i)
8080 Mask[i] = i * 2;
8081 return DAG.getNode(ISD::TRUNCATE, dl, VT,
8082 DAG.getVectorShuffle(
8083 MidVT, dl,
8084 DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
8085 DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00008086 }
8087 }
8088
Tim Northover3b0846e2014-05-24 12:50:23 +00008089 // Wait 'til after everything is legalized to try this. That way we have
8090 // legal vector types and such.
8091 if (DCI.isBeforeLegalizeOps())
8092 return SDValue();
8093
Tim Northover3b0846e2014-05-24 12:50:23 +00008094 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
8095 // splat. The indexed instructions are going to be expecting a DUPLANE64, so
8096 // canonicalise to that.
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00008097 if (N0 == N1 && VT.getVectorNumElements() == 2) {
Tim Northover3b0846e2014-05-24 12:50:23 +00008098 assert(VT.getVectorElementType().getSizeInBits() == 64);
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00008099 return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008100 DAG.getConstant(0, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008101 }
8102
8103 // Canonicalise concat_vectors so that the right-hand vector has as few
8104 // bit-casts as possible before its real operation. The primary matching
8105 // destination for these operations will be the narrowing "2" instructions,
8106 // which depend on the operation being performed on this right-hand vector.
8107 // For example,
8108 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS))))
8109 // becomes
8110 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
8111
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00008112 if (N1->getOpcode() != ISD::BITCAST)
Tim Northover3b0846e2014-05-24 12:50:23 +00008113 return SDValue();
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00008114 SDValue RHS = N1->getOperand(0);
Tim Northover3b0846e2014-05-24 12:50:23 +00008115 MVT RHSTy = RHS.getValueType().getSimpleVT();
8116 // If the RHS is not a vector, this is not the pattern we're looking for.
8117 if (!RHSTy.isVector())
8118 return SDValue();
8119
8120 DEBUG(dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
8121
8122 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
8123 RHSTy.getVectorNumElements() * 2);
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00008124 return DAG.getNode(ISD::BITCAST, dl, VT,
8125 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
8126 DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
8127 RHS));
Tim Northover3b0846e2014-05-24 12:50:23 +00008128}
8129
8130static SDValue tryCombineFixedPointConvert(SDNode *N,
8131 TargetLowering::DAGCombinerInfo &DCI,
8132 SelectionDAG &DAG) {
8133 // Wait 'til after everything is legalized to try this. That way we have
8134 // legal vector types and such.
8135 if (DCI.isBeforeLegalizeOps())
8136 return SDValue();
8137 // Transform a scalar conversion of a value from a lane extract into a
8138 // lane extract of a vector conversion. E.g., from foo1 to foo2:
8139 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
8140 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
8141 //
8142 // The second form interacts better with instruction selection and the
8143 // register allocator to avoid cross-class register copies that aren't
8144 // coalescable due to a lane reference.
8145
8146 // Check the operand and see if it originates from a lane extract.
8147 SDValue Op1 = N->getOperand(1);
8148 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8149 // Yep, no additional predication needed. Perform the transform.
8150 SDValue IID = N->getOperand(0);
8151 SDValue Shift = N->getOperand(2);
8152 SDValue Vec = Op1.getOperand(0);
8153 SDValue Lane = Op1.getOperand(1);
8154 EVT ResTy = N->getValueType(0);
8155 EVT VecResTy;
8156 SDLoc DL(N);
8157
8158 // The vector width should be 128 bits by the time we get here, even
8159 // if it started as 64 bits (the extract_vector handling will have
8160 // done so).
8161 assert(Vec.getValueType().getSizeInBits() == 128 &&
8162 "unexpected vector size on extract_vector_elt!");
8163 if (Vec.getValueType() == MVT::v4i32)
8164 VecResTy = MVT::v4f32;
8165 else if (Vec.getValueType() == MVT::v2i64)
8166 VecResTy = MVT::v2f64;
8167 else
Craig Topper2a30d782014-06-18 05:05:13 +00008168 llvm_unreachable("unexpected vector type!");
Tim Northover3b0846e2014-05-24 12:50:23 +00008169
8170 SDValue Convert =
8171 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
8172 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
8173 }
8174 return SDValue();
8175}
8176
8177// AArch64 high-vector "long" operations are formed by performing the non-high
8178// version on an extract_subvector of each operand which gets the high half:
8179//
8180// (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
8181//
8182// However, there are cases which don't have an extract_high explicitly, but
8183// have another operation that can be made compatible with one for free. For
8184// example:
8185//
8186// (dupv64 scalar) --> (extract_high (dup128 scalar))
8187//
8188// This routine does the actual conversion of such DUPs, once outer routines
8189// have determined that everything else is in order.
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008190// It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
8191// similarly here.
Tim Northover3b0846e2014-05-24 12:50:23 +00008192static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00008193 switch (N.getOpcode()) {
8194 case AArch64ISD::DUP:
Tim Northover3b0846e2014-05-24 12:50:23 +00008195 case AArch64ISD::DUPLANE8:
8196 case AArch64ISD::DUPLANE16:
8197 case AArch64ISD::DUPLANE32:
8198 case AArch64ISD::DUPLANE64:
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008199 case AArch64ISD::MOVI:
8200 case AArch64ISD::MOVIshift:
8201 case AArch64ISD::MOVIedit:
8202 case AArch64ISD::MOVImsl:
8203 case AArch64ISD::MVNIshift:
8204 case AArch64ISD::MVNImsl:
Tim Northover3b0846e2014-05-24 12:50:23 +00008205 break;
8206 default:
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008207 // FMOV could be supported, but isn't very useful, as it would only occur
8208 // if you passed a bitcast' floating point immediate to an eligible long
8209 // integer op (addl, smull, ...).
Tim Northover3b0846e2014-05-24 12:50:23 +00008210 return SDValue();
8211 }
8212
8213 MVT NarrowTy = N.getSimpleValueType();
8214 if (!NarrowTy.is64BitVector())
8215 return SDValue();
8216
8217 MVT ElementTy = NarrowTy.getVectorElementType();
8218 unsigned NumElems = NarrowTy.getVectorNumElements();
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008219 MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
Tim Northover3b0846e2014-05-24 12:50:23 +00008220
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008221 SDLoc dl(N);
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008222 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
8223 DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008224 DAG.getConstant(NumElems, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008225}
8226
8227static bool isEssentiallyExtractSubvector(SDValue N) {
8228 if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
8229 return true;
8230
8231 return N.getOpcode() == ISD::BITCAST &&
8232 N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
8233}
8234
8235/// \brief Helper structure to keep track of ISD::SET_CC operands.
8236struct GenericSetCCInfo {
8237 const SDValue *Opnd0;
8238 const SDValue *Opnd1;
8239 ISD::CondCode CC;
8240};
8241
8242/// \brief Helper structure to keep track of a SET_CC lowered into AArch64 code.
8243struct AArch64SetCCInfo {
8244 const SDValue *Cmp;
8245 AArch64CC::CondCode CC;
8246};
8247
8248/// \brief Helper structure to keep track of SetCC information.
8249union SetCCInfo {
8250 GenericSetCCInfo Generic;
8251 AArch64SetCCInfo AArch64;
8252};
8253
8254/// \brief Helper structure to be able to read SetCC information. If set to
8255/// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
8256/// GenericSetCCInfo.
8257struct SetCCInfoAndKind {
8258 SetCCInfo Info;
8259 bool IsAArch64;
8260};
8261
8262/// \brief Check whether or not \p Op is a SET_CC operation, either a generic or
8263/// an
8264/// AArch64 lowered one.
8265/// \p SetCCInfo is filled accordingly.
8266/// \post SetCCInfo is meanginfull only when this function returns true.
8267/// \return True when Op is a kind of SET_CC operation.
8268static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
8269 // If this is a setcc, this is straight forward.
8270 if (Op.getOpcode() == ISD::SETCC) {
8271 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
8272 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
8273 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8274 SetCCInfo.IsAArch64 = false;
8275 return true;
8276 }
8277 // Otherwise, check if this is a matching csel instruction.
8278 // In other words:
8279 // - csel 1, 0, cc
8280 // - csel 0, 1, !cc
8281 if (Op.getOpcode() != AArch64ISD::CSEL)
8282 return false;
8283 // Set the information about the operands.
8284 // TODO: we want the operands of the Cmp not the csel
8285 SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
8286 SetCCInfo.IsAArch64 = true;
8287 SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
8288 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
8289
8290 // Check that the operands matches the constraints:
8291 // (1) Both operands must be constants.
8292 // (2) One must be 1 and the other must be 0.
8293 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
8294 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8295
8296 // Check (1).
8297 if (!TValue || !FValue)
8298 return false;
8299
8300 // Check (2).
8301 if (!TValue->isOne()) {
8302 // Update the comparison when we are interested in !cc.
8303 std::swap(TValue, FValue);
8304 SetCCInfo.Info.AArch64.CC =
8305 AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
8306 }
8307 return TValue->isOne() && FValue->isNullValue();
8308}
8309
8310// Returns true if Op is setcc or zext of setcc.
8311static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
8312 if (isSetCC(Op, Info))
8313 return true;
8314 return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
8315 isSetCC(Op->getOperand(0), Info));
8316}
8317
8318// The folding we want to perform is:
8319// (add x, [zext] (setcc cc ...) )
8320// -->
8321// (csel x, (add x, 1), !cc ...)
8322//
8323// The latter will get matched to a CSINC instruction.
8324static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
8325 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
8326 SDValue LHS = Op->getOperand(0);
8327 SDValue RHS = Op->getOperand(1);
8328 SetCCInfoAndKind InfoAndKind;
8329
8330 // If neither operand is a SET_CC, give up.
8331 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
8332 std::swap(LHS, RHS);
8333 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
8334 return SDValue();
8335 }
8336
8337 // FIXME: This could be generatized to work for FP comparisons.
8338 EVT CmpVT = InfoAndKind.IsAArch64
8339 ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
8340 : InfoAndKind.Info.Generic.Opnd0->getValueType();
8341 if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
8342 return SDValue();
8343
8344 SDValue CCVal;
8345 SDValue Cmp;
8346 SDLoc dl(Op);
8347 if (InfoAndKind.IsAArch64) {
8348 CCVal = DAG.getConstant(
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008349 AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
8350 MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00008351 Cmp = *InfoAndKind.Info.AArch64.Cmp;
8352 } else
8353 Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
8354 *InfoAndKind.Info.Generic.Opnd1,
8355 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
8356 CCVal, DAG, dl);
8357
8358 EVT VT = Op->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008359 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
Tim Northover3b0846e2014-05-24 12:50:23 +00008360 return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
8361}
8362
8363// The basic add/sub long vector instructions have variants with "2" on the end
8364// which act on the high-half of their inputs. They are normally matched by
8365// patterns like:
8366//
8367// (add (zeroext (extract_high LHS)),
8368// (zeroext (extract_high RHS)))
8369// -> uaddl2 vD, vN, vM
8370//
8371// However, if one of the extracts is something like a duplicate, this
8372// instruction can still be used profitably. This function puts the DAG into a
8373// more appropriate form for those patterns to trigger.
8374static SDValue performAddSubLongCombine(SDNode *N,
8375 TargetLowering::DAGCombinerInfo &DCI,
8376 SelectionDAG &DAG) {
8377 if (DCI.isBeforeLegalizeOps())
8378 return SDValue();
8379
8380 MVT VT = N->getSimpleValueType(0);
8381 if (!VT.is128BitVector()) {
8382 if (N->getOpcode() == ISD::ADD)
8383 return performSetccAddFolding(N, DAG);
8384 return SDValue();
8385 }
8386
8387 // Make sure both branches are extended in the same way.
8388 SDValue LHS = N->getOperand(0);
8389 SDValue RHS = N->getOperand(1);
8390 if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
8391 LHS.getOpcode() != ISD::SIGN_EXTEND) ||
8392 LHS.getOpcode() != RHS.getOpcode())
8393 return SDValue();
8394
8395 unsigned ExtType = LHS.getOpcode();
8396
8397 // It's not worth doing if at least one of the inputs isn't already an
8398 // extract, but we don't know which it'll be so we have to try both.
8399 if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
8400 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
8401 if (!RHS.getNode())
8402 return SDValue();
8403
8404 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
8405 } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
8406 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
8407 if (!LHS.getNode())
8408 return SDValue();
8409
8410 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
8411 }
8412
8413 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
8414}
8415
8416// Massage DAGs which we can use the high-half "long" operations on into
8417// something isel will recognize better. E.g.
8418//
8419// (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
8420// (aarch64_neon_umull (extract_high (v2i64 vec)))
8421// (extract_high (v2i64 (dup128 scalar)))))
8422//
Hal Finkelcd8664c2015-12-11 23:11:52 +00008423static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
Tim Northover3b0846e2014-05-24 12:50:23 +00008424 TargetLowering::DAGCombinerInfo &DCI,
8425 SelectionDAG &DAG) {
8426 if (DCI.isBeforeLegalizeOps())
8427 return SDValue();
8428
Hal Finkelcd8664c2015-12-11 23:11:52 +00008429 SDValue LHS = N->getOperand(1);
8430 SDValue RHS = N->getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00008431 assert(LHS.getValueType().is64BitVector() &&
8432 RHS.getValueType().is64BitVector() &&
8433 "unexpected shape for long operation");
8434
8435 // Either node could be a DUP, but it's not worth doing both of them (you'd
8436 // just as well use the non-high version) so look for a corresponding extract
8437 // operation on the other "wing".
8438 if (isEssentiallyExtractSubvector(LHS)) {
8439 RHS = tryExtendDUPToExtractHigh(RHS, DAG);
8440 if (!RHS.getNode())
8441 return SDValue();
8442 } else if (isEssentiallyExtractSubvector(RHS)) {
8443 LHS = tryExtendDUPToExtractHigh(LHS, DAG);
8444 if (!LHS.getNode())
8445 return SDValue();
8446 }
8447
Hal Finkelcd8664c2015-12-11 23:11:52 +00008448 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
8449 N->getOperand(0), LHS, RHS);
Tim Northover3b0846e2014-05-24 12:50:23 +00008450}
8451
8452static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
8453 MVT ElemTy = N->getSimpleValueType(0).getScalarType();
8454 unsigned ElemBits = ElemTy.getSizeInBits();
8455
8456 int64_t ShiftAmount;
8457 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
8458 APInt SplatValue, SplatUndef;
8459 unsigned SplatBitSize;
8460 bool HasAnyUndefs;
8461 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
8462 HasAnyUndefs, ElemBits) ||
8463 SplatBitSize != ElemBits)
8464 return SDValue();
8465
8466 ShiftAmount = SplatValue.getSExtValue();
8467 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
8468 ShiftAmount = CVN->getSExtValue();
8469 } else
8470 return SDValue();
8471
8472 unsigned Opcode;
8473 bool IsRightShift;
8474 switch (IID) {
8475 default:
8476 llvm_unreachable("Unknown shift intrinsic");
8477 case Intrinsic::aarch64_neon_sqshl:
8478 Opcode = AArch64ISD::SQSHL_I;
8479 IsRightShift = false;
8480 break;
8481 case Intrinsic::aarch64_neon_uqshl:
8482 Opcode = AArch64ISD::UQSHL_I;
8483 IsRightShift = false;
8484 break;
8485 case Intrinsic::aarch64_neon_srshl:
8486 Opcode = AArch64ISD::SRSHR_I;
8487 IsRightShift = true;
8488 break;
8489 case Intrinsic::aarch64_neon_urshl:
8490 Opcode = AArch64ISD::URSHR_I;
8491 IsRightShift = true;
8492 break;
8493 case Intrinsic::aarch64_neon_sqshlu:
8494 Opcode = AArch64ISD::SQSHLU_I;
8495 IsRightShift = false;
8496 break;
8497 }
8498
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008499 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
8500 SDLoc dl(N);
8501 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8502 DAG.getConstant(-ShiftAmount, dl, MVT::i32));
8503 } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
8504 SDLoc dl(N);
8505 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8506 DAG.getConstant(ShiftAmount, dl, MVT::i32));
8507 }
Tim Northover3b0846e2014-05-24 12:50:23 +00008508
8509 return SDValue();
8510}
8511
8512// The CRC32[BH] instructions ignore the high bits of their data operand. Since
8513// the intrinsics must be legal and take an i32, this means there's almost
8514// certainly going to be a zext in the DAG which we can eliminate.
8515static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
8516 SDValue AndN = N->getOperand(2);
8517 if (AndN.getOpcode() != ISD::AND)
8518 return SDValue();
8519
8520 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
8521 if (!CMask || CMask->getZExtValue() != Mask)
8522 return SDValue();
8523
8524 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
8525 N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
8526}
8527
Ahmed Bougachafab58922015-03-10 20:45:38 +00008528static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
8529 SelectionDAG &DAG) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008530 SDLoc dl(N);
8531 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
8532 DAG.getNode(Opc, dl,
Ahmed Bougachafab58922015-03-10 20:45:38 +00008533 N->getOperand(1).getSimpleValueType(),
8534 N->getOperand(1)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008535 DAG.getConstant(0, dl, MVT::i64));
Ahmed Bougachafab58922015-03-10 20:45:38 +00008536}
8537
Tim Northover3b0846e2014-05-24 12:50:23 +00008538static SDValue performIntrinsicCombine(SDNode *N,
8539 TargetLowering::DAGCombinerInfo &DCI,
8540 const AArch64Subtarget *Subtarget) {
8541 SelectionDAG &DAG = DCI.DAG;
8542 unsigned IID = getIntrinsicID(N);
8543 switch (IID) {
8544 default:
8545 break;
8546 case Intrinsic::aarch64_neon_vcvtfxs2fp:
8547 case Intrinsic::aarch64_neon_vcvtfxu2fp:
8548 return tryCombineFixedPointConvert(N, DCI, DAG);
Ahmed Bougachafab58922015-03-10 20:45:38 +00008549 case Intrinsic::aarch64_neon_saddv:
8550 return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
8551 case Intrinsic::aarch64_neon_uaddv:
8552 return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
8553 case Intrinsic::aarch64_neon_sminv:
8554 return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
8555 case Intrinsic::aarch64_neon_uminv:
8556 return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
8557 case Intrinsic::aarch64_neon_smaxv:
8558 return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
8559 case Intrinsic::aarch64_neon_umaxv:
8560 return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00008561 case Intrinsic::aarch64_neon_fmax:
James Molloyedf38f02015-08-11 12:06:33 +00008562 return DAG.getNode(ISD::FMAXNAN, SDLoc(N), N->getValueType(0),
Tim Northover3b0846e2014-05-24 12:50:23 +00008563 N->getOperand(1), N->getOperand(2));
8564 case Intrinsic::aarch64_neon_fmin:
James Molloyedf38f02015-08-11 12:06:33 +00008565 return DAG.getNode(ISD::FMINNAN, SDLoc(N), N->getValueType(0),
Tim Northover3b0846e2014-05-24 12:50:23 +00008566 N->getOperand(1), N->getOperand(2));
James Molloyb7b2a1e2015-08-11 12:06:37 +00008567 case Intrinsic::aarch64_neon_fmaxnm:
8568 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
8569 N->getOperand(1), N->getOperand(2));
8570 case Intrinsic::aarch64_neon_fminnm:
8571 return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
8572 N->getOperand(1), N->getOperand(2));
Tim Northover3b0846e2014-05-24 12:50:23 +00008573 case Intrinsic::aarch64_neon_smull:
8574 case Intrinsic::aarch64_neon_umull:
8575 case Intrinsic::aarch64_neon_pmull:
8576 case Intrinsic::aarch64_neon_sqdmull:
Hal Finkelcd8664c2015-12-11 23:11:52 +00008577 return tryCombineLongOpWithDup(IID, N, DCI, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00008578 case Intrinsic::aarch64_neon_sqshl:
8579 case Intrinsic::aarch64_neon_uqshl:
8580 case Intrinsic::aarch64_neon_sqshlu:
8581 case Intrinsic::aarch64_neon_srshl:
8582 case Intrinsic::aarch64_neon_urshl:
8583 return tryCombineShiftImm(IID, N, DAG);
8584 case Intrinsic::aarch64_crc32b:
8585 case Intrinsic::aarch64_crc32cb:
8586 return tryCombineCRC32(0xff, N, DAG);
8587 case Intrinsic::aarch64_crc32h:
8588 case Intrinsic::aarch64_crc32ch:
8589 return tryCombineCRC32(0xffff, N, DAG);
8590 }
8591 return SDValue();
8592}
8593
8594static SDValue performExtendCombine(SDNode *N,
8595 TargetLowering::DAGCombinerInfo &DCI,
8596 SelectionDAG &DAG) {
8597 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
8598 // we can convert that DUP into another extract_high (of a bigger DUP), which
8599 // helps the backend to decide that an sabdl2 would be useful, saving a real
8600 // extract_high operation.
8601 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
Hal Finkelcd8664c2015-12-11 23:11:52 +00008602 N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
Tim Northover3b0846e2014-05-24 12:50:23 +00008603 SDNode *ABDNode = N->getOperand(0).getNode();
Hal Finkelcd8664c2015-12-11 23:11:52 +00008604 unsigned IID = getIntrinsicID(ABDNode);
8605 if (IID == Intrinsic::aarch64_neon_sabd ||
8606 IID == Intrinsic::aarch64_neon_uabd) {
8607 SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
8608 if (!NewABD.getNode())
8609 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00008610
Hal Finkelcd8664c2015-12-11 23:11:52 +00008611 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
8612 NewABD);
8613 }
Tim Northover3b0846e2014-05-24 12:50:23 +00008614 }
8615
8616 // This is effectively a custom type legalization for AArch64.
8617 //
8618 // Type legalization will split an extend of a small, legal, type to a larger
8619 // illegal type by first splitting the destination type, often creating
8620 // illegal source types, which then get legalized in isel-confusing ways,
8621 // leading to really terrible codegen. E.g.,
8622 // %result = v8i32 sext v8i8 %value
8623 // becomes
8624 // %losrc = extract_subreg %value, ...
8625 // %hisrc = extract_subreg %value, ...
8626 // %lo = v4i32 sext v4i8 %losrc
8627 // %hi = v4i32 sext v4i8 %hisrc
8628 // Things go rapidly downhill from there.
8629 //
8630 // For AArch64, the [sz]ext vector instructions can only go up one element
8631 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
8632 // take two instructions.
8633 //
8634 // This implies that the most efficient way to do the extend from v8i8
8635 // to two v4i32 values is to first extend the v8i8 to v8i16, then do
8636 // the normal splitting to happen for the v8i16->v8i32.
8637
8638 // This is pre-legalization to catch some cases where the default
8639 // type legalization will create ill-tempered code.
8640 if (!DCI.isBeforeLegalizeOps())
8641 return SDValue();
8642
8643 // We're only interested in cleaning things up for non-legal vector types
8644 // here. If both the source and destination are legal, things will just
8645 // work naturally without any fiddling.
Matthew Simpson13dddb02015-12-17 21:29:47 +00008646 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00008647 EVT ResVT = N->getValueType(0);
8648 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
8649 return SDValue();
8650 // If the vector type isn't a simple VT, it's beyond the scope of what
8651 // we're worried about here. Let legalization do its thing and hope for
8652 // the best.
Jim Grosbachec2b0d02014-08-28 22:08:28 +00008653 SDValue Src = N->getOperand(0);
8654 EVT SrcVT = Src->getValueType(0);
8655 if (!ResVT.isSimple() || !SrcVT.isSimple())
Tim Northover3b0846e2014-05-24 12:50:23 +00008656 return SDValue();
8657
Tim Northover3b0846e2014-05-24 12:50:23 +00008658 // If the source VT is a 64-bit vector, we can play games and get the
8659 // better results we want.
8660 if (SrcVT.getSizeInBits() != 64)
8661 return SDValue();
8662
8663 unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits();
8664 unsigned ElementCount = SrcVT.getVectorNumElements();
8665 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
8666 SDLoc DL(N);
8667 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
8668
8669 // Now split the rest of the operation into two halves, each with a 64
8670 // bit source.
8671 EVT LoVT, HiVT;
8672 SDValue Lo, Hi;
8673 unsigned NumElements = ResVT.getVectorNumElements();
8674 assert(!(NumElements & 1) && "Splitting vector, but not in half!");
8675 LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
8676 ResVT.getVectorElementType(), NumElements / 2);
8677
8678 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
8679 LoVT.getVectorNumElements());
8680 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008681 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008682 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008683 DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008684 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
8685 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
8686
8687 // Now combine the parts back together so we still have a single result
8688 // like the combiner expects.
8689 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
8690}
8691
8692/// Replace a splat of a scalar to a vector store by scalar stores of the scalar
8693/// value. The load store optimizer pass will merge them to store pair stores.
8694/// This has better performance than a splat of the scalar followed by a split
8695/// vector store. Even if the stores are not merged it is four stores vs a dup,
8696/// followed by an ext.b and two stores.
8697static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode *St) {
8698 SDValue StVal = St->getValue();
8699 EVT VT = StVal.getValueType();
8700
8701 // Don't replace floating point stores, they possibly won't be transformed to
8702 // stp because of the store pair suppress pass.
8703 if (VT.isFloatingPoint())
8704 return SDValue();
8705
8706 // Check for insert vector elements.
8707 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
8708 return SDValue();
8709
8710 // We can express a splat as store pair(s) for 2 or 4 elements.
8711 unsigned NumVecElts = VT.getVectorNumElements();
8712 if (NumVecElts != 4 && NumVecElts != 2)
8713 return SDValue();
8714 SDValue SplatVal = StVal.getOperand(1);
8715 unsigned RemainInsertElts = NumVecElts - 1;
8716
8717 // Check that this is a splat.
8718 while (--RemainInsertElts) {
8719 SDValue NextInsertElt = StVal.getOperand(0);
8720 if (NextInsertElt.getOpcode() != ISD::INSERT_VECTOR_ELT)
8721 return SDValue();
8722 if (NextInsertElt.getOperand(1) != SplatVal)
8723 return SDValue();
8724 StVal = NextInsertElt;
8725 }
8726 unsigned OrigAlignment = St->getAlignment();
8727 unsigned EltOffset = NumVecElts == 4 ? 4 : 8;
8728 unsigned Alignment = std::min(OrigAlignment, EltOffset);
8729
8730 // Create scalar stores. This is at least as good as the code sequence for a
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00008731 // split unaligned store which is a dup.s, ext.b, and two stores.
Tim Northover3b0846e2014-05-24 12:50:23 +00008732 // Most of the time the three stores should be replaced by store pair
8733 // instructions (stp).
8734 SDLoc DL(St);
8735 SDValue BasePtr = St->getBasePtr();
8736 SDValue NewST1 =
8737 DAG.getStore(St->getChain(), DL, SplatVal, BasePtr, St->getPointerInfo(),
Justin Lebar9c375812016-07-15 18:27:10 +00008738 St->getAlignment(), St->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +00008739
8740 unsigned Offset = EltOffset;
8741 while (--NumVecElts) {
8742 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008743 DAG.getConstant(Offset, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008744 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
Justin Lebar9c375812016-07-15 18:27:10 +00008745 St->getPointerInfo(), Alignment,
8746 St->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +00008747 Offset += EltOffset;
8748 }
8749 return NewST1;
8750}
8751
Tim Northover339c83e2015-11-10 00:44:23 +00008752static SDValue split16BStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
8753 SelectionDAG &DAG,
8754 const AArch64Subtarget *Subtarget) {
Tim Northover3b0846e2014-05-24 12:50:23 +00008755 if (!DCI.isBeforeLegalize())
8756 return SDValue();
8757
8758 StoreSDNode *S = cast<StoreSDNode>(N);
8759 if (S->isVolatile())
8760 return SDValue();
8761
Sanjay Patelbbbf9a12015-09-25 21:49:48 +00008762 // FIXME: The logic for deciding if an unaligned store should be split should
8763 // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
8764 // a call to that function here.
8765
Matthias Braun651cff42016-06-02 18:03:53 +00008766 if (!Subtarget->isMisaligned128StoreSlow())
Tim Northover3b0846e2014-05-24 12:50:23 +00008767 return SDValue();
8768
Sanjay Patel924879a2015-08-04 15:49:57 +00008769 // Don't split at -Oz.
8770 if (DAG.getMachineFunction().getFunction()->optForMinSize())
Tim Northover3b0846e2014-05-24 12:50:23 +00008771 return SDValue();
8772
8773 SDValue StVal = S->getValue();
8774 EVT VT = StVal.getValueType();
8775
8776 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
8777 // those up regresses performance on micro-benchmarks and olden/bh.
8778 if (!VT.isVector() || VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
8779 return SDValue();
8780
8781 // Split unaligned 16B stores. They are terrible for performance.
8782 // Don't split stores with alignment of 1 or 2. Code that uses clang vector
8783 // extensions can use this to mark that it does not want splitting to happen
8784 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
8785 // eliminating alignment hazards is only 1 in 8 for alignment of 2.
8786 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
8787 S->getAlignment() <= 2)
8788 return SDValue();
8789
8790 // If we get a splat of a scalar convert this vector store to a store of
8791 // scalars. They will be merged into store pairs thereby removing two
8792 // instructions.
Ahmed Bougacha239d6352015-08-04 00:48:02 +00008793 if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, S))
Tim Northover3b0846e2014-05-24 12:50:23 +00008794 return ReplacedSplat;
8795
8796 SDLoc DL(S);
8797 unsigned NumElts = VT.getVectorNumElements() / 2;
8798 // Split VT into two.
8799 EVT HalfVT =
8800 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
8801 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008802 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008803 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008804 DAG.getConstant(NumElts, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008805 SDValue BasePtr = S->getBasePtr();
8806 SDValue NewST1 =
8807 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
Justin Lebar9c375812016-07-15 18:27:10 +00008808 S->getAlignment(), S->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +00008809 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008810 DAG.getConstant(8, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008811 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
Justin Lebar9c375812016-07-15 18:27:10 +00008812 S->getPointerInfo(), S->getAlignment(),
8813 S->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +00008814}
8815
8816/// Target-specific DAG combine function for post-increment LD1 (lane) and
8817/// post-increment LD1R.
8818static SDValue performPostLD1Combine(SDNode *N,
8819 TargetLowering::DAGCombinerInfo &DCI,
8820 bool IsLaneOp) {
8821 if (DCI.isBeforeLegalizeOps())
8822 return SDValue();
8823
8824 SelectionDAG &DAG = DCI.DAG;
8825 EVT VT = N->getValueType(0);
8826
8827 unsigned LoadIdx = IsLaneOp ? 1 : 0;
8828 SDNode *LD = N->getOperand(LoadIdx).getNode();
8829 // If it is not LOAD, can not do such combine.
8830 if (LD->getOpcode() != ISD::LOAD)
8831 return SDValue();
8832
8833 LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
8834 EVT MemVT = LoadSDN->getMemoryVT();
8835 // Check if memory operand is the same type as the vector element.
8836 if (MemVT != VT.getVectorElementType())
8837 return SDValue();
8838
8839 // Check if there are other uses. If so, do not combine as it will introduce
8840 // an extra load.
8841 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
8842 ++UI) {
8843 if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
8844 continue;
8845 if (*UI != N)
8846 return SDValue();
8847 }
8848
8849 SDValue Addr = LD->getOperand(1);
8850 SDValue Vector = N->getOperand(0);
8851 // Search for a use of the address operand that is an increment.
8852 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
8853 Addr.getNode()->use_end(); UI != UE; ++UI) {
8854 SDNode *User = *UI;
8855 if (User->getOpcode() != ISD::ADD
8856 || UI.getUse().getResNo() != Addr.getResNo())
8857 continue;
8858
8859 // Check that the add is independent of the load. Otherwise, folding it
8860 // would create a cycle.
8861 if (User->isPredecessorOf(LD) || LD->isPredecessorOf(User))
8862 continue;
8863 // Also check that add is not used in the vector operand. This would also
8864 // create a cycle.
8865 if (User->isPredecessorOf(Vector.getNode()))
8866 continue;
8867
8868 // If the increment is a constant, it must match the memory ref size.
8869 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8870 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8871 uint32_t IncVal = CInc->getZExtValue();
8872 unsigned NumBytes = VT.getScalarSizeInBits() / 8;
8873 if (IncVal != NumBytes)
8874 continue;
8875 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
8876 }
8877
Ahmed Bougacha2448ef52015-04-17 21:02:30 +00008878 // Finally, check that the vector doesn't depend on the load.
8879 // Again, this would create a cycle.
8880 // The load depending on the vector is fine, as that's the case for the
8881 // LD1*post we'll eventually generate anyway.
8882 if (LoadSDN->isPredecessorOf(Vector.getNode()))
8883 continue;
8884
Tim Northover3b0846e2014-05-24 12:50:23 +00008885 SmallVector<SDValue, 8> Ops;
8886 Ops.push_back(LD->getOperand(0)); // Chain
8887 if (IsLaneOp) {
8888 Ops.push_back(Vector); // The vector to be inserted
8889 Ops.push_back(N->getOperand(2)); // The lane to be inserted in the vector
8890 }
8891 Ops.push_back(Addr);
8892 Ops.push_back(Inc);
8893
8894 EVT Tys[3] = { VT, MVT::i64, MVT::Other };
Craig Toppere1d12942014-08-27 05:25:25 +00008895 SDVTList SDTys = DAG.getVTList(Tys);
Tim Northover3b0846e2014-05-24 12:50:23 +00008896 unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
8897 SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
8898 MemVT,
8899 LoadSDN->getMemOperand());
8900
8901 // Update the uses.
Benjamin Kramer3bc1edf2016-07-02 11:41:39 +00008902 SDValue NewResults[] = {
8903 SDValue(LD, 0), // The result of load
8904 SDValue(UpdN.getNode(), 2) // Chain
8905 };
Tim Northover3b0846e2014-05-24 12:50:23 +00008906 DCI.CombineTo(LD, NewResults);
8907 DCI.CombineTo(N, SDValue(UpdN.getNode(), 0)); // Dup/Inserted Result
8908 DCI.CombineTo(User, SDValue(UpdN.getNode(), 1)); // Write back register
8909
8910 break;
8911 }
8912 return SDValue();
8913}
8914
Tim Northover339c83e2015-11-10 00:44:23 +00008915/// Simplify \Addr given that the top byte of it is ignored by HW during
8916/// address translation.
8917static bool performTBISimplification(SDValue Addr,
8918 TargetLowering::DAGCombinerInfo &DCI,
8919 SelectionDAG &DAG) {
8920 APInt DemandedMask = APInt::getLowBitsSet(64, 56);
8921 APInt KnownZero, KnownOne;
8922 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
8923 DCI.isBeforeLegalizeOps());
8924 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8925 if (TLI.SimplifyDemandedBits(Addr, DemandedMask, KnownZero, KnownOne, TLO)) {
8926 DCI.CommitTargetLoweringOpt(TLO);
8927 return true;
8928 }
8929 return false;
8930}
8931
8932static SDValue performSTORECombine(SDNode *N,
8933 TargetLowering::DAGCombinerInfo &DCI,
8934 SelectionDAG &DAG,
8935 const AArch64Subtarget *Subtarget) {
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00008936 if (SDValue Split = split16BStores(N, DCI, DAG, Subtarget))
Tim Northover339c83e2015-11-10 00:44:23 +00008937 return Split;
8938
8939 if (Subtarget->supportsAddressTopByteIgnored() &&
8940 performTBISimplification(N->getOperand(2), DCI, DAG))
8941 return SDValue(N, 0);
8942
8943 return SDValue();
8944}
8945
8946 /// This function handles the log2-shuffle pattern produced by the
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008947/// LoopVectorizer for the across vector reduction. It consists of
8948/// log2(NumVectorElements) steps and, in each step, 2^(s) elements
8949/// are reduced, where s is an induction variable from 0 to
8950/// log2(NumVectorElements).
8951static SDValue tryMatchAcrossLaneShuffleForReduction(SDNode *N, SDValue OpV,
8952 unsigned Op,
8953 SelectionDAG &DAG) {
8954 EVT VTy = OpV->getOperand(0).getValueType();
8955 if (!VTy.isVector())
Chad Rosier6c36eff2015-09-03 18:13:57 +00008956 return SDValue();
8957
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008958 int NumVecElts = VTy.getVectorNumElements();
Jun Bum Lim0aace132015-10-09 14:11:25 +00008959 if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) {
8960 if (NumVecElts != 4)
8961 return SDValue();
8962 } else {
8963 if (NumVecElts != 4 && NumVecElts != 8 && NumVecElts != 16)
8964 return SDValue();
8965 }
Chad Rosier6c36eff2015-09-03 18:13:57 +00008966
8967 int NumExpectedSteps = APInt(8, NumVecElts).logBase2();
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008968 SDValue PreOp = OpV;
Chad Rosier6c36eff2015-09-03 18:13:57 +00008969 // Iterate over each step of the across vector reduction.
8970 for (int CurStep = 0; CurStep != NumExpectedSteps; ++CurStep) {
Chad Rosier6c36eff2015-09-03 18:13:57 +00008971 SDValue CurOp = PreOp.getOperand(0);
8972 SDValue Shuffle = PreOp.getOperand(1);
8973 if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE) {
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008974 // Try to swap the 1st and 2nd operand as add and min/max instructions
8975 // are commutative.
Chad Rosier6c36eff2015-09-03 18:13:57 +00008976 CurOp = PreOp.getOperand(1);
8977 Shuffle = PreOp.getOperand(0);
8978 if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE)
8979 return SDValue();
8980 }
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008981
8982 // Check if the input vector is fed by the operator we want to handle,
8983 // except the last step; the very first input vector is not necessarily
8984 // the same operator we are handling.
8985 if (CurOp.getOpcode() != Op && (CurStep != (NumExpectedSteps - 1)))
8986 return SDValue();
8987
Chad Rosier6c36eff2015-09-03 18:13:57 +00008988 // Check if it forms one step of the across vector reduction.
8989 // E.g.,
8990 // %cur = add %1, %0
8991 // %shuffle = vector_shuffle %cur, <2, 3, u, u>
8992 // %pre = add %cur, %shuffle
8993 if (Shuffle.getOperand(0) != CurOp)
8994 return SDValue();
8995
8996 int NumMaskElts = 1 << CurStep;
8997 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Shuffle)->getMask();
8998 // Check mask values in each step.
8999 // We expect the shuffle mask in each step follows a specific pattern
9000 // denoted here by the <M, U> form, where M is a sequence of integers
9001 // starting from NumMaskElts, increasing by 1, and the number integers
9002 // in M should be NumMaskElts. U is a sequence of UNDEFs and the number
9003 // of undef in U should be NumVecElts - NumMaskElts.
9004 // E.g., for <8 x i16>, mask values in each step should be :
9005 // step 0 : <1,u,u,u,u,u,u,u>
9006 // step 1 : <2,3,u,u,u,u,u,u>
9007 // step 2 : <4,5,6,7,u,u,u,u>
9008 for (int i = 0; i < NumVecElts; ++i)
9009 if ((i < NumMaskElts && Mask[i] != (NumMaskElts + i)) ||
9010 (i >= NumMaskElts && !(Mask[i] < 0)))
9011 return SDValue();
9012
9013 PreOp = CurOp;
9014 }
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009015 unsigned Opcode;
Jun Bum Lim0aace132015-10-09 14:11:25 +00009016 bool IsIntrinsic = false;
9017
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009018 switch (Op) {
9019 default:
9020 llvm_unreachable("Unexpected operator for across vector reduction");
9021 case ISD::ADD:
9022 Opcode = AArch64ISD::UADDV;
9023 break;
9024 case ISD::SMAX:
9025 Opcode = AArch64ISD::SMAXV;
9026 break;
9027 case ISD::UMAX:
9028 Opcode = AArch64ISD::UMAXV;
9029 break;
9030 case ISD::SMIN:
9031 Opcode = AArch64ISD::SMINV;
9032 break;
9033 case ISD::UMIN:
9034 Opcode = AArch64ISD::UMINV;
9035 break;
Jun Bum Lim0aace132015-10-09 14:11:25 +00009036 case ISD::FMAXNUM:
9037 Opcode = Intrinsic::aarch64_neon_fmaxnmv;
9038 IsIntrinsic = true;
9039 break;
9040 case ISD::FMINNUM:
9041 Opcode = Intrinsic::aarch64_neon_fminnmv;
9042 IsIntrinsic = true;
9043 break;
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009044 }
Chad Rosier6c36eff2015-09-03 18:13:57 +00009045 SDLoc DL(N);
Jun Bum Lim0aace132015-10-09 14:11:25 +00009046
9047 return IsIntrinsic
9048 ? DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, N->getValueType(0),
9049 DAG.getConstant(Opcode, DL, MVT::i32), PreOp)
9050 : DAG.getNode(
9051 ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0),
9052 DAG.getNode(Opcode, DL, PreOp.getSimpleValueType(), PreOp),
9053 DAG.getConstant(0, DL, MVT::i64));
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009054}
9055
9056/// Target-specific DAG combine for the across vector min/max reductions.
9057/// This function specifically handles the final clean-up step of the vector
9058/// min/max reductions produced by the LoopVectorizer. It is the log2-shuffle
9059/// pattern, which narrows down and finds the final min/max value from all
9060/// elements of the vector.
9061/// For example, for a <16 x i8> vector :
9062/// svn0 = vector_shuffle %0, undef<8,9,10,11,12,13,14,15,u,u,u,u,u,u,u,u>
9063/// %smax0 = smax %arr, svn0
9064/// %svn1 = vector_shuffle %smax0, undef<4,5,6,7,u,u,u,u,u,u,u,u,u,u,u,u>
9065/// %smax1 = smax %smax0, %svn1
9066/// %svn2 = vector_shuffle %smax1, undef<2,3,u,u,u,u,u,u,u,u,u,u,u,u,u,u>
9067/// %smax2 = smax %smax1, svn2
9068/// %svn3 = vector_shuffle %smax2, undef<1,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u>
9069/// %sc = setcc %smax2, %svn3, gt
9070/// %n0 = extract_vector_elt %sc, #0
9071/// %n1 = extract_vector_elt %smax2, #0
9072/// %n2 = extract_vector_elt $smax2, #1
9073/// %result = select %n0, %n1, n2
9074/// becomes :
9075/// %1 = smaxv %0
9076/// %result = extract_vector_elt %1, 0
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009077static SDValue
9078performAcrossLaneMinMaxReductionCombine(SDNode *N, SelectionDAG &DAG,
9079 const AArch64Subtarget *Subtarget) {
9080 if (!Subtarget->hasNEON())
9081 return SDValue();
9082
9083 SDValue N0 = N->getOperand(0);
9084 SDValue IfTrue = N->getOperand(1);
9085 SDValue IfFalse = N->getOperand(2);
9086
9087 // Check if the SELECT merges up the final result of the min/max
9088 // from a vector.
9089 if (N0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9090 IfTrue.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9091 IfFalse.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9092 return SDValue();
9093
9094 // Expect N0 is fed by SETCC.
9095 SDValue SetCC = N0.getOperand(0);
9096 EVT SetCCVT = SetCC.getValueType();
9097 if (SetCC.getOpcode() != ISD::SETCC || !SetCCVT.isVector() ||
9098 SetCCVT.getVectorElementType() != MVT::i1)
9099 return SDValue();
9100
9101 SDValue VectorOp = SetCC.getOperand(0);
9102 unsigned Op = VectorOp->getOpcode();
9103 // Check if the input vector is fed by the operator we want to handle.
Jun Bum Lim0aace132015-10-09 14:11:25 +00009104 if (Op != ISD::SMAX && Op != ISD::UMAX && Op != ISD::SMIN &&
9105 Op != ISD::UMIN && Op != ISD::FMAXNUM && Op != ISD::FMINNUM)
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009106 return SDValue();
9107
9108 EVT VTy = VectorOp.getValueType();
9109 if (!VTy.isVector())
9110 return SDValue();
9111
Jun Bum Lim0aace132015-10-09 14:11:25 +00009112 if (VTy.getSizeInBits() < 64)
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009113 return SDValue();
9114
Jun Bum Lim0aace132015-10-09 14:11:25 +00009115 EVT EltTy = VTy.getVectorElementType();
9116 if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) {
9117 if (EltTy != MVT::f32)
9118 return SDValue();
9119 } else {
9120 if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8)
9121 return SDValue();
9122 }
9123
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009124 // Check if extracting from the same vector.
9125 // For example,
9126 // %sc = setcc %vector, %svn1, gt
9127 // %n0 = extract_vector_elt %sc, #0
9128 // %n1 = extract_vector_elt %vector, #0
9129 // %n2 = extract_vector_elt $vector, #1
9130 if (!(VectorOp == IfTrue->getOperand(0) &&
9131 VectorOp == IfFalse->getOperand(0)))
9132 return SDValue();
9133
9134 // Check if the condition code is matched with the operator type.
9135 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get();
9136 if ((Op == ISD::SMAX && CC != ISD::SETGT && CC != ISD::SETGE) ||
9137 (Op == ISD::UMAX && CC != ISD::SETUGT && CC != ISD::SETUGE) ||
9138 (Op == ISD::SMIN && CC != ISD::SETLT && CC != ISD::SETLE) ||
Jun Bum Lim0aace132015-10-09 14:11:25 +00009139 (Op == ISD::UMIN && CC != ISD::SETULT && CC != ISD::SETULE) ||
9140 (Op == ISD::FMAXNUM && CC != ISD::SETOGT && CC != ISD::SETOGE &&
9141 CC != ISD::SETUGT && CC != ISD::SETUGE && CC != ISD::SETGT &&
9142 CC != ISD::SETGE) ||
9143 (Op == ISD::FMINNUM && CC != ISD::SETOLT && CC != ISD::SETOLE &&
9144 CC != ISD::SETULT && CC != ISD::SETULE && CC != ISD::SETLT &&
9145 CC != ISD::SETLE))
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009146 return SDValue();
9147
9148 // Expect to check only lane 0 from the vector SETCC.
Artyom Skrobov314ee042015-11-25 19:41:11 +00009149 if (!isNullConstant(N0.getOperand(1)))
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009150 return SDValue();
9151
9152 // Expect to extract the true value from lane 0.
Artyom Skrobov314ee042015-11-25 19:41:11 +00009153 if (!isNullConstant(IfTrue.getOperand(1)))
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009154 return SDValue();
9155
9156 // Expect to extract the false value from lane 1.
Artyom Skrobov314ee042015-11-25 19:41:11 +00009157 if (!isOneConstant(IfFalse.getOperand(1)))
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009158 return SDValue();
9159
9160 return tryMatchAcrossLaneShuffleForReduction(N, SetCC, Op, DAG);
9161}
9162
9163/// Target-specific DAG combine for the across vector add reduction.
9164/// This function specifically handles the final clean-up step of the vector
9165/// add reduction produced by the LoopVectorizer. It is the log2-shuffle
9166/// pattern, which adds all elements of a vector together.
9167/// For example, for a <4 x i32> vector :
9168/// %1 = vector_shuffle %0, <2,3,u,u>
9169/// %2 = add %0, %1
9170/// %3 = vector_shuffle %2, <1,u,u,u>
9171/// %4 = add %2, %3
9172/// %result = extract_vector_elt %4, 0
9173/// becomes :
9174/// %0 = uaddv %0
9175/// %result = extract_vector_elt %0, 0
9176static SDValue
9177performAcrossLaneAddReductionCombine(SDNode *N, SelectionDAG &DAG,
9178 const AArch64Subtarget *Subtarget) {
9179 if (!Subtarget->hasNEON())
9180 return SDValue();
9181 SDValue N0 = N->getOperand(0);
9182 SDValue N1 = N->getOperand(1);
9183
9184 // Check if the input vector is fed by the ADD.
9185 if (N0->getOpcode() != ISD::ADD)
9186 return SDValue();
9187
9188 // The vector extract idx must constant zero because we only expect the final
9189 // result of the reduction is placed in lane 0.
Artyom Skrobov314ee042015-11-25 19:41:11 +00009190 if (!isNullConstant(N1))
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009191 return SDValue();
9192
9193 EVT VTy = N0.getValueType();
9194 if (!VTy.isVector())
9195 return SDValue();
9196
9197 EVT EltTy = VTy.getVectorElementType();
9198 if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8)
9199 return SDValue();
9200
Jun Bum Lim0aace132015-10-09 14:11:25 +00009201 if (VTy.getSizeInBits() < 64)
9202 return SDValue();
9203
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009204 return tryMatchAcrossLaneShuffleForReduction(N, N0, ISD::ADD, DAG);
Chad Rosier6c36eff2015-09-03 18:13:57 +00009205}
9206
Tim Northover3b0846e2014-05-24 12:50:23 +00009207/// Target-specific DAG combine function for NEON load/store intrinsics
9208/// to merge base address updates.
9209static SDValue performNEONPostLDSTCombine(SDNode *N,
9210 TargetLowering::DAGCombinerInfo &DCI,
9211 SelectionDAG &DAG) {
9212 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9213 return SDValue();
9214
9215 unsigned AddrOpIdx = N->getNumOperands() - 1;
9216 SDValue Addr = N->getOperand(AddrOpIdx);
9217
9218 // Search for a use of the address operand that is an increment.
9219 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9220 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9221 SDNode *User = *UI;
9222 if (User->getOpcode() != ISD::ADD ||
9223 UI.getUse().getResNo() != Addr.getResNo())
9224 continue;
9225
9226 // Check that the add is independent of the load/store. Otherwise, folding
9227 // it would create a cycle.
9228 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9229 continue;
9230
9231 // Find the new opcode for the updating load/store.
9232 bool IsStore = false;
9233 bool IsLaneOp = false;
9234 bool IsDupOp = false;
9235 unsigned NewOpc = 0;
9236 unsigned NumVecs = 0;
9237 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9238 switch (IntNo) {
9239 default: llvm_unreachable("unexpected intrinsic for Neon base update");
9240 case Intrinsic::aarch64_neon_ld2: NewOpc = AArch64ISD::LD2post;
9241 NumVecs = 2; break;
9242 case Intrinsic::aarch64_neon_ld3: NewOpc = AArch64ISD::LD3post;
9243 NumVecs = 3; break;
9244 case Intrinsic::aarch64_neon_ld4: NewOpc = AArch64ISD::LD4post;
9245 NumVecs = 4; break;
9246 case Intrinsic::aarch64_neon_st2: NewOpc = AArch64ISD::ST2post;
9247 NumVecs = 2; IsStore = true; break;
9248 case Intrinsic::aarch64_neon_st3: NewOpc = AArch64ISD::ST3post;
9249 NumVecs = 3; IsStore = true; break;
9250 case Intrinsic::aarch64_neon_st4: NewOpc = AArch64ISD::ST4post;
9251 NumVecs = 4; IsStore = true; break;
9252 case Intrinsic::aarch64_neon_ld1x2: NewOpc = AArch64ISD::LD1x2post;
9253 NumVecs = 2; break;
9254 case Intrinsic::aarch64_neon_ld1x3: NewOpc = AArch64ISD::LD1x3post;
9255 NumVecs = 3; break;
9256 case Intrinsic::aarch64_neon_ld1x4: NewOpc = AArch64ISD::LD1x4post;
9257 NumVecs = 4; break;
9258 case Intrinsic::aarch64_neon_st1x2: NewOpc = AArch64ISD::ST1x2post;
9259 NumVecs = 2; IsStore = true; break;
9260 case Intrinsic::aarch64_neon_st1x3: NewOpc = AArch64ISD::ST1x3post;
9261 NumVecs = 3; IsStore = true; break;
9262 case Intrinsic::aarch64_neon_st1x4: NewOpc = AArch64ISD::ST1x4post;
9263 NumVecs = 4; IsStore = true; break;
9264 case Intrinsic::aarch64_neon_ld2r: NewOpc = AArch64ISD::LD2DUPpost;
9265 NumVecs = 2; IsDupOp = true; break;
9266 case Intrinsic::aarch64_neon_ld3r: NewOpc = AArch64ISD::LD3DUPpost;
9267 NumVecs = 3; IsDupOp = true; break;
9268 case Intrinsic::aarch64_neon_ld4r: NewOpc = AArch64ISD::LD4DUPpost;
9269 NumVecs = 4; IsDupOp = true; break;
9270 case Intrinsic::aarch64_neon_ld2lane: NewOpc = AArch64ISD::LD2LANEpost;
9271 NumVecs = 2; IsLaneOp = true; break;
9272 case Intrinsic::aarch64_neon_ld3lane: NewOpc = AArch64ISD::LD3LANEpost;
9273 NumVecs = 3; IsLaneOp = true; break;
9274 case Intrinsic::aarch64_neon_ld4lane: NewOpc = AArch64ISD::LD4LANEpost;
9275 NumVecs = 4; IsLaneOp = true; break;
9276 case Intrinsic::aarch64_neon_st2lane: NewOpc = AArch64ISD::ST2LANEpost;
9277 NumVecs = 2; IsStore = true; IsLaneOp = true; break;
9278 case Intrinsic::aarch64_neon_st3lane: NewOpc = AArch64ISD::ST3LANEpost;
9279 NumVecs = 3; IsStore = true; IsLaneOp = true; break;
9280 case Intrinsic::aarch64_neon_st4lane: NewOpc = AArch64ISD::ST4LANEpost;
9281 NumVecs = 4; IsStore = true; IsLaneOp = true; break;
9282 }
9283
9284 EVT VecTy;
9285 if (IsStore)
9286 VecTy = N->getOperand(2).getValueType();
9287 else
9288 VecTy = N->getValueType(0);
9289
9290 // If the increment is a constant, it must match the memory ref size.
9291 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9292 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9293 uint32_t IncVal = CInc->getZExtValue();
9294 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9295 if (IsLaneOp || IsDupOp)
9296 NumBytes /= VecTy.getVectorNumElements();
9297 if (IncVal != NumBytes)
9298 continue;
9299 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
9300 }
9301 SmallVector<SDValue, 8> Ops;
9302 Ops.push_back(N->getOperand(0)); // Incoming chain
9303 // Load lane and store have vector list as input.
9304 if (IsLaneOp || IsStore)
9305 for (unsigned i = 2; i < AddrOpIdx; ++i)
9306 Ops.push_back(N->getOperand(i));
9307 Ops.push_back(Addr); // Base register
9308 Ops.push_back(Inc);
9309
9310 // Return Types.
9311 EVT Tys[6];
9312 unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
9313 unsigned n;
9314 for (n = 0; n < NumResultVecs; ++n)
9315 Tys[n] = VecTy;
9316 Tys[n++] = MVT::i64; // Type of write back register
9317 Tys[n] = MVT::Other; // Type of the chain
Craig Toppere1d12942014-08-27 05:25:25 +00009318 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
Tim Northover3b0846e2014-05-24 12:50:23 +00009319
9320 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9321 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
9322 MemInt->getMemoryVT(),
9323 MemInt->getMemOperand());
9324
9325 // Update the uses.
9326 std::vector<SDValue> NewResults;
9327 for (unsigned i = 0; i < NumResultVecs; ++i) {
9328 NewResults.push_back(SDValue(UpdN.getNode(), i));
9329 }
9330 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
9331 DCI.CombineTo(N, NewResults);
9332 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9333
9334 break;
9335 }
9336 return SDValue();
9337}
9338
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009339// Checks to see if the value is the prescribed width and returns information
9340// about its extension mode.
9341static
9342bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
9343 ExtType = ISD::NON_EXTLOAD;
9344 switch(V.getNode()->getOpcode()) {
9345 default:
9346 return false;
9347 case ISD::LOAD: {
9348 LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
9349 if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
9350 || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
9351 ExtType = LoadNode->getExtensionType();
9352 return true;
9353 }
9354 return false;
9355 }
9356 case ISD::AssertSext: {
9357 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9358 if ((TypeNode->getVT() == MVT::i8 && width == 8)
9359 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9360 ExtType = ISD::SEXTLOAD;
9361 return true;
9362 }
9363 return false;
9364 }
9365 case ISD::AssertZext: {
9366 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9367 if ((TypeNode->getVT() == MVT::i8 && width == 8)
9368 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9369 ExtType = ISD::ZEXTLOAD;
9370 return true;
9371 }
9372 return false;
9373 }
9374 case ISD::Constant:
9375 case ISD::TargetConstant: {
Eric Christopher114fa1c2016-02-29 22:50:49 +00009376 return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
9377 1LL << (width - 1);
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009378 }
9379 }
9380
9381 return true;
9382}
9383
9384// This function does a whole lot of voodoo to determine if the tests are
9385// equivalent without and with a mask. Essentially what happens is that given a
9386// DAG resembling:
9387//
9388// +-------------+ +-------------+ +-------------+ +-------------+
9389// | Input | | AddConstant | | CompConstant| | CC |
9390// +-------------+ +-------------+ +-------------+ +-------------+
9391// | | | |
9392// V V | +----------+
9393// +-------------+ +----+ | |
9394// | ADD | |0xff| | |
9395// +-------------+ +----+ | |
9396// | | | |
9397// V V | |
9398// +-------------+ | |
9399// | AND | | |
9400// +-------------+ | |
9401// | | |
9402// +-----+ | |
9403// | | |
9404// V V V
9405// +-------------+
9406// | CMP |
9407// +-------------+
9408//
9409// The AND node may be safely removed for some combinations of inputs. In
9410// particular we need to take into account the extension type of the Input,
9411// the exact values of AddConstant, CompConstant, and CC, along with the nominal
9412// width of the input (this can work for any width inputs, the above graph is
9413// specific to 8 bits.
9414//
9415// The specific equations were worked out by generating output tables for each
9416// AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
9417// problem was simplified by working with 4 bit inputs, which means we only
9418// needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
9419// extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
9420// patterns present in both extensions (0,7). For every distinct set of
9421// AddConstant and CompConstants bit patterns we can consider the masked and
9422// unmasked versions to be equivalent if the result of this function is true for
9423// all 16 distinct bit patterns of for the current extension type of Input (w0).
9424//
9425// sub w8, w0, w1
9426// and w10, w8, #0x0f
9427// cmp w8, w2
9428// cset w9, AArch64CC
9429// cmp w10, w2
9430// cset w11, AArch64CC
9431// cmp w9, w11
9432// cset w0, eq
9433// ret
9434//
9435// Since the above function shows when the outputs are equivalent it defines
9436// when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
9437// would be expensive to run during compiles. The equations below were written
9438// in a test harness that confirmed they gave equivalent outputs to the above
9439// for all inputs function, so they can be used determine if the removal is
9440// legal instead.
9441//
9442// isEquivalentMaskless() is the code for testing if the AND can be removed
9443// factored out of the DAG recognition as the DAG can take several forms.
9444
David Majnemere61e4bf2016-06-21 05:10:24 +00009445static bool isEquivalentMaskless(unsigned CC, unsigned width,
9446 ISD::LoadExtType ExtType, int AddConstant,
9447 int CompConstant) {
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009448 // By being careful about our equations and only writing the in term
9449 // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
9450 // make them generally applicable to all bit widths.
David Majnemere61e4bf2016-06-21 05:10:24 +00009451 int MaxUInt = (1 << width);
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009452
9453 // For the purposes of these comparisons sign extending the type is
9454 // equivalent to zero extending the add and displacing it by half the integer
9455 // width. Provided we are careful and make sure our equations are valid over
9456 // the whole range we can just adjust the input and avoid writing equations
9457 // for sign extended inputs.
9458 if (ExtType == ISD::SEXTLOAD)
9459 AddConstant -= (1 << (width-1));
9460
9461 switch(CC) {
9462 case AArch64CC::LE:
9463 case AArch64CC::GT: {
9464 if ((AddConstant == 0) ||
9465 (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
9466 (AddConstant >= 0 && CompConstant < 0) ||
9467 (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
9468 return true;
9469 } break;
9470 case AArch64CC::LT:
9471 case AArch64CC::GE: {
9472 if ((AddConstant == 0) ||
9473 (AddConstant >= 0 && CompConstant <= 0) ||
9474 (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
9475 return true;
9476 } break;
9477 case AArch64CC::HI:
9478 case AArch64CC::LS: {
9479 if ((AddConstant >= 0 && CompConstant < 0) ||
9480 (AddConstant <= 0 && CompConstant >= -1 &&
9481 CompConstant < AddConstant + MaxUInt))
9482 return true;
9483 } break;
9484 case AArch64CC::PL:
9485 case AArch64CC::MI: {
9486 if ((AddConstant == 0) ||
9487 (AddConstant > 0 && CompConstant <= 0) ||
9488 (AddConstant < 0 && CompConstant <= AddConstant))
9489 return true;
9490 } break;
9491 case AArch64CC::LO:
9492 case AArch64CC::HS: {
9493 if ((AddConstant >= 0 && CompConstant <= 0) ||
9494 (AddConstant <= 0 && CompConstant >= 0 &&
9495 CompConstant <= AddConstant + MaxUInt))
9496 return true;
9497 } break;
9498 case AArch64CC::EQ:
9499 case AArch64CC::NE: {
9500 if ((AddConstant > 0 && CompConstant < 0) ||
9501 (AddConstant < 0 && CompConstant >= 0 &&
9502 CompConstant < AddConstant + MaxUInt) ||
9503 (AddConstant >= 0 && CompConstant >= 0 &&
9504 CompConstant >= AddConstant) ||
9505 (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
9506
9507 return true;
9508 } break;
9509 case AArch64CC::VS:
9510 case AArch64CC::VC:
9511 case AArch64CC::AL:
9512 case AArch64CC::NV:
9513 return true;
9514 case AArch64CC::Invalid:
9515 break;
9516 }
9517
9518 return false;
9519}
9520
9521static
9522SDValue performCONDCombine(SDNode *N,
9523 TargetLowering::DAGCombinerInfo &DCI,
9524 SelectionDAG &DAG, unsigned CCIndex,
9525 unsigned CmpIndex) {
9526 unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
9527 SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
9528 unsigned CondOpcode = SubsNode->getOpcode();
9529
9530 if (CondOpcode != AArch64ISD::SUBS)
9531 return SDValue();
9532
9533 // There is a SUBS feeding this condition. Is it fed by a mask we can
9534 // use?
9535
9536 SDNode *AndNode = SubsNode->getOperand(0).getNode();
9537 unsigned MaskBits = 0;
9538
9539 if (AndNode->getOpcode() != ISD::AND)
9540 return SDValue();
9541
9542 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
9543 uint32_t CNV = CN->getZExtValue();
9544 if (CNV == 255)
9545 MaskBits = 8;
9546 else if (CNV == 65535)
9547 MaskBits = 16;
9548 }
9549
9550 if (!MaskBits)
9551 return SDValue();
9552
9553 SDValue AddValue = AndNode->getOperand(0);
9554
9555 if (AddValue.getOpcode() != ISD::ADD)
9556 return SDValue();
9557
9558 // The basic dag structure is correct, grab the inputs and validate them.
9559
9560 SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
9561 SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
9562 SDValue SubsInputValue = SubsNode->getOperand(1);
9563
9564 // The mask is present and the provenance of all the values is a smaller type,
9565 // lets see if the mask is superfluous.
9566
9567 if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
9568 !isa<ConstantSDNode>(SubsInputValue.getNode()))
9569 return SDValue();
9570
9571 ISD::LoadExtType ExtType;
9572
9573 if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
9574 !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
9575 !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
9576 return SDValue();
9577
9578 if(!isEquivalentMaskless(CC, MaskBits, ExtType,
9579 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
9580 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
9581 return SDValue();
9582
9583 // The AND is not necessary, remove it.
9584
9585 SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
9586 SubsNode->getValueType(1));
9587 SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
9588
9589 SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
9590 DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
9591
9592 return SDValue(N, 0);
9593}
9594
Tim Northover3b0846e2014-05-24 12:50:23 +00009595// Optimize compare with zero and branch.
9596static SDValue performBRCONDCombine(SDNode *N,
9597 TargetLowering::DAGCombinerInfo &DCI,
9598 SelectionDAG &DAG) {
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00009599 if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3))
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009600 N = NV.getNode();
Tim Northover3b0846e2014-05-24 12:50:23 +00009601 SDValue Chain = N->getOperand(0);
9602 SDValue Dest = N->getOperand(1);
9603 SDValue CCVal = N->getOperand(2);
9604 SDValue Cmp = N->getOperand(3);
9605
9606 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
9607 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
9608 if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
9609 return SDValue();
9610
9611 unsigned CmpOpc = Cmp.getOpcode();
9612 if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
9613 return SDValue();
9614
9615 // Only attempt folding if there is only one use of the flag and no use of the
9616 // value.
9617 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
9618 return SDValue();
9619
9620 SDValue LHS = Cmp.getOperand(0);
9621 SDValue RHS = Cmp.getOperand(1);
9622
9623 assert(LHS.getValueType() == RHS.getValueType() &&
9624 "Expected the value type to be the same for both operands!");
9625 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
9626 return SDValue();
9627
Artyom Skrobov314ee042015-11-25 19:41:11 +00009628 if (isNullConstant(LHS))
Tim Northover3b0846e2014-05-24 12:50:23 +00009629 std::swap(LHS, RHS);
9630
Artyom Skrobov314ee042015-11-25 19:41:11 +00009631 if (!isNullConstant(RHS))
Tim Northover3b0846e2014-05-24 12:50:23 +00009632 return SDValue();
9633
9634 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
9635 LHS.getOpcode() == ISD::SRL)
9636 return SDValue();
9637
9638 // Fold the compare into the branch instruction.
9639 SDValue BR;
9640 if (CC == AArch64CC::EQ)
9641 BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9642 else
9643 BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9644
9645 // Do not add new nodes to DAG combiner worklist.
9646 DCI.CombineTo(N, BR, false);
9647
9648 return SDValue();
9649}
9650
Geoff Berry9e934b02016-01-04 18:55:47 +00009651// Optimize some simple tbz/tbnz cases. Returns the new operand and bit to test
9652// as well as whether the test should be inverted. This code is required to
9653// catch these cases (as opposed to standard dag combines) because
9654// AArch64ISD::TBZ is matched during legalization.
9655static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert,
9656 SelectionDAG &DAG) {
9657
9658 if (!Op->hasOneUse())
9659 return Op;
9660
9661 // We don't handle undef/constant-fold cases below, as they should have
9662 // already been taken care of (e.g. and of 0, test of undefined shifted bits,
9663 // etc.)
9664
9665 // (tbz (trunc x), b) -> (tbz x, b)
9666 // This case is just here to enable more of the below cases to be caught.
9667 if (Op->getOpcode() == ISD::TRUNCATE &&
9668 Bit < Op->getValueType(0).getSizeInBits()) {
9669 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9670 }
9671
9672 if (Op->getNumOperands() != 2)
9673 return Op;
9674
9675 auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
9676 if (!C)
9677 return Op;
9678
9679 switch (Op->getOpcode()) {
9680 default:
9681 return Op;
9682
9683 // (tbz (and x, m), b) -> (tbz x, b)
9684 case ISD::AND:
9685 if ((C->getZExtValue() >> Bit) & 1)
9686 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9687 return Op;
9688
9689 // (tbz (shl x, c), b) -> (tbz x, b-c)
9690 case ISD::SHL:
9691 if (C->getZExtValue() <= Bit &&
9692 (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
9693 Bit = Bit - C->getZExtValue();
9694 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9695 }
9696 return Op;
9697
9698 // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
9699 case ISD::SRA:
9700 Bit = Bit + C->getZExtValue();
9701 if (Bit >= Op->getValueType(0).getSizeInBits())
9702 Bit = Op->getValueType(0).getSizeInBits() - 1;
9703 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9704
9705 // (tbz (srl x, c), b) -> (tbz x, b+c)
9706 case ISD::SRL:
9707 if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
9708 Bit = Bit + C->getZExtValue();
9709 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9710 }
9711 return Op;
9712
9713 // (tbz (xor x, -1), b) -> (tbnz x, b)
9714 case ISD::XOR:
9715 if ((C->getZExtValue() >> Bit) & 1)
9716 Invert = !Invert;
9717 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9718 }
9719}
9720
9721// Optimize test single bit zero/non-zero and branch.
9722static SDValue performTBZCombine(SDNode *N,
9723 TargetLowering::DAGCombinerInfo &DCI,
9724 SelectionDAG &DAG) {
9725 unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
9726 bool Invert = false;
9727 SDValue TestSrc = N->getOperand(1);
9728 SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG);
9729
9730 if (TestSrc == NewTestSrc)
9731 return SDValue();
9732
9733 unsigned NewOpc = N->getOpcode();
9734 if (Invert) {
9735 if (NewOpc == AArch64ISD::TBZ)
9736 NewOpc = AArch64ISD::TBNZ;
9737 else {
9738 assert(NewOpc == AArch64ISD::TBNZ);
9739 NewOpc = AArch64ISD::TBZ;
9740 }
9741 }
9742
9743 SDLoc DL(N);
9744 return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc,
9745 DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3));
9746}
9747
Tim Northover3b0846e2014-05-24 12:50:23 +00009748// vselect (v1i1 setcc) ->
9749// vselect (v1iXX setcc) (XX is the size of the compared operand type)
9750// FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
9751// condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
9752// such VSELECT.
9753static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
9754 SDValue N0 = N->getOperand(0);
9755 EVT CCVT = N0.getValueType();
9756
9757 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
9758 CCVT.getVectorElementType() != MVT::i1)
9759 return SDValue();
9760
9761 EVT ResVT = N->getValueType(0);
9762 EVT CmpVT = N0.getOperand(0).getValueType();
9763 // Only combine when the result type is of the same size as the compared
9764 // operands.
9765 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
9766 return SDValue();
9767
9768 SDValue IfTrue = N->getOperand(1);
9769 SDValue IfFalse = N->getOperand(2);
9770 SDValue SetCC =
9771 DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
9772 N0.getOperand(0), N0.getOperand(1),
9773 cast<CondCodeSDNode>(N0.getOperand(2))->get());
9774 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
9775 IfTrue, IfFalse);
9776}
9777
9778/// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
9779/// the compare-mask instructions rather than going via NZCV, even if LHS and
9780/// RHS are really scalar. This replaces any scalar setcc in the above pattern
9781/// with a vector one followed by a DUP shuffle on the result.
Ahmed Bougachac004c602015-04-27 21:43:12 +00009782static SDValue performSelectCombine(SDNode *N,
9783 TargetLowering::DAGCombinerInfo &DCI) {
9784 SelectionDAG &DAG = DCI.DAG;
Tim Northover3b0846e2014-05-24 12:50:23 +00009785 SDValue N0 = N->getOperand(0);
9786 EVT ResVT = N->getValueType(0);
Tim Northover3c0915e2014-08-29 15:34:58 +00009787
Ahmed Bougachac004c602015-04-27 21:43:12 +00009788 if (N0.getOpcode() != ISD::SETCC)
Tim Northover3c0915e2014-08-29 15:34:58 +00009789 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00009790
Ahmed Bougachac004c602015-04-27 21:43:12 +00009791 // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
9792 // scalar SetCCResultType. We also don't expect vectors, because we assume
9793 // that selects fed by vector SETCCs are canonicalized to VSELECT.
9794 assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
9795 "Scalar-SETCC feeding SELECT has unexpected result type!");
9796
Tim Northoverc1c05ae2014-08-29 13:05:18 +00009797 // If NumMaskElts == 0, the comparison is larger than select result. The
9798 // largest real NEON comparison is 64-bits per lane, which means the result is
9799 // at most 32-bits and an illegal vector. Just bail out for now.
Tim Northover3c0915e2014-08-29 15:34:58 +00009800 EVT SrcVT = N0.getOperand(0).getValueType();
Ahmed Bougachad0ce0582014-12-01 20:59:00 +00009801
9802 // Don't try to do this optimization when the setcc itself has i1 operands.
9803 // There are no legal vectors of i1, so this would be pointless.
9804 if (SrcVT == MVT::i1)
9805 return SDValue();
9806
Tim Northover3c0915e2014-08-29 15:34:58 +00009807 int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
Tim Northoverc1c05ae2014-08-29 13:05:18 +00009808 if (!ResVT.isVector() || NumMaskElts == 0)
Tim Northover3b0846e2014-05-24 12:50:23 +00009809 return SDValue();
9810
Tim Northoverc1c05ae2014-08-29 13:05:18 +00009811 SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
Tim Northover3b0846e2014-05-24 12:50:23 +00009812 EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
9813
Ahmed Bougacha89bba612015-04-27 21:01:20 +00009814 // Also bail out if the vector CCVT isn't the same size as ResVT.
9815 // This can happen if the SETCC operand size doesn't divide the ResVT size
9816 // (e.g., f64 vs v3f32).
9817 if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
9818 return SDValue();
9819
Ahmed Bougachac004c602015-04-27 21:43:12 +00009820 // Make sure we didn't create illegal types, if we're not supposed to.
9821 assert(DCI.isBeforeLegalize() ||
9822 DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
9823
Tim Northover3b0846e2014-05-24 12:50:23 +00009824 // First perform a vector comparison, where lane 0 is the one we're interested
9825 // in.
Tim Northoverc1c05ae2014-08-29 13:05:18 +00009826 SDLoc DL(N0);
Tim Northover3b0846e2014-05-24 12:50:23 +00009827 SDValue LHS =
9828 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
9829 SDValue RHS =
9830 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
9831 SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
9832
9833 // Now duplicate the comparison mask we want across all other lanes.
9834 SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
Craig Topper2bd8b4b2016-07-01 06:54:47 +00009835 SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask);
Tim Northoverc1c05ae2014-08-29 13:05:18 +00009836 Mask = DAG.getNode(ISD::BITCAST, DL,
9837 ResVT.changeVectorElementTypeToInteger(), Mask);
Tim Northover3b0846e2014-05-24 12:50:23 +00009838
9839 return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
9840}
9841
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009842/// Get rid of unnecessary NVCASTs (that don't change the type).
9843static SDValue performNVCASTCombine(SDNode *N) {
9844 if (N->getValueType(0) == N->getOperand(0).getValueType())
9845 return N->getOperand(0);
9846
9847 return SDValue();
9848}
9849
Tim Northover3b0846e2014-05-24 12:50:23 +00009850SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
9851 DAGCombinerInfo &DCI) const {
9852 SelectionDAG &DAG = DCI.DAG;
9853 switch (N->getOpcode()) {
9854 default:
9855 break;
9856 case ISD::ADD:
9857 case ISD::SUB:
9858 return performAddSubLongCombine(N, DCI, DAG);
9859 case ISD::XOR:
9860 return performXorCombine(N, DAG, DCI, Subtarget);
9861 case ISD::MUL:
9862 return performMulCombine(N, DAG, DCI, Subtarget);
9863 case ISD::SINT_TO_FP:
9864 case ISD::UINT_TO_FP:
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00009865 return performIntToFpCombine(N, DAG, Subtarget);
Chad Rosierfa30c9b2015-10-07 17:39:18 +00009866 case ISD::FP_TO_SINT:
9867 case ISD::FP_TO_UINT:
Silviu Barangafa00ba32016-08-08 13:13:57 +00009868 return performFpToIntCombine(N, DAG, DCI, Subtarget);
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00009869 case ISD::FDIV:
9870 return performFDivCombine(N, DAG, Subtarget);
Tim Northover3b0846e2014-05-24 12:50:23 +00009871 case ISD::OR:
9872 return performORCombine(N, DCI, Subtarget);
Chad Rosier14aa2ad2016-05-26 19:41:33 +00009873 case ISD::SRL:
9874 return performSRLCombine(N, DCI);
Tim Northover3b0846e2014-05-24 12:50:23 +00009875 case ISD::INTRINSIC_WO_CHAIN:
9876 return performIntrinsicCombine(N, DCI, Subtarget);
9877 case ISD::ANY_EXTEND:
9878 case ISD::ZERO_EXTEND:
9879 case ISD::SIGN_EXTEND:
9880 return performExtendCombine(N, DCI, DAG);
9881 case ISD::BITCAST:
9882 return performBitcastCombine(N, DCI, DAG);
9883 case ISD::CONCAT_VECTORS:
9884 return performConcatVectorsCombine(N, DCI, DAG);
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009885 case ISD::SELECT: {
9886 SDValue RV = performSelectCombine(N, DCI);
9887 if (!RV.getNode())
9888 RV = performAcrossLaneMinMaxReductionCombine(N, DAG, Subtarget);
9889 return RV;
9890 }
Tim Northover3b0846e2014-05-24 12:50:23 +00009891 case ISD::VSELECT:
9892 return performVSelectCombine(N, DCI.DAG);
Tim Northover339c83e2015-11-10 00:44:23 +00009893 case ISD::LOAD:
9894 if (performTBISimplification(N->getOperand(1), DCI, DAG))
9895 return SDValue(N, 0);
9896 break;
Tim Northover3b0846e2014-05-24 12:50:23 +00009897 case ISD::STORE:
9898 return performSTORECombine(N, DCI, DAG, Subtarget);
9899 case AArch64ISD::BRCOND:
9900 return performBRCONDCombine(N, DCI, DAG);
Geoff Berry9e934b02016-01-04 18:55:47 +00009901 case AArch64ISD::TBNZ:
9902 case AArch64ISD::TBZ:
9903 return performTBZCombine(N, DCI, DAG);
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009904 case AArch64ISD::CSEL:
9905 return performCONDCombine(N, DCI, DAG, 2, 3);
Tim Northover3b0846e2014-05-24 12:50:23 +00009906 case AArch64ISD::DUP:
9907 return performPostLD1Combine(N, DCI, false);
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009908 case AArch64ISD::NVCAST:
9909 return performNVCASTCombine(N);
Tim Northover3b0846e2014-05-24 12:50:23 +00009910 case ISD::INSERT_VECTOR_ELT:
9911 return performPostLD1Combine(N, DCI, true);
Chad Rosier6c36eff2015-09-03 18:13:57 +00009912 case ISD::EXTRACT_VECTOR_ELT:
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009913 return performAcrossLaneAddReductionCombine(N, DAG, Subtarget);
Tim Northover3b0846e2014-05-24 12:50:23 +00009914 case ISD::INTRINSIC_VOID:
9915 case ISD::INTRINSIC_W_CHAIN:
9916 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9917 case Intrinsic::aarch64_neon_ld2:
9918 case Intrinsic::aarch64_neon_ld3:
9919 case Intrinsic::aarch64_neon_ld4:
9920 case Intrinsic::aarch64_neon_ld1x2:
9921 case Intrinsic::aarch64_neon_ld1x3:
9922 case Intrinsic::aarch64_neon_ld1x4:
9923 case Intrinsic::aarch64_neon_ld2lane:
9924 case Intrinsic::aarch64_neon_ld3lane:
9925 case Intrinsic::aarch64_neon_ld4lane:
9926 case Intrinsic::aarch64_neon_ld2r:
9927 case Intrinsic::aarch64_neon_ld3r:
9928 case Intrinsic::aarch64_neon_ld4r:
9929 case Intrinsic::aarch64_neon_st2:
9930 case Intrinsic::aarch64_neon_st3:
9931 case Intrinsic::aarch64_neon_st4:
9932 case Intrinsic::aarch64_neon_st1x2:
9933 case Intrinsic::aarch64_neon_st1x3:
9934 case Intrinsic::aarch64_neon_st1x4:
9935 case Intrinsic::aarch64_neon_st2lane:
9936 case Intrinsic::aarch64_neon_st3lane:
9937 case Intrinsic::aarch64_neon_st4lane:
9938 return performNEONPostLDSTCombine(N, DCI, DAG);
9939 default:
9940 break;
9941 }
9942 }
9943 return SDValue();
9944}
9945
9946// Check if the return value is used as only a return value, as otherwise
9947// we can't perform a tail-call. In particular, we need to check for
9948// target ISD nodes that are returns and any other "odd" constructs
9949// that the generic analysis code won't necessarily catch.
9950bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
9951 SDValue &Chain) const {
9952 if (N->getNumValues() != 1)
9953 return false;
9954 if (!N->hasNUsesOfValue(1, 0))
9955 return false;
9956
9957 SDValue TCChain = Chain;
9958 SDNode *Copy = *N->use_begin();
9959 if (Copy->getOpcode() == ISD::CopyToReg) {
9960 // If the copy has a glue operand, we conservatively assume it isn't safe to
9961 // perform a tail call.
9962 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
9963 MVT::Glue)
9964 return false;
9965 TCChain = Copy->getOperand(0);
9966 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
9967 return false;
9968
9969 bool HasRet = false;
9970 for (SDNode *Node : Copy->uses()) {
9971 if (Node->getOpcode() != AArch64ISD::RET_FLAG)
9972 return false;
9973 HasRet = true;
9974 }
9975
9976 if (!HasRet)
9977 return false;
9978
9979 Chain = TCChain;
9980 return true;
9981}
9982
9983// Return whether the an instruction can potentially be optimized to a tail
9984// call. This will cause the optimizers to attempt to move, or duplicate,
9985// return instructions to help enable tail call optimizations for this
9986// instruction.
9987bool AArch64TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
Eric Christopher114fa1c2016-02-29 22:50:49 +00009988 return CI->isTailCall();
Tim Northover3b0846e2014-05-24 12:50:23 +00009989}
9990
9991bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
9992 SDValue &Offset,
9993 ISD::MemIndexedMode &AM,
9994 bool &IsInc,
9995 SelectionDAG &DAG) const {
9996 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
9997 return false;
9998
9999 Base = Op->getOperand(0);
10000 // All of the indexed addressing mode instructions take a signed
10001 // 9 bit immediate offset.
10002 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
10003 int64_t RHSC = (int64_t)RHS->getZExtValue();
10004 if (RHSC >= 256 || RHSC <= -256)
10005 return false;
10006 IsInc = (Op->getOpcode() == ISD::ADD);
10007 Offset = Op->getOperand(1);
10008 return true;
10009 }
10010 return false;
10011}
10012
10013bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10014 SDValue &Offset,
10015 ISD::MemIndexedMode &AM,
10016 SelectionDAG &DAG) const {
10017 EVT VT;
10018 SDValue Ptr;
10019 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10020 VT = LD->getMemoryVT();
10021 Ptr = LD->getBasePtr();
10022 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10023 VT = ST->getMemoryVT();
10024 Ptr = ST->getBasePtr();
10025 } else
10026 return false;
10027
10028 bool IsInc;
10029 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
10030 return false;
10031 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
10032 return true;
10033}
10034
10035bool AArch64TargetLowering::getPostIndexedAddressParts(
10036 SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
10037 ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
10038 EVT VT;
10039 SDValue Ptr;
10040 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10041 VT = LD->getMemoryVT();
10042 Ptr = LD->getBasePtr();
10043 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10044 VT = ST->getMemoryVT();
10045 Ptr = ST->getBasePtr();
10046 } else
10047 return false;
10048
10049 bool IsInc;
10050 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
10051 return false;
10052 // Post-indexing updates the base, so it's not a valid transform
10053 // if that's not the same as the load's pointer.
10054 if (Ptr != Base)
10055 return false;
10056 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
10057 return true;
10058}
10059
Tim Northoverf8bfe212014-07-18 13:07:05 +000010060static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
10061 SelectionDAG &DAG) {
Tim Northoverf8bfe212014-07-18 13:07:05 +000010062 SDLoc DL(N);
10063 SDValue Op = N->getOperand(0);
Ahmed Bougacha87946322014-12-01 20:52:32 +000010064
10065 if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
10066 return;
10067
Tim Northoverf8bfe212014-07-18 13:07:05 +000010068 Op = SDValue(
10069 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
10070 DAG.getUNDEF(MVT::i32), Op,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010071 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
Tim Northoverf8bfe212014-07-18 13:07:05 +000010072 0);
10073 Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
10074 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
10075}
10076
Charlie Turner434d4592015-10-16 15:38:25 +000010077static void ReplaceReductionResults(SDNode *N,
10078 SmallVectorImpl<SDValue> &Results,
10079 SelectionDAG &DAG, unsigned InterOp,
10080 unsigned AcrossOp) {
10081 EVT LoVT, HiVT;
10082 SDValue Lo, Hi;
10083 SDLoc dl(N);
10084 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
10085 std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
10086 SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
10087 SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
10088 Results.push_back(SplitVal);
10089}
10090
Tim Northover2f32e7f2016-08-04 19:32:28 +000010091static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) {
10092 SDLoc DL(N);
10093 SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N);
10094 SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64,
10095 DAG.getNode(ISD::SRL, DL, MVT::i128, N,
10096 DAG.getConstant(64, DL, MVT::i64)));
10097 return std::make_pair(Lo, Hi);
10098}
10099
Tim Northovercdf15292016-04-14 17:03:29 +000010100static void ReplaceCMP_SWAP_128Results(SDNode *N,
10101 SmallVectorImpl<SDValue> & Results,
10102 SelectionDAG &DAG) {
10103 assert(N->getValueType(0) == MVT::i128 &&
10104 "AtomicCmpSwap on types less than 128 should be legal");
Tim Northover2f32e7f2016-08-04 19:32:28 +000010105 auto Desired = splitInt128(N->getOperand(2), DAG);
10106 auto New = splitInt128(N->getOperand(3), DAG);
10107 SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second,
10108 New.first, New.second, N->getOperand(0)};
Tim Northovercdf15292016-04-14 17:03:29 +000010109 SDNode *CmpSwap = DAG.getMachineNode(
10110 AArch64::CMP_SWAP_128, SDLoc(N),
10111 DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops);
10112
10113 MachineFunction &MF = DAG.getMachineFunction();
10114 MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1);
10115 MemOp[0] = cast<MemSDNode>(N)->getMemOperand();
10116 cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1);
10117
10118 Results.push_back(SDValue(CmpSwap, 0));
10119 Results.push_back(SDValue(CmpSwap, 1));
10120 Results.push_back(SDValue(CmpSwap, 3));
10121}
10122
Tim Northover3b0846e2014-05-24 12:50:23 +000010123void AArch64TargetLowering::ReplaceNodeResults(
10124 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
10125 switch (N->getOpcode()) {
10126 default:
10127 llvm_unreachable("Don't know how to custom expand this");
Tim Northoverf8bfe212014-07-18 13:07:05 +000010128 case ISD::BITCAST:
10129 ReplaceBITCASTResults(N, Results, DAG);
10130 return;
Charlie Turner434d4592015-10-16 15:38:25 +000010131 case AArch64ISD::SADDV:
10132 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
10133 return;
10134 case AArch64ISD::UADDV:
10135 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
10136 return;
10137 case AArch64ISD::SMINV:
10138 ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
10139 return;
10140 case AArch64ISD::UMINV:
10141 ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
10142 return;
10143 case AArch64ISD::SMAXV:
10144 ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
10145 return;
10146 case AArch64ISD::UMAXV:
10147 ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
10148 return;
Tim Northover3b0846e2014-05-24 12:50:23 +000010149 case ISD::FP_TO_UINT:
10150 case ISD::FP_TO_SINT:
10151 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
10152 // Let normal code take care of it by not adding anything to Results.
10153 return;
Tim Northovercdf15292016-04-14 17:03:29 +000010154 case ISD::ATOMIC_CMP_SWAP:
10155 ReplaceCMP_SWAP_128Results(N, Results, DAG);
10156 return;
Tim Northover3b0846e2014-05-24 12:50:23 +000010157 }
10158}
10159
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +000010160bool AArch64TargetLowering::useLoadStackGuardNode() const {
Tim Shene885d5e2016-04-19 19:40:37 +000010161 if (!Subtarget->isTargetAndroid())
10162 return true;
10163 return TargetLowering::useLoadStackGuardNode();
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +000010164}
10165
Sanjay Patel1dd15592015-07-28 23:05:48 +000010166unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
Hao Liu44e5d7a2014-11-21 06:39:58 +000010167 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
10168 // reciprocal if there are three or more FDIVs.
Sanjay Patel1dd15592015-07-28 23:05:48 +000010169 return 3;
Hao Liu44e5d7a2014-11-21 06:39:58 +000010170}
10171
Chandler Carruth9d010ff2014-07-03 00:23:43 +000010172TargetLoweringBase::LegalizeTypeAction
10173AArch64TargetLowering::getPreferredVectorAction(EVT VT) const {
10174 MVT SVT = VT.getSimpleVT();
10175 // During type legalization, we prefer to widen v1i8, v1i16, v1i32 to v8i8,
10176 // v4i16, v2i32 instead of to promote.
10177 if (SVT == MVT::v1i8 || SVT == MVT::v1i16 || SVT == MVT::v1i32
10178 || SVT == MVT::v1f32)
10179 return TypeWidenVector;
10180
10181 return TargetLoweringBase::getPreferredVectorAction(VT);
10182}
10183
Robin Morisseted3d48f2014-09-03 21:29:59 +000010184// Loads and stores less than 128-bits are already atomic; ones above that
10185// are doomed anyway, so defer to the default libcall and blame the OS when
10186// things go wrong.
10187bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
10188 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
10189 return Size == 128;
10190}
10191
10192// Loads and stores less than 128-bits are already atomic; ones above that
10193// are doomed anyway, so defer to the default libcall and blame the OS when
10194// things go wrong.
Ahmed Bougacha52468672015-09-11 17:08:28 +000010195TargetLowering::AtomicExpansionKind
10196AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
Robin Morisseted3d48f2014-09-03 21:29:59 +000010197 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
Ahmed Bougacha52468672015-09-11 17:08:28 +000010198 return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
Robin Morisseted3d48f2014-09-03 21:29:59 +000010199}
10200
10201// For the real atomic operations, we have ldxr/stxr up to 128 bits,
Ahmed Bougacha52468672015-09-11 17:08:28 +000010202TargetLowering::AtomicExpansionKind
JF Bastienf14889e2015-03-04 15:47:57 +000010203AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
Robin Morisseted3d48f2014-09-03 21:29:59 +000010204 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
Ahmed Bougacha9d677132015-09-11 17:08:17 +000010205 return Size <= 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
Robin Morisseted3d48f2014-09-03 21:29:59 +000010206}
10207
Ahmed Bougacha52468672015-09-11 17:08:28 +000010208bool AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
10209 AtomicCmpXchgInst *AI) const {
Tim Northovercdf15292016-04-14 17:03:29 +000010210 // At -O0, fast-regalloc cannot cope with the live vregs necessary to
10211 // implement cmpxchg without spilling. If the address being exchanged is also
10212 // on the stack and close enough to the spill slot, this can lead to a
10213 // situation where the monitor always gets cleared and the atomic operation
10214 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
10215 return getTargetMachine().getOptLevel() != 0;
Robin Morisset25c8e312014-09-17 00:06:58 +000010216}
10217
Tim Northover3b0846e2014-05-24 12:50:23 +000010218Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
10219 AtomicOrdering Ord) const {
10220 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10221 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
JF Bastien800f87a2016-04-06 21:19:33 +000010222 bool IsAcquire = isAcquireOrStronger(Ord);
Tim Northover3b0846e2014-05-24 12:50:23 +000010223
10224 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
10225 // intrinsic must return {i64, i64} and we have to recombine them into a
10226 // single i128 here.
10227 if (ValTy->getPrimitiveSizeInBits() == 128) {
10228 Intrinsic::ID Int =
10229 IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
10230 Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int);
10231
10232 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10233 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
10234
10235 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
10236 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
10237 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
10238 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
10239 return Builder.CreateOr(
10240 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
10241 }
10242
10243 Type *Tys[] = { Addr->getType() };
10244 Intrinsic::ID Int =
10245 IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
10246 Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int, Tys);
10247
10248 return Builder.CreateTruncOrBitCast(
10249 Builder.CreateCall(Ldxr, Addr),
10250 cast<PointerType>(Addr->getType())->getElementType());
10251}
10252
Ahmed Bougacha07a844d2015-09-22 17:21:44 +000010253void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
10254 IRBuilder<> &Builder) const {
10255 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10256 Builder.CreateCall(
10257 llvm::Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
10258}
10259
Tim Northover3b0846e2014-05-24 12:50:23 +000010260Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
10261 Value *Val, Value *Addr,
10262 AtomicOrdering Ord) const {
10263 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
JF Bastien800f87a2016-04-06 21:19:33 +000010264 bool IsRelease = isReleaseOrStronger(Ord);
Tim Northover3b0846e2014-05-24 12:50:23 +000010265
10266 // Since the intrinsics must have legal type, the i128 intrinsics take two
10267 // parameters: "i64, i64". We must marshal Val into the appropriate form
10268 // before the call.
10269 if (Val->getType()->getPrimitiveSizeInBits() == 128) {
10270 Intrinsic::ID Int =
10271 IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
10272 Function *Stxr = Intrinsic::getDeclaration(M, Int);
10273 Type *Int64Ty = Type::getInt64Ty(M->getContext());
10274
10275 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
10276 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
10277 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
David Blaikieff6409d2015-05-18 22:13:54 +000010278 return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
Tim Northover3b0846e2014-05-24 12:50:23 +000010279 }
10280
10281 Intrinsic::ID Int =
10282 IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
10283 Type *Tys[] = { Addr->getType() };
10284 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
10285
David Blaikieff6409d2015-05-18 22:13:54 +000010286 return Builder.CreateCall(Stxr,
10287 {Builder.CreateZExtOrBitCast(
10288 Val, Stxr->getFunctionType()->getParamType(0)),
10289 Addr});
Tim Northover3b0846e2014-05-24 12:50:23 +000010290}
Tim Northover3c55cca2014-11-27 21:02:42 +000010291
10292bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
10293 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
10294 return Ty->isArrayTy();
10295}
Matthias Braunaf7d7702015-07-16 20:02:37 +000010296
10297bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
10298 EVT) const {
10299 return false;
10300}
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000010301
Tim Shen00127562016-04-08 21:26:31 +000010302Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const {
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +000010303 if (!Subtarget->isTargetAndroid())
Tim Shen00127562016-04-08 21:26:31 +000010304 return TargetLowering::getIRStackGuard(IRB);
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +000010305
10306 // Android provides a fixed TLS slot for the stack cookie. See the definition
10307 // of TLS_SLOT_STACK_GUARD in
10308 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
10309 const unsigned TlsOffset = 0x28;
10310 Module *M = IRB.GetInsertBlock()->getParent()->getParent();
10311 Function *ThreadPointerFunc =
Marcin Koscielnicki3fdc2572016-04-19 20:51:05 +000010312 Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +000010313 return IRB.CreatePointerCast(
10314 IRB.CreateConstGEP1_32(IRB.CreateCall(ThreadPointerFunc), TlsOffset),
10315 Type::getInt8PtrTy(IRB.getContext())->getPointerTo(0));
10316}
10317
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000010318Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
10319 if (!Subtarget->isTargetAndroid())
10320 return TargetLowering::getSafeStackPointerLocation(IRB);
10321
10322 // Android provides a fixed TLS slot for the SafeStack pointer. See the
10323 // definition of TLS_SLOT_SAFESTACK in
10324 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
10325 const unsigned TlsOffset = 0x48;
10326 Module *M = IRB.GetInsertBlock()->getParent()->getParent();
10327 Function *ThreadPointerFunc =
Marcin Koscielnicki3fdc2572016-04-19 20:51:05 +000010328 Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000010329 return IRB.CreatePointerCast(
10330 IRB.CreateConstGEP1_32(IRB.CreateCall(ThreadPointerFunc), TlsOffset),
10331 Type::getInt8PtrTy(IRB.getContext())->getPointerTo(0));
10332}
Manman Rencbe4f942015-12-16 21:04:19 +000010333
10334void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
10335 // Update IsSplitCSR in AArch64unctionInfo.
10336 AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>();
10337 AFI->setIsSplitCSR(true);
10338}
10339
10340void AArch64TargetLowering::insertCopiesSplitCSR(
10341 MachineBasicBlock *Entry,
10342 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
10343 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
10344 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
10345 if (!IStart)
10346 return;
10347
10348 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10349 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
Manman Ren4632e8e2016-01-15 20:13:28 +000010350 MachineBasicBlock::iterator MBBI = Entry->begin();
Manman Rencbe4f942015-12-16 21:04:19 +000010351 for (const MCPhysReg *I = IStart; *I; ++I) {
10352 const TargetRegisterClass *RC = nullptr;
10353 if (AArch64::GPR64RegClass.contains(*I))
10354 RC = &AArch64::GPR64RegClass;
10355 else if (AArch64::FPR64RegClass.contains(*I))
10356 RC = &AArch64::FPR64RegClass;
10357 else
10358 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
10359
10360 unsigned NewVR = MRI->createVirtualRegister(RC);
10361 // Create copy from CSR to a virtual register.
10362 // FIXME: this currently does not emit CFI pseudo-instructions, it works
10363 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
10364 // nounwind. If we want to generalize this later, we may need to emit
10365 // CFI pseudo-instructions.
10366 assert(Entry->getParent()->getFunction()->hasFnAttribute(
10367 Attribute::NoUnwind) &&
10368 "Function should be nounwind in insertCopiesSplitCSR!");
10369 Entry->addLiveIn(*I);
Manman Ren4632e8e2016-01-15 20:13:28 +000010370 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
Manman Rencbe4f942015-12-16 21:04:19 +000010371 .addReg(*I);
10372
Manman Ren4632e8e2016-01-15 20:13:28 +000010373 // Insert the copy-back instructions right before the terminator.
Manman Rencbe4f942015-12-16 21:04:19 +000010374 for (auto *Exit : Exits)
Manman Ren4632e8e2016-01-15 20:13:28 +000010375 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
10376 TII->get(TargetOpcode::COPY), *I)
Manman Rencbe4f942015-12-16 21:04:19 +000010377 .addReg(NewVR);
10378 }
10379}
Haicheng Wu6a6bc752016-03-28 18:17:07 +000010380
10381bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeSet Attr) const {
10382 // Integer division on AArch64 is expensive. However, when aggressively
10383 // optimizing for code size, we prefer to use a div instruction, as it is
10384 // usually smaller than the alternative sequence.
10385 // The exception to this is vector division. Since AArch64 doesn't have vector
10386 // integer division, leaving the division as-is is a loss even in terms of
10387 // size, because it will have to be scalarized, while the alternative code
10388 // sequence can be performed in vector form.
10389 bool OptSize =
10390 Attr.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
10391 return OptSize && !VT.isVector();
10392}