blob: dea10218b58fe1eff42b6b251ba969a3268745c9 [file] [log] [blame]
Tim Northover3b0846e2014-05-24 12:50:23 +00001//===-- AArch64ISelLowering.cpp - AArch64 DAG Lowering Implementation ----===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the AArch64TargetLowering class.
11//
12//===----------------------------------------------------------------------===//
13
14#include "AArch64ISelLowering.h"
Tim Northover3c55cca2014-11-27 21:02:42 +000015#include "AArch64CallingConvention.h"
Benjamin Kramer1f8930e2014-07-25 11:42:14 +000016#include "AArch64MachineFunctionInfo.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000017#include "AArch64PerfectShuffle.h"
18#include "AArch64Subtarget.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000019#include "AArch64TargetMachine.h"
20#include "AArch64TargetObjectFile.h"
21#include "MCTargetDesc/AArch64AddressingModes.h"
22#include "llvm/ADT/Statistic.h"
23#include "llvm/CodeGen/CallingConvLower.h"
24#include "llvm/CodeGen/MachineFrameInfo.h"
25#include "llvm/CodeGen/MachineInstrBuilder.h"
26#include "llvm/CodeGen/MachineRegisterInfo.h"
27#include "llvm/IR/Function.h"
David Blaikie457343d2015-05-21 21:12:43 +000028#include "llvm/IR/GetElementPtrTypeIterator.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000029#include "llvm/IR/Intrinsics.h"
30#include "llvm/IR/Type.h"
31#include "llvm/Support/CommandLine.h"
32#include "llvm/Support/Debug.h"
33#include "llvm/Support/ErrorHandling.h"
34#include "llvm/Support/raw_ostream.h"
35#include "llvm/Target/TargetOptions.h"
36using namespace llvm;
37
38#define DEBUG_TYPE "aarch64-lower"
39
40STATISTIC(NumTailCalls, "Number of tail calls");
41STATISTIC(NumShiftInserts, "Number of vector shift inserts");
42
Tim Northover3b0846e2014-05-24 12:50:23 +000043// Place holder until extr generation is tested fully.
44static cl::opt<bool>
45EnableAArch64ExtrGeneration("aarch64-extr-generation", cl::Hidden,
46 cl::desc("Allow AArch64 (or (shift)(shift))->extract"),
47 cl::init(true));
48
49static cl::opt<bool>
50EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden,
Kristof Beylsaea84612015-03-04 09:12:08 +000051 cl::desc("Allow AArch64 SLI/SRI formation"),
52 cl::init(false));
53
54// FIXME: The necessary dtprel relocations don't seem to be supported
55// well in the GNU bfd and gold linkers at the moment. Therefore, by
56// default, for now, fall back to GeneralDynamic code generation.
57cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration(
58 "aarch64-elf-ldtls-generation", cl::Hidden,
59 cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
60 cl::init(false));
Tim Northover3b0846e2014-05-24 12:50:23 +000061
Matthias Braunaf7d7702015-07-16 20:02:37 +000062/// Value type used for condition codes.
63static const MVT MVT_CC = MVT::i32;
64
Eric Christopher905f12d2015-01-29 00:19:42 +000065AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
66 const AArch64Subtarget &STI)
67 : TargetLowering(TM), Subtarget(&STI) {
Tim Northover3b0846e2014-05-24 12:50:23 +000068
69 // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
70 // we have to make something up. Arbitrarily, choose ZeroOrOne.
71 setBooleanContents(ZeroOrOneBooleanContent);
72 // When comparing vectors the result sets the different elements in the
73 // vector to all-one or all-zero.
74 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
75
76 // Set up the register classes.
77 addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
78 addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
79
80 if (Subtarget->hasFPARMv8()) {
81 addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
82 addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
83 addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
84 addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
85 }
86
87 if (Subtarget->hasNEON()) {
88 addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
89 addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
90 // Someone set us up the NEON.
91 addDRTypeForNEON(MVT::v2f32);
92 addDRTypeForNEON(MVT::v8i8);
93 addDRTypeForNEON(MVT::v4i16);
94 addDRTypeForNEON(MVT::v2i32);
95 addDRTypeForNEON(MVT::v1i64);
96 addDRTypeForNEON(MVT::v1f64);
Oliver Stannard89d15422014-08-27 16:16:04 +000097 addDRTypeForNEON(MVT::v4f16);
Tim Northover3b0846e2014-05-24 12:50:23 +000098
99 addQRTypeForNEON(MVT::v4f32);
100 addQRTypeForNEON(MVT::v2f64);
101 addQRTypeForNEON(MVT::v16i8);
102 addQRTypeForNEON(MVT::v8i16);
103 addQRTypeForNEON(MVT::v4i32);
104 addQRTypeForNEON(MVT::v2i64);
Oliver Stannard89d15422014-08-27 16:16:04 +0000105 addQRTypeForNEON(MVT::v8f16);
Tim Northover3b0846e2014-05-24 12:50:23 +0000106 }
107
108 // Compute derived properties from the register classes
Eric Christopher23a3a7c2015-02-26 00:00:24 +0000109 computeRegisterProperties(Subtarget->getRegisterInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +0000110
111 // Provide all sorts of operation actions
112 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
113 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
114 setOperationAction(ISD::SETCC, MVT::i32, Custom);
115 setOperationAction(ISD::SETCC, MVT::i64, Custom);
116 setOperationAction(ISD::SETCC, MVT::f32, Custom);
117 setOperationAction(ISD::SETCC, MVT::f64, Custom);
118 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
119 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
120 setOperationAction(ISD::BR_CC, MVT::i64, Custom);
121 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
122 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
123 setOperationAction(ISD::SELECT, MVT::i32, Custom);
124 setOperationAction(ISD::SELECT, MVT::i64, Custom);
125 setOperationAction(ISD::SELECT, MVT::f32, Custom);
126 setOperationAction(ISD::SELECT, MVT::f64, Custom);
127 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
128 setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
129 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
130 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
131 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
132 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
133
134 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
135 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
136 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
137
138 setOperationAction(ISD::FREM, MVT::f32, Expand);
139 setOperationAction(ISD::FREM, MVT::f64, Expand);
140 setOperationAction(ISD::FREM, MVT::f80, Expand);
141
142 // Custom lowering hooks are needed for XOR
143 // to fold it into CSINC/CSINV.
144 setOperationAction(ISD::XOR, MVT::i32, Custom);
145 setOperationAction(ISD::XOR, MVT::i64, Custom);
146
147 // Virtually no operation on f128 is legal, but LLVM can't expand them when
148 // there's a valid register class, so we need custom operations in most cases.
149 setOperationAction(ISD::FABS, MVT::f128, Expand);
150 setOperationAction(ISD::FADD, MVT::f128, Custom);
151 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
152 setOperationAction(ISD::FCOS, MVT::f128, Expand);
153 setOperationAction(ISD::FDIV, MVT::f128, Custom);
154 setOperationAction(ISD::FMA, MVT::f128, Expand);
155 setOperationAction(ISD::FMUL, MVT::f128, Custom);
156 setOperationAction(ISD::FNEG, MVT::f128, Expand);
157 setOperationAction(ISD::FPOW, MVT::f128, Expand);
158 setOperationAction(ISD::FREM, MVT::f128, Expand);
159 setOperationAction(ISD::FRINT, MVT::f128, Expand);
160 setOperationAction(ISD::FSIN, MVT::f128, Expand);
161 setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
162 setOperationAction(ISD::FSQRT, MVT::f128, Expand);
163 setOperationAction(ISD::FSUB, MVT::f128, Custom);
164 setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
165 setOperationAction(ISD::SETCC, MVT::f128, Custom);
166 setOperationAction(ISD::BR_CC, MVT::f128, Custom);
167 setOperationAction(ISD::SELECT, MVT::f128, Custom);
168 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
169 setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
170
171 // Lowering for many of the conversions is actually specified by the non-f128
172 // type. The LowerXXX function will be trivial when f128 isn't involved.
173 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
174 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
175 setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
176 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
177 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
178 setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
179 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
180 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
181 setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
182 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
183 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
184 setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
185 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
186 setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
187
188 // Variable arguments.
189 setOperationAction(ISD::VASTART, MVT::Other, Custom);
190 setOperationAction(ISD::VAARG, MVT::Other, Custom);
191 setOperationAction(ISD::VACOPY, MVT::Other, Custom);
192 setOperationAction(ISD::VAEND, MVT::Other, Expand);
193
194 // Variable-sized objects.
195 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
196 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
197 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
198
Tim Northover3b0846e2014-05-24 12:50:23 +0000199 // Constant pool entries
200 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
201
202 // BlockAddress
203 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
204
205 // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
206 setOperationAction(ISD::ADDC, MVT::i32, Custom);
207 setOperationAction(ISD::ADDE, MVT::i32, Custom);
208 setOperationAction(ISD::SUBC, MVT::i32, Custom);
209 setOperationAction(ISD::SUBE, MVT::i32, Custom);
210 setOperationAction(ISD::ADDC, MVT::i64, Custom);
211 setOperationAction(ISD::ADDE, MVT::i64, Custom);
212 setOperationAction(ISD::SUBC, MVT::i64, Custom);
213 setOperationAction(ISD::SUBE, MVT::i64, Custom);
214
215 // AArch64 lacks both left-rotate and popcount instructions.
216 setOperationAction(ISD::ROTL, MVT::i32, Expand);
217 setOperationAction(ISD::ROTL, MVT::i64, Expand);
Charlie Turner458e79b2015-10-27 10:25:20 +0000218 for (MVT VT : MVT::vector_valuetypes()) {
219 setOperationAction(ISD::ROTL, VT, Expand);
220 setOperationAction(ISD::ROTR, VT, Expand);
221 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000222
223 // AArch64 doesn't have {U|S}MUL_LOHI.
224 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
225 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
226
227
228 // Expand the undefined-at-zero variants to cttz/ctlz to their defined-at-zero
229 // counterparts, which AArch64 supports directly.
230 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
231 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
232 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
233 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
234
235 setOperationAction(ISD::CTPOP, MVT::i32, Custom);
236 setOperationAction(ISD::CTPOP, MVT::i64, Custom);
237
238 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
239 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
Chad Rosierf3491492015-12-04 21:38:44 +0000240 for (MVT VT : MVT::vector_valuetypes()) {
241 setOperationAction(ISD::SDIVREM, VT, Expand);
242 setOperationAction(ISD::UDIVREM, VT, Expand);
243 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000244 setOperationAction(ISD::SREM, MVT::i32, Expand);
245 setOperationAction(ISD::SREM, MVT::i64, Expand);
246 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
247 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
248 setOperationAction(ISD::UREM, MVT::i32, Expand);
249 setOperationAction(ISD::UREM, MVT::i64, Expand);
250
251 // Custom lower Add/Sub/Mul with overflow.
252 setOperationAction(ISD::SADDO, MVT::i32, Custom);
253 setOperationAction(ISD::SADDO, MVT::i64, Custom);
254 setOperationAction(ISD::UADDO, MVT::i32, Custom);
255 setOperationAction(ISD::UADDO, MVT::i64, Custom);
256 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
257 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
258 setOperationAction(ISD::USUBO, MVT::i32, Custom);
259 setOperationAction(ISD::USUBO, MVT::i64, Custom);
260 setOperationAction(ISD::SMULO, MVT::i32, Custom);
261 setOperationAction(ISD::SMULO, MVT::i64, Custom);
262 setOperationAction(ISD::UMULO, MVT::i32, Custom);
263 setOperationAction(ISD::UMULO, MVT::i64, Custom);
264
265 setOperationAction(ISD::FSIN, MVT::f32, Expand);
266 setOperationAction(ISD::FSIN, MVT::f64, Expand);
267 setOperationAction(ISD::FCOS, MVT::f32, Expand);
268 setOperationAction(ISD::FCOS, MVT::f64, Expand);
269 setOperationAction(ISD::FPOW, MVT::f32, Expand);
270 setOperationAction(ISD::FPOW, MVT::f64, Expand);
271 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
272 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
273
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +0000274 // f16 is a storage-only type, always promote it to f32.
275 setOperationAction(ISD::SETCC, MVT::f16, Promote);
276 setOperationAction(ISD::BR_CC, MVT::f16, Promote);
277 setOperationAction(ISD::SELECT_CC, MVT::f16, Promote);
278 setOperationAction(ISD::SELECT, MVT::f16, Promote);
279 setOperationAction(ISD::FADD, MVT::f16, Promote);
280 setOperationAction(ISD::FSUB, MVT::f16, Promote);
281 setOperationAction(ISD::FMUL, MVT::f16, Promote);
282 setOperationAction(ISD::FDIV, MVT::f16, Promote);
283 setOperationAction(ISD::FREM, MVT::f16, Promote);
284 setOperationAction(ISD::FMA, MVT::f16, Promote);
285 setOperationAction(ISD::FNEG, MVT::f16, Promote);
286 setOperationAction(ISD::FABS, MVT::f16, Promote);
287 setOperationAction(ISD::FCEIL, MVT::f16, Promote);
288 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote);
289 setOperationAction(ISD::FCOS, MVT::f16, Promote);
290 setOperationAction(ISD::FFLOOR, MVT::f16, Promote);
291 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote);
292 setOperationAction(ISD::FPOW, MVT::f16, Promote);
293 setOperationAction(ISD::FPOWI, MVT::f16, Promote);
294 setOperationAction(ISD::FRINT, MVT::f16, Promote);
295 setOperationAction(ISD::FSIN, MVT::f16, Promote);
296 setOperationAction(ISD::FSINCOS, MVT::f16, Promote);
297 setOperationAction(ISD::FSQRT, MVT::f16, Promote);
298 setOperationAction(ISD::FEXP, MVT::f16, Promote);
299 setOperationAction(ISD::FEXP2, MVT::f16, Promote);
300 setOperationAction(ISD::FLOG, MVT::f16, Promote);
301 setOperationAction(ISD::FLOG2, MVT::f16, Promote);
302 setOperationAction(ISD::FLOG10, MVT::f16, Promote);
303 setOperationAction(ISD::FROUND, MVT::f16, Promote);
304 setOperationAction(ISD::FTRUNC, MVT::f16, Promote);
305 setOperationAction(ISD::FMINNUM, MVT::f16, Promote);
306 setOperationAction(ISD::FMAXNUM, MVT::f16, Promote);
James Molloy63be1982015-08-14 09:08:50 +0000307 setOperationAction(ISD::FMINNAN, MVT::f16, Promote);
308 setOperationAction(ISD::FMAXNAN, MVT::f16, Promote);
Oliver Stannardf5469be2014-08-18 14:22:39 +0000309
Oliver Stannard89d15422014-08-27 16:16:04 +0000310 // v4f16 is also a storage-only type, so promote it to v4f32 when that is
311 // known to be safe.
312 setOperationAction(ISD::FADD, MVT::v4f16, Promote);
313 setOperationAction(ISD::FSUB, MVT::v4f16, Promote);
314 setOperationAction(ISD::FMUL, MVT::v4f16, Promote);
315 setOperationAction(ISD::FDIV, MVT::v4f16, Promote);
316 setOperationAction(ISD::FP_EXTEND, MVT::v4f16, Promote);
317 setOperationAction(ISD::FP_ROUND, MVT::v4f16, Promote);
318 AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32);
319 AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32);
320 AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32);
321 AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32);
322 AddPromotedToType(ISD::FP_EXTEND, MVT::v4f16, MVT::v4f32);
323 AddPromotedToType(ISD::FP_ROUND, MVT::v4f16, MVT::v4f32);
324
325 // Expand all other v4f16 operations.
326 // FIXME: We could generate better code by promoting some operations to
327 // a pair of v4f32s
328 setOperationAction(ISD::FABS, MVT::v4f16, Expand);
329 setOperationAction(ISD::FCEIL, MVT::v4f16, Expand);
330 setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand);
331 setOperationAction(ISD::FCOS, MVT::v4f16, Expand);
332 setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand);
333 setOperationAction(ISD::FMA, MVT::v4f16, Expand);
334 setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand);
335 setOperationAction(ISD::FNEG, MVT::v4f16, Expand);
336 setOperationAction(ISD::FPOW, MVT::v4f16, Expand);
337 setOperationAction(ISD::FPOWI, MVT::v4f16, Expand);
338 setOperationAction(ISD::FREM, MVT::v4f16, Expand);
339 setOperationAction(ISD::FROUND, MVT::v4f16, Expand);
340 setOperationAction(ISD::FRINT, MVT::v4f16, Expand);
341 setOperationAction(ISD::FSIN, MVT::v4f16, Expand);
342 setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand);
343 setOperationAction(ISD::FSQRT, MVT::v4f16, Expand);
344 setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand);
345 setOperationAction(ISD::SETCC, MVT::v4f16, Expand);
346 setOperationAction(ISD::BR_CC, MVT::v4f16, Expand);
347 setOperationAction(ISD::SELECT, MVT::v4f16, Expand);
348 setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand);
349 setOperationAction(ISD::FEXP, MVT::v4f16, Expand);
350 setOperationAction(ISD::FEXP2, MVT::v4f16, Expand);
351 setOperationAction(ISD::FLOG, MVT::v4f16, Expand);
352 setOperationAction(ISD::FLOG2, MVT::v4f16, Expand);
353 setOperationAction(ISD::FLOG10, MVT::v4f16, Expand);
354
355
356 // v8f16 is also a storage-only type, so expand it.
357 setOperationAction(ISD::FABS, MVT::v8f16, Expand);
358 setOperationAction(ISD::FADD, MVT::v8f16, Expand);
359 setOperationAction(ISD::FCEIL, MVT::v8f16, Expand);
360 setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand);
361 setOperationAction(ISD::FCOS, MVT::v8f16, Expand);
362 setOperationAction(ISD::FDIV, MVT::v8f16, Expand);
363 setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand);
364 setOperationAction(ISD::FMA, MVT::v8f16, Expand);
365 setOperationAction(ISD::FMUL, MVT::v8f16, Expand);
366 setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand);
367 setOperationAction(ISD::FNEG, MVT::v8f16, Expand);
368 setOperationAction(ISD::FPOW, MVT::v8f16, Expand);
369 setOperationAction(ISD::FPOWI, MVT::v8f16, Expand);
370 setOperationAction(ISD::FREM, MVT::v8f16, Expand);
371 setOperationAction(ISD::FROUND, MVT::v8f16, Expand);
372 setOperationAction(ISD::FRINT, MVT::v8f16, Expand);
373 setOperationAction(ISD::FSIN, MVT::v8f16, Expand);
374 setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
375 setOperationAction(ISD::FSQRT, MVT::v8f16, Expand);
376 setOperationAction(ISD::FSUB, MVT::v8f16, Expand);
377 setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand);
378 setOperationAction(ISD::SETCC, MVT::v8f16, Expand);
379 setOperationAction(ISD::BR_CC, MVT::v8f16, Expand);
380 setOperationAction(ISD::SELECT, MVT::v8f16, Expand);
381 setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand);
382 setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand);
383 setOperationAction(ISD::FEXP, MVT::v8f16, Expand);
384 setOperationAction(ISD::FEXP2, MVT::v8f16, Expand);
385 setOperationAction(ISD::FLOG, MVT::v8f16, Expand);
386 setOperationAction(ISD::FLOG2, MVT::v8f16, Expand);
387 setOperationAction(ISD::FLOG10, MVT::v8f16, Expand);
388
Tim Northover3b0846e2014-05-24 12:50:23 +0000389 // AArch64 has implementations of a lot of rounding-like FP operations.
Benjamin Kramer57a3d082015-03-08 16:07:39 +0000390 for (MVT Ty : {MVT::f32, MVT::f64}) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000391 setOperationAction(ISD::FFLOOR, Ty, Legal);
392 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
393 setOperationAction(ISD::FCEIL, Ty, Legal);
394 setOperationAction(ISD::FRINT, Ty, Legal);
395 setOperationAction(ISD::FTRUNC, Ty, Legal);
396 setOperationAction(ISD::FROUND, Ty, Legal);
James Molloyb7b2a1e2015-08-11 12:06:37 +0000397 setOperationAction(ISD::FMINNUM, Ty, Legal);
398 setOperationAction(ISD::FMAXNUM, Ty, Legal);
James Molloy88edc822015-08-17 07:13:20 +0000399 setOperationAction(ISD::FMINNAN, Ty, Legal);
400 setOperationAction(ISD::FMAXNAN, Ty, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000401 }
402
403 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
404
Ahmed Bougachab0ff6432015-09-01 16:23:45 +0000405 // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
406 // This requires the Performance Monitors extension.
407 if (Subtarget->hasPerfMon())
408 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
409
Tim Northover3b0846e2014-05-24 12:50:23 +0000410 if (Subtarget->isTargetMachO()) {
411 // For iOS, we don't want to the normal expansion of a libcall to
412 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
413 // traffic.
414 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
415 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
416 } else {
417 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
418 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
419 }
420
Juergen Ributzka23266502014-12-10 19:43:32 +0000421 // Make floating-point constants legal for the large code model, so they don't
422 // become loads from the constant pool.
423 if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
424 setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
425 setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
426 }
427
Tim Northover3b0846e2014-05-24 12:50:23 +0000428 // AArch64 does not have floating-point extending loads, i1 sign-extending
429 // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000430 for (MVT VT : MVT::fp_valuetypes()) {
431 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
432 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
433 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
434 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
435 }
436 for (MVT VT : MVT::integer_valuetypes())
437 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
438
Tim Northover3b0846e2014-05-24 12:50:23 +0000439 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
440 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
441 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
442 setTruncStoreAction(MVT::f128, MVT::f80, Expand);
443 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
444 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
445 setTruncStoreAction(MVT::f128, MVT::f16, Expand);
Tim Northoverf8bfe212014-07-18 13:07:05 +0000446
447 setOperationAction(ISD::BITCAST, MVT::i16, Custom);
448 setOperationAction(ISD::BITCAST, MVT::f16, Custom);
449
Tim Northover3b0846e2014-05-24 12:50:23 +0000450 // Indexed loads and stores are supported.
451 for (unsigned im = (unsigned)ISD::PRE_INC;
452 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
453 setIndexedLoadAction(im, MVT::i8, Legal);
454 setIndexedLoadAction(im, MVT::i16, Legal);
455 setIndexedLoadAction(im, MVT::i32, Legal);
456 setIndexedLoadAction(im, MVT::i64, Legal);
457 setIndexedLoadAction(im, MVT::f64, Legal);
458 setIndexedLoadAction(im, MVT::f32, Legal);
Ahmed Bougachae0e12db2015-08-04 01:29:38 +0000459 setIndexedLoadAction(im, MVT::f16, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000460 setIndexedStoreAction(im, MVT::i8, Legal);
461 setIndexedStoreAction(im, MVT::i16, Legal);
462 setIndexedStoreAction(im, MVT::i32, Legal);
463 setIndexedStoreAction(im, MVT::i64, Legal);
464 setIndexedStoreAction(im, MVT::f64, Legal);
465 setIndexedStoreAction(im, MVT::f32, Legal);
Ahmed Bougachae0e12db2015-08-04 01:29:38 +0000466 setIndexedStoreAction(im, MVT::f16, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000467 }
468
469 // Trap.
470 setOperationAction(ISD::TRAP, MVT::Other, Legal);
471
472 // We combine OR nodes for bitfield operations.
473 setTargetDAGCombine(ISD::OR);
474
475 // Vector add and sub nodes may conceal a high-half opportunity.
476 // Also, try to fold ADD into CSINC/CSINV..
477 setTargetDAGCombine(ISD::ADD);
478 setTargetDAGCombine(ISD::SUB);
479
480 setTargetDAGCombine(ISD::XOR);
481 setTargetDAGCombine(ISD::SINT_TO_FP);
482 setTargetDAGCombine(ISD::UINT_TO_FP);
483
Chad Rosierfa30c9b2015-10-07 17:39:18 +0000484 setTargetDAGCombine(ISD::FP_TO_SINT);
485 setTargetDAGCombine(ISD::FP_TO_UINT);
Chad Rosier7c6ac2b2015-10-07 17:51:37 +0000486 setTargetDAGCombine(ISD::FDIV);
Chad Rosierfa30c9b2015-10-07 17:39:18 +0000487
Tim Northover3b0846e2014-05-24 12:50:23 +0000488 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
489
490 setTargetDAGCombine(ISD::ANY_EXTEND);
491 setTargetDAGCombine(ISD::ZERO_EXTEND);
492 setTargetDAGCombine(ISD::SIGN_EXTEND);
493 setTargetDAGCombine(ISD::BITCAST);
494 setTargetDAGCombine(ISD::CONCAT_VECTORS);
495 setTargetDAGCombine(ISD::STORE);
Tim Northover339c83e2015-11-10 00:44:23 +0000496 if (Subtarget->supportsAddressTopByteIgnored())
497 setTargetDAGCombine(ISD::LOAD);
Tim Northover3b0846e2014-05-24 12:50:23 +0000498
499 setTargetDAGCombine(ISD::MUL);
500
501 setTargetDAGCombine(ISD::SELECT);
502 setTargetDAGCombine(ISD::VSELECT);
503
504 setTargetDAGCombine(ISD::INTRINSIC_VOID);
505 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
506 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
Chad Rosier6c36eff2015-09-03 18:13:57 +0000507 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
Tim Northover3b0846e2014-05-24 12:50:23 +0000508
509 MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 8;
510 MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 4;
511 MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = 4;
512
513 setStackPointerRegisterToSaveRestore(AArch64::SP);
514
515 setSchedulingPreference(Sched::Hybrid);
516
517 // Enable TBZ/TBNZ
518 MaskAndBranchFoldingIsLegal = true;
Quentin Colombet6843ac42015-03-31 20:52:32 +0000519 EnableExtLdPromotion = true;
Tim Northover3b0846e2014-05-24 12:50:23 +0000520
521 setMinFunctionAlignment(2);
522
Tim Northover3b0846e2014-05-24 12:50:23 +0000523 setHasExtractBitsInsn(true);
524
Adhemerval Zanella7bc33192015-07-28 13:03:31 +0000525 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
526
Tim Northover3b0846e2014-05-24 12:50:23 +0000527 if (Subtarget->hasNEON()) {
528 // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
529 // silliness like this:
530 setOperationAction(ISD::FABS, MVT::v1f64, Expand);
531 setOperationAction(ISD::FADD, MVT::v1f64, Expand);
532 setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
533 setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
534 setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
535 setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
536 setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
537 setOperationAction(ISD::FMA, MVT::v1f64, Expand);
538 setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
539 setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
540 setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
541 setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
542 setOperationAction(ISD::FREM, MVT::v1f64, Expand);
543 setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
544 setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
545 setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
546 setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
547 setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
548 setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
549 setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
550 setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
551 setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
552 setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
553 setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
554 setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
555
556 setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
557 setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
558 setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
559 setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
560 setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
561
562 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
563
564 // AArch64 doesn't have a direct vector ->f32 conversion instructions for
565 // elements smaller than i32, so promote the input to i32 first.
566 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Promote);
567 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Promote);
568 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Promote);
569 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Promote);
Pirama Arumuga Nainarb1881532015-04-23 17:16:27 +0000570 // i8 and i16 vector elements also need promotion to i32 for v8i8 or v8i16
571 // -> v8f16 conversions.
572 setOperationAction(ISD::SINT_TO_FP, MVT::v8i8, Promote);
573 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Promote);
574 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
575 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Promote);
Tim Northover3b0846e2014-05-24 12:50:23 +0000576 // Similarly, there is no direct i32 -> f64 vector conversion instruction.
577 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
578 setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
579 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
580 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
Pirama Arumuga Nainarb1881532015-04-23 17:16:27 +0000581 // Or, direct i32 -> f16 vector conversion. Set it so custom, so the
582 // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
583 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
584 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000585
586 // AArch64 doesn't have MUL.2d:
587 setOperationAction(ISD::MUL, MVT::v2i64, Expand);
Chad Rosierd9d0f862014-10-08 02:31:24 +0000588 // Custom handling for some quad-vector types to detect MULL.
589 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
590 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
591 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
592
Tim Northover3b0846e2014-05-24 12:50:23 +0000593 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
594 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
595 // Likewise, narrowing and extending vector loads/stores aren't handled
596 // directly.
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000597 for (MVT VT : MVT::vector_valuetypes()) {
598 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000599
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000600 setOperationAction(ISD::MULHS, VT, Expand);
601 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
602 setOperationAction(ISD::MULHU, VT, Expand);
603 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000604
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000605 setOperationAction(ISD::BSWAP, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000606
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000607 for (MVT InnerVT : MVT::vector_valuetypes()) {
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000608 setTruncStoreAction(VT, InnerVT, Expand);
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000609 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
610 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
611 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
612 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000613 }
614
615 // AArch64 has implementations of a lot of rounding-like FP operations.
Benjamin Kramer57a3d082015-03-08 16:07:39 +0000616 for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000617 setOperationAction(ISD::FFLOOR, Ty, Legal);
618 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
619 setOperationAction(ISD::FCEIL, Ty, Legal);
620 setOperationAction(ISD::FRINT, Ty, Legal);
621 setOperationAction(ISD::FTRUNC, Ty, Legal);
622 setOperationAction(ISD::FROUND, Ty, Legal);
623 }
624 }
James Molloyf089ab72014-08-06 10:42:18 +0000625
626 // Prefer likely predicted branches to selects on out-of-order cores.
627 if (Subtarget->isCortexA57())
628 PredictableSelectIsExpensive = true;
Tim Northover3b0846e2014-05-24 12:50:23 +0000629}
630
631void AArch64TargetLowering::addTypeForNEON(EVT VT, EVT PromotedBitwiseVT) {
Jiangning Liu08f4cda2014-08-29 01:31:42 +0000632 if (VT == MVT::v2f32 || VT == MVT::v4f16) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000633 setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
634 AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i32);
635
636 setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
637 AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i32);
Jiangning Liu08f4cda2014-08-29 01:31:42 +0000638 } else if (VT == MVT::v2f64 || VT == MVT::v4f32 || VT == MVT::v8f16) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000639 setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
640 AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i64);
641
642 setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
643 AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i64);
644 }
645
646 // Mark vector float intrinsics as expand.
647 if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
648 setOperationAction(ISD::FSIN, VT.getSimpleVT(), Expand);
649 setOperationAction(ISD::FCOS, VT.getSimpleVT(), Expand);
650 setOperationAction(ISD::FPOWI, VT.getSimpleVT(), Expand);
651 setOperationAction(ISD::FPOW, VT.getSimpleVT(), Expand);
652 setOperationAction(ISD::FLOG, VT.getSimpleVT(), Expand);
653 setOperationAction(ISD::FLOG2, VT.getSimpleVT(), Expand);
654 setOperationAction(ISD::FLOG10, VT.getSimpleVT(), Expand);
655 setOperationAction(ISD::FEXP, VT.getSimpleVT(), Expand);
656 setOperationAction(ISD::FEXP2, VT.getSimpleVT(), Expand);
Ahmed Bougachab0ae36f2015-08-04 00:42:34 +0000657
658 // But we do support custom-lowering for FCOPYSIGN.
659 setOperationAction(ISD::FCOPYSIGN, VT.getSimpleVT(), Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000660 }
661
662 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT.getSimpleVT(), Custom);
663 setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getSimpleVT(), Custom);
664 setOperationAction(ISD::BUILD_VECTOR, VT.getSimpleVT(), Custom);
665 setOperationAction(ISD::VECTOR_SHUFFLE, VT.getSimpleVT(), Custom);
666 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT.getSimpleVT(), Custom);
667 setOperationAction(ISD::SRA, VT.getSimpleVT(), Custom);
668 setOperationAction(ISD::SRL, VT.getSimpleVT(), Custom);
669 setOperationAction(ISD::SHL, VT.getSimpleVT(), Custom);
670 setOperationAction(ISD::AND, VT.getSimpleVT(), Custom);
671 setOperationAction(ISD::OR, VT.getSimpleVT(), Custom);
672 setOperationAction(ISD::SETCC, VT.getSimpleVT(), Custom);
673 setOperationAction(ISD::CONCAT_VECTORS, VT.getSimpleVT(), Legal);
674
675 setOperationAction(ISD::SELECT, VT.getSimpleVT(), Expand);
676 setOperationAction(ISD::SELECT_CC, VT.getSimpleVT(), Expand);
677 setOperationAction(ISD::VSELECT, VT.getSimpleVT(), Expand);
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000678 for (MVT InnerVT : MVT::all_valuetypes())
679 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT.getSimpleVT(), Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000680
681 // CNT supports only B element sizes.
682 if (VT != MVT::v8i8 && VT != MVT::v16i8)
683 setOperationAction(ISD::CTPOP, VT.getSimpleVT(), Expand);
684
685 setOperationAction(ISD::UDIV, VT.getSimpleVT(), Expand);
686 setOperationAction(ISD::SDIV, VT.getSimpleVT(), Expand);
687 setOperationAction(ISD::UREM, VT.getSimpleVT(), Expand);
688 setOperationAction(ISD::SREM, VT.getSimpleVT(), Expand);
689 setOperationAction(ISD::FREM, VT.getSimpleVT(), Expand);
690
691 setOperationAction(ISD::FP_TO_SINT, VT.getSimpleVT(), Custom);
692 setOperationAction(ISD::FP_TO_UINT, VT.getSimpleVT(), Custom);
693
Hal Finkelcd8664c2015-12-11 23:11:52 +0000694 // [SU][MIN|MAX] are available for all NEON types apart from i64.
James Molloycfb04432015-05-15 16:15:57 +0000695 if (!VT.isFloatingPoint() &&
696 VT.getSimpleVT() != MVT::v2i64 && VT.getSimpleVT() != MVT::v1i64)
Hal Finkelcd8664c2015-12-11 23:11:52 +0000697 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
James Molloycfb04432015-05-15 16:15:57 +0000698 setOperationAction(Opcode, VT.getSimpleVT(), Legal);
699
James Molloy63be1982015-08-14 09:08:50 +0000700 // F[MIN|MAX][NUM|NAN] are available for all FP NEON types (not f16 though!).
701 if (VT.isFloatingPoint() && VT.getVectorElementType() != MVT::f16)
James Molloyb7b2a1e2015-08-11 12:06:37 +0000702 for (unsigned Opcode : {ISD::FMINNAN, ISD::FMAXNAN,
703 ISD::FMINNUM, ISD::FMAXNUM})
James Molloyedf38f02015-08-11 12:06:33 +0000704 setOperationAction(Opcode, VT.getSimpleVT(), Legal);
705
Tim Northover3b0846e2014-05-24 12:50:23 +0000706 if (Subtarget->isLittleEndian()) {
707 for (unsigned im = (unsigned)ISD::PRE_INC;
708 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
709 setIndexedLoadAction(im, VT.getSimpleVT(), Legal);
710 setIndexedStoreAction(im, VT.getSimpleVT(), Legal);
711 }
712 }
713}
714
715void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
716 addRegisterClass(VT, &AArch64::FPR64RegClass);
717 addTypeForNEON(VT, MVT::v2i32);
718}
719
720void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
721 addRegisterClass(VT, &AArch64::FPR128RegClass);
722 addTypeForNEON(VT, MVT::v4i32);
723}
724
Mehdi Amini44ede332015-07-09 02:09:04 +0000725EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
726 EVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +0000727 if (!VT.isVector())
728 return MVT::i32;
729 return VT.changeVectorElementTypeToInteger();
730}
731
732/// computeKnownBitsForTargetNode - Determine which of the bits specified in
733/// Mask are known to be either zero or one and return them in the
734/// KnownZero/KnownOne bitsets.
735void AArch64TargetLowering::computeKnownBitsForTargetNode(
736 const SDValue Op, APInt &KnownZero, APInt &KnownOne,
737 const SelectionDAG &DAG, unsigned Depth) const {
738 switch (Op.getOpcode()) {
739 default:
740 break;
741 case AArch64ISD::CSEL: {
742 APInt KnownZero2, KnownOne2;
743 DAG.computeKnownBits(Op->getOperand(0), KnownZero, KnownOne, Depth + 1);
744 DAG.computeKnownBits(Op->getOperand(1), KnownZero2, KnownOne2, Depth + 1);
745 KnownZero &= KnownZero2;
746 KnownOne &= KnownOne2;
747 break;
748 }
749 case ISD::INTRINSIC_W_CHAIN: {
Jun Bum Lim4d3c5982015-09-08 16:11:22 +0000750 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +0000751 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
752 switch (IntID) {
753 default: return;
754 case Intrinsic::aarch64_ldaxr:
755 case Intrinsic::aarch64_ldxr: {
756 unsigned BitWidth = KnownOne.getBitWidth();
757 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
758 unsigned MemBits = VT.getScalarType().getSizeInBits();
759 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
760 return;
761 }
762 }
763 break;
764 }
765 case ISD::INTRINSIC_WO_CHAIN:
766 case ISD::INTRINSIC_VOID: {
767 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
768 switch (IntNo) {
769 default:
770 break;
771 case Intrinsic::aarch64_neon_umaxv:
772 case Intrinsic::aarch64_neon_uminv: {
773 // Figure out the datatype of the vector operand. The UMINV instruction
774 // will zero extend the result, so we can mark as known zero all the
775 // bits larger than the element datatype. 32-bit or larget doesn't need
776 // this as those are legal types and will be handled by isel directly.
777 MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
778 unsigned BitWidth = KnownZero.getBitWidth();
779 if (VT == MVT::v8i8 || VT == MVT::v16i8) {
780 assert(BitWidth >= 8 && "Unexpected width!");
781 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
782 KnownZero |= Mask;
783 } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
784 assert(BitWidth >= 16 && "Unexpected width!");
785 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
786 KnownZero |= Mask;
787 }
788 break;
789 } break;
790 }
791 }
792 }
793}
794
Mehdi Aminieaabc512015-07-09 15:12:23 +0000795MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
796 EVT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +0000797 return MVT::i64;
798}
799
Akira Hatanakaf53b0402015-07-29 14:17:26 +0000800bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
801 unsigned AddrSpace,
802 unsigned Align,
803 bool *Fast) const {
804 if (Subtarget->requiresStrictAlign())
805 return false;
Sanjay Patelbbbf9a12015-09-25 21:49:48 +0000806
807 // FIXME: This is mostly true for Cyclone, but not necessarily others.
808 if (Fast) {
809 // FIXME: Define an attribute for slow unaligned accesses instead of
810 // relying on the CPU type as a proxy.
811 // On Cyclone, unaligned 128-bit stores are slow.
812 *Fast = !Subtarget->isCyclone() || VT.getStoreSize() != 16 ||
813 // See comments in performSTORECombine() for more details about
814 // these conditions.
815
816 // Code that uses clang vector extensions can mark that it
817 // wants unaligned accesses to be treated as fast by
818 // underspecifying alignment to be 1 or 2.
819 Align <= 2 ||
820
821 // Disregard v2i64. Memcpy lowering produces those and splitting
822 // them regresses performance on micro-benchmarks and olden/bh.
823 VT == MVT::v2i64;
824 }
Akira Hatanakaf53b0402015-07-29 14:17:26 +0000825 return true;
826}
827
Tim Northover3b0846e2014-05-24 12:50:23 +0000828FastISel *
829AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
830 const TargetLibraryInfo *libInfo) const {
831 return AArch64::createFastISel(funcInfo, libInfo);
832}
833
834const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
Matthias Braund04893f2015-05-07 21:33:59 +0000835 switch ((AArch64ISD::NodeType)Opcode) {
836 case AArch64ISD::FIRST_NUMBER: break;
Tim Northover3b0846e2014-05-24 12:50:23 +0000837 case AArch64ISD::CALL: return "AArch64ISD::CALL";
838 case AArch64ISD::ADRP: return "AArch64ISD::ADRP";
839 case AArch64ISD::ADDlow: return "AArch64ISD::ADDlow";
840 case AArch64ISD::LOADgot: return "AArch64ISD::LOADgot";
841 case AArch64ISD::RET_FLAG: return "AArch64ISD::RET_FLAG";
842 case AArch64ISD::BRCOND: return "AArch64ISD::BRCOND";
843 case AArch64ISD::CSEL: return "AArch64ISD::CSEL";
844 case AArch64ISD::FCSEL: return "AArch64ISD::FCSEL";
845 case AArch64ISD::CSINV: return "AArch64ISD::CSINV";
846 case AArch64ISD::CSNEG: return "AArch64ISD::CSNEG";
847 case AArch64ISD::CSINC: return "AArch64ISD::CSINC";
848 case AArch64ISD::THREAD_POINTER: return "AArch64ISD::THREAD_POINTER";
Kristof Beylsaea84612015-03-04 09:12:08 +0000849 case AArch64ISD::TLSDESC_CALLSEQ: return "AArch64ISD::TLSDESC_CALLSEQ";
Tim Northover3b0846e2014-05-24 12:50:23 +0000850 case AArch64ISD::ADC: return "AArch64ISD::ADC";
851 case AArch64ISD::SBC: return "AArch64ISD::SBC";
852 case AArch64ISD::ADDS: return "AArch64ISD::ADDS";
853 case AArch64ISD::SUBS: return "AArch64ISD::SUBS";
854 case AArch64ISD::ADCS: return "AArch64ISD::ADCS";
855 case AArch64ISD::SBCS: return "AArch64ISD::SBCS";
856 case AArch64ISD::ANDS: return "AArch64ISD::ANDS";
Matthias Braunaf7d7702015-07-16 20:02:37 +0000857 case AArch64ISD::CCMP: return "AArch64ISD::CCMP";
858 case AArch64ISD::CCMN: return "AArch64ISD::CCMN";
859 case AArch64ISD::FCCMP: return "AArch64ISD::FCCMP";
Tim Northover3b0846e2014-05-24 12:50:23 +0000860 case AArch64ISD::FCMP: return "AArch64ISD::FCMP";
Tim Northover3b0846e2014-05-24 12:50:23 +0000861 case AArch64ISD::DUP: return "AArch64ISD::DUP";
862 case AArch64ISD::DUPLANE8: return "AArch64ISD::DUPLANE8";
863 case AArch64ISD::DUPLANE16: return "AArch64ISD::DUPLANE16";
864 case AArch64ISD::DUPLANE32: return "AArch64ISD::DUPLANE32";
865 case AArch64ISD::DUPLANE64: return "AArch64ISD::DUPLANE64";
866 case AArch64ISD::MOVI: return "AArch64ISD::MOVI";
867 case AArch64ISD::MOVIshift: return "AArch64ISD::MOVIshift";
868 case AArch64ISD::MOVIedit: return "AArch64ISD::MOVIedit";
869 case AArch64ISD::MOVImsl: return "AArch64ISD::MOVImsl";
870 case AArch64ISD::FMOV: return "AArch64ISD::FMOV";
871 case AArch64ISD::MVNIshift: return "AArch64ISD::MVNIshift";
872 case AArch64ISD::MVNImsl: return "AArch64ISD::MVNImsl";
873 case AArch64ISD::BICi: return "AArch64ISD::BICi";
874 case AArch64ISD::ORRi: return "AArch64ISD::ORRi";
875 case AArch64ISD::BSL: return "AArch64ISD::BSL";
876 case AArch64ISD::NEG: return "AArch64ISD::NEG";
877 case AArch64ISD::EXTR: return "AArch64ISD::EXTR";
878 case AArch64ISD::ZIP1: return "AArch64ISD::ZIP1";
879 case AArch64ISD::ZIP2: return "AArch64ISD::ZIP2";
880 case AArch64ISD::UZP1: return "AArch64ISD::UZP1";
881 case AArch64ISD::UZP2: return "AArch64ISD::UZP2";
882 case AArch64ISD::TRN1: return "AArch64ISD::TRN1";
883 case AArch64ISD::TRN2: return "AArch64ISD::TRN2";
884 case AArch64ISD::REV16: return "AArch64ISD::REV16";
885 case AArch64ISD::REV32: return "AArch64ISD::REV32";
886 case AArch64ISD::REV64: return "AArch64ISD::REV64";
887 case AArch64ISD::EXT: return "AArch64ISD::EXT";
888 case AArch64ISD::VSHL: return "AArch64ISD::VSHL";
889 case AArch64ISD::VLSHR: return "AArch64ISD::VLSHR";
890 case AArch64ISD::VASHR: return "AArch64ISD::VASHR";
891 case AArch64ISD::CMEQ: return "AArch64ISD::CMEQ";
892 case AArch64ISD::CMGE: return "AArch64ISD::CMGE";
893 case AArch64ISD::CMGT: return "AArch64ISD::CMGT";
894 case AArch64ISD::CMHI: return "AArch64ISD::CMHI";
895 case AArch64ISD::CMHS: return "AArch64ISD::CMHS";
896 case AArch64ISD::FCMEQ: return "AArch64ISD::FCMEQ";
897 case AArch64ISD::FCMGE: return "AArch64ISD::FCMGE";
898 case AArch64ISD::FCMGT: return "AArch64ISD::FCMGT";
899 case AArch64ISD::CMEQz: return "AArch64ISD::CMEQz";
900 case AArch64ISD::CMGEz: return "AArch64ISD::CMGEz";
901 case AArch64ISD::CMGTz: return "AArch64ISD::CMGTz";
902 case AArch64ISD::CMLEz: return "AArch64ISD::CMLEz";
903 case AArch64ISD::CMLTz: return "AArch64ISD::CMLTz";
904 case AArch64ISD::FCMEQz: return "AArch64ISD::FCMEQz";
905 case AArch64ISD::FCMGEz: return "AArch64ISD::FCMGEz";
906 case AArch64ISD::FCMGTz: return "AArch64ISD::FCMGTz";
907 case AArch64ISD::FCMLEz: return "AArch64ISD::FCMLEz";
908 case AArch64ISD::FCMLTz: return "AArch64ISD::FCMLTz";
Ahmed Bougachafab58922015-03-10 20:45:38 +0000909 case AArch64ISD::SADDV: return "AArch64ISD::SADDV";
910 case AArch64ISD::UADDV: return "AArch64ISD::UADDV";
911 case AArch64ISD::SMINV: return "AArch64ISD::SMINV";
912 case AArch64ISD::UMINV: return "AArch64ISD::UMINV";
913 case AArch64ISD::SMAXV: return "AArch64ISD::SMAXV";
914 case AArch64ISD::UMAXV: return "AArch64ISD::UMAXV";
Tim Northover3b0846e2014-05-24 12:50:23 +0000915 case AArch64ISD::NOT: return "AArch64ISD::NOT";
916 case AArch64ISD::BIT: return "AArch64ISD::BIT";
917 case AArch64ISD::CBZ: return "AArch64ISD::CBZ";
918 case AArch64ISD::CBNZ: return "AArch64ISD::CBNZ";
919 case AArch64ISD::TBZ: return "AArch64ISD::TBZ";
920 case AArch64ISD::TBNZ: return "AArch64ISD::TBNZ";
921 case AArch64ISD::TC_RETURN: return "AArch64ISD::TC_RETURN";
Matthias Braund04893f2015-05-07 21:33:59 +0000922 case AArch64ISD::PREFETCH: return "AArch64ISD::PREFETCH";
Tim Northover3b0846e2014-05-24 12:50:23 +0000923 case AArch64ISD::SITOF: return "AArch64ISD::SITOF";
924 case AArch64ISD::UITOF: return "AArch64ISD::UITOF";
Asiri Rathnayake530b3ed2014-10-01 09:59:45 +0000925 case AArch64ISD::NVCAST: return "AArch64ISD::NVCAST";
Tim Northover3b0846e2014-05-24 12:50:23 +0000926 case AArch64ISD::SQSHL_I: return "AArch64ISD::SQSHL_I";
927 case AArch64ISD::UQSHL_I: return "AArch64ISD::UQSHL_I";
928 case AArch64ISD::SRSHR_I: return "AArch64ISD::SRSHR_I";
929 case AArch64ISD::URSHR_I: return "AArch64ISD::URSHR_I";
930 case AArch64ISD::SQSHLU_I: return "AArch64ISD::SQSHLU_I";
931 case AArch64ISD::WrapperLarge: return "AArch64ISD::WrapperLarge";
932 case AArch64ISD::LD2post: return "AArch64ISD::LD2post";
933 case AArch64ISD::LD3post: return "AArch64ISD::LD3post";
934 case AArch64ISD::LD4post: return "AArch64ISD::LD4post";
935 case AArch64ISD::ST2post: return "AArch64ISD::ST2post";
936 case AArch64ISD::ST3post: return "AArch64ISD::ST3post";
937 case AArch64ISD::ST4post: return "AArch64ISD::ST4post";
938 case AArch64ISD::LD1x2post: return "AArch64ISD::LD1x2post";
939 case AArch64ISD::LD1x3post: return "AArch64ISD::LD1x3post";
940 case AArch64ISD::LD1x4post: return "AArch64ISD::LD1x4post";
941 case AArch64ISD::ST1x2post: return "AArch64ISD::ST1x2post";
942 case AArch64ISD::ST1x3post: return "AArch64ISD::ST1x3post";
943 case AArch64ISD::ST1x4post: return "AArch64ISD::ST1x4post";
944 case AArch64ISD::LD1DUPpost: return "AArch64ISD::LD1DUPpost";
945 case AArch64ISD::LD2DUPpost: return "AArch64ISD::LD2DUPpost";
946 case AArch64ISD::LD3DUPpost: return "AArch64ISD::LD3DUPpost";
947 case AArch64ISD::LD4DUPpost: return "AArch64ISD::LD4DUPpost";
948 case AArch64ISD::LD1LANEpost: return "AArch64ISD::LD1LANEpost";
949 case AArch64ISD::LD2LANEpost: return "AArch64ISD::LD2LANEpost";
950 case AArch64ISD::LD3LANEpost: return "AArch64ISD::LD3LANEpost";
951 case AArch64ISD::LD4LANEpost: return "AArch64ISD::LD4LANEpost";
952 case AArch64ISD::ST2LANEpost: return "AArch64ISD::ST2LANEpost";
953 case AArch64ISD::ST3LANEpost: return "AArch64ISD::ST3LANEpost";
954 case AArch64ISD::ST4LANEpost: return "AArch64ISD::ST4LANEpost";
Chad Rosierd9d0f862014-10-08 02:31:24 +0000955 case AArch64ISD::SMULL: return "AArch64ISD::SMULL";
956 case AArch64ISD::UMULL: return "AArch64ISD::UMULL";
Tim Northover3b0846e2014-05-24 12:50:23 +0000957 }
Matthias Braund04893f2015-05-07 21:33:59 +0000958 return nullptr;
Tim Northover3b0846e2014-05-24 12:50:23 +0000959}
960
961MachineBasicBlock *
962AArch64TargetLowering::EmitF128CSEL(MachineInstr *MI,
963 MachineBasicBlock *MBB) const {
964 // We materialise the F128CSEL pseudo-instruction as some control flow and a
965 // phi node:
966
967 // OrigBB:
968 // [... previous instrs leading to comparison ...]
969 // b.ne TrueBB
970 // b EndBB
971 // TrueBB:
972 // ; Fallthrough
973 // EndBB:
974 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
975
Tim Northover3b0846e2014-05-24 12:50:23 +0000976 MachineFunction *MF = MBB->getParent();
Eric Christopher905f12d2015-01-29 00:19:42 +0000977 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +0000978 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
979 DebugLoc DL = MI->getDebugLoc();
Duncan P. N. Exon Smithd3b9df02015-10-13 20:02:15 +0000980 MachineFunction::iterator It = ++MBB->getIterator();
Tim Northover3b0846e2014-05-24 12:50:23 +0000981
982 unsigned DestReg = MI->getOperand(0).getReg();
983 unsigned IfTrueReg = MI->getOperand(1).getReg();
984 unsigned IfFalseReg = MI->getOperand(2).getReg();
985 unsigned CondCode = MI->getOperand(3).getImm();
986 bool NZCVKilled = MI->getOperand(4).isKill();
987
988 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
989 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
990 MF->insert(It, TrueBB);
991 MF->insert(It, EndBB);
992
993 // Transfer rest of current basic-block to EndBB
994 EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
995 MBB->end());
996 EndBB->transferSuccessorsAndUpdatePHIs(MBB);
997
998 BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
999 BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
1000 MBB->addSuccessor(TrueBB);
1001 MBB->addSuccessor(EndBB);
1002
1003 // TrueBB falls through to the end.
1004 TrueBB->addSuccessor(EndBB);
1005
1006 if (!NZCVKilled) {
1007 TrueBB->addLiveIn(AArch64::NZCV);
1008 EndBB->addLiveIn(AArch64::NZCV);
1009 }
1010
1011 BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
1012 .addReg(IfTrueReg)
1013 .addMBB(TrueBB)
1014 .addReg(IfFalseReg)
1015 .addMBB(MBB);
1016
1017 MI->eraseFromParent();
1018 return EndBB;
1019}
1020
1021MachineBasicBlock *
1022AArch64TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1023 MachineBasicBlock *BB) const {
1024 switch (MI->getOpcode()) {
1025 default:
1026#ifndef NDEBUG
1027 MI->dump();
1028#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:
1182 Invert = true; // Fallthrough
1183 case ISD::SETO:
1184 CondCode = AArch64CC::MI;
1185 CondCode2 = AArch64CC::GE;
1186 break;
1187 case ISD::SETUEQ:
1188 case ISD::SETULT:
1189 case ISD::SETULE:
1190 case ISD::SETUGT:
1191 case ISD::SETUGE:
1192 // All of the compare-mask comparisons are ordered, but we can switch
1193 // between the two by a double inversion. E.g. ULE == !OGT.
1194 Invert = true;
1195 changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1196 break;
1197 }
1198}
1199
1200static bool isLegalArithImmed(uint64_t C) {
1201 // Matches AArch64DAGToDAGISel::SelectArithImmed().
1202 return (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1203}
1204
1205static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1206 SDLoc dl, SelectionDAG &DAG) {
1207 EVT VT = LHS.getValueType();
1208
1209 if (VT.isFloatingPoint())
1210 return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
1211
1212 // The CMP instruction is just an alias for SUBS, and representing it as
1213 // SUBS means that it's possible to get CSE with subtract operations.
1214 // A later phase can perform the optimization of setting the destination
1215 // register to WZR/XZR if it ends up being unused.
1216 unsigned Opcode = AArch64ISD::SUBS;
1217
Artyom Skrobov314ee042015-11-25 19:41:11 +00001218 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001219 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1220 // We'd like to combine a (CMP op1, (sub 0, op2) into a CMN instruction on
1221 // the grounds that "op1 - (-op2) == op1 + op2". However, the C and V flags
1222 // can be set differently by this operation. It comes down to whether
1223 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1224 // everything is fine. If not then the optimization is wrong. Thus general
1225 // comparisons are only valid if op2 != 0.
1226
1227 // So, finally, the only LLVM-native comparisons that don't mention C and V
1228 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1229 // the absence of information about op2.
1230 Opcode = AArch64ISD::ADDS;
1231 RHS = RHS.getOperand(1);
Artyom Skrobov314ee042015-11-25 19:41:11 +00001232 } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001233 !isUnsignedIntSetCC(CC)) {
1234 // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1235 // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1236 // of the signed comparisons.
1237 Opcode = AArch64ISD::ANDS;
1238 RHS = LHS.getOperand(1);
1239 LHS = LHS.getOperand(0);
1240 }
1241
Matthias Braunaf7d7702015-07-16 20:02:37 +00001242 return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
Tim Northover3b0846e2014-05-24 12:50:23 +00001243 .getValue(1);
1244}
1245
Matthias Braunaf7d7702015-07-16 20:02:37 +00001246/// \defgroup AArch64CCMP CMP;CCMP matching
1247///
1248/// These functions deal with the formation of CMP;CCMP;... sequences.
1249/// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1250/// a comparison. They set the NZCV flags to a predefined value if their
1251/// predicate is false. This allows to express arbitrary conjunctions, for
1252/// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B))))"
1253/// expressed as:
1254/// cmp A
1255/// ccmp B, inv(CB), CA
1256/// check for CB flags
1257///
1258/// In general we can create code for arbitrary "... (and (and A B) C)"
1259/// sequences. We can also implement some "or" expressions, because "(or A B)"
1260/// is equivalent to "not (and (not A) (not B))" and we can implement some
1261/// negation operations:
1262/// We can negate the results of a single comparison by inverting the flags
1263/// used when the predicate fails and inverting the flags tested in the next
1264/// instruction; We can also negate the results of the whole previous
1265/// conditional compare sequence by inverting the flags tested in the next
1266/// instruction. However there is no way to negate the result of a partial
1267/// sequence.
1268///
1269/// Therefore on encountering an "or" expression we can negate the subtree on
1270/// one side and have to be able to push the negate to the leafs of the subtree
1271/// on the other side (see also the comments in code). As complete example:
1272/// "or (or (setCA (cmp A)) (setCB (cmp B)))
1273/// (and (setCC (cmp C)) (setCD (cmp D)))"
1274/// is transformed to
1275/// "not (and (not (and (setCC (cmp C)) (setCC (cmp D))))
1276/// (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1277/// and implemented as:
1278/// cmp C
1279/// ccmp D, inv(CD), CC
1280/// ccmp A, CA, inv(CD)
1281/// ccmp B, CB, inv(CA)
1282/// check for CB flags
1283/// A counterexample is "or (and A B) (and C D)" which cannot be implemented
1284/// by conditional compare sequences.
1285/// @{
1286
Geoff Berrye41c2df2015-07-20 22:03:52 +00001287/// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001288static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1289 ISD::CondCode CC, SDValue CCOp,
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001290 AArch64CC::CondCode Predicate,
1291 AArch64CC::CondCode OutCC,
Matthias Braunaf7d7702015-07-16 20:02:37 +00001292 SDLoc DL, SelectionDAG &DAG) {
1293 unsigned Opcode = 0;
1294 if (LHS.getValueType().isFloatingPoint())
1295 Opcode = AArch64ISD::FCCMP;
1296 else if (RHS.getOpcode() == ISD::SUB) {
1297 SDValue SubOp0 = RHS.getOperand(0);
Artyom Skrobov314ee042015-11-25 19:41:11 +00001298 if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
Matthias Braunfd13c142016-01-23 04:05:16 +00001299 // See emitComparison() on why we can only do this for SETEQ and SETNE.
1300 Opcode = AArch64ISD::CCMN;
1301 RHS = RHS.getOperand(1);
1302 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001303 }
1304 if (Opcode == 0)
1305 Opcode = AArch64ISD::CCMP;
1306
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001307 SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC);
1308 AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1309 unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001310 SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1311 return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1312}
1313
1314/// Returns true if @p Val is a tree of AND/OR/SETCC operations.
1315/// CanPushNegate is set to true if we can push a negate operation through
1316/// the tree in a was that we are left with AND operations and negate operations
1317/// at the leafs only. i.e. "not (or (or x y) z)" can be changed to
1318/// "and (and (not x) (not y)) (not z)"; "not (or (and x y) z)" cannot be
1319/// brought into such a form.
1320static bool isConjunctionDisjunctionTree(const SDValue Val, bool &CanPushNegate,
1321 unsigned Depth = 0) {
1322 if (!Val.hasOneUse())
1323 return false;
1324 unsigned Opcode = Val->getOpcode();
1325 if (Opcode == ISD::SETCC) {
1326 CanPushNegate = true;
1327 return true;
1328 }
1329 // Protect against stack overflow.
1330 if (Depth > 15)
1331 return false;
1332 if (Opcode == ISD::AND || Opcode == ISD::OR) {
1333 SDValue O0 = Val->getOperand(0);
1334 SDValue O1 = Val->getOperand(1);
1335 bool CanPushNegateL;
1336 if (!isConjunctionDisjunctionTree(O0, CanPushNegateL, Depth+1))
1337 return false;
1338 bool CanPushNegateR;
1339 if (!isConjunctionDisjunctionTree(O1, CanPushNegateR, Depth+1))
1340 return false;
1341 // We cannot push a negate through an AND operation (it would become an OR),
1342 // we can however change a (not (or x y)) to (and (not x) (not y)) if we can
1343 // push the negate through the x/y subtrees.
1344 CanPushNegate = (Opcode == ISD::OR) && CanPushNegateL && CanPushNegateR;
1345 return true;
1346 }
1347 return false;
1348}
1349
1350/// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1351/// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1352/// Tries to transform the given i1 producing node @p Val to a series compare
1353/// and conditional compare operations. @returns an NZCV flags producing node
1354/// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1355/// transformation was not possible.
1356/// On recursive invocations @p PushNegate may be set to true to have negation
1357/// effects pushed to the tree leafs; @p Predicate is an NZCV flag predicate
1358/// for the comparisons in the current subtree; @p Depth limits the search
1359/// depth to avoid stack overflow.
1360static SDValue emitConjunctionDisjunctionTree(SelectionDAG &DAG, SDValue Val,
1361 AArch64CC::CondCode &OutCC, bool PushNegate = false,
1362 SDValue CCOp = SDValue(), AArch64CC::CondCode Predicate = AArch64CC::AL,
1363 unsigned Depth = 0) {
1364 // We're at a tree leaf, produce a conditional comparison operation.
1365 unsigned Opcode = Val->getOpcode();
1366 if (Opcode == ISD::SETCC) {
1367 SDValue LHS = Val->getOperand(0);
1368 SDValue RHS = Val->getOperand(1);
1369 ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1370 bool isInteger = LHS.getValueType().isInteger();
1371 if (PushNegate)
1372 CC = getSetCCInverse(CC, isInteger);
1373 SDLoc DL(Val);
1374 // Determine OutCC and handle FP special case.
1375 if (isInteger) {
1376 OutCC = changeIntCCToAArch64CC(CC);
1377 } else {
1378 assert(LHS.getValueType().isFloatingPoint());
1379 AArch64CC::CondCode ExtraCC;
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001380 changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
1381 // Some floating point conditions can't be tested with a single condition
1382 // code. Construct an additional comparison in this case.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001383 if (ExtraCC != AArch64CC::AL) {
1384 SDValue ExtraCmp;
1385 if (!CCOp.getNode())
1386 ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001387 else
1388 ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate,
1389 ExtraCC, DL, DAG);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001390 CCOp = ExtraCmp;
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001391 Predicate = ExtraCC;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001392 }
1393 }
1394
1395 // Produce a normal comparison if we are first in the chain
1396 if (!CCOp.getNode())
1397 return emitComparison(LHS, RHS, CC, DL, DAG);
1398 // Otherwise produce a ccmp.
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001399 return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL,
Matthias Braunaf7d7702015-07-16 20:02:37 +00001400 DAG);
Matthias Braun266204b2015-08-20 23:33:31 +00001401 } else if ((Opcode != ISD::AND && Opcode != ISD::OR) || !Val->hasOneUse())
Matthias Braunaf7d7702015-07-16 20:02:37 +00001402 return SDValue();
1403
1404 assert((Opcode == ISD::OR || !PushNegate)
1405 && "Can only push negate through OR operation");
1406
1407 // Check if both sides can be transformed.
1408 SDValue LHS = Val->getOperand(0);
1409 SDValue RHS = Val->getOperand(1);
1410 bool CanPushNegateL;
1411 if (!isConjunctionDisjunctionTree(LHS, CanPushNegateL, Depth+1))
1412 return SDValue();
1413 bool CanPushNegateR;
1414 if (!isConjunctionDisjunctionTree(RHS, CanPushNegateR, Depth+1))
1415 return SDValue();
1416
1417 // Do we need to negate our operands?
1418 bool NegateOperands = Opcode == ISD::OR;
1419 // We can negate the results of all previous operations by inverting the
1420 // predicate flags giving us a free negation for one side. For the other side
1421 // we need to be able to push the negation to the leafs of the tree.
1422 if (NegateOperands) {
1423 if (!CanPushNegateL && !CanPushNegateR)
1424 return SDValue();
1425 // Order the side where we can push the negate through to LHS.
Matthias Braun46e56392015-08-20 23:33:34 +00001426 if (!CanPushNegateL && CanPushNegateR)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001427 std::swap(LHS, RHS);
Matthias Braun46e56392015-08-20 23:33:34 +00001428 } else {
1429 bool NeedsNegOutL = LHS->getOpcode() == ISD::OR;
1430 bool NeedsNegOutR = RHS->getOpcode() == ISD::OR;
1431 if (NeedsNegOutL && NeedsNegOutR)
1432 return SDValue();
1433 // Order the side where we need to negate the output flags to RHS so it
1434 // gets emitted first.
1435 if (NeedsNegOutL)
1436 std::swap(LHS, RHS);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001437 }
1438
1439 // Emit RHS. If we want to negate the tree we only need to push a negate
1440 // through if we are already in a PushNegate case, otherwise we can negate
1441 // the "flags to test" afterwards.
1442 AArch64CC::CondCode RHSCC;
1443 SDValue CmpR = emitConjunctionDisjunctionTree(DAG, RHS, RHSCC, PushNegate,
1444 CCOp, Predicate, Depth+1);
Ahmed Bougacha6345b9e2016-01-22 19:43:43 +00001445 assert(CmpR && "Transform legality should have been checked already!");
Matthias Braunaf7d7702015-07-16 20:02:37 +00001446 if (NegateOperands && !PushNegate)
1447 RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
1448 // Emit LHS. We must push the negate through if we need to negate it.
1449 SDValue CmpL = emitConjunctionDisjunctionTree(DAG, LHS, OutCC, NegateOperands,
1450 CmpR, RHSCC, Depth+1);
Ahmed Bougacha6345b9e2016-01-22 19:43:43 +00001451 assert(CmpL && "Transform legality should have been checked already!");
Matthias Braunaf7d7702015-07-16 20:02:37 +00001452 // If we transformed an OR to and AND then we have to negate the result
1453 // (or absorb a PushNegate resulting in a double negation).
1454 if (Opcode == ISD::OR && !PushNegate)
1455 OutCC = AArch64CC::getInvertedCondCode(OutCC);
1456 return CmpL;
1457}
1458
1459/// @}
1460
Tim Northover3b0846e2014-05-24 12:50:23 +00001461static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1462 SDValue &AArch64cc, SelectionDAG &DAG, SDLoc dl) {
1463 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1464 EVT VT = RHS.getValueType();
1465 uint64_t C = RHSC->getZExtValue();
1466 if (!isLegalArithImmed(C)) {
1467 // Constant does not fit, try adjusting it by one?
1468 switch (CC) {
1469 default:
1470 break;
1471 case ISD::SETLT:
1472 case ISD::SETGE:
1473 if ((VT == MVT::i32 && C != 0x80000000 &&
1474 isLegalArithImmed((uint32_t)(C - 1))) ||
1475 (VT == MVT::i64 && C != 0x80000000ULL &&
1476 isLegalArithImmed(C - 1ULL))) {
1477 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1478 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001479 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001480 }
1481 break;
1482 case ISD::SETULT:
1483 case ISD::SETUGE:
1484 if ((VT == MVT::i32 && C != 0 &&
1485 isLegalArithImmed((uint32_t)(C - 1))) ||
1486 (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1487 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1488 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001489 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001490 }
1491 break;
1492 case ISD::SETLE:
1493 case ISD::SETGT:
Oliver Stannard269a275c2014-11-03 15:28:40 +00001494 if ((VT == MVT::i32 && C != INT32_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001495 isLegalArithImmed((uint32_t)(C + 1))) ||
Oliver Stannard269a275c2014-11-03 15:28:40 +00001496 (VT == MVT::i64 && C != INT64_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001497 isLegalArithImmed(C + 1ULL))) {
1498 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1499 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001500 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001501 }
1502 break;
1503 case ISD::SETULE:
1504 case ISD::SETUGT:
Oliver Stannard269a275c2014-11-03 15:28:40 +00001505 if ((VT == MVT::i32 && C != UINT32_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001506 isLegalArithImmed((uint32_t)(C + 1))) ||
Oliver Stannard269a275c2014-11-03 15:28:40 +00001507 (VT == MVT::i64 && C != UINT64_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001508 isLegalArithImmed(C + 1ULL))) {
1509 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1510 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001511 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001512 }
1513 break;
1514 }
1515 }
1516 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001517 SDValue Cmp;
1518 AArch64CC::CondCode AArch64CC;
David Xuee978202014-08-28 04:59:53 +00001519 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001520 const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
1521
1522 // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
1523 // For the i8 operand, the largest immediate is 255, so this can be easily
1524 // encoded in the compare instruction. For the i16 operand, however, the
1525 // largest immediate cannot be encoded in the compare.
1526 // Therefore, use a sign extending load and cmn to avoid materializing the
1527 // -1 constant. For example,
1528 // movz w1, #65535
1529 // ldrh w0, [x0, #0]
1530 // cmp w0, w1
1531 // >
1532 // ldrsh w0, [x0, #0]
1533 // cmn w0, #1
1534 // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
1535 // if and only if (sext LHS) == (sext RHS). The checks are in place to
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001536 // ensure both the LHS and RHS are truly zero extended and to make sure the
Matthias Braunaf7d7702015-07-16 20:02:37 +00001537 // transformation is profitable.
1538 if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
1539 cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
1540 cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
1541 LHS.getNode()->hasNUsesOfValue(1, 0)) {
1542 int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
1543 if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
1544 SDValue SExt =
1545 DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
1546 DAG.getValueType(MVT::i16));
1547 Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
1548 RHS.getValueType()),
1549 CC, dl, DAG);
1550 AArch64CC = changeIntCCToAArch64CC(CC);
1551 }
1552 }
1553
1554 if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
1555 if ((Cmp = emitConjunctionDisjunctionTree(DAG, LHS, AArch64CC))) {
1556 if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
1557 AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
David Xuee978202014-08-28 04:59:53 +00001558 }
1559 }
1560 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001561
1562 if (!Cmp) {
1563 Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
1564 AArch64CC = changeIntCCToAArch64CC(CC);
1565 }
1566 AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
Tim Northover3b0846e2014-05-24 12:50:23 +00001567 return Cmp;
1568}
1569
1570static std::pair<SDValue, SDValue>
1571getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
1572 assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
1573 "Unsupported value type");
1574 SDValue Value, Overflow;
1575 SDLoc DL(Op);
1576 SDValue LHS = Op.getOperand(0);
1577 SDValue RHS = Op.getOperand(1);
1578 unsigned Opc = 0;
1579 switch (Op.getOpcode()) {
1580 default:
1581 llvm_unreachable("Unknown overflow instruction!");
1582 case ISD::SADDO:
1583 Opc = AArch64ISD::ADDS;
1584 CC = AArch64CC::VS;
1585 break;
1586 case ISD::UADDO:
1587 Opc = AArch64ISD::ADDS;
1588 CC = AArch64CC::HS;
1589 break;
1590 case ISD::SSUBO:
1591 Opc = AArch64ISD::SUBS;
1592 CC = AArch64CC::VS;
1593 break;
1594 case ISD::USUBO:
1595 Opc = AArch64ISD::SUBS;
1596 CC = AArch64CC::LO;
1597 break;
1598 // Multiply needs a little bit extra work.
1599 case ISD::SMULO:
1600 case ISD::UMULO: {
1601 CC = AArch64CC::NE;
David Blaikie186d2cb2015-03-24 16:24:01 +00001602 bool IsSigned = Op.getOpcode() == ISD::SMULO;
Tim Northover3b0846e2014-05-24 12:50:23 +00001603 if (Op.getValueType() == MVT::i32) {
1604 unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1605 // For a 32 bit multiply with overflow check we want the instruction
1606 // selector to generate a widening multiply (SMADDL/UMADDL). For that we
1607 // need to generate the following pattern:
1608 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
1609 LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
1610 RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
1611 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1612 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001613 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001614 // On AArch64 the upper 32 bits are always zero extended for a 32 bit
1615 // operation. We need to clear out the upper 32 bits, because we used a
1616 // widening multiply that wrote all 64 bits. In the end this should be a
1617 // noop.
1618 Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
1619 if (IsSigned) {
1620 // The signed overflow check requires more than just a simple check for
1621 // any bit set in the upper 32 bits of the result. These bits could be
1622 // just the sign bits of a negative number. To perform the overflow
1623 // check we have to arithmetic shift right the 32nd bit of the result by
1624 // 31 bits. Then we compare the result to the upper 32 bits.
1625 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001626 DAG.getConstant(32, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001627 UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
1628 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001629 DAG.getConstant(31, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001630 // It is important that LowerBits is last, otherwise the arithmetic
1631 // shift will not be folded into the compare (SUBS).
1632 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
1633 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1634 .getValue(1);
1635 } else {
1636 // The overflow check for unsigned multiply is easy. We only need to
1637 // check if any of the upper 32 bits are set. This can be done with a
1638 // CMP (shifted register). For that we need to generate the following
1639 // pattern:
1640 // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
1641 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001642 DAG.getConstant(32, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001643 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1644 Overflow =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001645 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1646 DAG.getConstant(0, DL, MVT::i64),
Tim Northover3b0846e2014-05-24 12:50:23 +00001647 UpperBits).getValue(1);
1648 }
1649 break;
1650 }
1651 assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
1652 // For the 64 bit multiply
1653 Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1654 if (IsSigned) {
1655 SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
1656 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001657 DAG.getConstant(63, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001658 // It is important that LowerBits is last, otherwise the arithmetic
1659 // shift will not be folded into the compare (SUBS).
1660 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1661 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1662 .getValue(1);
1663 } else {
1664 SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
1665 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1666 Overflow =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001667 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1668 DAG.getConstant(0, DL, MVT::i64),
Tim Northover3b0846e2014-05-24 12:50:23 +00001669 UpperBits).getValue(1);
1670 }
1671 break;
1672 }
1673 } // switch (...)
1674
1675 if (Opc) {
1676 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
1677
1678 // Emit the AArch64 operation with overflow check.
1679 Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
1680 Overflow = Value.getValue(1);
1681 }
1682 return std::make_pair(Value, Overflow);
1683}
1684
1685SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
1686 RTLIB::Libcall Call) const {
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00001687 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
Craig Topper8fe40e02015-10-22 17:05:00 +00001688 return makeLibCall(DAG, Call, MVT::f128, Ops, false, SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00001689}
1690
1691static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
1692 SDValue Sel = Op.getOperand(0);
1693 SDValue Other = Op.getOperand(1);
1694
1695 // If neither operand is a SELECT_CC, give up.
1696 if (Sel.getOpcode() != ISD::SELECT_CC)
1697 std::swap(Sel, Other);
1698 if (Sel.getOpcode() != ISD::SELECT_CC)
1699 return Op;
1700
1701 // The folding we want to perform is:
1702 // (xor x, (select_cc a, b, cc, 0, -1) )
1703 // -->
1704 // (csel x, (xor x, -1), cc ...)
1705 //
1706 // The latter will get matched to a CSINV instruction.
1707
1708 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
1709 SDValue LHS = Sel.getOperand(0);
1710 SDValue RHS = Sel.getOperand(1);
1711 SDValue TVal = Sel.getOperand(2);
1712 SDValue FVal = Sel.getOperand(3);
1713 SDLoc dl(Sel);
1714
1715 // FIXME: This could be generalized to non-integer comparisons.
1716 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
1717 return Op;
1718
1719 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
1720 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
1721
Eric Christopher572e03a2015-06-19 01:53:21 +00001722 // The values aren't constants, this isn't the pattern we're looking for.
Tim Northover3b0846e2014-05-24 12:50:23 +00001723 if (!CFVal || !CTVal)
1724 return Op;
1725
1726 // We can commute the SELECT_CC by inverting the condition. This
1727 // might be needed to make this fit into a CSINV pattern.
1728 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
1729 std::swap(TVal, FVal);
1730 std::swap(CTVal, CFVal);
1731 CC = ISD::getSetCCInverse(CC, true);
1732 }
1733
1734 // If the constants line up, perform the transform!
1735 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
1736 SDValue CCVal;
1737 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
1738
1739 FVal = Other;
1740 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001741 DAG.getConstant(-1ULL, dl, Other.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00001742
1743 return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
1744 CCVal, Cmp);
1745 }
1746
1747 return Op;
1748}
1749
1750static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
1751 EVT VT = Op.getValueType();
1752
1753 // Let legalize expand this if it isn't a legal type yet.
1754 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
1755 return SDValue();
1756
1757 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
1758
1759 unsigned Opc;
1760 bool ExtraOp = false;
1761 switch (Op.getOpcode()) {
1762 default:
Craig Topper2a30d782014-06-18 05:05:13 +00001763 llvm_unreachable("Invalid code");
Tim Northover3b0846e2014-05-24 12:50:23 +00001764 case ISD::ADDC:
1765 Opc = AArch64ISD::ADDS;
1766 break;
1767 case ISD::SUBC:
1768 Opc = AArch64ISD::SUBS;
1769 break;
1770 case ISD::ADDE:
1771 Opc = AArch64ISD::ADCS;
1772 ExtraOp = true;
1773 break;
1774 case ISD::SUBE:
1775 Opc = AArch64ISD::SBCS;
1776 ExtraOp = true;
1777 break;
1778 }
1779
1780 if (!ExtraOp)
1781 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
1782 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
1783 Op.getOperand(2));
1784}
1785
1786static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
1787 // Let legalize expand this if it isn't a legal type yet.
1788 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
1789 return SDValue();
1790
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001791 SDLoc dl(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00001792 AArch64CC::CondCode CC;
1793 // The actual operation that sets the overflow or carry flag.
1794 SDValue Value, Overflow;
1795 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
1796
1797 // We use 0 and 1 as false and true values.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001798 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
1799 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00001800
1801 // We use an inverted condition, because the conditional select is inverted
1802 // too. This will allow it to be selected to a single instruction:
1803 // CSINC Wd, WZR, WZR, invert(cond).
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001804 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
1805 Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
Tim Northover3b0846e2014-05-24 12:50:23 +00001806 CCVal, Overflow);
1807
1808 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001809 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
Tim Northover3b0846e2014-05-24 12:50:23 +00001810}
1811
1812// Prefetch operands are:
1813// 1: Address to prefetch
1814// 2: bool isWrite
1815// 3: int locality (0 = no locality ... 3 = extreme locality)
1816// 4: bool isDataCache
1817static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
1818 SDLoc DL(Op);
1819 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
1820 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
Yi Konge56de692014-08-05 12:46:47 +00001821 unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00001822
1823 bool IsStream = !Locality;
1824 // When the locality number is set
1825 if (Locality) {
1826 // The front-end should have filtered out the out-of-range values
1827 assert(Locality <= 3 && "Prefetch locality out-of-range");
1828 // The locality degree is the opposite of the cache speed.
1829 // Put the number the other way around.
1830 // The encoding starts at 0 for level 1
1831 Locality = 3 - Locality;
1832 }
1833
1834 // built the mask value encoding the expected behavior.
1835 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit
Yi Konge56de692014-08-05 12:46:47 +00001836 (!IsData << 3) | // IsDataCache bit
Tim Northover3b0846e2014-05-24 12:50:23 +00001837 (Locality << 1) | // Cache level bits
1838 (unsigned)IsStream; // Stream bit
1839 return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001840 DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00001841}
1842
1843SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
1844 SelectionDAG &DAG) const {
1845 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
1846
1847 RTLIB::Libcall LC;
1848 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
1849
1850 return LowerF128Call(Op, DAG, LC);
1851}
1852
1853SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
1854 SelectionDAG &DAG) const {
1855 if (Op.getOperand(0).getValueType() != MVT::f128) {
1856 // It's legal except when f128 is involved
1857 return Op;
1858 }
1859
1860 RTLIB::Libcall LC;
1861 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
1862
1863 // FP_ROUND node has a second operand indicating whether it is known to be
1864 // precise. That doesn't take part in the LibCall so we can't directly use
1865 // LowerF128Call.
1866 SDValue SrcVal = Op.getOperand(0);
Craig Topper8fe40e02015-10-22 17:05:00 +00001867 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
1868 SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00001869}
1870
1871static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
1872 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1873 // Any additional optimization in this function should be recorded
1874 // in the cost tables.
1875 EVT InVT = Op.getOperand(0).getValueType();
1876 EVT VT = Op.getValueType();
Pirama Arumuga Nainar1317d5f2015-12-10 17:16:49 +00001877 unsigned NumElts = InVT.getVectorNumElements();
1878
1879 // f16 vectors are promoted to f32 before a conversion.
1880 if (InVT.getVectorElementType() == MVT::f16) {
1881 MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
1882 SDLoc dl(Op);
1883 return DAG.getNode(
1884 Op.getOpcode(), dl, Op.getValueType(),
1885 DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
1886 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001887
Tim Northoverdbecc3b2014-06-15 09:27:15 +00001888 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001889 SDLoc dl(Op);
1890 SDValue Cv =
1891 DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
1892 Op.getOperand(0));
1893 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
Tim Northoverdbecc3b2014-06-15 09:27:15 +00001894 }
1895
1896 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001897 SDLoc dl(Op);
Oliver Stannard89d15422014-08-27 16:16:04 +00001898 MVT ExtVT =
1899 MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
1900 VT.getVectorNumElements());
1901 SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
Tim Northover3b0846e2014-05-24 12:50:23 +00001902 return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
1903 }
1904
1905 // Type changing conversions are illegal.
Tim Northoverdbecc3b2014-06-15 09:27:15 +00001906 return Op;
Tim Northover3b0846e2014-05-24 12:50:23 +00001907}
1908
1909SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
1910 SelectionDAG &DAG) const {
1911 if (Op.getOperand(0).getValueType().isVector())
1912 return LowerVectorFP_TO_INT(Op, DAG);
1913
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00001914 // f16 conversions are promoted to f32.
1915 if (Op.getOperand(0).getValueType() == MVT::f16) {
1916 SDLoc dl(Op);
1917 return DAG.getNode(
1918 Op.getOpcode(), dl, Op.getValueType(),
1919 DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
1920 }
1921
Tim Northover3b0846e2014-05-24 12:50:23 +00001922 if (Op.getOperand(0).getValueType() != MVT::f128) {
1923 // It's legal except when f128 is involved
1924 return Op;
1925 }
1926
1927 RTLIB::Libcall LC;
1928 if (Op.getOpcode() == ISD::FP_TO_SINT)
1929 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
1930 else
1931 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
1932
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00001933 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
Craig Topper8fe40e02015-10-22 17:05:00 +00001934 return makeLibCall(DAG, LC, Op.getValueType(), Ops, false, SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00001935}
1936
1937static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
1938 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1939 // Any additional optimization in this function should be recorded
1940 // in the cost tables.
1941 EVT VT = Op.getValueType();
1942 SDLoc dl(Op);
1943 SDValue In = Op.getOperand(0);
1944 EVT InVT = In.getValueType();
1945
Tim Northoveref0d7602014-06-15 09:27:06 +00001946 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
1947 MVT CastVT =
1948 MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
1949 InVT.getVectorNumElements());
1950 In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001951 return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
Tim Northover3b0846e2014-05-24 12:50:23 +00001952 }
1953
Tim Northoveref0d7602014-06-15 09:27:06 +00001954 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
1955 unsigned CastOpc =
1956 Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1957 EVT CastVT = VT.changeVectorElementTypeToInteger();
1958 In = DAG.getNode(CastOpc, dl, CastVT, In);
1959 return DAG.getNode(Op.getOpcode(), dl, VT, In);
Tim Northover3b0846e2014-05-24 12:50:23 +00001960 }
1961
Tim Northoveref0d7602014-06-15 09:27:06 +00001962 return Op;
Tim Northover3b0846e2014-05-24 12:50:23 +00001963}
1964
1965SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
1966 SelectionDAG &DAG) const {
1967 if (Op.getValueType().isVector())
1968 return LowerVectorINT_TO_FP(Op, DAG);
1969
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00001970 // f16 conversions are promoted to f32.
1971 if (Op.getValueType() == MVT::f16) {
1972 SDLoc dl(Op);
1973 return DAG.getNode(
1974 ISD::FP_ROUND, dl, MVT::f16,
1975 DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001976 DAG.getIntPtrConstant(0, dl));
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00001977 }
1978
Tim Northover3b0846e2014-05-24 12:50:23 +00001979 // i128 conversions are libcalls.
1980 if (Op.getOperand(0).getValueType() == MVT::i128)
1981 return SDValue();
1982
1983 // Other conversions are legal, unless it's to the completely software-based
1984 // fp128.
1985 if (Op.getValueType() != MVT::f128)
1986 return Op;
1987
1988 RTLIB::Libcall LC;
1989 if (Op.getOpcode() == ISD::SINT_TO_FP)
1990 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
1991 else
1992 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
1993
1994 return LowerF128Call(Op, DAG, LC);
1995}
1996
1997SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
1998 SelectionDAG &DAG) const {
1999 // For iOS, we want to call an alternative entry point: __sincos_stret,
2000 // which returns the values in two S / D registers.
2001 SDLoc dl(Op);
2002 SDValue Arg = Op.getOperand(0);
2003 EVT ArgVT = Arg.getValueType();
2004 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2005
2006 ArgListTy Args;
2007 ArgListEntry Entry;
2008
2009 Entry.Node = Arg;
2010 Entry.Ty = ArgTy;
2011 Entry.isSExt = false;
2012 Entry.isZExt = false;
2013 Args.push_back(Entry);
2014
2015 const char *LibcallName =
2016 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
Mehdi Amini44ede332015-07-09 02:09:04 +00002017 SDValue Callee =
2018 DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00002019
Reid Kleckner343c3952014-11-20 23:51:47 +00002020 StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
Tim Northover3b0846e2014-05-24 12:50:23 +00002021 TargetLowering::CallLoweringInfo CLI(DAG);
2022 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
Juergen Ributzka3bd03c72014-07-01 22:01:54 +00002023 .setCallee(CallingConv::Fast, RetTy, Callee, std::move(Args), 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00002024
2025 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2026 return CallResult.first;
2027}
2028
Tim Northoverf8bfe212014-07-18 13:07:05 +00002029static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
2030 if (Op.getValueType() != MVT::f16)
2031 return SDValue();
2032
2033 assert(Op.getOperand(0).getValueType() == MVT::i16);
2034 SDLoc DL(Op);
2035
2036 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
2037 Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
2038 return SDValue(
2039 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002040 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
Tim Northoverf8bfe212014-07-18 13:07:05 +00002041 0);
2042}
2043
Chad Rosierd9d0f862014-10-08 02:31:24 +00002044static EVT getExtensionTo64Bits(const EVT &OrigVT) {
2045 if (OrigVT.getSizeInBits() >= 64)
2046 return OrigVT;
2047
2048 assert(OrigVT.isSimple() && "Expecting a simple value type");
2049
2050 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
2051 switch (OrigSimpleTy) {
2052 default: llvm_unreachable("Unexpected Vector Type");
2053 case MVT::v2i8:
2054 case MVT::v2i16:
2055 return MVT::v2i32;
2056 case MVT::v4i8:
2057 return MVT::v4i16;
2058 }
2059}
2060
2061static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2062 const EVT &OrigTy,
2063 const EVT &ExtTy,
2064 unsigned ExtOpcode) {
2065 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2066 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2067 // 64-bits we need to insert a new extension so that it will be 64-bits.
2068 assert(ExtTy.is128BitVector() && "Unexpected extension size");
2069 if (OrigTy.getSizeInBits() >= 64)
2070 return N;
2071
2072 // Must extend size to at least 64 bits to be used as an operand for VMULL.
2073 EVT NewVT = getExtensionTo64Bits(OrigTy);
2074
2075 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2076}
2077
2078static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2079 bool isSigned) {
2080 EVT VT = N->getValueType(0);
2081
2082 if (N->getOpcode() != ISD::BUILD_VECTOR)
2083 return false;
2084
Pete Cooper3af9a252015-06-26 18:17:36 +00002085 for (const SDValue &Elt : N->op_values()) {
Chad Rosierd9d0f862014-10-08 02:31:24 +00002086 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
2087 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
2088 unsigned HalfSize = EltSize / 2;
2089 if (isSigned) {
2090 if (!isIntN(HalfSize, C->getSExtValue()))
2091 return false;
2092 } else {
2093 if (!isUIntN(HalfSize, C->getZExtValue()))
2094 return false;
2095 }
2096 continue;
2097 }
2098 return false;
2099 }
2100
2101 return true;
2102}
2103
2104static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2105 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2106 return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2107 N->getOperand(0)->getValueType(0),
2108 N->getValueType(0),
2109 N->getOpcode());
2110
2111 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2112 EVT VT = N->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002113 SDLoc dl(N);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002114 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
2115 unsigned NumElts = VT.getVectorNumElements();
2116 MVT TruncVT = MVT::getIntegerVT(EltSize);
2117 SmallVector<SDValue, 8> Ops;
2118 for (unsigned i = 0; i != NumElts; ++i) {
2119 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2120 const APInt &CInt = C->getAPIntValue();
2121 // Element types smaller than 32 bits are not legal, so use i32 elements.
2122 // The values are implicitly truncated so sext vs. zext doesn't matter.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002123 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
Chad Rosierd9d0f862014-10-08 02:31:24 +00002124 }
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002125 return DAG.getNode(ISD::BUILD_VECTOR, dl,
Chad Rosierd9d0f862014-10-08 02:31:24 +00002126 MVT::getVectorVT(TruncVT, NumElts), Ops);
2127}
2128
2129static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
2130 if (N->getOpcode() == ISD::SIGN_EXTEND)
2131 return true;
2132 if (isExtendedBUILD_VECTOR(N, DAG, true))
2133 return true;
2134 return false;
2135}
2136
2137static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
2138 if (N->getOpcode() == ISD::ZERO_EXTEND)
2139 return true;
2140 if (isExtendedBUILD_VECTOR(N, DAG, false))
2141 return true;
2142 return false;
2143}
2144
2145static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2146 unsigned Opcode = N->getOpcode();
2147 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2148 SDNode *N0 = N->getOperand(0).getNode();
2149 SDNode *N1 = N->getOperand(1).getNode();
2150 return N0->hasOneUse() && N1->hasOneUse() &&
2151 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2152 }
2153 return false;
2154}
2155
2156static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2157 unsigned Opcode = N->getOpcode();
2158 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2159 SDNode *N0 = N->getOperand(0).getNode();
2160 SDNode *N1 = N->getOperand(1).getNode();
2161 return N0->hasOneUse() && N1->hasOneUse() &&
2162 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2163 }
2164 return false;
2165}
2166
2167static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2168 // Multiplications are only custom-lowered for 128-bit vectors so that
2169 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
2170 EVT VT = Op.getValueType();
2171 assert(VT.is128BitVector() && VT.isInteger() &&
2172 "unexpected type for custom-lowering ISD::MUL");
2173 SDNode *N0 = Op.getOperand(0).getNode();
2174 SDNode *N1 = Op.getOperand(1).getNode();
2175 unsigned NewOpc = 0;
2176 bool isMLA = false;
2177 bool isN0SExt = isSignExtended(N0, DAG);
2178 bool isN1SExt = isSignExtended(N1, DAG);
2179 if (isN0SExt && isN1SExt)
2180 NewOpc = AArch64ISD::SMULL;
2181 else {
2182 bool isN0ZExt = isZeroExtended(N0, DAG);
2183 bool isN1ZExt = isZeroExtended(N1, DAG);
2184 if (isN0ZExt && isN1ZExt)
2185 NewOpc = AArch64ISD::UMULL;
2186 else if (isN1SExt || isN1ZExt) {
2187 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2188 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2189 if (isN1SExt && isAddSubSExt(N0, DAG)) {
2190 NewOpc = AArch64ISD::SMULL;
2191 isMLA = true;
2192 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2193 NewOpc = AArch64ISD::UMULL;
2194 isMLA = true;
2195 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2196 std::swap(N0, N1);
2197 NewOpc = AArch64ISD::UMULL;
2198 isMLA = true;
2199 }
2200 }
2201
2202 if (!NewOpc) {
2203 if (VT == MVT::v2i64)
2204 // Fall through to expand this. It is not legal.
2205 return SDValue();
2206 else
2207 // Other vector multiplications are legal.
2208 return Op;
2209 }
2210 }
2211
2212 // Legalize to a S/UMULL instruction
2213 SDLoc DL(Op);
2214 SDValue Op0;
2215 SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2216 if (!isMLA) {
2217 Op0 = skipExtensionForVectorMULL(N0, DAG);
2218 assert(Op0.getValueType().is64BitVector() &&
2219 Op1.getValueType().is64BitVector() &&
2220 "unexpected types for extended operands to VMULL");
2221 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2222 }
2223 // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2224 // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2225 // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2226 SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2227 SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2228 EVT Op1VT = Op1.getValueType();
2229 return DAG.getNode(N0->getOpcode(), DL, VT,
2230 DAG.getNode(NewOpc, DL, VT,
2231 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2232 DAG.getNode(NewOpc, DL, VT,
2233 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2234}
Tim Northoverf8bfe212014-07-18 13:07:05 +00002235
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002236SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2237 SelectionDAG &DAG) const {
2238 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2239 SDLoc dl(Op);
2240 switch (IntNo) {
2241 default: return SDValue(); // Don't custom lower most intrinsics.
2242 case Intrinsic::aarch64_thread_pointer: {
2243 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2244 return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
2245 }
Silviu Barangadb1ddb32015-08-26 11:11:14 +00002246 case Intrinsic::aarch64_neon_smax:
2247 return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
2248 Op.getOperand(1), Op.getOperand(2));
2249 case Intrinsic::aarch64_neon_umax:
2250 return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
2251 Op.getOperand(1), Op.getOperand(2));
2252 case Intrinsic::aarch64_neon_smin:
2253 return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
2254 Op.getOperand(1), Op.getOperand(2));
2255 case Intrinsic::aarch64_neon_umin:
2256 return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
2257 Op.getOperand(1), Op.getOperand(2));
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002258 }
2259}
2260
Tim Northover3b0846e2014-05-24 12:50:23 +00002261SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
2262 SelectionDAG &DAG) const {
2263 switch (Op.getOpcode()) {
2264 default:
2265 llvm_unreachable("unimplemented operand");
2266 return SDValue();
Tim Northoverf8bfe212014-07-18 13:07:05 +00002267 case ISD::BITCAST:
2268 return LowerBITCAST(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002269 case ISD::GlobalAddress:
2270 return LowerGlobalAddress(Op, DAG);
2271 case ISD::GlobalTLSAddress:
2272 return LowerGlobalTLSAddress(Op, DAG);
2273 case ISD::SETCC:
2274 return LowerSETCC(Op, DAG);
2275 case ISD::BR_CC:
2276 return LowerBR_CC(Op, DAG);
2277 case ISD::SELECT:
2278 return LowerSELECT(Op, DAG);
2279 case ISD::SELECT_CC:
2280 return LowerSELECT_CC(Op, DAG);
2281 case ISD::JumpTable:
2282 return LowerJumpTable(Op, DAG);
2283 case ISD::ConstantPool:
2284 return LowerConstantPool(Op, DAG);
2285 case ISD::BlockAddress:
2286 return LowerBlockAddress(Op, DAG);
2287 case ISD::VASTART:
2288 return LowerVASTART(Op, DAG);
2289 case ISD::VACOPY:
2290 return LowerVACOPY(Op, DAG);
2291 case ISD::VAARG:
2292 return LowerVAARG(Op, DAG);
2293 case ISD::ADDC:
2294 case ISD::ADDE:
2295 case ISD::SUBC:
2296 case ISD::SUBE:
2297 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
2298 case ISD::SADDO:
2299 case ISD::UADDO:
2300 case ISD::SSUBO:
2301 case ISD::USUBO:
2302 case ISD::SMULO:
2303 case ISD::UMULO:
2304 return LowerXALUO(Op, DAG);
2305 case ISD::FADD:
2306 return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
2307 case ISD::FSUB:
2308 return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
2309 case ISD::FMUL:
2310 return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
2311 case ISD::FDIV:
2312 return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
2313 case ISD::FP_ROUND:
2314 return LowerFP_ROUND(Op, DAG);
2315 case ISD::FP_EXTEND:
2316 return LowerFP_EXTEND(Op, DAG);
2317 case ISD::FRAMEADDR:
2318 return LowerFRAMEADDR(Op, DAG);
2319 case ISD::RETURNADDR:
2320 return LowerRETURNADDR(Op, DAG);
2321 case ISD::INSERT_VECTOR_ELT:
2322 return LowerINSERT_VECTOR_ELT(Op, DAG);
2323 case ISD::EXTRACT_VECTOR_ELT:
2324 return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2325 case ISD::BUILD_VECTOR:
2326 return LowerBUILD_VECTOR(Op, DAG);
2327 case ISD::VECTOR_SHUFFLE:
2328 return LowerVECTOR_SHUFFLE(Op, DAG);
2329 case ISD::EXTRACT_SUBVECTOR:
2330 return LowerEXTRACT_SUBVECTOR(Op, DAG);
2331 case ISD::SRA:
2332 case ISD::SRL:
2333 case ISD::SHL:
2334 return LowerVectorSRA_SRL_SHL(Op, DAG);
2335 case ISD::SHL_PARTS:
2336 return LowerShiftLeftParts(Op, DAG);
2337 case ISD::SRL_PARTS:
2338 case ISD::SRA_PARTS:
2339 return LowerShiftRightParts(Op, DAG);
2340 case ISD::CTPOP:
2341 return LowerCTPOP(Op, DAG);
2342 case ISD::FCOPYSIGN:
2343 return LowerFCOPYSIGN(Op, DAG);
2344 case ISD::AND:
2345 return LowerVectorAND(Op, DAG);
2346 case ISD::OR:
2347 return LowerVectorOR(Op, DAG);
2348 case ISD::XOR:
2349 return LowerXOR(Op, DAG);
2350 case ISD::PREFETCH:
2351 return LowerPREFETCH(Op, DAG);
2352 case ISD::SINT_TO_FP:
2353 case ISD::UINT_TO_FP:
2354 return LowerINT_TO_FP(Op, DAG);
2355 case ISD::FP_TO_SINT:
2356 case ISD::FP_TO_UINT:
2357 return LowerFP_TO_INT(Op, DAG);
2358 case ISD::FSINCOS:
2359 return LowerFSINCOS(Op, DAG);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002360 case ISD::MUL:
2361 return LowerMUL(Op, DAG);
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002362 case ISD::INTRINSIC_WO_CHAIN:
2363 return LowerINTRINSIC_WO_CHAIN(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002364 }
2365}
2366
Tim Northover3b0846e2014-05-24 12:50:23 +00002367//===----------------------------------------------------------------------===//
2368// Calling Convention Implementation
2369//===----------------------------------------------------------------------===//
2370
2371#include "AArch64GenCallingConv.inc"
2372
Robin Morisset039781e2014-08-29 21:53:01 +00002373/// Selects the correct CCAssignFn for a given CallingConvention value.
Tim Northover3b0846e2014-05-24 12:50:23 +00002374CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2375 bool IsVarArg) const {
2376 switch (CC) {
2377 default:
2378 llvm_unreachable("Unsupported calling convention.");
2379 case CallingConv::WebKit_JS:
2380 return CC_AArch64_WebKit_JS;
Greg Fitzgeraldfa78d082015-01-19 17:40:05 +00002381 case CallingConv::GHC:
2382 return CC_AArch64_GHC;
Tim Northover3b0846e2014-05-24 12:50:23 +00002383 case CallingConv::C:
2384 case CallingConv::Fast:
2385 if (!Subtarget->isTargetDarwin())
2386 return CC_AArch64_AAPCS;
2387 return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
2388 }
2389}
2390
2391SDValue AArch64TargetLowering::LowerFormalArguments(
2392 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2393 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2394 SmallVectorImpl<SDValue> &InVals) const {
2395 MachineFunction &MF = DAG.getMachineFunction();
2396 MachineFrameInfo *MFI = MF.getFrameInfo();
2397
2398 // Assign locations to all of the incoming arguments.
2399 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002400 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2401 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002402
2403 // At this point, Ins[].VT may already be promoted to i32. To correctly
2404 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2405 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2406 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
2407 // we use a special version of AnalyzeFormalArguments to pass in ValVT and
2408 // LocVT.
2409 unsigned NumArgs = Ins.size();
2410 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2411 unsigned CurArgIdx = 0;
2412 for (unsigned i = 0; i != NumArgs; ++i) {
2413 MVT ValVT = Ins[i].VT;
Andrew Trick05938a52015-02-16 18:10:47 +00002414 if (Ins[i].isOrigArg()) {
2415 std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
2416 CurArgIdx = Ins[i].getOrigArgIndex();
Tim Northover3b0846e2014-05-24 12:50:23 +00002417
Andrew Trick05938a52015-02-16 18:10:47 +00002418 // Get type of the original argument.
Mehdi Amini44ede332015-07-09 02:09:04 +00002419 EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
2420 /*AllowUnknown*/ true);
Andrew Trick05938a52015-02-16 18:10:47 +00002421 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
2422 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2423 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2424 ValVT = MVT::i8;
2425 else if (ActualMVT == MVT::i16)
2426 ValVT = MVT::i16;
2427 }
Tim Northover3b0846e2014-05-24 12:50:23 +00002428 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2429 bool Res =
Tim Northover47e003c2014-05-26 17:21:53 +00002430 AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00002431 assert(!Res && "Call operand has unhandled type");
2432 (void)Res;
2433 }
2434 assert(ArgLocs.size() == Ins.size());
2435 SmallVector<SDValue, 16> ArgValues;
2436 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2437 CCValAssign &VA = ArgLocs[i];
2438
2439 if (Ins[i].Flags.isByVal()) {
2440 // Byval is used for HFAs in the PCS, but the system should work in a
2441 // non-compliant manner for larger structs.
Mehdi Amini44ede332015-07-09 02:09:04 +00002442 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00002443 int Size = Ins[i].Flags.getByValSize();
2444 unsigned NumRegs = (Size + 7) / 8;
2445
2446 // FIXME: This works on big-endian for composite byvals, which are the common
2447 // case. It should also work for fundamental types too.
2448 unsigned FrameIdx =
2449 MFI->CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
Mehdi Amini44ede332015-07-09 02:09:04 +00002450 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00002451 InVals.push_back(FrameIdxN);
2452
2453 continue;
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002454 }
Junmo Park3b8c7152016-01-05 09:36:47 +00002455
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002456 if (VA.isRegLoc()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00002457 // Arguments stored in registers.
2458 EVT RegVT = VA.getLocVT();
2459
2460 SDValue ArgValue;
2461 const TargetRegisterClass *RC;
2462
2463 if (RegVT == MVT::i32)
2464 RC = &AArch64::GPR32RegClass;
2465 else if (RegVT == MVT::i64)
2466 RC = &AArch64::GPR64RegClass;
Oliver Stannard6eda6ff2014-07-11 13:33:46 +00002467 else if (RegVT == MVT::f16)
2468 RC = &AArch64::FPR16RegClass;
Tim Northover3b0846e2014-05-24 12:50:23 +00002469 else if (RegVT == MVT::f32)
2470 RC = &AArch64::FPR32RegClass;
2471 else if (RegVT == MVT::f64 || RegVT.is64BitVector())
2472 RC = &AArch64::FPR64RegClass;
2473 else if (RegVT == MVT::f128 || RegVT.is128BitVector())
2474 RC = &AArch64::FPR128RegClass;
2475 else
2476 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2477
2478 // Transform the arguments in physical registers into virtual ones.
2479 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2480 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2481
2482 // If this is an 8, 16 or 32-bit value, it is really passed promoted
2483 // to 64 bits. Insert an assert[sz]ext to capture this, then
2484 // truncate to the right size.
2485 switch (VA.getLocInfo()) {
2486 default:
2487 llvm_unreachable("Unknown loc info!");
2488 case CCValAssign::Full:
2489 break;
2490 case CCValAssign::BCvt:
2491 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
2492 break;
Tim Northover47e003c2014-05-26 17:21:53 +00002493 case CCValAssign::AExt:
Tim Northover3b0846e2014-05-24 12:50:23 +00002494 case CCValAssign::SExt:
Tim Northover3b0846e2014-05-24 12:50:23 +00002495 case CCValAssign::ZExt:
Tim Northover47e003c2014-05-26 17:21:53 +00002496 // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
2497 // nodes after our lowering.
2498 assert(RegVT == Ins[i].VT && "incorrect register location selected");
Tim Northover3b0846e2014-05-24 12:50:23 +00002499 break;
2500 }
2501
2502 InVals.push_back(ArgValue);
2503
2504 } else { // VA.isRegLoc()
2505 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
2506 unsigned ArgOffset = VA.getLocMemOffset();
Amara Emerson82da7d02014-08-15 14:29:57 +00002507 unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
Tim Northover3b0846e2014-05-24 12:50:23 +00002508
2509 uint32_t BEAlign = 0;
Tim Northover293d4142014-12-03 17:49:26 +00002510 if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
2511 !Ins[i].Flags.isInConsecutiveRegs())
Tim Northover3b0846e2014-05-24 12:50:23 +00002512 BEAlign = 8 - ArgSize;
2513
2514 int FI = MFI->CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
2515
2516 // Create load nodes to retrieve arguments from the stack.
Mehdi Amini44ede332015-07-09 02:09:04 +00002517 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00002518 SDValue ArgValue;
2519
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002520 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
Tim Northover47e003c2014-05-26 17:21:53 +00002521 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002522 MVT MemVT = VA.getValVT();
2523
Tim Northover47e003c2014-05-26 17:21:53 +00002524 switch (VA.getLocInfo()) {
2525 default:
2526 break;
Tim Northover6890add2014-06-03 13:54:53 +00002527 case CCValAssign::BCvt:
2528 MemVT = VA.getLocVT();
2529 break;
Tim Northover47e003c2014-05-26 17:21:53 +00002530 case CCValAssign::SExt:
2531 ExtType = ISD::SEXTLOAD;
2532 break;
2533 case CCValAssign::ZExt:
2534 ExtType = ISD::ZEXTLOAD;
2535 break;
2536 case CCValAssign::AExt:
2537 ExtType = ISD::EXTLOAD;
2538 break;
Tim Northover3b0846e2014-05-24 12:50:23 +00002539 }
2540
Alex Lorenze40c8a22015-08-11 23:09:45 +00002541 ArgValue = DAG.getExtLoad(
2542 ExtType, DL, VA.getLocVT(), Chain, FIN,
2543 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
2544 MemVT, false, false, false, 0);
Tim Northover47e003c2014-05-26 17:21:53 +00002545
Tim Northover3b0846e2014-05-24 12:50:23 +00002546 InVals.push_back(ArgValue);
2547 }
2548 }
2549
2550 // varargs
2551 if (isVarArg) {
2552 if (!Subtarget->isTargetDarwin()) {
2553 // The AAPCS variadic function ABI is identical to the non-variadic
2554 // one. As a result there may be more arguments in registers and we should
2555 // save them for future reference.
2556 saveVarArgRegisters(CCInfo, DAG, DL, Chain);
2557 }
2558
2559 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
2560 // This will point to the next argument passed via stack.
2561 unsigned StackOffset = CCInfo.getNextStackOffset();
2562 // We currently pass all varargs at 8-byte alignment.
2563 StackOffset = ((StackOffset + 7) & ~7);
2564 AFI->setVarArgsStackIndex(MFI->CreateFixedObject(4, StackOffset, true));
2565 }
2566
2567 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2568 unsigned StackArgSize = CCInfo.getNextStackOffset();
2569 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2570 if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
2571 // This is a non-standard ABI so by fiat I say we're allowed to make full
2572 // use of the stack area to be popped, which must be aligned to 16 bytes in
2573 // any case:
Rui Ueyamada00f2f2016-01-14 21:06:47 +00002574 StackArgSize = alignTo(StackArgSize, 16);
Tim Northover3b0846e2014-05-24 12:50:23 +00002575
2576 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
2577 // a multiple of 16.
2578 FuncInfo->setArgumentStackToRestore(StackArgSize);
2579
2580 // This realignment carries over to the available bytes below. Our own
2581 // callers will guarantee the space is free by giving an aligned value to
2582 // CALLSEQ_START.
2583 }
2584 // Even if we're not expected to free up the space, it's useful to know how
2585 // much is there while considering tail calls (because we can reuse it).
2586 FuncInfo->setBytesInStackArgArea(StackArgSize);
2587
2588 return Chain;
2589}
2590
2591void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
2592 SelectionDAG &DAG, SDLoc DL,
2593 SDValue &Chain) const {
2594 MachineFunction &MF = DAG.getMachineFunction();
2595 MachineFrameInfo *MFI = MF.getFrameInfo();
2596 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Mehdi Amini44ede332015-07-09 02:09:04 +00002597 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00002598
2599 SmallVector<SDValue, 8> MemOps;
2600
2601 static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
2602 AArch64::X3, AArch64::X4, AArch64::X5,
2603 AArch64::X6, AArch64::X7 };
2604 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
Tim Northover3b6b7ca2015-02-21 02:11:17 +00002605 unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
Tim Northover3b0846e2014-05-24 12:50:23 +00002606
2607 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
2608 int GPRIdx = 0;
2609 if (GPRSaveSize != 0) {
2610 GPRIdx = MFI->CreateStackObject(GPRSaveSize, 8, false);
2611
Mehdi Amini44ede332015-07-09 02:09:04 +00002612 SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00002613
2614 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
2615 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
2616 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
Alex Lorenze40c8a22015-08-11 23:09:45 +00002617 SDValue Store = DAG.getStore(
2618 Val.getValue(1), DL, Val, FIN,
2619 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8), false,
2620 false, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00002621 MemOps.push_back(Store);
Mehdi Amini44ede332015-07-09 02:09:04 +00002622 FIN =
2623 DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00002624 }
2625 }
2626 FuncInfo->setVarArgsGPRIndex(GPRIdx);
2627 FuncInfo->setVarArgsGPRSize(GPRSaveSize);
2628
2629 if (Subtarget->hasFPARMv8()) {
2630 static const MCPhysReg FPRArgRegs[] = {
2631 AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
2632 AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
2633 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
Tim Northover3b6b7ca2015-02-21 02:11:17 +00002634 unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
Tim Northover3b0846e2014-05-24 12:50:23 +00002635
2636 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
2637 int FPRIdx = 0;
2638 if (FPRSaveSize != 0) {
2639 FPRIdx = MFI->CreateStackObject(FPRSaveSize, 16, false);
2640
Mehdi Amini44ede332015-07-09 02:09:04 +00002641 SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00002642
2643 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
2644 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
2645 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
2646
Alex Lorenze40c8a22015-08-11 23:09:45 +00002647 SDValue Store = DAG.getStore(
2648 Val.getValue(1), DL, Val, FIN,
2649 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16),
2650 false, false, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00002651 MemOps.push_back(Store);
Mehdi Amini44ede332015-07-09 02:09:04 +00002652 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
2653 DAG.getConstant(16, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00002654 }
2655 }
2656 FuncInfo->setVarArgsFPRIndex(FPRIdx);
2657 FuncInfo->setVarArgsFPRSize(FPRSaveSize);
2658 }
2659
2660 if (!MemOps.empty()) {
2661 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
2662 }
2663}
2664
2665/// LowerCallResult - Lower the result values of a call into the
2666/// appropriate copies out of appropriate physical registers.
2667SDValue AArch64TargetLowering::LowerCallResult(
2668 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
2669 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2670 SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
2671 SDValue ThisVal) const {
2672 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
2673 ? RetCC_AArch64_WebKit_JS
2674 : RetCC_AArch64_AAPCS;
2675 // Assign locations to each value returned by this call.
2676 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002677 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2678 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002679 CCInfo.AnalyzeCallResult(Ins, RetCC);
2680
2681 // Copy all of the result registers out of their specified physreg.
2682 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2683 CCValAssign VA = RVLocs[i];
2684
2685 // Pass 'this' value directly from the argument to return value, to avoid
2686 // reg unit interference
2687 if (i == 0 && isThisReturn) {
2688 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
2689 "unexpected return calling convention register assignment");
2690 InVals.push_back(ThisVal);
2691 continue;
2692 }
2693
2694 SDValue Val =
2695 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2696 Chain = Val.getValue(1);
2697 InFlag = Val.getValue(2);
2698
2699 switch (VA.getLocInfo()) {
2700 default:
2701 llvm_unreachable("Unknown loc info!");
2702 case CCValAssign::Full:
2703 break;
2704 case CCValAssign::BCvt:
2705 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2706 break;
2707 }
2708
2709 InVals.push_back(Val);
2710 }
2711
2712 return Chain;
2713}
2714
2715bool AArch64TargetLowering::isEligibleForTailCallOptimization(
2716 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
2717 bool isCalleeStructRet, bool isCallerStructRet,
2718 const SmallVectorImpl<ISD::OutputArg> &Outs,
2719 const SmallVectorImpl<SDValue> &OutVals,
2720 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2721 // For CallingConv::C this function knows whether the ABI needs
2722 // changing. That's not true for other conventions so they will have to opt in
2723 // manually.
2724 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
2725 return false;
2726
2727 const MachineFunction &MF = DAG.getMachineFunction();
2728 const Function *CallerF = MF.getFunction();
2729 CallingConv::ID CallerCC = CallerF->getCallingConv();
2730 bool CCMatch = CallerCC == CalleeCC;
2731
2732 // Byval parameters hand the function a pointer directly into the stack area
2733 // we want to reuse during a tail call. Working around this *is* possible (see
2734 // X86) but less efficient and uglier in LowerCall.
2735 for (Function::const_arg_iterator i = CallerF->arg_begin(),
2736 e = CallerF->arg_end();
2737 i != e; ++i)
2738 if (i->hasByValAttr())
2739 return false;
2740
2741 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2742 if (IsTailCallConvention(CalleeCC) && CCMatch)
2743 return true;
2744 return false;
2745 }
2746
Oliver Stannard12993dd2014-08-18 12:42:15 +00002747 // Externally-defined functions with weak linkage should not be
2748 // tail-called on AArch64 when the OS does not support dynamic
2749 // pre-emption of symbols, as the AAELF spec requires normal calls
2750 // to undefined weak functions to be replaced with a NOP or jump to the
2751 // next instruction. The behaviour of branch instructions in this
2752 // situation (as used for tail calls) is implementation-defined, so we
2753 // cannot rely on the linker replacing the tail call with a return.
2754 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2755 const GlobalValue *GV = G->getGlobal();
Daniel Sandersc81f4502015-06-16 15:44:21 +00002756 const Triple &TT = getTargetMachine().getTargetTriple();
Saleem Abdulrasool67f72992015-01-03 21:35:00 +00002757 if (GV->hasExternalWeakLinkage() &&
2758 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
Oliver Stannard12993dd2014-08-18 12:42:15 +00002759 return false;
2760 }
2761
Tim Northover3b0846e2014-05-24 12:50:23 +00002762 // Now we search for cases where we can use a tail call without changing the
2763 // ABI. Sibcall is used in some places (particularly gcc) to refer to this
2764 // concept.
2765
2766 // I want anyone implementing a new calling convention to think long and hard
2767 // about this assert.
2768 assert((!isVarArg || CalleeCC == CallingConv::C) &&
2769 "Unexpected variadic calling convention");
2770
2771 if (isVarArg && !Outs.empty()) {
2772 // At least two cases here: if caller is fastcc then we can't have any
2773 // memory arguments (we'd be expected to clean up the stack afterwards). If
2774 // caller is C then we could potentially use its argument area.
2775
2776 // FIXME: for now we take the most conservative of these in both cases:
2777 // disallow all variadic memory operands.
2778 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002779 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2780 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002781
2782 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
Pete Cooper7be8f8f2015-08-03 19:04:32 +00002783 for (const CCValAssign &ArgLoc : ArgLocs)
2784 if (!ArgLoc.isRegLoc())
Tim Northover3b0846e2014-05-24 12:50:23 +00002785 return false;
2786 }
2787
2788 // If the calling conventions do not match, then we'd better make sure the
2789 // results are returned in the same way as what the caller expects.
2790 if (!CCMatch) {
2791 SmallVector<CCValAssign, 16> RVLocs1;
Eric Christopherb5217502014-08-06 18:45:26 +00002792 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2793 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002794 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForCall(CalleeCC, isVarArg));
2795
2796 SmallVector<CCValAssign, 16> RVLocs2;
Eric Christopherb5217502014-08-06 18:45:26 +00002797 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2798 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002799 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForCall(CallerCC, isVarArg));
2800
2801 if (RVLocs1.size() != RVLocs2.size())
2802 return false;
2803 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2804 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2805 return false;
2806 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2807 return false;
2808 if (RVLocs1[i].isRegLoc()) {
2809 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2810 return false;
2811 } else {
2812 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2813 return false;
2814 }
2815 }
2816 }
2817
2818 // Nothing more to check if the callee is taking no arguments
2819 if (Outs.empty())
2820 return true;
2821
2822 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002823 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2824 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002825
2826 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2827
2828 const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2829
2830 // If the stack arguments for this call would fit into our own save area then
2831 // the call can be made tail.
2832 return CCInfo.getNextStackOffset() <= FuncInfo->getBytesInStackArgArea();
2833}
2834
2835SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
2836 SelectionDAG &DAG,
2837 MachineFrameInfo *MFI,
2838 int ClobberedFI) const {
2839 SmallVector<SDValue, 8> ArgChains;
2840 int64_t FirstByte = MFI->getObjectOffset(ClobberedFI);
2841 int64_t LastByte = FirstByte + MFI->getObjectSize(ClobberedFI) - 1;
2842
2843 // Include the original chain at the beginning of the list. When this is
2844 // used by target LowerCall hooks, this helps legalize find the
2845 // CALLSEQ_BEGIN node.
2846 ArgChains.push_back(Chain);
2847
2848 // Add a chain value for each stack argument corresponding
2849 for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
2850 UE = DAG.getEntryNode().getNode()->use_end();
2851 U != UE; ++U)
2852 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
2853 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
2854 if (FI->getIndex() < 0) {
2855 int64_t InFirstByte = MFI->getObjectOffset(FI->getIndex());
2856 int64_t InLastByte = InFirstByte;
2857 InLastByte += MFI->getObjectSize(FI->getIndex()) - 1;
2858
2859 if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
2860 (FirstByte <= InFirstByte && InFirstByte <= LastByte))
2861 ArgChains.push_back(SDValue(L, 1));
2862 }
2863
2864 // Build a tokenfactor for all the chains.
2865 return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
2866}
2867
2868bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
2869 bool TailCallOpt) const {
2870 return CallCC == CallingConv::Fast && TailCallOpt;
2871}
2872
2873bool AArch64TargetLowering::IsTailCallConvention(CallingConv::ID CallCC) const {
2874 return CallCC == CallingConv::Fast;
2875}
2876
2877/// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
2878/// and add input and output parameter nodes.
2879SDValue
2880AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
2881 SmallVectorImpl<SDValue> &InVals) const {
2882 SelectionDAG &DAG = CLI.DAG;
2883 SDLoc &DL = CLI.DL;
2884 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2885 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2886 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2887 SDValue Chain = CLI.Chain;
2888 SDValue Callee = CLI.Callee;
2889 bool &IsTailCall = CLI.IsTailCall;
2890 CallingConv::ID CallConv = CLI.CallConv;
2891 bool IsVarArg = CLI.IsVarArg;
2892
2893 MachineFunction &MF = DAG.getMachineFunction();
2894 bool IsStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
2895 bool IsThisReturn = false;
2896
2897 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2898 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2899 bool IsSibCall = false;
2900
2901 if (IsTailCall) {
2902 // Check if it's really possible to do a tail call.
2903 IsTailCall = isEligibleForTailCallOptimization(
2904 Callee, CallConv, IsVarArg, IsStructRet,
2905 MF.getFunction()->hasStructRetAttr(), Outs, OutVals, Ins, DAG);
2906 if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
2907 report_fatal_error("failed to perform tail call elimination on a call "
2908 "site marked musttail");
2909
2910 // A sibling call is one where we're under the usual C ABI and not planning
2911 // to change that but can still do a tail call:
2912 if (!TailCallOpt && IsTailCall)
2913 IsSibCall = true;
2914
2915 if (IsTailCall)
2916 ++NumTailCalls;
2917 }
2918
2919 // Analyze operands of the call, assigning locations to each operand.
2920 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002921 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
2922 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002923
2924 if (IsVarArg) {
2925 // Handle fixed and variable vector arguments differently.
2926 // Variable vector arguments always go into memory.
2927 unsigned NumArgs = Outs.size();
2928
2929 for (unsigned i = 0; i != NumArgs; ++i) {
2930 MVT ArgVT = Outs[i].VT;
2931 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2932 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
2933 /*IsVarArg=*/ !Outs[i].IsFixed);
2934 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
2935 assert(!Res && "Call operand has unhandled type");
2936 (void)Res;
2937 }
2938 } else {
2939 // At this point, Outs[].VT may already be promoted to i32. To correctly
2940 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2941 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2942 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
2943 // we use a special version of AnalyzeCallOperands to pass in ValVT and
2944 // LocVT.
2945 unsigned NumArgs = Outs.size();
2946 for (unsigned i = 0; i != NumArgs; ++i) {
2947 MVT ValVT = Outs[i].VT;
2948 // Get type of the original argument.
Mehdi Amini44ede332015-07-09 02:09:04 +00002949 EVT ActualVT = getValueType(DAG.getDataLayout(),
2950 CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
Tim Northover3b0846e2014-05-24 12:50:23 +00002951 /*AllowUnknown*/ true);
2952 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
2953 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2954 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
Tim Northover3b0846e2014-05-24 12:50:23 +00002955 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
Tim Northover47e003c2014-05-26 17:21:53 +00002956 ValVT = MVT::i8;
Tim Northover3b0846e2014-05-24 12:50:23 +00002957 else if (ActualMVT == MVT::i16)
Tim Northover47e003c2014-05-26 17:21:53 +00002958 ValVT = MVT::i16;
Tim Northover3b0846e2014-05-24 12:50:23 +00002959
2960 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
Tim Northover47e003c2014-05-26 17:21:53 +00002961 bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00002962 assert(!Res && "Call operand has unhandled type");
2963 (void)Res;
2964 }
2965 }
2966
2967 // Get a count of how many bytes are to be pushed on the stack.
2968 unsigned NumBytes = CCInfo.getNextStackOffset();
2969
2970 if (IsSibCall) {
2971 // Since we're not changing the ABI to make this a tail call, the memory
2972 // operands are already available in the caller's incoming argument space.
2973 NumBytes = 0;
2974 }
2975
2976 // FPDiff is the byte offset of the call's argument area from the callee's.
2977 // Stores to callee stack arguments will be placed in FixedStackSlots offset
2978 // by this amount for a tail call. In a sibling call it must be 0 because the
2979 // caller will deallocate the entire stack and the callee still expects its
2980 // arguments to begin at SP+0. Completely unused for non-tail calls.
2981 int FPDiff = 0;
2982
2983 if (IsTailCall && !IsSibCall) {
2984 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
2985
2986 // Since callee will pop argument stack as a tail call, we must keep the
2987 // popped size 16-byte aligned.
Rui Ueyamada00f2f2016-01-14 21:06:47 +00002988 NumBytes = alignTo(NumBytes, 16);
Tim Northover3b0846e2014-05-24 12:50:23 +00002989
2990 // FPDiff will be negative if this tail call requires more space than we
2991 // would automatically have in our incoming argument space. Positive if we
2992 // can actually shrink the stack.
2993 FPDiff = NumReusableBytes - NumBytes;
2994
2995 // The stack pointer must be 16-byte aligned at all times it's used for a
2996 // memory operation, which in practice means at *all* times and in
2997 // particular across call boundaries. Therefore our own arguments started at
2998 // a 16-byte aligned SP and the delta applied for the tail call should
2999 // satisfy the same constraint.
3000 assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
3001 }
3002
3003 // Adjust the stack pointer for the new arguments...
3004 // These operations are automatically eliminated by the prolog/epilog pass
3005 if (!IsSibCall)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003006 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, DL,
3007 true),
3008 DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003009
Mehdi Amini44ede332015-07-09 02:09:04 +00003010 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
3011 getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00003012
3013 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3014 SmallVector<SDValue, 8> MemOpChains;
Mehdi Amini44ede332015-07-09 02:09:04 +00003015 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003016
3017 // Walk the register/memloc assignments, inserting copies/loads.
3018 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
3019 ++i, ++realArgIdx) {
3020 CCValAssign &VA = ArgLocs[i];
3021 SDValue Arg = OutVals[realArgIdx];
3022 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
3023
3024 // Promote the value if needed.
3025 switch (VA.getLocInfo()) {
3026 default:
3027 llvm_unreachable("Unknown loc info!");
3028 case CCValAssign::Full:
3029 break;
3030 case CCValAssign::SExt:
3031 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3032 break;
3033 case CCValAssign::ZExt:
3034 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3035 break;
3036 case CCValAssign::AExt:
Tim Northover68ae5032014-05-26 17:22:07 +00003037 if (Outs[realArgIdx].ArgVT == MVT::i1) {
3038 // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
3039 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3040 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
3041 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003042 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3043 break;
3044 case CCValAssign::BCvt:
3045 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3046 break;
3047 case CCValAssign::FPExt:
3048 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3049 break;
3050 }
3051
3052 if (VA.isRegLoc()) {
3053 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i64) {
3054 assert(VA.getLocVT() == MVT::i64 &&
3055 "unexpected calling convention register assignment");
3056 assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
3057 "unexpected use of 'returned'");
3058 IsThisReturn = true;
3059 }
3060 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3061 } else {
3062 assert(VA.isMemLoc());
3063
3064 SDValue DstAddr;
3065 MachinePointerInfo DstInfo;
3066
3067 // FIXME: This works on big-endian for composite byvals, which are the
3068 // common case. It should also work for fundamental types too.
3069 uint32_t BEAlign = 0;
3070 unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
Amara Emerson82da7d02014-08-15 14:29:57 +00003071 : VA.getValVT().getSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00003072 OpSize = (OpSize + 7) / 8;
Tim Northover293d4142014-12-03 17:49:26 +00003073 if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
3074 !Flags.isInConsecutiveRegs()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003075 if (OpSize < 8)
3076 BEAlign = 8 - OpSize;
3077 }
3078 unsigned LocMemOffset = VA.getLocMemOffset();
3079 int32_t Offset = LocMemOffset + BEAlign;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003080 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
Mehdi Amini44ede332015-07-09 02:09:04 +00003081 PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
Tim Northover3b0846e2014-05-24 12:50:23 +00003082
3083 if (IsTailCall) {
3084 Offset = Offset + FPDiff;
3085 int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3086
Mehdi Amini44ede332015-07-09 02:09:04 +00003087 DstAddr = DAG.getFrameIndex(FI, PtrVT);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003088 DstInfo =
3089 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
Tim Northover3b0846e2014-05-24 12:50:23 +00003090
3091 // Make sure any stack arguments overlapping with where we're storing
3092 // are loaded before this eventual operation. Otherwise they'll be
3093 // clobbered.
3094 Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
3095 } else {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003096 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003097
Mehdi Amini44ede332015-07-09 02:09:04 +00003098 DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003099 DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
3100 LocMemOffset);
Tim Northover3b0846e2014-05-24 12:50:23 +00003101 }
3102
3103 if (Outs[i].Flags.isByVal()) {
3104 SDValue SizeNode =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003105 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00003106 SDValue Cpy = DAG.getMemcpy(
3107 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
Krzysztof Parzyszeka46c36b2015-04-13 17:16:45 +00003108 /*isVol = */ false, /*AlwaysInline = */ false,
3109 /*isTailCall = */ false,
3110 DstInfo, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00003111
3112 MemOpChains.push_back(Cpy);
3113 } else {
3114 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
3115 // promoted to a legal register type i32, we should truncate Arg back to
3116 // i1/i8/i16.
Tim Northover6890add2014-06-03 13:54:53 +00003117 if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
3118 VA.getValVT() == MVT::i16)
3119 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
Tim Northover3b0846e2014-05-24 12:50:23 +00003120
3121 SDValue Store =
3122 DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, false, false, 0);
3123 MemOpChains.push_back(Store);
3124 }
3125 }
3126 }
3127
3128 if (!MemOpChains.empty())
3129 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3130
3131 // Build a sequence of copy-to-reg nodes chained together with token chain
3132 // and flag operands which copy the outgoing args into the appropriate regs.
3133 SDValue InFlag;
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003134 for (auto &RegToPass : RegsToPass) {
3135 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3136 RegToPass.second, InFlag);
Tim Northover3b0846e2014-05-24 12:50:23 +00003137 InFlag = Chain.getValue(1);
3138 }
3139
3140 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3141 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3142 // node so that legalize doesn't hack it.
3143 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3144 Subtarget->isTargetMachO()) {
3145 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3146 const GlobalValue *GV = G->getGlobal();
3147 bool InternalLinkage = GV->hasInternalLinkage();
3148 if (InternalLinkage)
Mehdi Amini44ede332015-07-09 02:09:04 +00003149 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00003150 else {
Mehdi Amini44ede332015-07-09 02:09:04 +00003151 Callee =
3152 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT);
3153 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
Tim Northover3b0846e2014-05-24 12:50:23 +00003154 }
3155 } else if (ExternalSymbolSDNode *S =
3156 dyn_cast<ExternalSymbolSDNode>(Callee)) {
3157 const char *Sym = S->getSymbol();
Mehdi Amini44ede332015-07-09 02:09:04 +00003158 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
3159 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
Tim Northover3b0846e2014-05-24 12:50:23 +00003160 }
3161 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3162 const GlobalValue *GV = G->getGlobal();
Mehdi Amini44ede332015-07-09 02:09:04 +00003163 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00003164 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3165 const char *Sym = S->getSymbol();
Mehdi Amini44ede332015-07-09 02:09:04 +00003166 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00003167 }
3168
3169 // We don't usually want to end the call-sequence here because we would tidy
3170 // the frame up *after* the call, however in the ABI-changing tail-call case
3171 // we've carefully laid out the parameters so that when sp is reset they'll be
3172 // in the correct location.
3173 if (IsTailCall && !IsSibCall) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003174 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3175 DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003176 InFlag = Chain.getValue(1);
3177 }
3178
3179 std::vector<SDValue> Ops;
3180 Ops.push_back(Chain);
3181 Ops.push_back(Callee);
3182
3183 if (IsTailCall) {
3184 // Each tail call may have to adjust the stack by a different amount, so
3185 // this information must travel along with the operation for eventual
3186 // consumption by emitEpilogue.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003187 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00003188 }
3189
3190 // Add argument registers to the end of the list so that they are known live
3191 // into the call.
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003192 for (auto &RegToPass : RegsToPass)
3193 Ops.push_back(DAG.getRegister(RegToPass.first,
3194 RegToPass.second.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00003195
3196 // Add a register mask operand representing the call-preserved registers.
3197 const uint32_t *Mask;
Eric Christopher905f12d2015-01-29 00:19:42 +00003198 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00003199 if (IsThisReturn) {
3200 // For 'this' returns, use the X0-preserving mask if applicable
Eric Christopher9deb75d2015-03-11 22:42:13 +00003201 Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003202 if (!Mask) {
3203 IsThisReturn = false;
Eric Christopher9deb75d2015-03-11 22:42:13 +00003204 Mask = TRI->getCallPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003205 }
3206 } else
Eric Christopher9deb75d2015-03-11 22:42:13 +00003207 Mask = TRI->getCallPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003208
3209 assert(Mask && "Missing call preserved mask for calling convention");
3210 Ops.push_back(DAG.getRegisterMask(Mask));
3211
3212 if (InFlag.getNode())
3213 Ops.push_back(InFlag);
3214
3215 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3216
3217 // If we're doing a tall call, use a TC_RETURN here rather than an
3218 // actual call instruction.
Arnold Schwaighoferf54b73d2015-05-08 23:52:00 +00003219 if (IsTailCall) {
3220 MF.getFrameInfo()->setHasTailCall();
Tim Northover3b0846e2014-05-24 12:50:23 +00003221 return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
Arnold Schwaighoferf54b73d2015-05-08 23:52:00 +00003222 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003223
3224 // Returns a chain and a flag for retval copy to use.
3225 Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
3226 InFlag = Chain.getValue(1);
3227
Rui Ueyamada00f2f2016-01-14 21:06:47 +00003228 uint64_t CalleePopBytes =
3229 DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00003230
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003231 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3232 DAG.getIntPtrConstant(CalleePopBytes, DL, true),
Tim Northover3b0846e2014-05-24 12:50:23 +00003233 InFlag, DL);
3234 if (!Ins.empty())
3235 InFlag = Chain.getValue(1);
3236
3237 // Handle result values, copying them out of physregs into vregs that we
3238 // return.
3239 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3240 InVals, IsThisReturn,
3241 IsThisReturn ? OutVals[0] : SDValue());
3242}
3243
3244bool AArch64TargetLowering::CanLowerReturn(
3245 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
3246 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
3247 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3248 ? RetCC_AArch64_WebKit_JS
3249 : RetCC_AArch64_AAPCS;
3250 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003251 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
Tim Northover3b0846e2014-05-24 12:50:23 +00003252 return CCInfo.CheckReturn(Outs, RetCC);
3253}
3254
3255SDValue
3256AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3257 bool isVarArg,
3258 const SmallVectorImpl<ISD::OutputArg> &Outs,
3259 const SmallVectorImpl<SDValue> &OutVals,
3260 SDLoc DL, SelectionDAG &DAG) const {
3261 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3262 ? RetCC_AArch64_WebKit_JS
3263 : RetCC_AArch64_AAPCS;
3264 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003265 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3266 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00003267 CCInfo.AnalyzeReturn(Outs, RetCC);
3268
3269 // Copy the result values into the output registers.
3270 SDValue Flag;
3271 SmallVector<SDValue, 4> RetOps(1, Chain);
3272 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
3273 ++i, ++realRVLocIdx) {
3274 CCValAssign &VA = RVLocs[i];
3275 assert(VA.isRegLoc() && "Can only return in registers!");
3276 SDValue Arg = OutVals[realRVLocIdx];
3277
3278 switch (VA.getLocInfo()) {
3279 default:
3280 llvm_unreachable("Unknown loc info!");
3281 case CCValAssign::Full:
Tim Northover68ae5032014-05-26 17:22:07 +00003282 if (Outs[i].ArgVT == MVT::i1) {
3283 // AAPCS requires i1 to be zero-extended to i8 by the producer of the
3284 // value. This is strictly redundant on Darwin (which uses "zeroext
3285 // i1"), but will be optimised out before ISel.
3286 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3287 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3288 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003289 break;
3290 case CCValAssign::BCvt:
3291 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3292 break;
3293 }
3294
3295 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
3296 Flag = Chain.getValue(1);
3297 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3298 }
Manman Rencbe4f942015-12-16 21:04:19 +00003299 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3300 const MCPhysReg *I =
3301 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
3302 if (I) {
3303 for (; *I; ++I) {
3304 if (AArch64::GPR64RegClass.contains(*I))
3305 RetOps.push_back(DAG.getRegister(*I, MVT::i64));
3306 else if (AArch64::FPR64RegClass.contains(*I))
3307 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
3308 else
3309 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
3310 }
3311 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003312
3313 RetOps[0] = Chain; // Update chain.
3314
3315 // Add the flag if we have it.
3316 if (Flag.getNode())
3317 RetOps.push_back(Flag);
3318
3319 return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
3320}
3321
3322//===----------------------------------------------------------------------===//
3323// Other Lowering Code
3324//===----------------------------------------------------------------------===//
3325
3326SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
3327 SelectionDAG &DAG) const {
Mehdi Amini44ede332015-07-09 02:09:04 +00003328 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003329 SDLoc DL(Op);
Asiri Rathnayake369c0302014-09-10 13:54:38 +00003330 const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
3331 const GlobalValue *GV = GN->getGlobal();
Tim Northover3b0846e2014-05-24 12:50:23 +00003332 unsigned char OpFlags =
3333 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
3334
3335 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
3336 "unexpected offset in global node");
3337
3338 // This also catched the large code model case for Darwin.
3339 if ((OpFlags & AArch64II::MO_GOT) != 0) {
3340 SDValue GotAddr = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
3341 // FIXME: Once remat is capable of dealing with instructions with register
3342 // operands, expand this into two nodes instead of using a wrapper node.
3343 return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
3344 }
3345
Asiri Rathnayake369c0302014-09-10 13:54:38 +00003346 if ((OpFlags & AArch64II::MO_CONSTPOOL) != 0) {
3347 assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
3348 "use of MO_CONSTPOOL only supported on small model");
3349 SDValue Hi = DAG.getTargetConstantPool(GV, PtrVT, 0, 0, AArch64II::MO_PAGE);
3350 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3351 unsigned char LoFlags = AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
3352 SDValue Lo = DAG.getTargetConstantPool(GV, PtrVT, 0, 0, LoFlags);
3353 SDValue PoolAddr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003354 SDValue GlobalAddr = DAG.getLoad(
3355 PtrVT, DL, DAG.getEntryNode(), PoolAddr,
3356 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
3357 /*isVolatile=*/false,
3358 /*isNonTemporal=*/true,
3359 /*isInvariant=*/true, 8);
Asiri Rathnayake369c0302014-09-10 13:54:38 +00003360 if (GN->getOffset() != 0)
3361 return DAG.getNode(ISD::ADD, DL, PtrVT, GlobalAddr,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003362 DAG.getConstant(GN->getOffset(), DL, PtrVT));
Asiri Rathnayake369c0302014-09-10 13:54:38 +00003363 return GlobalAddr;
3364 }
3365
Tim Northover3b0846e2014-05-24 12:50:23 +00003366 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
3367 const unsigned char MO_NC = AArch64II::MO_NC;
3368 return DAG.getNode(
3369 AArch64ISD::WrapperLarge, DL, PtrVT,
3370 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G3),
3371 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
3372 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
3373 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
3374 } else {
3375 // Use ADRP/ADD or ADRP/LDR for everything else: the small model on ELF and
3376 // the only correct model on Darwin.
3377 SDValue Hi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
3378 OpFlags | AArch64II::MO_PAGE);
3379 unsigned char LoFlags = OpFlags | AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
3380 SDValue Lo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, LoFlags);
3381
3382 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3383 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3384 }
3385}
3386
3387/// \brief Convert a TLS address reference into the correct sequence of loads
3388/// and calls to compute the variable's address (for Darwin, currently) and
3389/// return an SDValue containing the final node.
3390
3391/// Darwin only has one TLS scheme which must be capable of dealing with the
3392/// fully general situation, in the worst case. This means:
3393/// + "extern __thread" declaration.
3394/// + Defined in a possibly unknown dynamic library.
3395///
3396/// The general system is that each __thread variable has a [3 x i64] descriptor
3397/// which contains information used by the runtime to calculate the address. The
3398/// only part of this the compiler needs to know about is the first xword, which
3399/// contains a function pointer that must be called with the address of the
3400/// entire descriptor in "x0".
3401///
3402/// Since this descriptor may be in a different unit, in general even the
3403/// descriptor must be accessed via an indirect load. The "ideal" code sequence
3404/// is:
3405/// adrp x0, _var@TLVPPAGE
3406/// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor
3407/// ldr x1, [x0] ; x1 contains 1st entry of descriptor,
3408/// ; the function pointer
3409/// blr x1 ; Uses descriptor address in x0
3410/// ; Address of _var is now in x0.
3411///
3412/// If the address of _var's descriptor *is* known to the linker, then it can
3413/// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
3414/// a slight efficiency gain.
3415SDValue
3416AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
3417 SelectionDAG &DAG) const {
3418 assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
3419
3420 SDLoc DL(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00003421 MVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003422 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3423
3424 SDValue TLVPAddr =
3425 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3426 SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
3427
3428 // The first entry in the descriptor is a function pointer that we must call
3429 // to obtain the address of the variable.
3430 SDValue Chain = DAG.getEntryNode();
3431 SDValue FuncTLVGet =
Alex Lorenze40c8a22015-08-11 23:09:45 +00003432 DAG.getLoad(MVT::i64, DL, Chain, DescAddr,
3433 MachinePointerInfo::getGOT(DAG.getMachineFunction()), false,
3434 true, true, 8);
Tim Northover3b0846e2014-05-24 12:50:23 +00003435 Chain = FuncTLVGet.getValue(1);
3436
3437 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3438 MFI->setAdjustsStack(true);
3439
3440 // TLS calls preserve all registers except those that absolutely must be
3441 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
3442 // silly).
Eric Christopher6c901622015-01-28 03:51:33 +00003443 const uint32_t *Mask =
Eric Christopher905f12d2015-01-29 00:19:42 +00003444 Subtarget->getRegisterInfo()->getTLSCallPreservedMask();
Tim Northover3b0846e2014-05-24 12:50:23 +00003445
3446 // Finally, we can make the call. This is just a degenerate version of a
3447 // normal AArch64 call node: x0 takes the address of the descriptor, and
3448 // returns the address of the variable in this thread.
3449 Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
3450 Chain =
3451 DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3452 Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
3453 DAG.getRegisterMask(Mask), Chain.getValue(1));
3454 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
3455}
3456
3457/// When accessing thread-local variables under either the general-dynamic or
3458/// local-dynamic system, we make a "TLS-descriptor" call. The variable will
3459/// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
Kristof Beylsaea84612015-03-04 09:12:08 +00003460/// is a function pointer to carry out the resolution.
Tim Northover3b0846e2014-05-24 12:50:23 +00003461///
Kristof Beylsaea84612015-03-04 09:12:08 +00003462/// The sequence is:
3463/// adrp x0, :tlsdesc:var
3464/// ldr x1, [x0, #:tlsdesc_lo12:var]
3465/// add x0, x0, #:tlsdesc_lo12:var
3466/// .tlsdesccall var
3467/// blr x1
3468/// (TPIDR_EL0 offset now in x0)
Tim Northover3b0846e2014-05-24 12:50:23 +00003469///
Kristof Beylsaea84612015-03-04 09:12:08 +00003470/// The above sequence must be produced unscheduled, to enable the linker to
3471/// optimize/relax this sequence.
3472/// Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
3473/// above sequence, and expanded really late in the compilation flow, to ensure
3474/// the sequence is produced as per above.
3475SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr, SDLoc DL,
3476 SelectionDAG &DAG) const {
Mehdi Amini44ede332015-07-09 02:09:04 +00003477 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003478
Kristof Beylsaea84612015-03-04 09:12:08 +00003479 SDValue Chain = DAG.getEntryNode();
Tim Northover3b0846e2014-05-24 12:50:23 +00003480 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
Kristof Beylsaea84612015-03-04 09:12:08 +00003481
3482 SmallVector<SDValue, 2> Ops;
3483 Ops.push_back(Chain);
3484 Ops.push_back(SymAddr);
3485
3486 Chain = DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, Ops);
3487 SDValue Glue = Chain.getValue(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00003488
3489 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
3490}
3491
3492SDValue
3493AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
3494 SelectionDAG &DAG) const {
3495 assert(Subtarget->isTargetELF() && "This function expects an ELF target");
3496 assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
3497 "ELF TLS only supported in small memory model");
Kristof Beylsaea84612015-03-04 09:12:08 +00003498 // Different choices can be made for the maximum size of the TLS area for a
3499 // module. For the small address model, the default TLS size is 16MiB and the
3500 // maximum TLS size is 4GiB.
3501 // FIXME: add -mtls-size command line option and make it control the 16MiB
3502 // vs. 4GiB code sequence generation.
Tim Northover3b0846e2014-05-24 12:50:23 +00003503 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3504
3505 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
Chih-Hung Hsieh1e859582015-07-28 16:24:05 +00003506
3507 if (DAG.getTarget().Options.EmulatedTLS)
3508 return LowerToTLSEmulatedModel(GA, DAG);
3509
Kristof Beylsaea84612015-03-04 09:12:08 +00003510 if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
3511 if (Model == TLSModel::LocalDynamic)
3512 Model = TLSModel::GeneralDynamic;
3513 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003514
3515 SDValue TPOff;
Mehdi Amini44ede332015-07-09 02:09:04 +00003516 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003517 SDLoc DL(Op);
3518 const GlobalValue *GV = GA->getGlobal();
3519
3520 SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
3521
3522 if (Model == TLSModel::LocalExec) {
3523 SDValue HiVar = DAG.getTargetGlobalAddress(
Kristof Beylsaea84612015-03-04 09:12:08 +00003524 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
Tim Northover3b0846e2014-05-24 12:50:23 +00003525 SDValue LoVar = DAG.getTargetGlobalAddress(
3526 GV, DL, PtrVT, 0,
Kristof Beylsaea84612015-03-04 09:12:08 +00003527 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
Tim Northover3b0846e2014-05-24 12:50:23 +00003528
Kristof Beylsaea84612015-03-04 09:12:08 +00003529 SDValue TPWithOff_lo =
3530 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003531 HiVar,
3532 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003533 0);
3534 SDValue TPWithOff =
3535 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003536 LoVar,
3537 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003538 0);
3539 return TPWithOff;
Tim Northover3b0846e2014-05-24 12:50:23 +00003540 } else if (Model == TLSModel::InitialExec) {
3541 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3542 TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
3543 } else if (Model == TLSModel::LocalDynamic) {
3544 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
3545 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
3546 // the beginning of the module's TLS region, followed by a DTPREL offset
3547 // calculation.
3548
3549 // These accesses will need deduplicating if there's more than one.
3550 AArch64FunctionInfo *MFI =
3551 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
3552 MFI->incNumLocalDynamicTLSAccesses();
3553
Tim Northover3b0846e2014-05-24 12:50:23 +00003554 // The call needs a relocation too for linker relaxation. It doesn't make
3555 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3556 // the address.
3557 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
3558 AArch64II::MO_TLS);
3559
3560 // Now we can calculate the offset from TPIDR_EL0 to this module's
3561 // thread-local area.
Kristof Beylsaea84612015-03-04 09:12:08 +00003562 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00003563
3564 // Now use :dtprel_whatever: operations to calculate this variable's offset
3565 // in its thread-storage area.
3566 SDValue HiVar = DAG.getTargetGlobalAddress(
Kristof Beylsaea84612015-03-04 09:12:08 +00003567 GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
Tim Northover3b0846e2014-05-24 12:50:23 +00003568 SDValue LoVar = DAG.getTargetGlobalAddress(
3569 GV, DL, MVT::i64, 0,
Tim Northover3b0846e2014-05-24 12:50:23 +00003570 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3571
Kristof Beylsaea84612015-03-04 09:12:08 +00003572 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003573 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003574 0);
3575 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003576 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003577 0);
3578 } else if (Model == TLSModel::GeneralDynamic) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003579 // The call needs a relocation too for linker relaxation. It doesn't make
3580 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3581 // the address.
3582 SDValue SymAddr =
3583 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3584
3585 // Finally we can make a call to calculate the offset from tpidr_el0.
Kristof Beylsaea84612015-03-04 09:12:08 +00003586 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00003587 } else
3588 llvm_unreachable("Unsupported ELF TLS access model");
3589
3590 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
3591}
3592
3593SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
3594 SelectionDAG &DAG) const {
3595 if (Subtarget->isTargetDarwin())
3596 return LowerDarwinGlobalTLSAddress(Op, DAG);
3597 else if (Subtarget->isTargetELF())
3598 return LowerELFGlobalTLSAddress(Op, DAG);
3599
3600 llvm_unreachable("Unexpected platform trying to use TLS");
3601}
3602SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3603 SDValue Chain = Op.getOperand(0);
3604 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3605 SDValue LHS = Op.getOperand(2);
3606 SDValue RHS = Op.getOperand(3);
3607 SDValue Dest = Op.getOperand(4);
3608 SDLoc dl(Op);
3609
3610 // Handle f128 first, since lowering it will result in comparing the return
3611 // value of a libcall against zero, which is just what the rest of LowerBR_CC
3612 // is expecting to deal with.
3613 if (LHS.getValueType() == MVT::f128) {
3614 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3615
3616 // If softenSetCCOperands returned a scalar, we need to compare the result
3617 // against zero to select between true and false values.
3618 if (!RHS.getNode()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003619 RHS = DAG.getConstant(0, dl, LHS.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00003620 CC = ISD::SETNE;
3621 }
3622 }
3623
3624 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
3625 // instruction.
3626 unsigned Opc = LHS.getOpcode();
Artyom Skrobov314ee042015-11-25 19:41:11 +00003627 if (LHS.getResNo() == 1 && isOneConstant(RHS) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00003628 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3629 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
3630 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
3631 "Unexpected condition code.");
3632 // Only lower legal XALUO ops.
3633 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
3634 return SDValue();
3635
3636 // The actual operation with overflow check.
3637 AArch64CC::CondCode OFCC;
3638 SDValue Value, Overflow;
3639 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
3640
3641 if (CC == ISD::SETNE)
3642 OFCC = getInvertedCondCode(OFCC);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003643 SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003644
Ahmed Bougachadf956a22015-02-06 23:15:39 +00003645 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3646 Overflow);
Tim Northover3b0846e2014-05-24 12:50:23 +00003647 }
3648
3649 if (LHS.getValueType().isInteger()) {
3650 assert((LHS.getValueType() == RHS.getValueType()) &&
3651 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3652
3653 // If the RHS of the comparison is zero, we can potentially fold this
3654 // to a specialized branch.
3655 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
3656 if (RHSC && RHSC->getZExtValue() == 0) {
3657 if (CC == ISD::SETEQ) {
3658 // See if we can use a TBZ to fold in an AND as well.
3659 // TBZ has a smaller branch displacement than CBZ. If the offset is
3660 // out of bounds, a late MI-layer pass rewrites branches.
3661 // 403.gcc is an example that hits this case.
3662 if (LHS.getOpcode() == ISD::AND &&
3663 isa<ConstantSDNode>(LHS.getOperand(1)) &&
3664 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3665 SDValue Test = LHS.getOperand(0);
3666 uint64_t Mask = LHS.getConstantOperandVal(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00003667 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003668 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3669 Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00003670 }
3671
3672 return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
3673 } else if (CC == ISD::SETNE) {
3674 // See if we can use a TBZ to fold in an AND as well.
3675 // TBZ has a smaller branch displacement than CBZ. If the offset is
3676 // out of bounds, a late MI-layer pass rewrites branches.
3677 // 403.gcc is an example that hits this case.
3678 if (LHS.getOpcode() == ISD::AND &&
3679 isa<ConstantSDNode>(LHS.getOperand(1)) &&
3680 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3681 SDValue Test = LHS.getOperand(0);
3682 uint64_t Mask = LHS.getConstantOperandVal(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00003683 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003684 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3685 Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00003686 }
3687
3688 return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
Chad Rosier579c02c2014-08-01 14:48:56 +00003689 } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
3690 // Don't combine AND since emitComparison converts the AND to an ANDS
3691 // (a.k.a. TST) and the test in the test bit and branch instruction
3692 // becomes redundant. This would also increase register pressure.
3693 uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
3694 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003695 DAG.getConstant(Mask, dl, MVT::i64), Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00003696 }
3697 }
Chad Rosier579c02c2014-08-01 14:48:56 +00003698 if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
3699 LHS.getOpcode() != ISD::AND) {
3700 // Don't combine AND since emitComparison converts the AND to an ANDS
3701 // (a.k.a. TST) and the test in the test bit and branch instruction
3702 // becomes redundant. This would also increase register pressure.
3703 uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
3704 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003705 DAG.getConstant(Mask, dl, MVT::i64), Dest);
Chad Rosier579c02c2014-08-01 14:48:56 +00003706 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003707
3708 SDValue CCVal;
3709 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3710 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3711 Cmp);
3712 }
3713
3714 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3715
3716 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
3717 // clean. Some of them require two branches to implement.
3718 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3719 AArch64CC::CondCode CC1, CC2;
3720 changeFPCCToAArch64CC(CC, CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003721 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003722 SDValue BR1 =
3723 DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
3724 if (CC2 != AArch64CC::AL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003725 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003726 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
3727 Cmp);
3728 }
3729
3730 return BR1;
3731}
3732
3733SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
3734 SelectionDAG &DAG) const {
3735 EVT VT = Op.getValueType();
3736 SDLoc DL(Op);
3737
3738 SDValue In1 = Op.getOperand(0);
3739 SDValue In2 = Op.getOperand(1);
3740 EVT SrcVT = In2.getValueType();
Ahmed Bougacha2a97b1b2015-08-13 01:13:56 +00003741
3742 if (SrcVT.bitsLT(VT))
3743 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
3744 else if (SrcVT.bitsGT(VT))
3745 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
Tim Northover3b0846e2014-05-24 12:50:23 +00003746
3747 EVT VecVT;
3748 EVT EltVT;
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00003749 uint64_t EltMask;
3750 SDValue VecVal1, VecVal2;
Tim Northover3b0846e2014-05-24 12:50:23 +00003751 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
3752 EltVT = MVT::i32;
Ahmed Bougachab0ae36f2015-08-04 00:42:34 +00003753 VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00003754 EltMask = 0x80000000ULL;
Tim Northover3b0846e2014-05-24 12:50:23 +00003755
3756 if (!VT.isVector()) {
3757 VecVal1 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3758 DAG.getUNDEF(VecVT), In1);
3759 VecVal2 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3760 DAG.getUNDEF(VecVT), In2);
3761 } else {
3762 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3763 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3764 }
3765 } else if (VT == MVT::f64 || VT == MVT::v2f64) {
3766 EltVT = MVT::i64;
3767 VecVT = MVT::v2i64;
3768
Eric Christopher572e03a2015-06-19 01:53:21 +00003769 // We want to materialize a mask with the high bit set, but the AdvSIMD
Tim Northover3b0846e2014-05-24 12:50:23 +00003770 // immediate moves cannot materialize that in a single instruction for
3771 // 64-bit elements. Instead, materialize zero and then negate it.
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00003772 EltMask = 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00003773
3774 if (!VT.isVector()) {
3775 VecVal1 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3776 DAG.getUNDEF(VecVT), In1);
3777 VecVal2 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3778 DAG.getUNDEF(VecVT), In2);
3779 } else {
3780 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3781 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3782 }
3783 } else {
3784 llvm_unreachable("Invalid type for copysign!");
3785 }
3786
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003787 SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00003788
3789 // If we couldn't materialize the mask above, then the mask vector will be
3790 // the zero vector, and we need to negate it here.
3791 if (VT == MVT::f64 || VT == MVT::v2f64) {
3792 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
3793 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
3794 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
3795 }
3796
3797 SDValue Sel =
3798 DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
3799
3800 if (VT == MVT::f32)
3801 return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
3802 else if (VT == MVT::f64)
3803 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
3804 else
3805 return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
3806}
3807
3808SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
Duncan P. N. Exon Smith003bb7d2015-02-14 02:09:06 +00003809 if (DAG.getMachineFunction().getFunction()->hasFnAttribute(
3810 Attribute::NoImplicitFloat))
Tim Northover3b0846e2014-05-24 12:50:23 +00003811 return SDValue();
3812
Weiming Zhao7a2d1562014-11-19 00:29:14 +00003813 if (!Subtarget->hasNEON())
3814 return SDValue();
3815
Tim Northover3b0846e2014-05-24 12:50:23 +00003816 // While there is no integer popcount instruction, it can
3817 // be more efficiently lowered to the following sequence that uses
3818 // AdvSIMD registers/instructions as long as the copies to/from
3819 // the AdvSIMD registers are cheap.
3820 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd
3821 // CNT V0.8B, V0.8B // 8xbyte pop-counts
3822 // ADDV B0, V0.8B // sum 8xbyte pop-counts
3823 // UMOV X0, V0.B[0] // copy byte result back to integer reg
3824 SDValue Val = Op.getOperand(0);
3825 SDLoc DL(Op);
3826 EVT VT = Op.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00003827
Hao Liue0335d72015-01-30 02:13:53 +00003828 if (VT == MVT::i32)
3829 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
3830 Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
Tim Northover3b0846e2014-05-24 12:50:23 +00003831
Hao Liue0335d72015-01-30 02:13:53 +00003832 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
Tim Northover3b0846e2014-05-24 12:50:23 +00003833 SDValue UaddLV = DAG.getNode(
3834 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003835 DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
Tim Northover3b0846e2014-05-24 12:50:23 +00003836
3837 if (VT == MVT::i64)
3838 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
3839 return UaddLV;
3840}
3841
3842SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3843
3844 if (Op.getValueType().isVector())
3845 return LowerVSETCC(Op, DAG);
3846
3847 SDValue LHS = Op.getOperand(0);
3848 SDValue RHS = Op.getOperand(1);
3849 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3850 SDLoc dl(Op);
3851
3852 // We chose ZeroOrOneBooleanContents, so use zero and one.
3853 EVT VT = Op.getValueType();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003854 SDValue TVal = DAG.getConstant(1, dl, VT);
3855 SDValue FVal = DAG.getConstant(0, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00003856
3857 // Handle f128 first, since one possible outcome is a normal integer
3858 // comparison which gets picked up by the next if statement.
3859 if (LHS.getValueType() == MVT::f128) {
3860 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3861
3862 // If softenSetCCOperands returned a scalar, use it.
3863 if (!RHS.getNode()) {
3864 assert(LHS.getValueType() == Op.getValueType() &&
3865 "Unexpected setcc expansion!");
3866 return LHS;
3867 }
3868 }
3869
3870 if (LHS.getValueType().isInteger()) {
3871 SDValue CCVal;
3872 SDValue Cmp =
3873 getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
3874
3875 // Note that we inverted the condition above, so we reverse the order of
3876 // the true and false operands here. This will allow the setcc to be
3877 // matched to a single CSINC instruction.
3878 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
3879 }
3880
3881 // Now we know we're dealing with FP values.
3882 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3883
3884 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
3885 // and do the comparison.
3886 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3887
3888 AArch64CC::CondCode CC1, CC2;
3889 changeFPCCToAArch64CC(CC, CC1, CC2);
3890 if (CC2 == AArch64CC::AL) {
3891 changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003892 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003893
3894 // Note that we inverted the condition above, so we reverse the order of
3895 // the true and false operands here. This will allow the setcc to be
3896 // matched to a single CSINC instruction.
3897 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
3898 } else {
3899 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
3900 // totally clean. Some of them require two CSELs to implement. As is in
3901 // this case, we emit the first CSEL and then emit a second using the output
3902 // of the first as the RHS. We're effectively OR'ing the two CC's together.
3903
3904 // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003905 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003906 SDValue CS1 =
3907 DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3908
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003909 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003910 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3911 }
3912}
3913
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00003914SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
3915 SDValue RHS, SDValue TVal,
3916 SDValue FVal, SDLoc dl,
Tim Northover3b0846e2014-05-24 12:50:23 +00003917 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00003918 // Handle f128 first, because it will result in a comparison of some RTLIB
3919 // call result against zero.
3920 if (LHS.getValueType() == MVT::f128) {
3921 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3922
3923 // If softenSetCCOperands returned a scalar, we need to compare the result
3924 // against zero to select between true and false values.
3925 if (!RHS.getNode()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003926 RHS = DAG.getConstant(0, dl, LHS.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00003927 CC = ISD::SETNE;
3928 }
3929 }
3930
Ahmed Bougacha88ddeae2015-11-17 16:45:40 +00003931 // Also handle f16, for which we need to do a f32 comparison.
3932 if (LHS.getValueType() == MVT::f16) {
3933 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
3934 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
3935 }
3936
3937 // Next, handle integers.
Tim Northover3b0846e2014-05-24 12:50:23 +00003938 if (LHS.getValueType().isInteger()) {
3939 assert((LHS.getValueType() == RHS.getValueType()) &&
3940 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3941
3942 unsigned Opcode = AArch64ISD::CSEL;
3943
3944 // If both the TVal and the FVal are constants, see if we can swap them in
3945 // order to for a CSINV or CSINC out of them.
3946 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
3947 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
3948
3949 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
3950 std::swap(TVal, FVal);
3951 std::swap(CTVal, CFVal);
3952 CC = ISD::getSetCCInverse(CC, true);
3953 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
3954 std::swap(TVal, FVal);
3955 std::swap(CTVal, CFVal);
3956 CC = ISD::getSetCCInverse(CC, true);
3957 } else if (TVal.getOpcode() == ISD::XOR) {
3958 // If TVal is a NOT we want to swap TVal and FVal so that we can match
3959 // with a CSINV rather than a CSEL.
Artyom Skrobov314ee042015-11-25 19:41:11 +00003960 if (isAllOnesConstant(TVal.getOperand(1))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003961 std::swap(TVal, FVal);
3962 std::swap(CTVal, CFVal);
3963 CC = ISD::getSetCCInverse(CC, true);
3964 }
3965 } else if (TVal.getOpcode() == ISD::SUB) {
3966 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
3967 // that we can match with a CSNEG rather than a CSEL.
Artyom Skrobov314ee042015-11-25 19:41:11 +00003968 if (isNullConstant(TVal.getOperand(0))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003969 std::swap(TVal, FVal);
3970 std::swap(CTVal, CFVal);
3971 CC = ISD::getSetCCInverse(CC, true);
3972 }
3973 } else if (CTVal && CFVal) {
3974 const int64_t TrueVal = CTVal->getSExtValue();
3975 const int64_t FalseVal = CFVal->getSExtValue();
3976 bool Swap = false;
3977
3978 // If both TVal and FVal are constants, see if FVal is the
3979 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
3980 // instead of a CSEL in that case.
3981 if (TrueVal == ~FalseVal) {
3982 Opcode = AArch64ISD::CSINV;
3983 } else if (TrueVal == -FalseVal) {
3984 Opcode = AArch64ISD::CSNEG;
3985 } else if (TVal.getValueType() == MVT::i32) {
3986 // If our operands are only 32-bit wide, make sure we use 32-bit
3987 // arithmetic for the check whether we can use CSINC. This ensures that
3988 // the addition in the check will wrap around properly in case there is
3989 // an overflow (which would not be the case if we do the check with
3990 // 64-bit arithmetic).
3991 const uint32_t TrueVal32 = CTVal->getZExtValue();
3992 const uint32_t FalseVal32 = CFVal->getZExtValue();
3993
3994 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
3995 Opcode = AArch64ISD::CSINC;
3996
3997 if (TrueVal32 > FalseVal32) {
3998 Swap = true;
3999 }
4000 }
4001 // 64-bit check whether we can use CSINC.
4002 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
4003 Opcode = AArch64ISD::CSINC;
4004
4005 if (TrueVal > FalseVal) {
4006 Swap = true;
4007 }
4008 }
4009
4010 // Swap TVal and FVal if necessary.
4011 if (Swap) {
4012 std::swap(TVal, FVal);
4013 std::swap(CTVal, CFVal);
4014 CC = ISD::getSetCCInverse(CC, true);
4015 }
4016
4017 if (Opcode != AArch64ISD::CSEL) {
4018 // Drop FVal since we can get its value by simply inverting/negating
4019 // TVal.
4020 FVal = TVal;
4021 }
4022 }
4023
4024 SDValue CCVal;
4025 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
4026
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004027 EVT VT = TVal.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00004028 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
4029 }
4030
4031 // Now we know we're dealing with FP values.
4032 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
4033 assert(LHS.getValueType() == RHS.getValueType());
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004034 EVT VT = TVal.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00004035 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
4036
4037 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4038 // clean. Some of them require two CSELs to implement.
4039 AArch64CC::CondCode CC1, CC2;
4040 changeFPCCToAArch64CC(CC, CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004041 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004042 SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4043
4044 // If we need a second CSEL, emit it, using the output of the first as the
4045 // RHS. We're effectively OR'ing the two CC's together.
4046 if (CC2 != AArch64CC::AL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004047 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004048 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4049 }
4050
4051 // Otherwise, return the output of the first CSEL.
4052 return CS1;
4053}
4054
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004055SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
4056 SelectionDAG &DAG) const {
4057 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4058 SDValue LHS = Op.getOperand(0);
4059 SDValue RHS = Op.getOperand(1);
4060 SDValue TVal = Op.getOperand(2);
4061 SDValue FVal = Op.getOperand(3);
4062 SDLoc DL(Op);
4063 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4064}
4065
4066SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
4067 SelectionDAG &DAG) const {
4068 SDValue CCVal = Op->getOperand(0);
4069 SDValue TVal = Op->getOperand(1);
4070 SDValue FVal = Op->getOperand(2);
4071 SDLoc DL(Op);
4072
4073 unsigned Opc = CCVal.getOpcode();
4074 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
4075 // instruction.
4076 if (CCVal.getResNo() == 1 &&
4077 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4078 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
4079 // Only lower legal XALUO ops.
4080 if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
4081 return SDValue();
4082
4083 AArch64CC::CondCode OFCC;
4084 SDValue Value, Overflow;
4085 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004086 SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004087
4088 return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
4089 CCVal, Overflow);
4090 }
4091
4092 // Lower it the same way as we would lower a SELECT_CC node.
4093 ISD::CondCode CC;
4094 SDValue LHS, RHS;
4095 if (CCVal.getOpcode() == ISD::SETCC) {
4096 LHS = CCVal.getOperand(0);
4097 RHS = CCVal.getOperand(1);
4098 CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
4099 } else {
4100 LHS = CCVal;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004101 RHS = DAG.getConstant(0, DL, CCVal.getValueType());
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004102 CC = ISD::SETNE;
4103 }
4104 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4105}
4106
Tim Northover3b0846e2014-05-24 12:50:23 +00004107SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
4108 SelectionDAG &DAG) const {
4109 // Jump table entries as PC relative offsets. No additional tweaking
4110 // is necessary here. Just get the address of the jump table.
4111 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00004112 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004113 SDLoc DL(Op);
4114
4115 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4116 !Subtarget->isTargetMachO()) {
4117 const unsigned char MO_NC = AArch64II::MO_NC;
4118 return DAG.getNode(
4119 AArch64ISD::WrapperLarge, DL, PtrVT,
4120 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G3),
4121 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G2 | MO_NC),
4122 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G1 | MO_NC),
4123 DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4124 AArch64II::MO_G0 | MO_NC));
4125 }
4126
4127 SDValue Hi =
4128 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_PAGE);
4129 SDValue Lo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4130 AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4131 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4132 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4133}
4134
4135SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
4136 SelectionDAG &DAG) const {
4137 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00004138 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004139 SDLoc DL(Op);
4140
4141 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4142 // Use the GOT for the large code model on iOS.
4143 if (Subtarget->isTargetMachO()) {
4144 SDValue GotAddr = DAG.getTargetConstantPool(
4145 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4146 AArch64II::MO_GOT);
4147 return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
4148 }
4149
4150 const unsigned char MO_NC = AArch64II::MO_NC;
4151 return DAG.getNode(
4152 AArch64ISD::WrapperLarge, DL, PtrVT,
4153 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4154 CP->getOffset(), AArch64II::MO_G3),
4155 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4156 CP->getOffset(), AArch64II::MO_G2 | MO_NC),
4157 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4158 CP->getOffset(), AArch64II::MO_G1 | MO_NC),
4159 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4160 CP->getOffset(), AArch64II::MO_G0 | MO_NC));
4161 } else {
4162 // Use ADRP/ADD or ADRP/LDR for everything else: the small memory model on
4163 // ELF, the only valid one on Darwin.
4164 SDValue Hi =
4165 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4166 CP->getOffset(), AArch64II::MO_PAGE);
4167 SDValue Lo = DAG.getTargetConstantPool(
4168 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4169 AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4170
4171 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4172 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4173 }
4174}
4175
4176SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
4177 SelectionDAG &DAG) const {
4178 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
Mehdi Amini44ede332015-07-09 02:09:04 +00004179 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004180 SDLoc DL(Op);
4181 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4182 !Subtarget->isTargetMachO()) {
4183 const unsigned char MO_NC = AArch64II::MO_NC;
4184 return DAG.getNode(
4185 AArch64ISD::WrapperLarge, DL, PtrVT,
4186 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G3),
4187 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
4188 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
4189 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
4190 } else {
4191 SDValue Hi = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGE);
4192 SDValue Lo = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGEOFF |
4193 AArch64II::MO_NC);
4194 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4195 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4196 }
4197}
4198
4199SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
4200 SelectionDAG &DAG) const {
4201 AArch64FunctionInfo *FuncInfo =
4202 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4203
4204 SDLoc DL(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00004205 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
4206 getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00004207 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4208 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
4209 MachinePointerInfo(SV), false, false, 0);
4210}
4211
4212SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
4213 SelectionDAG &DAG) const {
4214 // The layout of the va_list struct is specified in the AArch64 Procedure Call
4215 // Standard, section B.3.
4216 MachineFunction &MF = DAG.getMachineFunction();
4217 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Mehdi Amini44ede332015-07-09 02:09:04 +00004218 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004219 SDLoc DL(Op);
4220
4221 SDValue Chain = Op.getOperand(0);
4222 SDValue VAList = Op.getOperand(1);
4223 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4224 SmallVector<SDValue, 4> MemOps;
4225
4226 // void *__stack at offset 0
Mehdi Amini44ede332015-07-09 02:09:04 +00004227 SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004228 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
4229 MachinePointerInfo(SV), false, false, 8));
4230
4231 // void *__gr_top at offset 8
4232 int GPRSize = FuncInfo->getVarArgsGPRSize();
4233 if (GPRSize > 0) {
4234 SDValue GRTop, GRTopAddr;
4235
Mehdi Amini44ede332015-07-09 02:09:04 +00004236 GRTopAddr =
4237 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004238
Mehdi Amini44ede332015-07-09 02:09:04 +00004239 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
4240 GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
4241 DAG.getConstant(GPRSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004242
4243 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
4244 MachinePointerInfo(SV, 8), false, false, 8));
4245 }
4246
4247 // void *__vr_top at offset 16
4248 int FPRSize = FuncInfo->getVarArgsFPRSize();
4249 if (FPRSize > 0) {
4250 SDValue VRTop, VRTopAddr;
Mehdi Amini44ede332015-07-09 02:09:04 +00004251 VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4252 DAG.getConstant(16, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004253
Mehdi Amini44ede332015-07-09 02:09:04 +00004254 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
4255 VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
4256 DAG.getConstant(FPRSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004257
4258 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
4259 MachinePointerInfo(SV, 16), false, false, 8));
4260 }
4261
4262 // int __gr_offs at offset 24
Mehdi Amini44ede332015-07-09 02:09:04 +00004263 SDValue GROffsAddr =
4264 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004265 MemOps.push_back(DAG.getStore(Chain, DL,
4266 DAG.getConstant(-GPRSize, DL, MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00004267 GROffsAddr, MachinePointerInfo(SV, 24), false,
4268 false, 4));
4269
4270 // int __vr_offs at offset 28
Mehdi Amini44ede332015-07-09 02:09:04 +00004271 SDValue VROffsAddr =
4272 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004273 MemOps.push_back(DAG.getStore(Chain, DL,
4274 DAG.getConstant(-FPRSize, DL, MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00004275 VROffsAddr, MachinePointerInfo(SV, 28), false,
4276 false, 4));
4277
4278 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
4279}
4280
4281SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
4282 SelectionDAG &DAG) const {
4283 return Subtarget->isTargetDarwin() ? LowerDarwin_VASTART(Op, DAG)
4284 : LowerAAPCS_VASTART(Op, DAG);
4285}
4286
4287SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
4288 SelectionDAG &DAG) const {
4289 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
4290 // pointer.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004291 SDLoc DL(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00004292 unsigned VaListSize = Subtarget->isTargetDarwin() ? 8 : 32;
4293 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4294 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4295
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004296 return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1),
4297 Op.getOperand(2),
4298 DAG.getConstant(VaListSize, DL, MVT::i32),
Krzysztof Parzyszeka46c36b2015-04-13 17:16:45 +00004299 8, false, false, false, MachinePointerInfo(DestSV),
Tim Northover3b0846e2014-05-24 12:50:23 +00004300 MachinePointerInfo(SrcSV));
4301}
4302
4303SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
4304 assert(Subtarget->isTargetDarwin() &&
4305 "automatic va_arg instruction only works on Darwin");
4306
4307 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4308 EVT VT = Op.getValueType();
4309 SDLoc DL(Op);
4310 SDValue Chain = Op.getOperand(0);
4311 SDValue Addr = Op.getOperand(1);
4312 unsigned Align = Op.getConstantOperandVal(3);
Mehdi Amini44ede332015-07-09 02:09:04 +00004313 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004314
Mehdi Amini44ede332015-07-09 02:09:04 +00004315 SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V),
4316 false, false, false, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00004317 Chain = VAList.getValue(1);
4318
4319 if (Align > 8) {
4320 assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
Mehdi Amini44ede332015-07-09 02:09:04 +00004321 VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4322 DAG.getConstant(Align - 1, DL, PtrVT));
4323 VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
4324 DAG.getConstant(-(int64_t)Align, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004325 }
4326
4327 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
Mehdi Amini44ede332015-07-09 02:09:04 +00004328 uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
Tim Northover3b0846e2014-05-24 12:50:23 +00004329
4330 // Scalar integer and FP values smaller than 64 bits are implicitly extended
4331 // up to 64 bits. At the very least, we have to increase the striding of the
4332 // vaargs list to match this, and for FP values we need to introduce
4333 // FP_ROUND nodes as well.
4334 if (VT.isInteger() && !VT.isVector())
4335 ArgSize = 8;
4336 bool NeedFPTrunc = false;
4337 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
4338 ArgSize = 8;
4339 NeedFPTrunc = true;
4340 }
4341
4342 // Increment the pointer, VAList, to the next vaarg
Mehdi Amini44ede332015-07-09 02:09:04 +00004343 SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4344 DAG.getConstant(ArgSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004345 // Store the incremented VAList to the legalized pointer
4346 SDValue APStore = DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V),
4347 false, false, 0);
4348
4349 // Load the actual argument out of the pointer VAList
4350 if (NeedFPTrunc) {
4351 // Load the value as an f64.
4352 SDValue WideFP = DAG.getLoad(MVT::f64, DL, APStore, VAList,
4353 MachinePointerInfo(), false, false, false, 0);
4354 // Round the value down to an f32.
4355 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004356 DAG.getIntPtrConstant(1, DL));
Tim Northover3b0846e2014-05-24 12:50:23 +00004357 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
4358 // Merge the rounded value with the chain output of the load.
4359 return DAG.getMergeValues(Ops, DL);
4360 }
4361
4362 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo(), false,
4363 false, false, 0);
4364}
4365
4366SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
4367 SelectionDAG &DAG) const {
4368 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4369 MFI->setFrameAddressIsTaken(true);
4370
4371 EVT VT = Op.getValueType();
4372 SDLoc DL(Op);
4373 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4374 SDValue FrameAddr =
4375 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
4376 while (Depth--)
4377 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
4378 MachinePointerInfo(), false, false, false, 0);
4379 return FrameAddr;
4380}
4381
4382// FIXME? Maybe this could be a TableGen attribute on some registers and
4383// this table could be generated automatically from RegInfo.
Pat Gavlina717f252015-07-09 17:40:29 +00004384unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT,
4385 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004386 unsigned Reg = StringSwitch<unsigned>(RegName)
4387 .Case("sp", AArch64::SP)
4388 .Default(0);
4389 if (Reg)
4390 return Reg;
Luke Cheeseman85fd06d2015-06-01 12:02:47 +00004391 report_fatal_error(Twine("Invalid register name \""
4392 + StringRef(RegName) + "\"."));
Tim Northover3b0846e2014-05-24 12:50:23 +00004393}
4394
4395SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
4396 SelectionDAG &DAG) const {
4397 MachineFunction &MF = DAG.getMachineFunction();
4398 MachineFrameInfo *MFI = MF.getFrameInfo();
4399 MFI->setReturnAddressIsTaken(true);
4400
4401 EVT VT = Op.getValueType();
4402 SDLoc DL(Op);
4403 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4404 if (Depth) {
4405 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
Mehdi Amini44ede332015-07-09 02:09:04 +00004406 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00004407 return DAG.getLoad(VT, DL, DAG.getEntryNode(),
4408 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
4409 MachinePointerInfo(), false, false, false, 0);
4410 }
4411
4412 // Return LR, which contains the return address. Mark it an implicit live-in.
4413 unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
4414 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4415}
4416
4417/// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4418/// i64 values and take a 2 x i64 value to shift plus a shift amount.
4419SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
4420 SelectionDAG &DAG) const {
4421 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4422 EVT VT = Op.getValueType();
4423 unsigned VTBits = VT.getSizeInBits();
4424 SDLoc dl(Op);
4425 SDValue ShOpLo = Op.getOperand(0);
4426 SDValue ShOpHi = Op.getOperand(1);
4427 SDValue ShAmt = Op.getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00004428 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4429
4430 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4431
4432 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004433 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
Tim Northoverf3be9d52015-12-02 00:33:54 +00004434 SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4435
4436 // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
4437 // is "undef". We wanted 0, so CSEL it directly.
4438 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
4439 ISD::SETEQ, dl, DAG);
4440 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
4441 HiBitsForLo =
4442 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
4443 HiBitsForLo, CCVal, Cmp);
4444
Tim Northover3b0846e2014-05-24 12:50:23 +00004445 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004446 DAG.getConstant(VTBits, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00004447
Tim Northoverf3be9d52015-12-02 00:33:54 +00004448 SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4449 SDValue LoForNormalShift =
4450 DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
Tim Northover3b0846e2014-05-24 12:50:23 +00004451
Tim Northoverf3be9d52015-12-02 00:33:54 +00004452 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
4453 dl, DAG);
4454 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4455 SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4456 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
4457 LoForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00004458
4459 // AArch64 shifts larger than the register width are wrapped rather than
4460 // clamped, so we can't just emit "hi >> x".
Tim Northoverf3be9d52015-12-02 00:33:54 +00004461 SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4462 SDValue HiForBigShift =
4463 Opc == ISD::SRA
4464 ? DAG.getNode(Opc, dl, VT, ShOpHi,
4465 DAG.getConstant(VTBits - 1, dl, MVT::i64))
4466 : DAG.getConstant(0, dl, VT);
4467 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
4468 HiForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00004469
4470 SDValue Ops[2] = { Lo, Hi };
4471 return DAG.getMergeValues(Ops, dl);
4472}
4473
Tim Northoverf3be9d52015-12-02 00:33:54 +00004474
Tim Northover3b0846e2014-05-24 12:50:23 +00004475/// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4476/// i64 values and take a 2 x i64 value to shift plus a shift amount.
4477SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
Tim Northoverf3be9d52015-12-02 00:33:54 +00004478 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004479 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4480 EVT VT = Op.getValueType();
4481 unsigned VTBits = VT.getSizeInBits();
4482 SDLoc dl(Op);
4483 SDValue ShOpLo = Op.getOperand(0);
4484 SDValue ShOpHi = Op.getOperand(1);
4485 SDValue ShAmt = Op.getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00004486
4487 assert(Op.getOpcode() == ISD::SHL_PARTS);
4488 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004489 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
Tim Northoverf3be9d52015-12-02 00:33:54 +00004490 SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4491
4492 // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
4493 // is "undef". We wanted 0, so CSEL it directly.
4494 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
4495 ISD::SETEQ, dl, DAG);
4496 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
4497 LoBitsForHi =
4498 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
4499 LoBitsForHi, CCVal, Cmp);
4500
Tim Northover3b0846e2014-05-24 12:50:23 +00004501 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004502 DAG.getConstant(VTBits, dl, MVT::i64));
Tim Northoverf3be9d52015-12-02 00:33:54 +00004503 SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4504 SDValue HiForNormalShift =
4505 DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
Tim Northover3b0846e2014-05-24 12:50:23 +00004506
Tim Northoverf3be9d52015-12-02 00:33:54 +00004507 SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
Tim Northover3b0846e2014-05-24 12:50:23 +00004508
Tim Northoverf3be9d52015-12-02 00:33:54 +00004509 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
4510 dl, DAG);
4511 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4512 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
4513 HiForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00004514
4515 // AArch64 shifts of larger than register sizes are wrapped rather than
4516 // clamped, so we can't just emit "lo << a" if a is too big.
Tim Northoverf3be9d52015-12-02 00:33:54 +00004517 SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
4518 SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4519 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
4520 LoForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00004521
4522 SDValue Ops[2] = { Lo, Hi };
4523 return DAG.getMergeValues(Ops, dl);
4524}
4525
4526bool AArch64TargetLowering::isOffsetFoldingLegal(
4527 const GlobalAddressSDNode *GA) const {
4528 // The AArch64 target doesn't support folding offsets into global addresses.
4529 return false;
4530}
4531
4532bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4533 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
4534 // FIXME: We should be able to handle f128 as well with a clever lowering.
4535 if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32))
4536 return true;
4537
4538 if (VT == MVT::f64)
4539 return AArch64_AM::getFP64Imm(Imm) != -1;
4540 else if (VT == MVT::f32)
4541 return AArch64_AM::getFP32Imm(Imm) != -1;
4542 return false;
4543}
4544
4545//===----------------------------------------------------------------------===//
4546// AArch64 Optimization Hooks
4547//===----------------------------------------------------------------------===//
4548
4549//===----------------------------------------------------------------------===//
4550// AArch64 Inline Assembly Support
4551//===----------------------------------------------------------------------===//
4552
4553// Table of Constraints
4554// TODO: This is the current set of constraints supported by ARM for the
4555// compiler, not all of them may make sense, e.g. S may be difficult to support.
4556//
4557// r - A general register
4558// w - An FP/SIMD register of some size in the range v0-v31
4559// x - An FP/SIMD register of some size in the range v0-v15
4560// I - Constant that can be used with an ADD instruction
4561// J - Constant that can be used with a SUB instruction
4562// K - Constant that can be used with a 32-bit logical instruction
4563// L - Constant that can be used with a 64-bit logical instruction
4564// M - Constant that can be used as a 32-bit MOV immediate
4565// N - Constant that can be used as a 64-bit MOV immediate
4566// Q - A memory reference with base register and no offset
4567// S - A symbolic address
4568// Y - Floating point constant zero
4569// Z - Integer constant zero
4570//
4571// Note that general register operands will be output using their 64-bit x
4572// register name, whatever the size of the variable, unless the asm operand
4573// is prefixed by the %w modifier. Floating-point and SIMD register operands
4574// will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
4575// %q modifier.
4576
4577/// getConstraintType - Given a constraint letter, return the type of
4578/// constraint it is for this target.
4579AArch64TargetLowering::ConstraintType
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00004580AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004581 if (Constraint.size() == 1) {
4582 switch (Constraint[0]) {
4583 default:
4584 break;
4585 case 'z':
4586 return C_Other;
4587 case 'x':
4588 case 'w':
4589 return C_RegisterClass;
4590 // An address with a single base register. Due to the way we
4591 // currently handle addresses it is the same as 'r'.
4592 case 'Q':
4593 return C_Memory;
4594 }
4595 }
4596 return TargetLowering::getConstraintType(Constraint);
4597}
4598
4599/// Examine constraint type and operand type and determine a weight value.
4600/// This object must already have been set up with the operand type
4601/// and the current alternative constraint selected.
4602TargetLowering::ConstraintWeight
4603AArch64TargetLowering::getSingleConstraintMatchWeight(
4604 AsmOperandInfo &info, const char *constraint) const {
4605 ConstraintWeight weight = CW_Invalid;
4606 Value *CallOperandVal = info.CallOperandVal;
4607 // If we don't have a value, we can't do a match,
4608 // but allow it at the lowest weight.
4609 if (!CallOperandVal)
4610 return CW_Default;
4611 Type *type = CallOperandVal->getType();
4612 // Look at the constraint type.
4613 switch (*constraint) {
4614 default:
4615 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
4616 break;
4617 case 'x':
4618 case 'w':
4619 if (type->isFloatingPointTy() || type->isVectorTy())
4620 weight = CW_Register;
4621 break;
4622 case 'z':
4623 weight = CW_Constant;
4624 break;
4625 }
4626 return weight;
4627}
4628
4629std::pair<unsigned, const TargetRegisterClass *>
4630AArch64TargetLowering::getRegForInlineAsmConstraint(
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00004631 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004632 if (Constraint.size() == 1) {
4633 switch (Constraint[0]) {
4634 case 'r':
4635 if (VT.getSizeInBits() == 64)
4636 return std::make_pair(0U, &AArch64::GPR64commonRegClass);
4637 return std::make_pair(0U, &AArch64::GPR32commonRegClass);
4638 case 'w':
4639 if (VT == MVT::f32)
4640 return std::make_pair(0U, &AArch64::FPR32RegClass);
4641 if (VT.getSizeInBits() == 64)
4642 return std::make_pair(0U, &AArch64::FPR64RegClass);
4643 if (VT.getSizeInBits() == 128)
4644 return std::make_pair(0U, &AArch64::FPR128RegClass);
4645 break;
4646 // The instructions that this constraint is designed for can
4647 // only take 128-bit registers so just use that regclass.
4648 case 'x':
4649 if (VT.getSizeInBits() == 128)
4650 return std::make_pair(0U, &AArch64::FPR128_loRegClass);
4651 break;
4652 }
4653 }
4654 if (StringRef("{cc}").equals_lower(Constraint))
4655 return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
4656
4657 // Use the default implementation in TargetLowering to convert the register
4658 // constraint into a member of a register class.
4659 std::pair<unsigned, const TargetRegisterClass *> Res;
Eric Christopher11e4df72015-02-26 22:38:43 +00004660 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004661
4662 // Not found as a standard register?
4663 if (!Res.second) {
4664 unsigned Size = Constraint.size();
4665 if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
4666 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00004667 int RegNo;
4668 bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
4669 if (!Failed && RegNo >= 0 && RegNo <= 31) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004670 // v0 - v31 are aliases of q0 - q31.
4671 // By default we'll emit v0-v31 for this unless there's a modifier where
4672 // we'll emit the correct register as well.
4673 Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
4674 Res.second = &AArch64::FPR128RegClass;
4675 }
4676 }
4677 }
4678
4679 return Res;
4680}
4681
4682/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
4683/// vector. If it is invalid, don't add anything to Ops.
4684void AArch64TargetLowering::LowerAsmOperandForConstraint(
4685 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
4686 SelectionDAG &DAG) const {
4687 SDValue Result;
4688
4689 // Currently only support length 1 constraints.
4690 if (Constraint.length() != 1)
4691 return;
4692
4693 char ConstraintLetter = Constraint[0];
4694 switch (ConstraintLetter) {
4695 default:
4696 break;
4697
4698 // This set of constraints deal with valid constants for various instructions.
4699 // Validate and return a target constant for them if we can.
4700 case 'z': {
4701 // 'z' maps to xzr or wzr so it needs an input of 0.
Artyom Skrobov314ee042015-11-25 19:41:11 +00004702 if (!isNullConstant(Op))
Tim Northover3b0846e2014-05-24 12:50:23 +00004703 return;
4704
4705 if (Op.getValueType() == MVT::i64)
4706 Result = DAG.getRegister(AArch64::XZR, MVT::i64);
4707 else
4708 Result = DAG.getRegister(AArch64::WZR, MVT::i32);
4709 break;
4710 }
4711
4712 case 'I':
4713 case 'J':
4714 case 'K':
4715 case 'L':
4716 case 'M':
4717 case 'N':
4718 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4719 if (!C)
4720 return;
4721
4722 // Grab the value and do some validation.
4723 uint64_t CVal = C->getZExtValue();
4724 switch (ConstraintLetter) {
4725 // The I constraint applies only to simple ADD or SUB immediate operands:
4726 // i.e. 0 to 4095 with optional shift by 12
4727 // The J constraint applies only to ADD or SUB immediates that would be
4728 // valid when negated, i.e. if [an add pattern] were to be output as a SUB
4729 // instruction [or vice versa], in other words -1 to -4095 with optional
4730 // left shift by 12.
4731 case 'I':
4732 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
4733 break;
4734 return;
4735 case 'J': {
4736 uint64_t NVal = -C->getSExtValue();
Tim Northover2c46beb2014-07-27 07:10:29 +00004737 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
4738 CVal = C->getSExtValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00004739 break;
Tim Northover2c46beb2014-07-27 07:10:29 +00004740 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004741 return;
4742 }
4743 // The K and L constraints apply *only* to logical immediates, including
4744 // what used to be the MOVI alias for ORR (though the MOVI alias has now
4745 // been removed and MOV should be used). So these constraints have to
4746 // distinguish between bit patterns that are valid 32-bit or 64-bit
4747 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
4748 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
4749 // versa.
4750 case 'K':
4751 if (AArch64_AM::isLogicalImmediate(CVal, 32))
4752 break;
4753 return;
4754 case 'L':
4755 if (AArch64_AM::isLogicalImmediate(CVal, 64))
4756 break;
4757 return;
4758 // The M and N constraints are a superset of K and L respectively, for use
4759 // with the MOV (immediate) alias. As well as the logical immediates they
4760 // also match 32 or 64-bit immediates that can be loaded either using a
4761 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
4762 // (M) or 64-bit 0x1234000000000000 (N) etc.
4763 // As a note some of this code is liberally stolen from the asm parser.
4764 case 'M': {
4765 if (!isUInt<32>(CVal))
4766 return;
4767 if (AArch64_AM::isLogicalImmediate(CVal, 32))
4768 break;
4769 if ((CVal & 0xFFFF) == CVal)
4770 break;
4771 if ((CVal & 0xFFFF0000ULL) == CVal)
4772 break;
4773 uint64_t NCVal = ~(uint32_t)CVal;
4774 if ((NCVal & 0xFFFFULL) == NCVal)
4775 break;
4776 if ((NCVal & 0xFFFF0000ULL) == NCVal)
4777 break;
4778 return;
4779 }
4780 case 'N': {
4781 if (AArch64_AM::isLogicalImmediate(CVal, 64))
4782 break;
4783 if ((CVal & 0xFFFFULL) == CVal)
4784 break;
4785 if ((CVal & 0xFFFF0000ULL) == CVal)
4786 break;
4787 if ((CVal & 0xFFFF00000000ULL) == CVal)
4788 break;
4789 if ((CVal & 0xFFFF000000000000ULL) == CVal)
4790 break;
4791 uint64_t NCVal = ~CVal;
4792 if ((NCVal & 0xFFFFULL) == NCVal)
4793 break;
4794 if ((NCVal & 0xFFFF0000ULL) == NCVal)
4795 break;
4796 if ((NCVal & 0xFFFF00000000ULL) == NCVal)
4797 break;
4798 if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
4799 break;
4800 return;
4801 }
4802 default:
4803 return;
4804 }
4805
4806 // All assembler immediates are 64-bit integers.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004807 Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00004808 break;
4809 }
4810
4811 if (Result.getNode()) {
4812 Ops.push_back(Result);
4813 return;
4814 }
4815
4816 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
4817}
4818
4819//===----------------------------------------------------------------------===//
4820// AArch64 Advanced SIMD Support
4821//===----------------------------------------------------------------------===//
4822
4823/// WidenVector - Given a value in the V64 register class, produce the
4824/// equivalent value in the V128 register class.
4825static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
4826 EVT VT = V64Reg.getValueType();
4827 unsigned NarrowSize = VT.getVectorNumElements();
4828 MVT EltTy = VT.getVectorElementType().getSimpleVT();
4829 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
4830 SDLoc DL(V64Reg);
4831
4832 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004833 V64Reg, DAG.getConstant(0, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00004834}
4835
4836/// getExtFactor - Determine the adjustment factor for the position when
4837/// generating an "extract from vector registers" instruction.
4838static unsigned getExtFactor(SDValue &V) {
4839 EVT EltType = V.getValueType().getVectorElementType();
4840 return EltType.getSizeInBits() / 8;
4841}
4842
4843/// NarrowVector - Given a value in the V128 register class, produce the
4844/// equivalent value in the V64 register class.
4845static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
4846 EVT VT = V128Reg.getValueType();
4847 unsigned WideSize = VT.getVectorNumElements();
4848 MVT EltTy = VT.getVectorElementType().getSimpleVT();
4849 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
4850 SDLoc DL(V128Reg);
4851
4852 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
4853}
4854
4855// Gather data to see if the operation can be modelled as a
4856// shuffle in combination with VEXTs.
4857SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
4858 SelectionDAG &DAG) const {
Kevin Qinf0ec9af2014-06-18 05:54:42 +00004859 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
Tim Northover3b0846e2014-05-24 12:50:23 +00004860 SDLoc dl(Op);
4861 EVT VT = Op.getValueType();
4862 unsigned NumElts = VT.getVectorNumElements();
4863
Tim Northover7324e842014-07-24 15:39:55 +00004864 struct ShuffleSourceInfo {
4865 SDValue Vec;
4866 unsigned MinElt;
4867 unsigned MaxElt;
Tim Northover3b0846e2014-05-24 12:50:23 +00004868
Tim Northover7324e842014-07-24 15:39:55 +00004869 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
4870 // be compatible with the shuffle we intend to construct. As a result
4871 // ShuffleVec will be some sliding window into the original Vec.
4872 SDValue ShuffleVec;
4873
4874 // Code should guarantee that element i in Vec starts at element "WindowBase
4875 // + i * WindowScale in ShuffleVec".
4876 int WindowBase;
4877 int WindowScale;
4878
4879 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
4880 ShuffleSourceInfo(SDValue Vec)
4881 : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
4882 WindowScale(1) {}
4883 };
4884
4885 // First gather all vectors used as an immediate source for this BUILD_VECTOR
4886 // node.
4887 SmallVector<ShuffleSourceInfo, 2> Sources;
Tim Northover3b0846e2014-05-24 12:50:23 +00004888 for (unsigned i = 0; i < NumElts; ++i) {
4889 SDValue V = Op.getOperand(i);
4890 if (V.getOpcode() == ISD::UNDEF)
4891 continue;
Ahmed Bougachadfc77352016-01-14 02:12:30 +00004892 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4893 !isa<ConstantSDNode>(V.getOperand(1))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004894 // A shuffle can only come from building a vector from various
Ahmed Bougachadfc77352016-01-14 02:12:30 +00004895 // elements of other vectors, provided their indices are constant.
Tim Northover3b0846e2014-05-24 12:50:23 +00004896 return SDValue();
4897 }
4898
Tim Northover7324e842014-07-24 15:39:55 +00004899 // Add this element source to the list if it's not already there.
Tim Northover3b0846e2014-05-24 12:50:23 +00004900 SDValue SourceVec = V.getOperand(0);
Tim Northover7324e842014-07-24 15:39:55 +00004901 auto Source = std::find(Sources.begin(), Sources.end(), SourceVec);
4902 if (Source == Sources.end())
James Molloyf497d552014-10-17 17:06:31 +00004903 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
Tim Northover3b0846e2014-05-24 12:50:23 +00004904
Tim Northover7324e842014-07-24 15:39:55 +00004905 // Update the minimum and maximum lane number seen.
4906 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4907 Source->MinElt = std::min(Source->MinElt, EltNo);
4908 Source->MaxElt = std::max(Source->MaxElt, EltNo);
Tim Northover3b0846e2014-05-24 12:50:23 +00004909 }
4910
4911 // Currently only do something sane when at most two source vectors
Tim Northover7324e842014-07-24 15:39:55 +00004912 // are involved.
4913 if (Sources.size() > 2)
Tim Northover3b0846e2014-05-24 12:50:23 +00004914 return SDValue();
4915
Kevin Qin9a2a2c52014-07-24 02:05:42 +00004916 // Find out the smallest element size among result and two sources, and use
4917 // it as element size to build the shuffle_vector.
4918 EVT SmallestEltTy = VT.getVectorElementType();
Tim Northover7324e842014-07-24 15:39:55 +00004919 for (auto &Source : Sources) {
4920 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00004921 if (SrcEltTy.bitsLT(SmallestEltTy)) {
4922 SmallestEltTy = SrcEltTy;
4923 }
4924 }
4925 unsigned ResMultiplier =
4926 VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00004927 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
4928 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
Tim Northover3b0846e2014-05-24 12:50:23 +00004929
Tim Northover7324e842014-07-24 15:39:55 +00004930 // If the source vector is too wide or too narrow, we may nevertheless be able
4931 // to construct a compatible shuffle either by concatenating it with UNDEF or
4932 // extracting a suitable range of elements.
4933 for (auto &Src : Sources) {
4934 EVT SrcVT = Src.ShuffleVec.getValueType();
Kevin Qinf0ec9af2014-06-18 05:54:42 +00004935
Tim Northover7324e842014-07-24 15:39:55 +00004936 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
Tim Northover3b0846e2014-05-24 12:50:23 +00004937 continue;
Tim Northover7324e842014-07-24 15:39:55 +00004938
4939 // This stage of the search produces a source with the same element type as
4940 // the original, but with a total width matching the BUILD_VECTOR output.
4941 EVT EltVT = SrcVT.getVectorElementType();
James Molloyf497d552014-10-17 17:06:31 +00004942 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
4943 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
Tim Northover7324e842014-07-24 15:39:55 +00004944
4945 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
4946 assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00004947 // We can pad out the smaller vector for free, so if it's part of a
4948 // shuffle...
Tim Northover7324e842014-07-24 15:39:55 +00004949 Src.ShuffleVec =
4950 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
4951 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00004952 continue;
4953 }
4954
Tim Northover7324e842014-07-24 15:39:55 +00004955 assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00004956
James Molloyf497d552014-10-17 17:06:31 +00004957 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004958 // Span too large for a VEXT to cope
4959 return SDValue();
4960 }
4961
James Molloyf497d552014-10-17 17:06:31 +00004962 if (Src.MinElt >= NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004963 // The extraction can just take the second half
Tim Northover7324e842014-07-24 15:39:55 +00004964 Src.ShuffleVec =
4965 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004966 DAG.getConstant(NumSrcElts, dl, MVT::i64));
James Molloyf497d552014-10-17 17:06:31 +00004967 Src.WindowBase = -NumSrcElts;
4968 } else if (Src.MaxElt < NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004969 // The extraction can just take the first half
Tim Northover5e84fe32014-12-06 00:33:37 +00004970 Src.ShuffleVec =
4971 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004972 DAG.getConstant(0, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00004973 } else {
4974 // An actual VEXT is needed
Tim Northover5e84fe32014-12-06 00:33:37 +00004975 SDValue VEXTSrc1 =
4976 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004977 DAG.getConstant(0, dl, MVT::i64));
Tim Northover7324e842014-07-24 15:39:55 +00004978 SDValue VEXTSrc2 =
4979 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004980 DAG.getConstant(NumSrcElts, dl, MVT::i64));
Tim Northover7324e842014-07-24 15:39:55 +00004981 unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
4982
4983 Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004984 VEXTSrc2,
4985 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover7324e842014-07-24 15:39:55 +00004986 Src.WindowBase = -Src.MinElt;
Tim Northover3b0846e2014-05-24 12:50:23 +00004987 }
4988 }
4989
Tim Northover7324e842014-07-24 15:39:55 +00004990 // Another possible incompatibility occurs from the vector element types. We
4991 // can fix this by bitcasting the source vectors to the same type we intend
4992 // for the shuffle.
4993 for (auto &Src : Sources) {
4994 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
4995 if (SrcEltTy == SmallestEltTy)
4996 continue;
4997 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
4998 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
4999 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
5000 Src.WindowBase *= Src.WindowScale;
5001 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005002
Tim Northover7324e842014-07-24 15:39:55 +00005003 // Final sanity check before we try to actually produce a shuffle.
5004 DEBUG(
5005 for (auto Src : Sources)
5006 assert(Src.ShuffleVec.getValueType() == ShuffleVT);
5007 );
5008
5009 // The stars all align, our next step is to produce the mask for the shuffle.
5010 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
5011 int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00005012 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005013 SDValue Entry = Op.getOperand(i);
Tim Northover7324e842014-07-24 15:39:55 +00005014 if (Entry.getOpcode() == ISD::UNDEF)
5015 continue;
Tim Northover3b0846e2014-05-24 12:50:23 +00005016
Tim Northover7324e842014-07-24 15:39:55 +00005017 auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0));
5018 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
5019
5020 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
5021 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
5022 // segment.
5023 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
5024 int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
5025 VT.getVectorElementType().getSizeInBits());
5026 int LanesDefined = BitsDefined / BitsPerShuffleLane;
5027
5028 // This source is expected to fill ResMultiplier lanes of the final shuffle,
5029 // starting at the appropriate offset.
5030 int *LaneMask = &Mask[i * ResMultiplier];
5031
5032 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
5033 ExtractBase += NumElts * (Src - Sources.begin());
5034 for (int j = 0; j < LanesDefined; ++j)
5035 LaneMask[j] = ExtractBase + j;
Tim Northover3b0846e2014-05-24 12:50:23 +00005036 }
5037
5038 // Final check before we try to produce nonsense...
Tim Northover7324e842014-07-24 15:39:55 +00005039 if (!isShuffleMaskLegal(Mask, ShuffleVT))
5040 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00005041
Tim Northover7324e842014-07-24 15:39:55 +00005042 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
5043 for (unsigned i = 0; i < Sources.size(); ++i)
5044 ShuffleOps[i] = Sources[i].ShuffleVec;
5045
5046 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
5047 ShuffleOps[1], &Mask[0]);
5048 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
Tim Northover3b0846e2014-05-24 12:50:23 +00005049}
5050
5051// check if an EXT instruction can handle the shuffle mask when the
5052// vector sources of the shuffle are the same.
5053static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
5054 unsigned NumElts = VT.getVectorNumElements();
5055
5056 // Assume that the first shuffle index is not UNDEF. Fail if it is.
5057 if (M[0] < 0)
5058 return false;
5059
5060 Imm = M[0];
5061
5062 // If this is a VEXT shuffle, the immediate value is the index of the first
5063 // element. The other shuffle indices must be the successive elements after
5064 // the first one.
5065 unsigned ExpectedElt = Imm;
5066 for (unsigned i = 1; i < NumElts; ++i) {
5067 // Increment the expected index. If it wraps around, just follow it
5068 // back to index zero and keep going.
5069 ++ExpectedElt;
5070 if (ExpectedElt == NumElts)
5071 ExpectedElt = 0;
5072
5073 if (M[i] < 0)
5074 continue; // ignore UNDEF indices
5075 if (ExpectedElt != static_cast<unsigned>(M[i]))
5076 return false;
5077 }
5078
5079 return true;
5080}
5081
5082// check if an EXT instruction can handle the shuffle mask when the
5083// vector sources of the shuffle are different.
5084static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
5085 unsigned &Imm) {
5086 // Look for the first non-undef element.
5087 const int *FirstRealElt = std::find_if(M.begin(), M.end(),
5088 [](int Elt) {return Elt >= 0;});
5089
5090 // Benefit form APInt to handle overflow when calculating expected element.
5091 unsigned NumElts = VT.getVectorNumElements();
5092 unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
5093 APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
5094 // The following shuffle indices must be the successive elements after the
5095 // first real element.
5096 const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
5097 [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
5098 if (FirstWrongElt != M.end())
5099 return false;
5100
5101 // The index of an EXT is the first element if it is not UNDEF.
5102 // Watch out for the beginning UNDEFs. The EXT index should be the expected
Junmo Park3b8c7152016-01-05 09:36:47 +00005103 // value of the first element. E.g.
Tim Northover3b0846e2014-05-24 12:50:23 +00005104 // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
5105 // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
5106 // ExpectedElt is the last mask index plus 1.
5107 Imm = ExpectedElt.getZExtValue();
5108
5109 // There are two difference cases requiring to reverse input vectors.
5110 // For example, for vector <4 x i32> we have the following cases,
5111 // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
5112 // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
5113 // For both cases, we finally use mask <5, 6, 7, 0>, which requires
5114 // to reverse two input vectors.
5115 if (Imm < NumElts)
5116 ReverseEXT = true;
5117 else
5118 Imm -= NumElts;
5119
5120 return true;
5121}
5122
5123/// isREVMask - Check if a vector shuffle corresponds to a REV
5124/// instruction with the specified blocksize. (The order of the elements
5125/// within each block of the vector is reversed.)
5126static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5127 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
5128 "Only possible block sizes for REV are: 16, 32, 64");
5129
5130 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5131 if (EltSz == 64)
5132 return false;
5133
5134 unsigned NumElts = VT.getVectorNumElements();
5135 unsigned BlockElts = M[0] + 1;
5136 // If the first shuffle index is UNDEF, be optimistic.
5137 if (M[0] < 0)
5138 BlockElts = BlockSize / EltSz;
5139
5140 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5141 return false;
5142
5143 for (unsigned i = 0; i < NumElts; ++i) {
5144 if (M[i] < 0)
5145 continue; // ignore UNDEF indices
5146 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
5147 return false;
5148 }
5149
5150 return true;
5151}
5152
5153static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5154 unsigned NumElts = VT.getVectorNumElements();
5155 WhichResult = (M[0] == 0 ? 0 : 1);
5156 unsigned Idx = WhichResult * NumElts / 2;
5157 for (unsigned i = 0; i != NumElts; i += 2) {
5158 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5159 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
5160 return false;
5161 Idx += 1;
5162 }
5163
5164 return true;
5165}
5166
5167static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5168 unsigned NumElts = VT.getVectorNumElements();
5169 WhichResult = (M[0] == 0 ? 0 : 1);
5170 for (unsigned i = 0; i != NumElts; ++i) {
5171 if (M[i] < 0)
5172 continue; // ignore UNDEF indices
5173 if ((unsigned)M[i] != 2 * i + WhichResult)
5174 return false;
5175 }
5176
5177 return true;
5178}
5179
5180static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5181 unsigned NumElts = VT.getVectorNumElements();
5182 WhichResult = (M[0] == 0 ? 0 : 1);
5183 for (unsigned i = 0; i < NumElts; i += 2) {
5184 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5185 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
5186 return false;
5187 }
5188 return true;
5189}
5190
5191/// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
5192/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5193/// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5194static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5195 unsigned NumElts = VT.getVectorNumElements();
5196 WhichResult = (M[0] == 0 ? 0 : 1);
5197 unsigned Idx = WhichResult * NumElts / 2;
5198 for (unsigned i = 0; i != NumElts; i += 2) {
5199 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5200 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
5201 return false;
5202 Idx += 1;
5203 }
5204
5205 return true;
5206}
5207
5208/// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
5209/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5210/// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5211static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5212 unsigned Half = VT.getVectorNumElements() / 2;
5213 WhichResult = (M[0] == 0 ? 0 : 1);
5214 for (unsigned j = 0; j != 2; ++j) {
5215 unsigned Idx = WhichResult;
5216 for (unsigned i = 0; i != Half; ++i) {
5217 int MIdx = M[i + j * Half];
5218 if (MIdx >= 0 && (unsigned)MIdx != Idx)
5219 return false;
5220 Idx += 2;
5221 }
5222 }
5223
5224 return true;
5225}
5226
5227/// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
5228/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5229/// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5230static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5231 unsigned NumElts = VT.getVectorNumElements();
5232 WhichResult = (M[0] == 0 ? 0 : 1);
5233 for (unsigned i = 0; i < NumElts; i += 2) {
5234 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5235 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
5236 return false;
5237 }
5238 return true;
5239}
5240
5241static bool isINSMask(ArrayRef<int> M, int NumInputElements,
5242 bool &DstIsLeft, int &Anomaly) {
5243 if (M.size() != static_cast<size_t>(NumInputElements))
5244 return false;
5245
5246 int NumLHSMatch = 0, NumRHSMatch = 0;
5247 int LastLHSMismatch = -1, LastRHSMismatch = -1;
5248
5249 for (int i = 0; i < NumInputElements; ++i) {
5250 if (M[i] == -1) {
5251 ++NumLHSMatch;
5252 ++NumRHSMatch;
5253 continue;
5254 }
5255
5256 if (M[i] == i)
5257 ++NumLHSMatch;
5258 else
5259 LastLHSMismatch = i;
5260
5261 if (M[i] == i + NumInputElements)
5262 ++NumRHSMatch;
5263 else
5264 LastRHSMismatch = i;
5265 }
5266
5267 if (NumLHSMatch == NumInputElements - 1) {
5268 DstIsLeft = true;
5269 Anomaly = LastLHSMismatch;
5270 return true;
5271 } else if (NumRHSMatch == NumInputElements - 1) {
5272 DstIsLeft = false;
5273 Anomaly = LastRHSMismatch;
5274 return true;
5275 }
5276
5277 return false;
5278}
5279
5280static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
5281 if (VT.getSizeInBits() != 128)
5282 return false;
5283
5284 unsigned NumElts = VT.getVectorNumElements();
5285
5286 for (int I = 0, E = NumElts / 2; I != E; I++) {
5287 if (Mask[I] != I)
5288 return false;
5289 }
5290
5291 int Offset = NumElts / 2;
5292 for (int I = NumElts / 2, E = NumElts; I != E; I++) {
5293 if (Mask[I] != I + SplitLHS * Offset)
5294 return false;
5295 }
5296
5297 return true;
5298}
5299
5300static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
5301 SDLoc DL(Op);
5302 EVT VT = Op.getValueType();
5303 SDValue V0 = Op.getOperand(0);
5304 SDValue V1 = Op.getOperand(1);
5305 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
5306
5307 if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
5308 VT.getVectorElementType() != V1.getValueType().getVectorElementType())
5309 return SDValue();
5310
5311 bool SplitV0 = V0.getValueType().getSizeInBits() == 128;
5312
5313 if (!isConcatMask(Mask, VT, SplitV0))
5314 return SDValue();
5315
5316 EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
5317 VT.getVectorNumElements() / 2);
5318 if (SplitV0) {
5319 V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005320 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005321 }
5322 if (V1.getValueType().getSizeInBits() == 128) {
5323 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005324 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005325 }
5326 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
5327}
5328
5329/// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5330/// the specified operations to build the shuffle.
5331static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5332 SDValue RHS, SelectionDAG &DAG,
5333 SDLoc dl) {
5334 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5335 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
5336 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
5337
5338 enum {
5339 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5340 OP_VREV,
5341 OP_VDUP0,
5342 OP_VDUP1,
5343 OP_VDUP2,
5344 OP_VDUP3,
5345 OP_VEXT1,
5346 OP_VEXT2,
5347 OP_VEXT3,
5348 OP_VUZPL, // VUZP, left result
5349 OP_VUZPR, // VUZP, right result
5350 OP_VZIPL, // VZIP, left result
5351 OP_VZIPR, // VZIP, right result
5352 OP_VTRNL, // VTRN, left result
5353 OP_VTRNR // VTRN, right result
5354 };
5355
5356 if (OpNum == OP_COPY) {
5357 if (LHSID == (1 * 9 + 2) * 9 + 3)
5358 return LHS;
5359 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
5360 return RHS;
5361 }
5362
5363 SDValue OpLHS, OpRHS;
5364 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5365 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5366 EVT VT = OpLHS.getValueType();
5367
5368 switch (OpNum) {
5369 default:
5370 llvm_unreachable("Unknown shuffle opcode!");
5371 case OP_VREV:
5372 // VREV divides the vector in half and swaps within the half.
5373 if (VT.getVectorElementType() == MVT::i32 ||
5374 VT.getVectorElementType() == MVT::f32)
5375 return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
5376 // vrev <4 x i16> -> REV32
Oliver Stannard89d15422014-08-27 16:16:04 +00005377 if (VT.getVectorElementType() == MVT::i16 ||
5378 VT.getVectorElementType() == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00005379 return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
5380 // vrev <4 x i8> -> REV16
5381 assert(VT.getVectorElementType() == MVT::i8);
5382 return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
5383 case OP_VDUP0:
5384 case OP_VDUP1:
5385 case OP_VDUP2:
5386 case OP_VDUP3: {
5387 EVT EltTy = VT.getVectorElementType();
5388 unsigned Opcode;
5389 if (EltTy == MVT::i8)
5390 Opcode = AArch64ISD::DUPLANE8;
Ahmed Bougacha941420d2015-04-16 23:57:07 +00005391 else if (EltTy == MVT::i16 || EltTy == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00005392 Opcode = AArch64ISD::DUPLANE16;
5393 else if (EltTy == MVT::i32 || EltTy == MVT::f32)
5394 Opcode = AArch64ISD::DUPLANE32;
5395 else if (EltTy == MVT::i64 || EltTy == MVT::f64)
5396 Opcode = AArch64ISD::DUPLANE64;
5397 else
5398 llvm_unreachable("Invalid vector element type?");
5399
5400 if (VT.getSizeInBits() == 64)
5401 OpLHS = WidenVector(OpLHS, DAG);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005402 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00005403 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
5404 }
5405 case OP_VEXT1:
5406 case OP_VEXT2:
5407 case OP_VEXT3: {
5408 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
5409 return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005410 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005411 }
5412 case OP_VUZPL:
5413 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
5414 OpRHS);
5415 case OP_VUZPR:
5416 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
5417 OpRHS);
5418 case OP_VZIPL:
5419 return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
5420 OpRHS);
5421 case OP_VZIPR:
5422 return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
5423 OpRHS);
5424 case OP_VTRNL:
5425 return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
5426 OpRHS);
5427 case OP_VTRNR:
5428 return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
5429 OpRHS);
5430 }
5431}
5432
5433static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
5434 SelectionDAG &DAG) {
5435 // Check to see if we can use the TBL instruction.
5436 SDValue V1 = Op.getOperand(0);
5437 SDValue V2 = Op.getOperand(1);
5438 SDLoc DL(Op);
5439
5440 EVT EltVT = Op.getValueType().getVectorElementType();
5441 unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
5442
5443 SmallVector<SDValue, 8> TBLMask;
5444 for (int Val : ShuffleMask) {
5445 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
5446 unsigned Offset = Byte + Val * BytesPerElt;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005447 TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005448 }
5449 }
5450
5451 MVT IndexVT = MVT::v8i8;
5452 unsigned IndexLen = 8;
5453 if (Op.getValueType().getSizeInBits() == 128) {
5454 IndexVT = MVT::v16i8;
5455 IndexLen = 16;
5456 }
5457
5458 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
5459 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
5460
5461 SDValue Shuffle;
5462 if (V2.getNode()->getOpcode() == ISD::UNDEF) {
5463 if (IndexLen == 8)
5464 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
5465 Shuffle = DAG.getNode(
5466 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005467 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
Tim Northover3b0846e2014-05-24 12:50:23 +00005468 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5469 makeArrayRef(TBLMask.data(), IndexLen)));
5470 } else {
5471 if (IndexLen == 8) {
5472 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
5473 Shuffle = DAG.getNode(
5474 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005475 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
Tim Northover3b0846e2014-05-24 12:50:23 +00005476 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5477 makeArrayRef(TBLMask.data(), IndexLen)));
5478 } else {
5479 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
5480 // cannot currently represent the register constraints on the input
5481 // table registers.
5482 // Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
5483 // DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5484 // &TBLMask[0], IndexLen));
5485 Shuffle = DAG.getNode(
5486 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005487 DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32),
5488 V1Cst, V2Cst,
Tim Northover3b0846e2014-05-24 12:50:23 +00005489 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5490 makeArrayRef(TBLMask.data(), IndexLen)));
5491 }
5492 }
5493 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
5494}
5495
5496static unsigned getDUPLANEOp(EVT EltType) {
5497 if (EltType == MVT::i8)
5498 return AArch64ISD::DUPLANE8;
Oliver Stannard89d15422014-08-27 16:16:04 +00005499 if (EltType == MVT::i16 || EltType == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00005500 return AArch64ISD::DUPLANE16;
5501 if (EltType == MVT::i32 || EltType == MVT::f32)
5502 return AArch64ISD::DUPLANE32;
5503 if (EltType == MVT::i64 || EltType == MVT::f64)
5504 return AArch64ISD::DUPLANE64;
5505
5506 llvm_unreachable("Invalid vector element type?");
5507}
5508
5509SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5510 SelectionDAG &DAG) const {
5511 SDLoc dl(Op);
5512 EVT VT = Op.getValueType();
5513
5514 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5515
5516 // Convert shuffles that are directly supported on NEON to target-specific
5517 // DAG nodes, instead of keeping them as shuffles and matching them again
5518 // during code selection. This is more efficient and avoids the possibility
5519 // of inconsistencies between legalization and selection.
5520 ArrayRef<int> ShuffleMask = SVN->getMask();
5521
5522 SDValue V1 = Op.getOperand(0);
5523 SDValue V2 = Op.getOperand(1);
5524
5525 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0],
5526 V1.getValueType().getSimpleVT())) {
5527 int Lane = SVN->getSplatIndex();
5528 // If this is undef splat, generate it via "just" vdup, if possible.
5529 if (Lane == -1)
5530 Lane = 0;
5531
5532 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
5533 return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
5534 V1.getOperand(0));
5535 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
5536 // constant. If so, we can just reference the lane's definition directly.
5537 if (V1.getOpcode() == ISD::BUILD_VECTOR &&
5538 !isa<ConstantSDNode>(V1.getOperand(Lane)))
5539 return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
5540
5541 // Otherwise, duplicate from the lane of the input vector.
5542 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
5543
5544 // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
5545 // to make a vector of the same size as this SHUFFLE. We can ignore the
5546 // extract entirely, and canonicalise the concat using WidenVector.
5547 if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
5548 Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
5549 V1 = V1.getOperand(0);
5550 } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
5551 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
5552 Lane -= Idx * VT.getVectorNumElements() / 2;
5553 V1 = WidenVector(V1.getOperand(Idx), DAG);
5554 } else if (VT.getSizeInBits() == 64)
5555 V1 = WidenVector(V1, DAG);
5556
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005557 return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005558 }
5559
5560 if (isREVMask(ShuffleMask, VT, 64))
5561 return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
5562 if (isREVMask(ShuffleMask, VT, 32))
5563 return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
5564 if (isREVMask(ShuffleMask, VT, 16))
5565 return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
5566
5567 bool ReverseEXT = false;
5568 unsigned Imm;
5569 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
5570 if (ReverseEXT)
5571 std::swap(V1, V2);
5572 Imm *= getExtFactor(V1);
5573 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005574 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005575 } else if (V2->getOpcode() == ISD::UNDEF &&
5576 isSingletonEXTMask(ShuffleMask, VT, Imm)) {
5577 Imm *= getExtFactor(V1);
5578 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005579 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005580 }
5581
5582 unsigned WhichResult;
5583 if (isZIPMask(ShuffleMask, VT, WhichResult)) {
5584 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5585 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5586 }
5587 if (isUZPMask(ShuffleMask, VT, WhichResult)) {
5588 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5589 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5590 }
5591 if (isTRNMask(ShuffleMask, VT, WhichResult)) {
5592 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5593 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5594 }
5595
5596 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5597 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5598 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5599 }
5600 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5601 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5602 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5603 }
5604 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5605 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5606 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5607 }
5608
5609 SDValue Concat = tryFormConcatFromShuffle(Op, DAG);
5610 if (Concat.getNode())
5611 return Concat;
5612
5613 bool DstIsLeft;
5614 int Anomaly;
5615 int NumInputElements = V1.getValueType().getVectorNumElements();
5616 if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
5617 SDValue DstVec = DstIsLeft ? V1 : V2;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005618 SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00005619
5620 SDValue SrcVec = V1;
5621 int SrcLane = ShuffleMask[Anomaly];
5622 if (SrcLane >= NumInputElements) {
5623 SrcVec = V2;
5624 SrcLane -= VT.getVectorNumElements();
5625 }
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005626 SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00005627
5628 EVT ScalarVT = VT.getVectorElementType();
Oliver Stannard89d15422014-08-27 16:16:04 +00005629
5630 if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00005631 ScalarVT = MVT::i32;
5632
5633 return DAG.getNode(
5634 ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5635 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
5636 DstLaneV);
5637 }
5638
5639 // If the shuffle is not directly supported and it has 4 elements, use
5640 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5641 unsigned NumElts = VT.getVectorNumElements();
5642 if (NumElts == 4) {
5643 unsigned PFIndexes[4];
5644 for (unsigned i = 0; i != 4; ++i) {
5645 if (ShuffleMask[i] < 0)
5646 PFIndexes[i] = 8;
5647 else
5648 PFIndexes[i] = ShuffleMask[i];
5649 }
5650
5651 // Compute the index in the perfect shuffle table.
5652 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
5653 PFIndexes[2] * 9 + PFIndexes[3];
5654 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5655 unsigned Cost = (PFEntry >> 30);
5656
5657 if (Cost <= 4)
5658 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5659 }
5660
5661 return GenerateTBL(Op, ShuffleMask, DAG);
5662}
5663
5664static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
5665 APInt &UndefBits) {
5666 EVT VT = BVN->getValueType(0);
5667 APInt SplatBits, SplatUndef;
5668 unsigned SplatBitSize;
5669 bool HasAnyUndefs;
5670 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5671 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
5672
5673 for (unsigned i = 0; i < NumSplats; ++i) {
5674 CnstBits <<= SplatBitSize;
5675 UndefBits <<= SplatBitSize;
5676 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
5677 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
5678 }
5679
5680 return true;
5681 }
5682
5683 return false;
5684}
5685
5686SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op,
5687 SelectionDAG &DAG) const {
5688 BuildVectorSDNode *BVN =
5689 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5690 SDValue LHS = Op.getOperand(0);
5691 SDLoc dl(Op);
5692 EVT VT = Op.getValueType();
5693
5694 if (!BVN)
5695 return Op;
5696
5697 APInt CnstBits(VT.getSizeInBits(), 0);
5698 APInt UndefBits(VT.getSizeInBits(), 0);
5699 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5700 // We only have BIC vector immediate instruction, which is and-not.
5701 CnstBits = ~CnstBits;
5702
5703 // We make use of a little bit of goto ickiness in order to avoid having to
5704 // duplicate the immediate matching logic for the undef toggled case.
5705 bool SecondTry = false;
5706 AttemptModImm:
5707
5708 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5709 CnstBits = CnstBits.zextOrTrunc(64);
5710 uint64_t CnstVal = CnstBits.getZExtValue();
5711
5712 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5713 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5714 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5715 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005716 DAG.getConstant(CnstVal, dl, MVT::i32),
5717 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005718 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005719 }
5720
5721 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5722 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5723 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5724 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005725 DAG.getConstant(CnstVal, dl, MVT::i32),
5726 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005727 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005728 }
5729
5730 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5731 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5732 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5733 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005734 DAG.getConstant(CnstVal, dl, MVT::i32),
5735 DAG.getConstant(16, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005736 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005737 }
5738
5739 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5740 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5741 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5742 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005743 DAG.getConstant(CnstVal, dl, MVT::i32),
5744 DAG.getConstant(24, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005745 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005746 }
5747
5748 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5749 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5750 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5751 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005752 DAG.getConstant(CnstVal, dl, MVT::i32),
5753 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005754 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005755 }
5756
5757 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5758 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5759 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5760 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005761 DAG.getConstant(CnstVal, dl, MVT::i32),
5762 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005763 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005764 }
5765 }
5766
5767 if (SecondTry)
5768 goto FailedModImm;
5769 SecondTry = true;
5770 CnstBits = ~UndefBits;
5771 goto AttemptModImm;
5772 }
5773
5774// We can always fall back to a non-immediate AND.
5775FailedModImm:
5776 return Op;
5777}
5778
5779// Specialized code to quickly find if PotentialBVec is a BuildVector that
5780// consists of only the same constant int value, returned in reference arg
5781// ConstVal
5782static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
5783 uint64_t &ConstVal) {
5784 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
5785 if (!Bvec)
5786 return false;
5787 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
5788 if (!FirstElt)
5789 return false;
5790 EVT VT = Bvec->getValueType(0);
5791 unsigned NumElts = VT.getVectorNumElements();
5792 for (unsigned i = 1; i < NumElts; ++i)
5793 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
5794 return false;
5795 ConstVal = FirstElt->getZExtValue();
5796 return true;
5797}
5798
5799static unsigned getIntrinsicID(const SDNode *N) {
5800 unsigned Opcode = N->getOpcode();
5801 switch (Opcode) {
5802 default:
5803 return Intrinsic::not_intrinsic;
5804 case ISD::INTRINSIC_WO_CHAIN: {
5805 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
5806 if (IID < Intrinsic::num_intrinsics)
5807 return IID;
5808 return Intrinsic::not_intrinsic;
5809 }
5810 }
5811}
5812
5813// Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
5814// to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
5815// BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
5816// Also, logical shift right -> sri, with the same structure.
5817static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
5818 EVT VT = N->getValueType(0);
5819
5820 if (!VT.isVector())
5821 return SDValue();
5822
5823 SDLoc DL(N);
5824
5825 // Is the first op an AND?
5826 const SDValue And = N->getOperand(0);
5827 if (And.getOpcode() != ISD::AND)
5828 return SDValue();
5829
5830 // Is the second op an shl or lshr?
5831 SDValue Shift = N->getOperand(1);
5832 // This will have been turned into: AArch64ISD::VSHL vector, #shift
5833 // or AArch64ISD::VLSHR vector, #shift
5834 unsigned ShiftOpc = Shift.getOpcode();
5835 if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
5836 return SDValue();
5837 bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
5838
5839 // Is the shift amount constant?
5840 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
5841 if (!C2node)
5842 return SDValue();
5843
5844 // Is the and mask vector all constant?
5845 uint64_t C1;
5846 if (!isAllConstantBuildVector(And.getOperand(1), C1))
5847 return SDValue();
5848
5849 // Is C1 == ~C2, taking into account how much one can shift elements of a
5850 // particular size?
5851 uint64_t C2 = C2node->getZExtValue();
5852 unsigned ElemSizeInBits = VT.getVectorElementType().getSizeInBits();
5853 if (C2 > ElemSizeInBits)
5854 return SDValue();
5855 unsigned ElemMask = (1 << ElemSizeInBits) - 1;
5856 if ((C1 & ElemMask) != (~C2 & ElemMask))
5857 return SDValue();
5858
5859 SDValue X = And.getOperand(0);
5860 SDValue Y = Shift.getOperand(0);
5861
5862 unsigned Intrin =
5863 IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
5864 SDValue ResultSLI =
5865 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005866 DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
5867 Shift.getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00005868
5869 DEBUG(dbgs() << "aarch64-lower: transformed: \n");
5870 DEBUG(N->dump(&DAG));
5871 DEBUG(dbgs() << "into: \n");
5872 DEBUG(ResultSLI->dump(&DAG));
5873
5874 ++NumShiftInserts;
5875 return ResultSLI;
5876}
5877
5878SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
5879 SelectionDAG &DAG) const {
5880 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
5881 if (EnableAArch64SlrGeneration) {
5882 SDValue Res = tryLowerToSLI(Op.getNode(), DAG);
5883 if (Res.getNode())
5884 return Res;
5885 }
5886
5887 BuildVectorSDNode *BVN =
5888 dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
5889 SDValue LHS = Op.getOperand(1);
5890 SDLoc dl(Op);
5891 EVT VT = Op.getValueType();
5892
5893 // OR commutes, so try swapping the operands.
5894 if (!BVN) {
5895 LHS = Op.getOperand(0);
5896 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5897 }
5898 if (!BVN)
5899 return Op;
5900
5901 APInt CnstBits(VT.getSizeInBits(), 0);
5902 APInt UndefBits(VT.getSizeInBits(), 0);
5903 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5904 // We make use of a little bit of goto ickiness in order to avoid having to
5905 // duplicate the immediate matching logic for the undef toggled case.
5906 bool SecondTry = false;
5907 AttemptModImm:
5908
5909 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5910 CnstBits = CnstBits.zextOrTrunc(64);
5911 uint64_t CnstVal = CnstBits.getZExtValue();
5912
5913 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5914 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5915 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5916 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005917 DAG.getConstant(CnstVal, dl, MVT::i32),
5918 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005919 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005920 }
5921
5922 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5923 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5924 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5925 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005926 DAG.getConstant(CnstVal, dl, MVT::i32),
5927 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005928 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005929 }
5930
5931 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5932 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5933 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5934 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005935 DAG.getConstant(CnstVal, dl, MVT::i32),
5936 DAG.getConstant(16, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005937 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005938 }
5939
5940 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5941 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5942 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5943 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005944 DAG.getConstant(CnstVal, dl, MVT::i32),
5945 DAG.getConstant(24, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005946 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005947 }
5948
5949 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5950 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5951 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5952 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005953 DAG.getConstant(CnstVal, dl, MVT::i32),
5954 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005955 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005956 }
5957
5958 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5959 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5960 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5961 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005962 DAG.getConstant(CnstVal, dl, MVT::i32),
5963 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005964 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005965 }
5966 }
5967
5968 if (SecondTry)
5969 goto FailedModImm;
5970 SecondTry = true;
5971 CnstBits = UndefBits;
5972 goto AttemptModImm;
5973 }
5974
5975// We can always fall back to a non-immediate OR.
5976FailedModImm:
5977 return Op;
5978}
5979
Kevin Qin4473c192014-07-07 02:45:40 +00005980// Normalize the operands of BUILD_VECTOR. The value of constant operands will
5981// be truncated to fit element width.
5982static SDValue NormalizeBuildVector(SDValue Op,
5983 SelectionDAG &DAG) {
5984 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
Tim Northover3b0846e2014-05-24 12:50:23 +00005985 SDLoc dl(Op);
5986 EVT VT = Op.getValueType();
Kevin Qin4473c192014-07-07 02:45:40 +00005987 EVT EltTy= VT.getVectorElementType();
5988
5989 if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
5990 return Op;
5991
5992 SmallVector<SDValue, 16> Ops;
Pete Cooper7be8f8f2015-08-03 19:04:32 +00005993 for (SDValue Lane : Op->ops()) {
5994 if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
Kevin Qin4473c192014-07-07 02:45:40 +00005995 APInt LowBits(EltTy.getSizeInBits(),
Pete Cooper7be8f8f2015-08-03 19:04:32 +00005996 CstLane->getZExtValue());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005997 Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
Kevin Qin4473c192014-07-07 02:45:40 +00005998 }
5999 Ops.push_back(Lane);
6000 }
6001 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6002}
6003
6004SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
6005 SelectionDAG &DAG) const {
6006 SDLoc dl(Op);
6007 EVT VT = Op.getValueType();
6008 Op = NormalizeBuildVector(Op, DAG);
6009 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
Tim Northover3b0846e2014-05-24 12:50:23 +00006010
6011 APInt CnstBits(VT.getSizeInBits(), 0);
6012 APInt UndefBits(VT.getSizeInBits(), 0);
6013 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
6014 // We make use of a little bit of goto ickiness in order to avoid having to
6015 // duplicate the immediate matching logic for the undef toggled case.
6016 bool SecondTry = false;
6017 AttemptModImm:
6018
6019 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
6020 CnstBits = CnstBits.zextOrTrunc(64);
6021 uint64_t CnstVal = CnstBits.getZExtValue();
6022
6023 // Certain magic vector constants (used to express things like NOT
6024 // and NEG) are passed through unmodified. This allows codegen patterns
6025 // for these operations to match. Special-purpose patterns will lower
6026 // these immediates to MOVIs if it proves necessary.
6027 if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL))
6028 return Op;
6029
6030 // The many faces of MOVI...
6031 if (AArch64_AM::isAdvSIMDModImmType10(CnstVal)) {
6032 CnstVal = AArch64_AM::encodeAdvSIMDModImmType10(CnstVal);
6033 if (VT.getSizeInBits() == 128) {
6034 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::v2i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006035 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006036 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006037 }
6038
6039 // Support the V64 version via subregister insertion.
6040 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::f64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006041 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006042 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006043 }
6044
6045 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6046 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6047 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6048 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006049 DAG.getConstant(CnstVal, dl, MVT::i32),
6050 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006051 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006052 }
6053
6054 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6055 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6056 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6057 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006058 DAG.getConstant(CnstVal, dl, MVT::i32),
6059 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006060 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006061 }
6062
6063 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6064 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6065 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6066 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006067 DAG.getConstant(CnstVal, dl, MVT::i32),
6068 DAG.getConstant(16, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006069 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006070 }
6071
6072 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6073 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6074 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6075 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006076 DAG.getConstant(CnstVal, dl, MVT::i32),
6077 DAG.getConstant(24, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006078 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006079 }
6080
6081 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6082 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6083 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6084 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006085 DAG.getConstant(CnstVal, dl, MVT::i32),
6086 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006087 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006088 }
6089
6090 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6091 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6092 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6093 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006094 DAG.getConstant(CnstVal, dl, MVT::i32),
6095 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006096 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006097 }
6098
6099 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6100 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6101 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6102 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006103 DAG.getConstant(CnstVal, dl, MVT::i32),
6104 DAG.getConstant(264, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006105 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006106 }
6107
6108 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6109 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6110 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6111 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006112 DAG.getConstant(CnstVal, dl, MVT::i32),
6113 DAG.getConstant(272, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006114 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006115 }
6116
6117 if (AArch64_AM::isAdvSIMDModImmType9(CnstVal)) {
6118 CnstVal = AArch64_AM::encodeAdvSIMDModImmType9(CnstVal);
6119 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
6120 SDValue Mov = DAG.getNode(AArch64ISD::MOVI, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006121 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006122 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006123 }
6124
6125 // The few faces of FMOV...
6126 if (AArch64_AM::isAdvSIMDModImmType11(CnstVal)) {
6127 CnstVal = AArch64_AM::encodeAdvSIMDModImmType11(CnstVal);
6128 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32;
6129 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006130 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006131 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006132 }
6133
6134 if (AArch64_AM::isAdvSIMDModImmType12(CnstVal) &&
6135 VT.getSizeInBits() == 128) {
6136 CnstVal = AArch64_AM::encodeAdvSIMDModImmType12(CnstVal);
6137 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MVT::v2f64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006138 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006139 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006140 }
6141
6142 // The many faces of MVNI...
6143 CnstVal = ~CnstVal;
6144 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6145 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6146 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6147 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006148 DAG.getConstant(CnstVal, dl, MVT::i32),
6149 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006150 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006151 }
6152
6153 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6154 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6155 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6156 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006157 DAG.getConstant(CnstVal, dl, MVT::i32),
6158 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006159 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006160 }
6161
6162 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6163 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6164 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6165 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006166 DAG.getConstant(CnstVal, dl, MVT::i32),
6167 DAG.getConstant(16, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006168 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006169 }
6170
6171 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6172 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6173 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6174 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006175 DAG.getConstant(CnstVal, dl, MVT::i32),
6176 DAG.getConstant(24, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006177 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006178 }
6179
6180 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6181 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6182 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6183 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006184 DAG.getConstant(CnstVal, dl, MVT::i32),
6185 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006186 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006187 }
6188
6189 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6190 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6191 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6192 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006193 DAG.getConstant(CnstVal, dl, MVT::i32),
6194 DAG.getConstant(8, 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 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6199 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6200 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6201 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006202 DAG.getConstant(CnstVal, dl, MVT::i32),
6203 DAG.getConstant(264, 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::isAdvSIMDModImmType8(CnstVal)) {
6208 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6209 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6210 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006211 DAG.getConstant(CnstVal, dl, MVT::i32),
6212 DAG.getConstant(272, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006213 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006214 }
6215 }
6216
6217 if (SecondTry)
6218 goto FailedModImm;
6219 SecondTry = true;
6220 CnstBits = UndefBits;
6221 goto AttemptModImm;
6222 }
6223FailedModImm:
6224
6225 // Scan through the operands to find some interesting properties we can
6226 // exploit:
6227 // 1) If only one value is used, we can use a DUP, or
6228 // 2) if only the low element is not undef, we can just insert that, or
6229 // 3) if only one constant value is used (w/ some non-constant lanes),
6230 // we can splat the constant value into the whole vector then fill
6231 // in the non-constant lanes.
6232 // 4) FIXME: If different constant values are used, but we can intelligently
6233 // select the values we'll be overwriting for the non-constant
6234 // lanes such that we can directly materialize the vector
6235 // some other way (MOVI, e.g.), we can be sneaky.
6236 unsigned NumElts = VT.getVectorNumElements();
6237 bool isOnlyLowElement = true;
6238 bool usesOnlyOneValue = true;
6239 bool usesOnlyOneConstantValue = true;
6240 bool isConstant = true;
6241 unsigned NumConstantLanes = 0;
6242 SDValue Value;
6243 SDValue ConstantValue;
6244 for (unsigned i = 0; i < NumElts; ++i) {
6245 SDValue V = Op.getOperand(i);
6246 if (V.getOpcode() == ISD::UNDEF)
6247 continue;
6248 if (i > 0)
6249 isOnlyLowElement = false;
6250 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6251 isConstant = false;
6252
6253 if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
6254 ++NumConstantLanes;
6255 if (!ConstantValue.getNode())
6256 ConstantValue = V;
6257 else if (ConstantValue != V)
6258 usesOnlyOneConstantValue = false;
6259 }
6260
6261 if (!Value.getNode())
6262 Value = V;
6263 else if (V != Value)
6264 usesOnlyOneValue = false;
6265 }
6266
6267 if (!Value.getNode())
6268 return DAG.getUNDEF(VT);
6269
6270 if (isOnlyLowElement)
6271 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
6272
6273 // Use DUP for non-constant splats. For f32 constant splats, reduce to
6274 // i32 and try again.
6275 if (usesOnlyOneValue) {
6276 if (!isConstant) {
6277 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6278 Value.getValueType() != VT)
6279 return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
6280
6281 // This is actually a DUPLANExx operation, which keeps everything vectory.
6282
6283 // DUPLANE works on 128-bit vectors, widen it if necessary.
6284 SDValue Lane = Value.getOperand(1);
6285 Value = Value.getOperand(0);
6286 if (Value.getValueType().getSizeInBits() == 64)
6287 Value = WidenVector(Value, DAG);
6288
6289 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
6290 return DAG.getNode(Opcode, dl, VT, Value, Lane);
6291 }
6292
6293 if (VT.getVectorElementType().isFloatingPoint()) {
6294 SmallVector<SDValue, 8> Ops;
Pirama Arumuga Nainar12aeefc2015-03-17 23:10:29 +00006295 EVT EltTy = VT.getVectorElementType();
6296 assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
6297 "Unsupported floating-point vector type");
6298 MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00006299 for (unsigned i = 0; i < NumElts; ++i)
6300 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
6301 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
6302 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
6303 Val = LowerBUILD_VECTOR(Val, DAG);
6304 if (Val.getNode())
6305 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6306 }
6307 }
6308
6309 // If there was only one constant value used and for more than one lane,
6310 // start by splatting that value, then replace the non-constant lanes. This
6311 // is better than the default, which will perform a separate initialization
6312 // for each lane.
6313 if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
6314 SDValue Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
6315 // Now insert the non-constant lanes.
6316 for (unsigned i = 0; i < NumElts; ++i) {
6317 SDValue V = Op.getOperand(i);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006318 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006319 if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) {
6320 // Note that type legalization likely mucked about with the VT of the
6321 // source operand, so we may have to convert it here before inserting.
6322 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
6323 }
6324 }
6325 return Val;
6326 }
6327
6328 // If all elements are constants and the case above didn't get hit, fall back
6329 // to the default expansion, which will generate a load from the constant
6330 // pool.
6331 if (isConstant)
6332 return SDValue();
6333
6334 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6335 if (NumElts >= 4) {
Ahmed Bougacha239d6352015-08-04 00:48:02 +00006336 if (SDValue shuffle = ReconstructShuffle(Op, DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00006337 return shuffle;
6338 }
6339
6340 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6341 // know the default expansion would otherwise fall back on something even
6342 // worse. For a vector with one or two non-undef values, that's
6343 // scalar_to_vector for the elements followed by a shuffle (provided the
6344 // shuffle is valid for the target) and materialization element by element
6345 // on the stack followed by a load for everything else.
6346 if (!isConstant && !usesOnlyOneValue) {
6347 SDValue Vec = DAG.getUNDEF(VT);
6348 SDValue Op0 = Op.getOperand(0);
6349 unsigned ElemSize = VT.getVectorElementType().getSizeInBits();
6350 unsigned i = 0;
6351 // For 32 and 64 bit types, use INSERT_SUBREG for lane zero to
6352 // a) Avoid a RMW dependency on the full vector register, and
6353 // b) Allow the register coalescer to fold away the copy if the
6354 // value is already in an S or D register.
Matthias Braun0acbd082015-08-31 18:25:15 +00006355 // Do not do this for UNDEF/LOAD nodes because we have better patterns
6356 // for those avoiding the SCALAR_TO_VECTOR/BUILD_VECTOR.
6357 if (Op0.getOpcode() != ISD::UNDEF && Op0.getOpcode() != ISD::LOAD &&
6358 (ElemSize == 32 || ElemSize == 64)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006359 unsigned SubIdx = ElemSize == 32 ? AArch64::ssub : AArch64::dsub;
6360 MachineSDNode *N =
6361 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl, VT, Vec, Op0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006362 DAG.getTargetConstant(SubIdx, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006363 Vec = SDValue(N, 0);
6364 ++i;
6365 }
6366 for (; i < NumElts; ++i) {
6367 SDValue V = Op.getOperand(i);
6368 if (V.getOpcode() == ISD::UNDEF)
6369 continue;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006370 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006371 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6372 }
6373 return Vec;
6374 }
6375
6376 // Just use the default expansion. We failed to find a better alternative.
6377 return SDValue();
6378}
6379
6380SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
6381 SelectionDAG &DAG) const {
6382 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
6383
Tim Northovere4b8e132014-07-15 10:00:26 +00006384 // Check for non-constant or out of range lane.
6385 EVT VT = Op.getOperand(0).getValueType();
6386 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
6387 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
Tim Northover3b0846e2014-05-24 12:50:23 +00006388 return SDValue();
6389
Tim Northover3b0846e2014-05-24 12:50:23 +00006390
6391 // Insertion/extraction are legal for V128 types.
6392 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
Oliver Stannard89d15422014-08-27 16:16:04 +00006393 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6394 VT == MVT::v8f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006395 return Op;
6396
6397 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
Oliver Stannard89d15422014-08-27 16:16:04 +00006398 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006399 return SDValue();
6400
6401 // For V64 types, we perform insertion by expanding the value
6402 // to a V128 type and perform the insertion on that.
6403 SDLoc DL(Op);
6404 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6405 EVT WideTy = WideVec.getValueType();
6406
6407 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
6408 Op.getOperand(1), Op.getOperand(2));
6409 // Re-narrow the resultant vector.
6410 return NarrowVector(Node, DAG);
6411}
6412
6413SDValue
6414AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6415 SelectionDAG &DAG) const {
6416 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
6417
Tim Northovere4b8e132014-07-15 10:00:26 +00006418 // Check for non-constant or out of range lane.
6419 EVT VT = Op.getOperand(0).getValueType();
6420 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6421 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
Tim Northover3b0846e2014-05-24 12:50:23 +00006422 return SDValue();
6423
Tim Northover3b0846e2014-05-24 12:50:23 +00006424
6425 // Insertion/extraction are legal for V128 types.
6426 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
Oliver Stannard89d15422014-08-27 16:16:04 +00006427 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6428 VT == MVT::v8f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006429 return Op;
6430
6431 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
Oliver Stannard89d15422014-08-27 16:16:04 +00006432 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006433 return SDValue();
6434
6435 // For V64 types, we perform extraction by expanding the value
6436 // to a V128 type and perform the extraction on that.
6437 SDLoc DL(Op);
6438 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6439 EVT WideTy = WideVec.getValueType();
6440
6441 EVT ExtrTy = WideTy.getVectorElementType();
6442 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
6443 ExtrTy = MVT::i32;
6444
6445 // For extractions, we just return the result directly.
6446 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
6447 Op.getOperand(1));
6448}
6449
6450SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
6451 SelectionDAG &DAG) const {
6452 EVT VT = Op.getOperand(0).getValueType();
6453 SDLoc dl(Op);
6454 // Just in case...
6455 if (!VT.isVector())
6456 return SDValue();
6457
6458 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6459 if (!Cst)
6460 return SDValue();
6461 unsigned Val = Cst->getZExtValue();
6462
6463 unsigned Size = Op.getValueType().getSizeInBits();
Charlie Turner7b7b06f2015-11-09 12:45:11 +00006464
6465 // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
6466 if (Val == 0)
6467 return Op;
6468
Tim Northover3b0846e2014-05-24 12:50:23 +00006469 // If this is extracting the upper 64-bits of a 128-bit vector, we match
6470 // that directly.
6471 if (Size == 64 && Val * VT.getVectorElementType().getSizeInBits() == 64)
6472 return Op;
6473
6474 return SDValue();
6475}
6476
6477bool AArch64TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
6478 EVT VT) const {
6479 if (VT.getVectorNumElements() == 4 &&
6480 (VT.is128BitVector() || VT.is64BitVector())) {
6481 unsigned PFIndexes[4];
6482 for (unsigned i = 0; i != 4; ++i) {
6483 if (M[i] < 0)
6484 PFIndexes[i] = 8;
6485 else
6486 PFIndexes[i] = M[i];
6487 }
6488
6489 // Compute the index in the perfect shuffle table.
6490 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6491 PFIndexes[2] * 9 + PFIndexes[3];
6492 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6493 unsigned Cost = (PFEntry >> 30);
6494
6495 if (Cost <= 4)
6496 return true;
6497 }
6498
6499 bool DummyBool;
6500 int DummyInt;
6501 unsigned DummyUnsigned;
6502
6503 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
6504 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
6505 isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
6506 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
6507 isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
6508 isZIPMask(M, VT, DummyUnsigned) ||
6509 isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
6510 isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
6511 isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
6512 isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
6513 isConcatMask(M, VT, VT.getSizeInBits() == 128));
6514}
6515
6516/// getVShiftImm - Check if this is a valid build_vector for the immediate
6517/// operand of a vector shift operation, where all the elements of the
6518/// build_vector must have the same constant integer value.
6519static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
6520 // Ignore bit_converts.
6521 while (Op.getOpcode() == ISD::BITCAST)
6522 Op = Op.getOperand(0);
6523 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6524 APInt SplatBits, SplatUndef;
6525 unsigned SplatBitSize;
6526 bool HasAnyUndefs;
6527 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
6528 HasAnyUndefs, ElementBits) ||
6529 SplatBitSize > ElementBits)
6530 return false;
6531 Cnt = SplatBits.getSExtValue();
6532 return true;
6533}
6534
6535/// isVShiftLImm - Check if this is a valid build_vector for the immediate
6536/// operand of a vector shift left operation. That value must be in the range:
6537/// 0 <= Value < ElementBits for a left shift; or
6538/// 0 <= Value <= ElementBits for a long left shift.
6539static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
6540 assert(VT.isVector() && "vector shift count is not a vector type");
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00006541 int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00006542 if (!getVShiftImm(Op, ElementBits, Cnt))
6543 return false;
6544 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
6545}
6546
6547/// isVShiftRImm - Check if this is a valid build_vector for the immediate
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00006548/// operand of a vector shift right operation. The value must be in the range:
6549/// 1 <= Value <= ElementBits for a right shift; or
6550static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006551 assert(VT.isVector() && "vector shift count is not a vector type");
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00006552 int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00006553 if (!getVShiftImm(Op, ElementBits, Cnt))
6554 return false;
Tim Northover3b0846e2014-05-24 12:50:23 +00006555 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
6556}
6557
6558SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
6559 SelectionDAG &DAG) const {
6560 EVT VT = Op.getValueType();
6561 SDLoc DL(Op);
6562 int64_t Cnt;
6563
6564 if (!Op.getOperand(1).getValueType().isVector())
6565 return Op;
6566 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6567
6568 switch (Op.getOpcode()) {
6569 default:
6570 llvm_unreachable("unexpected shift opcode");
6571
6572 case ISD::SHL:
6573 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006574 return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
6575 DAG.getConstant(Cnt, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006576 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006577 DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
6578 MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00006579 Op.getOperand(0), Op.getOperand(1));
6580 case ISD::SRA:
6581 case ISD::SRL:
6582 // Right shift immediate
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00006583 if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006584 unsigned Opc =
6585 (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006586 return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
6587 DAG.getConstant(Cnt, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006588 }
6589
6590 // Right shift register. Note, there is not a shift right register
6591 // instruction, but the shift left register instruction takes a signed
6592 // value, where negative numbers specify a right shift.
6593 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
6594 : Intrinsic::aarch64_neon_ushl;
6595 // negate the shift amount
6596 SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
6597 SDValue NegShiftLeft =
6598 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006599 DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
6600 NegShift);
Tim Northover3b0846e2014-05-24 12:50:23 +00006601 return NegShiftLeft;
6602 }
6603
6604 return SDValue();
6605}
6606
6607static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
6608 AArch64CC::CondCode CC, bool NoNans, EVT VT,
6609 SDLoc dl, SelectionDAG &DAG) {
6610 EVT SrcVT = LHS.getValueType();
Tim Northover45aa89c2015-02-08 00:50:47 +00006611 assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
6612 "function only supposed to emit natural comparisons");
Tim Northover3b0846e2014-05-24 12:50:23 +00006613
6614 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
6615 APInt CnstBits(VT.getSizeInBits(), 0);
6616 APInt UndefBits(VT.getSizeInBits(), 0);
6617 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
6618 bool IsZero = IsCnst && (CnstBits == 0);
6619
6620 if (SrcVT.getVectorElementType().isFloatingPoint()) {
6621 switch (CC) {
6622 default:
6623 return SDValue();
6624 case AArch64CC::NE: {
6625 SDValue Fcmeq;
6626 if (IsZero)
6627 Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6628 else
6629 Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6630 return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
6631 }
6632 case AArch64CC::EQ:
6633 if (IsZero)
6634 return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6635 return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6636 case AArch64CC::GE:
6637 if (IsZero)
6638 return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
6639 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
6640 case AArch64CC::GT:
6641 if (IsZero)
6642 return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
6643 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
6644 case AArch64CC::LS:
6645 if (IsZero)
6646 return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
6647 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
6648 case AArch64CC::LT:
6649 if (!NoNans)
6650 return SDValue();
6651 // If we ignore NaNs then we can use to the MI implementation.
6652 // Fallthrough.
6653 case AArch64CC::MI:
6654 if (IsZero)
6655 return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
6656 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
6657 }
6658 }
6659
6660 switch (CC) {
6661 default:
6662 return SDValue();
6663 case AArch64CC::NE: {
6664 SDValue Cmeq;
6665 if (IsZero)
6666 Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6667 else
6668 Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6669 return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
6670 }
6671 case AArch64CC::EQ:
6672 if (IsZero)
6673 return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6674 return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6675 case AArch64CC::GE:
6676 if (IsZero)
6677 return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
6678 return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
6679 case AArch64CC::GT:
6680 if (IsZero)
6681 return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
6682 return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
6683 case AArch64CC::LE:
6684 if (IsZero)
6685 return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
6686 return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
6687 case AArch64CC::LS:
6688 return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
6689 case AArch64CC::LO:
6690 return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
6691 case AArch64CC::LT:
6692 if (IsZero)
6693 return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
6694 return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
6695 case AArch64CC::HI:
6696 return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
6697 case AArch64CC::HS:
6698 return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
6699 }
6700}
6701
6702SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
6703 SelectionDAG &DAG) const {
6704 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6705 SDValue LHS = Op.getOperand(0);
6706 SDValue RHS = Op.getOperand(1);
Tim Northover45aa89c2015-02-08 00:50:47 +00006707 EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
Tim Northover3b0846e2014-05-24 12:50:23 +00006708 SDLoc dl(Op);
6709
6710 if (LHS.getValueType().getVectorElementType().isInteger()) {
6711 assert(LHS.getValueType() == RHS.getValueType());
6712 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
Tim Northover45aa89c2015-02-08 00:50:47 +00006713 SDValue Cmp =
6714 EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
6715 return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00006716 }
6717
Pirama Arumuga Nainar71e9a2a2016-01-22 01:16:57 +00006718 if (LHS.getValueType().getVectorElementType() == MVT::f16)
6719 return SDValue();
6720
Tim Northover3b0846e2014-05-24 12:50:23 +00006721 assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
6722 LHS.getValueType().getVectorElementType() == MVT::f64);
6723
6724 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
6725 // clean. Some of them require two branches to implement.
6726 AArch64CC::CondCode CC1, CC2;
6727 bool ShouldInvert;
6728 changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
6729
6730 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
6731 SDValue Cmp =
Tim Northover45aa89c2015-02-08 00:50:47 +00006732 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00006733 if (!Cmp.getNode())
6734 return SDValue();
6735
6736 if (CC2 != AArch64CC::AL) {
6737 SDValue Cmp2 =
Tim Northover45aa89c2015-02-08 00:50:47 +00006738 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00006739 if (!Cmp2.getNode())
6740 return SDValue();
6741
Tim Northover45aa89c2015-02-08 00:50:47 +00006742 Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
Tim Northover3b0846e2014-05-24 12:50:23 +00006743 }
6744
Tim Northover45aa89c2015-02-08 00:50:47 +00006745 Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
6746
Tim Northover3b0846e2014-05-24 12:50:23 +00006747 if (ShouldInvert)
6748 return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
6749
6750 return Cmp;
6751}
6752
6753/// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
6754/// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
6755/// specified in the intrinsic calls.
6756bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
6757 const CallInst &I,
6758 unsigned Intrinsic) const {
Mehdi Aminia749f2a2015-07-09 02:09:52 +00006759 auto &DL = I.getModule()->getDataLayout();
Tim Northover3b0846e2014-05-24 12:50:23 +00006760 switch (Intrinsic) {
6761 case Intrinsic::aarch64_neon_ld2:
6762 case Intrinsic::aarch64_neon_ld3:
6763 case Intrinsic::aarch64_neon_ld4:
6764 case Intrinsic::aarch64_neon_ld1x2:
6765 case Intrinsic::aarch64_neon_ld1x3:
6766 case Intrinsic::aarch64_neon_ld1x4:
6767 case Intrinsic::aarch64_neon_ld2lane:
6768 case Intrinsic::aarch64_neon_ld3lane:
6769 case Intrinsic::aarch64_neon_ld4lane:
6770 case Intrinsic::aarch64_neon_ld2r:
6771 case Intrinsic::aarch64_neon_ld3r:
6772 case Intrinsic::aarch64_neon_ld4r: {
6773 Info.opc = ISD::INTRINSIC_W_CHAIN;
6774 // Conservatively set memVT to the entire set of vectors loaded.
Ahmed Bougacha97564c32015-12-09 01:19:50 +00006775 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00006776 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6777 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6778 Info.offset = 0;
6779 Info.align = 0;
6780 Info.vol = false; // volatile loads with NEON intrinsics not supported
6781 Info.readMem = true;
6782 Info.writeMem = false;
6783 return true;
6784 }
6785 case Intrinsic::aarch64_neon_st2:
6786 case Intrinsic::aarch64_neon_st3:
6787 case Intrinsic::aarch64_neon_st4:
6788 case Intrinsic::aarch64_neon_st1x2:
6789 case Intrinsic::aarch64_neon_st1x3:
6790 case Intrinsic::aarch64_neon_st1x4:
6791 case Intrinsic::aarch64_neon_st2lane:
6792 case Intrinsic::aarch64_neon_st3lane:
6793 case Intrinsic::aarch64_neon_st4lane: {
6794 Info.opc = ISD::INTRINSIC_VOID;
6795 // Conservatively set memVT to the entire set of vectors stored.
6796 unsigned NumElts = 0;
6797 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
6798 Type *ArgTy = I.getArgOperand(ArgI)->getType();
6799 if (!ArgTy->isVectorTy())
6800 break;
Ahmed Bougacha97564c32015-12-09 01:19:50 +00006801 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00006802 }
6803 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6804 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6805 Info.offset = 0;
6806 Info.align = 0;
6807 Info.vol = false; // volatile stores with NEON intrinsics not supported
6808 Info.readMem = false;
6809 Info.writeMem = true;
6810 return true;
6811 }
6812 case Intrinsic::aarch64_ldaxr:
6813 case Intrinsic::aarch64_ldxr: {
6814 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
6815 Info.opc = ISD::INTRINSIC_W_CHAIN;
6816 Info.memVT = MVT::getVT(PtrTy->getElementType());
6817 Info.ptrVal = I.getArgOperand(0);
6818 Info.offset = 0;
Mehdi Aminia749f2a2015-07-09 02:09:52 +00006819 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
Tim Northover3b0846e2014-05-24 12:50:23 +00006820 Info.vol = true;
6821 Info.readMem = true;
6822 Info.writeMem = false;
6823 return true;
6824 }
6825 case Intrinsic::aarch64_stlxr:
6826 case Intrinsic::aarch64_stxr: {
6827 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
6828 Info.opc = ISD::INTRINSIC_W_CHAIN;
6829 Info.memVT = MVT::getVT(PtrTy->getElementType());
6830 Info.ptrVal = I.getArgOperand(1);
6831 Info.offset = 0;
Mehdi Aminia749f2a2015-07-09 02:09:52 +00006832 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
Tim Northover3b0846e2014-05-24 12:50:23 +00006833 Info.vol = true;
6834 Info.readMem = false;
6835 Info.writeMem = true;
6836 return true;
6837 }
6838 case Intrinsic::aarch64_ldaxp:
6839 case Intrinsic::aarch64_ldxp: {
6840 Info.opc = ISD::INTRINSIC_W_CHAIN;
6841 Info.memVT = MVT::i128;
6842 Info.ptrVal = I.getArgOperand(0);
6843 Info.offset = 0;
6844 Info.align = 16;
6845 Info.vol = true;
6846 Info.readMem = true;
6847 Info.writeMem = false;
6848 return true;
6849 }
6850 case Intrinsic::aarch64_stlxp:
6851 case Intrinsic::aarch64_stxp: {
6852 Info.opc = ISD::INTRINSIC_W_CHAIN;
6853 Info.memVT = MVT::i128;
6854 Info.ptrVal = I.getArgOperand(2);
6855 Info.offset = 0;
6856 Info.align = 16;
6857 Info.vol = true;
6858 Info.readMem = false;
6859 Info.writeMem = true;
6860 return true;
6861 }
6862 default:
6863 break;
6864 }
6865
6866 return false;
6867}
6868
6869// Truncations from 64-bit GPR to 32-bit GPR is free.
6870bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
6871 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6872 return false;
6873 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6874 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00006875 return NumBits1 > NumBits2;
Tim Northover3b0846e2014-05-24 12:50:23 +00006876}
6877bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
Hao Liu40914502014-05-29 09:19:07 +00006878 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00006879 return false;
6880 unsigned NumBits1 = VT1.getSizeInBits();
6881 unsigned NumBits2 = VT2.getSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00006882 return NumBits1 > NumBits2;
Tim Northover3b0846e2014-05-24 12:50:23 +00006883}
6884
Chad Rosier54390052015-02-23 19:15:16 +00006885/// Check if it is profitable to hoist instruction in then/else to if.
6886/// Not profitable if I and it's user can form a FMA instruction
6887/// because we prefer FMSUB/FMADD.
6888bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
6889 if (I->getOpcode() != Instruction::FMul)
6890 return true;
6891
6892 if (I->getNumUses() != 1)
6893 return true;
6894
6895 Instruction *User = I->user_back();
6896
6897 if (User &&
6898 !(User->getOpcode() == Instruction::FSub ||
6899 User->getOpcode() == Instruction::FAdd))
6900 return true;
6901
6902 const TargetOptions &Options = getTargetMachine().Options;
Mehdi Amini44ede332015-07-09 02:09:04 +00006903 const DataLayout &DL = I->getModule()->getDataLayout();
6904 EVT VT = getValueType(DL, User->getOperand(0)->getType());
Chad Rosier54390052015-02-23 19:15:16 +00006905
6906 if (isFMAFasterThanFMulAndFAdd(VT) &&
6907 isOperationLegalOrCustom(ISD::FMA, VT) &&
6908 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath))
6909 return false;
6910
6911 return true;
6912}
6913
Tim Northover3b0846e2014-05-24 12:50:23 +00006914// All 32-bit GPR operations implicitly zero the high-half of the corresponding
6915// 64-bit GPR.
6916bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
6917 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6918 return false;
6919 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6920 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00006921 return NumBits1 == 32 && NumBits2 == 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00006922}
6923bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
Hao Liu40914502014-05-29 09:19:07 +00006924 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00006925 return false;
6926 unsigned NumBits1 = VT1.getSizeInBits();
6927 unsigned NumBits2 = VT2.getSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00006928 return NumBits1 == 32 && NumBits2 == 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00006929}
6930
6931bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
6932 EVT VT1 = Val.getValueType();
6933 if (isZExtFree(VT1, VT2)) {
6934 return true;
6935 }
6936
6937 if (Val.getOpcode() != ISD::LOAD)
6938 return false;
6939
6940 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
Hao Liu40914502014-05-29 09:19:07 +00006941 return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
6942 VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
6943 VT1.getSizeInBits() <= 32);
Tim Northover3b0846e2014-05-24 12:50:23 +00006944}
6945
Quentin Colombet6843ac42015-03-31 20:52:32 +00006946bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
6947 if (isa<FPExtInst>(Ext))
6948 return false;
6949
6950 // Vector types are next free.
6951 if (Ext->getType()->isVectorTy())
6952 return false;
6953
6954 for (const Use &U : Ext->uses()) {
6955 // The extension is free if we can fold it with a left shift in an
6956 // addressing mode or an arithmetic operation: add, sub, and cmp.
6957
6958 // Is there a shift?
6959 const Instruction *Instr = cast<Instruction>(U.getUser());
6960
6961 // Is this a constant shift?
6962 switch (Instr->getOpcode()) {
6963 case Instruction::Shl:
6964 if (!isa<ConstantInt>(Instr->getOperand(1)))
6965 return false;
6966 break;
6967 case Instruction::GetElementPtr: {
6968 gep_type_iterator GTI = gep_type_begin(Instr);
Mehdi Aminia749f2a2015-07-09 02:09:52 +00006969 auto &DL = Ext->getModule()->getDataLayout();
Quentin Colombet6843ac42015-03-31 20:52:32 +00006970 std::advance(GTI, U.getOperandNo());
6971 Type *IdxTy = *GTI;
6972 // This extension will end up with a shift because of the scaling factor.
6973 // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
6974 // Get the shift amount based on the scaling factor:
6975 // log2(sizeof(IdxTy)) - log2(8).
6976 uint64_t ShiftAmt =
Mehdi Aminia749f2a2015-07-09 02:09:52 +00006977 countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3;
Quentin Colombet6843ac42015-03-31 20:52:32 +00006978 // Is the constant foldable in the shift of the addressing mode?
6979 // I.e., shift amount is between 1 and 4 inclusive.
6980 if (ShiftAmt == 0 || ShiftAmt > 4)
6981 return false;
6982 break;
6983 }
6984 case Instruction::Trunc:
6985 // Check if this is a noop.
6986 // trunc(sext ty1 to ty2) to ty1.
6987 if (Instr->getType() == Ext->getOperand(0)->getType())
6988 continue;
6989 // FALL THROUGH.
6990 default:
6991 return false;
6992 }
6993
6994 // At this point we can use the bfm family, so this extension is free
6995 // for that use.
6996 }
6997 return true;
6998}
6999
Tim Northover3b0846e2014-05-24 12:50:23 +00007000bool AArch64TargetLowering::hasPairedLoad(Type *LoadedType,
7001 unsigned &RequiredAligment) const {
7002 if (!LoadedType->isIntegerTy() && !LoadedType->isFloatTy())
7003 return false;
7004 // Cyclone supports unaligned accesses.
7005 RequiredAligment = 0;
7006 unsigned NumBits = LoadedType->getPrimitiveSizeInBits();
7007 return NumBits == 32 || NumBits == 64;
7008}
7009
7010bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
7011 unsigned &RequiredAligment) const {
7012 if (!LoadedType.isSimple() ||
7013 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
7014 return false;
7015 // Cyclone supports unaligned accesses.
7016 RequiredAligment = 0;
7017 unsigned NumBits = LoadedType.getSizeInBits();
7018 return NumBits == 32 || NumBits == 64;
7019}
7020
Hao Liu7ec8ee32015-06-26 02:32:07 +00007021/// \brief Lower an interleaved load into a ldN intrinsic.
7022///
7023/// E.g. Lower an interleaved load (Factor = 2):
7024/// %wide.vec = load <8 x i32>, <8 x i32>* %ptr
7025/// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
7026/// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
7027///
7028/// Into:
7029/// %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
7030/// %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
7031/// %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
7032bool AArch64TargetLowering::lowerInterleavedLoad(
7033 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
7034 ArrayRef<unsigned> Indices, unsigned Factor) const {
7035 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7036 "Invalid interleave factor");
7037 assert(!Shuffles.empty() && "Empty shufflevector input");
7038 assert(Shuffles.size() == Indices.size() &&
7039 "Unmatched number of shufflevectors and indices");
7040
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007041 const DataLayout &DL = LI->getModule()->getDataLayout();
Hao Liu7ec8ee32015-06-26 02:32:07 +00007042
7043 VectorType *VecTy = Shuffles[0]->getType();
Ahmed Bougacha97564c32015-12-09 01:19:50 +00007044 unsigned VecSize = DL.getTypeSizeInBits(VecTy);
Hao Liu7ec8ee32015-06-26 02:32:07 +00007045
Jeroen Ketemaaebca092015-10-07 14:53:29 +00007046 // Skip if we do not have NEON and skip illegal vector types.
7047 if (!Subtarget->hasNEON() || (VecSize != 64 && VecSize != 128))
Hao Liu7ec8ee32015-06-26 02:32:07 +00007048 return false;
7049
7050 // A pointer vector can not be the return type of the ldN intrinsics. Need to
7051 // load integer vectors first and then convert to pointer vectors.
7052 Type *EltTy = VecTy->getVectorElementType();
7053 if (EltTy->isPointerTy())
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007054 VecTy =
7055 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
Hao Liu7ec8ee32015-06-26 02:32:07 +00007056
7057 Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
7058 Type *Tys[2] = {VecTy, PtrTy};
7059 static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
7060 Intrinsic::aarch64_neon_ld3,
7061 Intrinsic::aarch64_neon_ld4};
7062 Function *LdNFunc =
7063 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
7064
7065 IRBuilder<> Builder(LI);
7066 Value *Ptr = Builder.CreateBitCast(LI->getPointerOperand(), PtrTy);
7067
7068 CallInst *LdN = Builder.CreateCall(LdNFunc, Ptr, "ldN");
7069
7070 // Replace uses of each shufflevector with the corresponding vector loaded
7071 // by ldN.
7072 for (unsigned i = 0; i < Shuffles.size(); i++) {
7073 ShuffleVectorInst *SVI = Shuffles[i];
7074 unsigned Index = Indices[i];
7075
7076 Value *SubVec = Builder.CreateExtractValue(LdN, Index);
7077
7078 // Convert the integer vector to pointer vector if the element is pointer.
7079 if (EltTy->isPointerTy())
7080 SubVec = Builder.CreateIntToPtr(SubVec, SVI->getType());
7081
7082 SVI->replaceAllUsesWith(SubVec);
7083 }
7084
7085 return true;
7086}
7087
7088/// \brief Get a mask consisting of sequential integers starting from \p Start.
7089///
7090/// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
7091static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
7092 unsigned NumElts) {
7093 SmallVector<Constant *, 16> Mask;
7094 for (unsigned i = 0; i < NumElts; i++)
7095 Mask.push_back(Builder.getInt32(Start + i));
7096
7097 return ConstantVector::get(Mask);
7098}
7099
7100/// \brief Lower an interleaved store into a stN intrinsic.
7101///
7102/// E.g. Lower an interleaved store (Factor = 3):
7103/// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
7104/// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
7105/// store <12 x i32> %i.vec, <12 x i32>* %ptr
7106///
7107/// Into:
7108/// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
7109/// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
7110/// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
7111/// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
7112///
7113/// Note that the new shufflevectors will be removed and we'll only generate one
7114/// st3 instruction in CodeGen.
7115bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
7116 ShuffleVectorInst *SVI,
7117 unsigned Factor) const {
7118 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7119 "Invalid interleave factor");
7120
7121 VectorType *VecTy = SVI->getType();
7122 assert(VecTy->getVectorNumElements() % Factor == 0 &&
7123 "Invalid interleaved store");
7124
7125 unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
7126 Type *EltTy = VecTy->getVectorElementType();
7127 VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
7128
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007129 const DataLayout &DL = SI->getModule()->getDataLayout();
Ahmed Bougacha97564c32015-12-09 01:19:50 +00007130 unsigned SubVecSize = DL.getTypeSizeInBits(SubVecTy);
Hao Liu7ec8ee32015-06-26 02:32:07 +00007131
Jeroen Ketemaaebca092015-10-07 14:53:29 +00007132 // Skip if we do not have NEON and skip illegal vector types.
7133 if (!Subtarget->hasNEON() || (SubVecSize != 64 && SubVecSize != 128))
Hao Liu7ec8ee32015-06-26 02:32:07 +00007134 return false;
7135
7136 Value *Op0 = SVI->getOperand(0);
7137 Value *Op1 = SVI->getOperand(1);
7138 IRBuilder<> Builder(SI);
7139
7140 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
7141 // vectors to integer vectors.
7142 if (EltTy->isPointerTy()) {
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007143 Type *IntTy = DL.getIntPtrType(EltTy);
Hao Liu7ec8ee32015-06-26 02:32:07 +00007144 unsigned NumOpElts =
7145 dyn_cast<VectorType>(Op0->getType())->getVectorNumElements();
7146
7147 // Convert to the corresponding integer vector.
7148 Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
7149 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
7150 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
7151
7152 SubVecTy = VectorType::get(IntTy, NumSubElts);
7153 }
7154
7155 Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
7156 Type *Tys[2] = {SubVecTy, PtrTy};
7157 static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
7158 Intrinsic::aarch64_neon_st3,
7159 Intrinsic::aarch64_neon_st4};
7160 Function *StNFunc =
7161 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
7162
7163 SmallVector<Value *, 5> Ops;
7164
7165 // Split the shufflevector operands into sub vectors for the new stN call.
7166 for (unsigned i = 0; i < Factor; i++)
7167 Ops.push_back(Builder.CreateShuffleVector(
7168 Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
7169
7170 Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), PtrTy));
7171 Builder.CreateCall(StNFunc, Ops);
7172 return true;
7173}
7174
Tim Northover3b0846e2014-05-24 12:50:23 +00007175static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
7176 unsigned AlignCheck) {
7177 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
7178 (DstAlign == 0 || DstAlign % AlignCheck == 0));
7179}
7180
7181EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
7182 unsigned SrcAlign, bool IsMemset,
7183 bool ZeroMemset,
7184 bool MemcpyStrSrc,
7185 MachineFunction &MF) const {
7186 // Don't use AdvSIMD to implement 16-byte memset. It would have taken one
7187 // instruction to materialize the v2i64 zero and one store (with restrictive
7188 // addressing mode). Just do two i64 store of zero-registers.
7189 bool Fast;
7190 const Function *F = MF.getFunction();
7191 if (Subtarget->hasFPARMv8() && !IsMemset && Size >= 16 &&
Duncan P. N. Exon Smith003bb7d2015-02-14 02:09:06 +00007192 !F->hasFnAttribute(Attribute::NoImplicitFloat) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00007193 (memOpAlign(SrcAlign, DstAlign, 16) ||
Matt Arsenault6f2a5262014-07-27 17:46:40 +00007194 (allowsMisalignedMemoryAccesses(MVT::f128, 0, 1, &Fast) && Fast)))
Tim Northover3b0846e2014-05-24 12:50:23 +00007195 return MVT::f128;
7196
Lang Hames90333852015-04-09 03:40:33 +00007197 if (Size >= 8 &&
7198 (memOpAlign(SrcAlign, DstAlign, 8) ||
7199 (allowsMisalignedMemoryAccesses(MVT::i64, 0, 1, &Fast) && Fast)))
7200 return MVT::i64;
7201
7202 if (Size >= 4 &&
7203 (memOpAlign(SrcAlign, DstAlign, 4) ||
7204 (allowsMisalignedMemoryAccesses(MVT::i32, 0, 1, &Fast) && Fast)))
Lang Hames522bf132015-04-09 05:34:57 +00007205 return MVT::i32;
Lang Hames90333852015-04-09 03:40:33 +00007206
7207 return MVT::Other;
Tim Northover3b0846e2014-05-24 12:50:23 +00007208}
7209
7210// 12-bit optionally shifted immediates are legal for adds.
7211bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
7212 if ((Immed >> 12) == 0 || ((Immed & 0xfff) == 0 && Immed >> 24 == 0))
7213 return true;
7214 return false;
7215}
7216
7217// Integer comparisons are implemented with ADDS/SUBS, so the range of valid
7218// immediates is the same as for an add or a sub.
7219bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
7220 if (Immed < 0)
7221 Immed *= -1;
7222 return isLegalAddImmediate(Immed);
7223}
7224
7225/// isLegalAddressingMode - Return true if the addressing mode represented
7226/// by AM is legal for this target, for a load/store of the specified type.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00007227bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
7228 const AddrMode &AM, Type *Ty,
Matt Arsenaultbd7d80a2015-06-01 05:31:59 +00007229 unsigned AS) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00007230 // AArch64 has five basic addressing modes:
7231 // reg
7232 // reg + 9-bit signed offset
7233 // reg + SIZE_IN_BYTES * 12-bit unsigned offset
7234 // reg1 + reg2
7235 // reg + SIZE_IN_BYTES * reg
7236
7237 // No global is ever allowed as a base.
7238 if (AM.BaseGV)
7239 return false;
7240
7241 // No reg+reg+imm addressing.
7242 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
7243 return false;
7244
7245 // check reg + imm case:
7246 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
7247 uint64_t NumBytes = 0;
7248 if (Ty->isSized()) {
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00007249 uint64_t NumBits = DL.getTypeSizeInBits(Ty);
Tim Northover3b0846e2014-05-24 12:50:23 +00007250 NumBytes = NumBits / 8;
7251 if (!isPowerOf2_64(NumBits))
7252 NumBytes = 0;
7253 }
7254
7255 if (!AM.Scale) {
7256 int64_t Offset = AM.BaseOffs;
7257
7258 // 9-bit signed offset
7259 if (Offset >= -(1LL << 9) && Offset <= (1LL << 9) - 1)
7260 return true;
7261
7262 // 12-bit unsigned offset
7263 unsigned shift = Log2_64(NumBytes);
7264 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
7265 // Must be a multiple of NumBytes (NumBytes is a power of 2)
7266 (Offset >> shift) << shift == Offset)
7267 return true;
7268 return false;
7269 }
7270
7271 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
7272
7273 if (!AM.Scale || AM.Scale == 1 ||
7274 (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes))
7275 return true;
7276 return false;
7277}
7278
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00007279int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
7280 const AddrMode &AM, Type *Ty,
Matt Arsenaultbd7d80a2015-06-01 05:31:59 +00007281 unsigned AS) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00007282 // Scaling factors are not free at all.
7283 // Operands | Rt Latency
7284 // -------------------------------------------
7285 // Rt, [Xn, Xm] | 4
7286 // -------------------------------------------
7287 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5
7288 // Rt, [Xn, Wm, <extend> #imm] |
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00007289 if (isLegalAddressingMode(DL, AM, Ty, AS))
Tim Northover3b0846e2014-05-24 12:50:23 +00007290 // Scale represents reg2 * scale, thus account for 1 if
7291 // it is not equal to 0 or 1.
7292 return AM.Scale != 0 && AM.Scale != 1;
7293 return -1;
7294}
7295
7296bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
7297 VT = VT.getScalarType();
7298
7299 if (!VT.isSimple())
7300 return false;
7301
7302 switch (VT.getSimpleVT().SimpleTy) {
7303 case MVT::f32:
7304 case MVT::f64:
7305 return true;
7306 default:
7307 break;
7308 }
7309
7310 return false;
7311}
7312
7313const MCPhysReg *
7314AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
7315 // LR is a callee-save register, but we must treat it as clobbered by any call
7316 // site. Hence we include LR in the scratch registers, which are in turn added
7317 // as implicit-defs for stackmaps and patchpoints.
7318 static const MCPhysReg ScratchRegs[] = {
7319 AArch64::X16, AArch64::X17, AArch64::LR, 0
7320 };
7321 return ScratchRegs;
7322}
7323
7324bool
7325AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N) const {
7326 EVT VT = N->getValueType(0);
7327 // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
7328 // it with shift to let it be lowered to UBFX.
7329 if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
7330 isa<ConstantSDNode>(N->getOperand(1))) {
7331 uint64_t TruncMask = N->getConstantOperandVal(1);
7332 if (isMask_64(TruncMask) &&
7333 N->getOperand(0).getOpcode() == ISD::SRL &&
7334 isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
7335 return false;
7336 }
7337 return true;
7338}
7339
7340bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
7341 Type *Ty) const {
7342 assert(Ty->isIntegerTy());
7343
7344 unsigned BitSize = Ty->getPrimitiveSizeInBits();
7345 if (BitSize == 0)
7346 return false;
7347
7348 int64_t Val = Imm.getSExtValue();
7349 if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
7350 return true;
7351
7352 if ((int64_t)Val < 0)
7353 Val = ~Val;
7354 if (BitSize == 32)
7355 Val &= (1LL << 32) - 1;
7356
7357 unsigned LZ = countLeadingZeros((uint64_t)Val);
7358 unsigned Shift = (63 - LZ) / 16;
7359 // MOVZ is free so return true for one or fewer MOVK.
David Blaikie186d2cb2015-03-24 16:24:01 +00007360 return Shift < 3;
Tim Northover3b0846e2014-05-24 12:50:23 +00007361}
7362
7363// Generate SUBS and CSEL for integer abs.
7364static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
7365 EVT VT = N->getValueType(0);
7366
7367 SDValue N0 = N->getOperand(0);
7368 SDValue N1 = N->getOperand(1);
7369 SDLoc DL(N);
7370
7371 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
7372 // and change it to SUB and CSEL.
7373 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
7374 N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
7375 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
7376 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
7377 if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007378 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
Tim Northover3b0846e2014-05-24 12:50:23 +00007379 N0.getOperand(0));
7380 // Generate SUBS & CSEL.
7381 SDValue Cmp =
7382 DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007383 N0.getOperand(0), DAG.getConstant(0, DL, VT));
Tim Northover3b0846e2014-05-24 12:50:23 +00007384 return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007385 DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00007386 SDValue(Cmp.getNode(), 1));
7387 }
7388 return SDValue();
7389}
7390
7391// performXorCombine - Attempts to handle integer ABS.
7392static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
7393 TargetLowering::DAGCombinerInfo &DCI,
7394 const AArch64Subtarget *Subtarget) {
7395 if (DCI.isBeforeLegalizeOps())
7396 return SDValue();
7397
7398 return performIntegerAbsCombine(N, DAG);
7399}
7400
Chad Rosier17020f92014-07-23 14:57:52 +00007401SDValue
7402AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
7403 SelectionDAG &DAG,
7404 std::vector<SDNode *> *Created) const {
7405 // fold (sdiv X, pow2)
7406 EVT VT = N->getValueType(0);
7407 if ((VT != MVT::i32 && VT != MVT::i64) ||
7408 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
7409 return SDValue();
7410
7411 SDLoc DL(N);
7412 SDValue N0 = N->getOperand(0);
7413 unsigned Lg2 = Divisor.countTrailingZeros();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007414 SDValue Zero = DAG.getConstant(0, DL, VT);
7415 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
Chad Rosier17020f92014-07-23 14:57:52 +00007416
7417 // Add (N0 < 0) ? Pow2 - 1 : 0;
7418 SDValue CCVal;
7419 SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
7420 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
7421 SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
7422
7423 if (Created) {
7424 Created->push_back(Cmp.getNode());
7425 Created->push_back(Add.getNode());
7426 Created->push_back(CSel.getNode());
7427 }
7428
7429 // Divide by pow2.
7430 SDValue SRA =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007431 DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
Chad Rosier17020f92014-07-23 14:57:52 +00007432
7433 // If we're dividing by a positive value, we're done. Otherwise, we must
7434 // negate the result.
7435 if (Divisor.isNonNegative())
7436 return SRA;
7437
7438 if (Created)
7439 Created->push_back(SRA.getNode());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007440 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
Chad Rosier17020f92014-07-23 14:57:52 +00007441}
7442
Tim Northover3b0846e2014-05-24 12:50:23 +00007443static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
7444 TargetLowering::DAGCombinerInfo &DCI,
7445 const AArch64Subtarget *Subtarget) {
7446 if (DCI.isBeforeLegalizeOps())
7447 return SDValue();
7448
7449 // Multiplication of a power of two plus/minus one can be done more
7450 // cheaply as as shift+add/sub. For now, this is true unilaterally. If
7451 // future CPUs have a cheaper MADD instruction, this may need to be
7452 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
7453 // 64-bit is 5 cycles, so this is always a win.
7454 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
7455 APInt Value = C->getAPIntValue();
7456 EVT VT = N->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007457 SDLoc DL(N);
Chad Rosiere6b87612014-06-30 14:51:14 +00007458 if (Value.isNonNegative()) {
7459 // (mul x, 2^N + 1) => (add (shl x, N), x)
7460 APInt VM1 = Value - 1;
7461 if (VM1.isPowerOf2()) {
7462 SDValue ShiftedVal =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007463 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7464 DAG.getConstant(VM1.logBase2(), DL, MVT::i64));
7465 return DAG.getNode(ISD::ADD, DL, VT, ShiftedVal,
Chad Rosiere6b87612014-06-30 14:51:14 +00007466 N->getOperand(0));
7467 }
7468 // (mul x, 2^N - 1) => (sub (shl x, N), x)
7469 APInt VP1 = Value + 1;
7470 if (VP1.isPowerOf2()) {
7471 SDValue ShiftedVal =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007472 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7473 DAG.getConstant(VP1.logBase2(), DL, MVT::i64));
7474 return DAG.getNode(ISD::SUB, DL, VT, ShiftedVal,
Chad Rosiere6b87612014-06-30 14:51:14 +00007475 N->getOperand(0));
7476 }
7477 } else {
Chad Rosier8e38f302015-03-03 17:31:01 +00007478 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7479 APInt VNP1 = -Value + 1;
7480 if (VNP1.isPowerOf2()) {
7481 SDValue ShiftedVal =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007482 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7483 DAG.getConstant(VNP1.logBase2(), DL, MVT::i64));
7484 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0),
Chad Rosier8e38f302015-03-03 17:31:01 +00007485 ShiftedVal);
7486 }
Chad Rosiere6b87612014-06-30 14:51:14 +00007487 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7488 APInt VNM1 = -Value - 1;
7489 if (VNM1.isPowerOf2()) {
7490 SDValue ShiftedVal =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007491 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7492 DAG.getConstant(VNM1.logBase2(), DL, MVT::i64));
Chad Rosiere6b87612014-06-30 14:51:14 +00007493 SDValue Add =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007494 DAG.getNode(ISD::ADD, DL, VT, ShiftedVal, N->getOperand(0));
7495 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Add);
Chad Rosiere6b87612014-06-30 14:51:14 +00007496 }
Chad Rosierd96e9f12014-06-09 01:25:51 +00007497 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007498 }
7499 return SDValue();
7500}
7501
Jim Grosbachf7502c42014-07-18 00:40:52 +00007502static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
7503 SelectionDAG &DAG) {
7504 // Take advantage of vector comparisons producing 0 or -1 in each lane to
7505 // optimize away operation when it's from a constant.
7506 //
7507 // The general transformation is:
7508 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
7509 // AND(VECTOR_CMP(x,y), constant2)
7510 // constant2 = UNARYOP(constant)
7511
Jim Grosbach8f6f0852014-07-23 20:41:38 +00007512 // Early exit if this isn't a vector operation, the operand of the
7513 // unary operation isn't a bitwise AND, or if the sizes of the operations
7514 // aren't the same.
Jim Grosbachf7502c42014-07-18 00:40:52 +00007515 EVT VT = N->getValueType(0);
7516 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
Jim Grosbach8f6f0852014-07-23 20:41:38 +00007517 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
7518 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
Jim Grosbachf7502c42014-07-18 00:40:52 +00007519 return SDValue();
7520
Jim Grosbach724e4382014-07-23 20:41:43 +00007521 // Now check that the other operand of the AND is a constant. We could
Jim Grosbachf7502c42014-07-18 00:40:52 +00007522 // make the transformation for non-constant splats as well, but it's unclear
7523 // that would be a benefit as it would not eliminate any operations, just
7524 // perform one more step in scalar code before moving to the vector unit.
7525 if (BuildVectorSDNode *BV =
7526 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
Jim Grosbach724e4382014-07-23 20:41:43 +00007527 // Bail out if the vector isn't a constant.
7528 if (!BV->isConstant())
Jim Grosbachf7502c42014-07-18 00:40:52 +00007529 return SDValue();
7530
7531 // Everything checks out. Build up the new and improved node.
7532 SDLoc DL(N);
7533 EVT IntVT = BV->getValueType(0);
7534 // Create a new constant of the appropriate type for the transformed
7535 // DAG.
7536 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
7537 // The AND node needs bitcasts to/from an integer vector type around it.
7538 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
7539 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
7540 N->getOperand(0)->getOperand(0), MaskConst);
7541 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
7542 return Res;
7543 }
7544
7545 return SDValue();
7546}
7547
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00007548static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
7549 const AArch64Subtarget *Subtarget) {
Jim Grosbachf7502c42014-07-18 00:40:52 +00007550 // First try to optimize away the conversion when it's conditionally from
7551 // a constant. Vectors only.
Ahmed Bougacha239d6352015-08-04 00:48:02 +00007552 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
Jim Grosbachf7502c42014-07-18 00:40:52 +00007553 return Res;
7554
Tim Northover3b0846e2014-05-24 12:50:23 +00007555 EVT VT = N->getValueType(0);
7556 if (VT != MVT::f32 && VT != MVT::f64)
7557 return SDValue();
Jim Grosbachf7502c42014-07-18 00:40:52 +00007558
Tim Northover3b0846e2014-05-24 12:50:23 +00007559 // Only optimize when the source and destination types have the same width.
7560 if (VT.getSizeInBits() != N->getOperand(0).getValueType().getSizeInBits())
7561 return SDValue();
7562
7563 // If the result of an integer load is only used by an integer-to-float
7564 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
Chad Rosier1f385612015-10-02 16:42:59 +00007565 // This eliminates an "integer-to-vector-move" UOP and improves throughput.
Tim Northover3b0846e2014-05-24 12:50:23 +00007566 SDValue N0 = N->getOperand(0);
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00007567 if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Tim Northover3b0846e2014-05-24 12:50:23 +00007568 // Do not change the width of a volatile load.
7569 !cast<LoadSDNode>(N0)->isVolatile()) {
7570 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7571 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
7572 LN0->getPointerInfo(), LN0->isVolatile(),
7573 LN0->isNonTemporal(), LN0->isInvariant(),
7574 LN0->getAlignment());
7575
7576 // Make sure successors of the original load stay after it by updating them
7577 // to use the new Chain.
7578 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
7579
7580 unsigned Opcode =
7581 (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
7582 return DAG.getNode(Opcode, SDLoc(N), VT, Load);
7583 }
7584
7585 return SDValue();
7586}
7587
Chad Rosierfa30c9b2015-10-07 17:39:18 +00007588/// Fold a floating-point multiply by power of two into floating-point to
7589/// fixed-point conversion.
7590static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
7591 const AArch64Subtarget *Subtarget) {
7592 if (!Subtarget->hasNEON())
7593 return SDValue();
7594
7595 SDValue Op = N->getOperand(0);
7596 if (!Op.getValueType().isVector() || Op.getOpcode() != ISD::FMUL)
7597 return SDValue();
7598
7599 SDValue ConstVec = Op->getOperand(1);
7600 if (!isa<BuildVectorSDNode>(ConstVec))
7601 return SDValue();
7602
7603 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
7604 uint32_t FloatBits = FloatTy.getSizeInBits();
7605 if (FloatBits != 32 && FloatBits != 64)
7606 return SDValue();
7607
7608 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
7609 uint32_t IntBits = IntTy.getSizeInBits();
7610 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
7611 return SDValue();
7612
7613 // Avoid conversions where iN is larger than the float (e.g., float -> i64).
7614 if (IntBits > FloatBits)
7615 return SDValue();
7616
7617 BitVector UndefElements;
7618 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
7619 int32_t Bits = IntBits == 64 ? 64 : 32;
7620 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
7621 if (C == -1 || C == 0 || C > Bits)
7622 return SDValue();
7623
7624 MVT ResTy;
7625 unsigned NumLanes = Op.getValueType().getVectorNumElements();
7626 switch (NumLanes) {
7627 default:
7628 return SDValue();
7629 case 2:
7630 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
7631 break;
7632 case 4:
7633 ResTy = MVT::v4i32;
7634 break;
7635 }
7636
7637 SDLoc DL(N);
7638 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
7639 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
7640 : Intrinsic::aarch64_neon_vcvtfp2fxu;
7641 SDValue FixConv =
7642 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
7643 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
7644 Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
7645 // We can handle smaller integers by generating an extra trunc.
7646 if (IntBits < FloatBits)
7647 FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
7648
7649 return FixConv;
7650}
7651
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00007652/// Fold a floating-point divide by power of two into fixed-point to
7653/// floating-point conversion.
7654static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
7655 const AArch64Subtarget *Subtarget) {
7656 if (!Subtarget->hasNEON())
7657 return SDValue();
7658
7659 SDValue Op = N->getOperand(0);
7660 unsigned Opc = Op->getOpcode();
7661 if (!Op.getValueType().isVector() ||
7662 (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
7663 return SDValue();
7664
7665 SDValue ConstVec = N->getOperand(1);
7666 if (!isa<BuildVectorSDNode>(ConstVec))
7667 return SDValue();
7668
7669 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
7670 int32_t IntBits = IntTy.getSizeInBits();
7671 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
7672 return SDValue();
7673
7674 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
7675 int32_t FloatBits = FloatTy.getSizeInBits();
7676 if (FloatBits != 32 && FloatBits != 64)
7677 return SDValue();
7678
7679 // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
7680 if (IntBits > FloatBits)
7681 return SDValue();
7682
7683 BitVector UndefElements;
7684 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
7685 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
7686 if (C == -1 || C == 0 || C > FloatBits)
7687 return SDValue();
7688
7689 MVT ResTy;
7690 unsigned NumLanes = Op.getValueType().getVectorNumElements();
7691 switch (NumLanes) {
7692 default:
7693 return SDValue();
7694 case 2:
7695 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
7696 break;
7697 case 4:
7698 ResTy = MVT::v4i32;
7699 break;
7700 }
7701
7702 SDLoc DL(N);
7703 SDValue ConvInput = Op.getOperand(0);
7704 bool IsSigned = Opc == ISD::SINT_TO_FP;
7705 if (IntBits < FloatBits)
7706 ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
7707 ResTy, ConvInput);
7708
7709 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
7710 : Intrinsic::aarch64_neon_vcvtfxu2fp;
7711 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
7712 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
7713 DAG.getConstant(C, DL, MVT::i32));
7714}
7715
Tim Northover3b0846e2014-05-24 12:50:23 +00007716/// An EXTR instruction is made up of two shifts, ORed together. This helper
7717/// searches for and classifies those shifts.
7718static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
7719 bool &FromHi) {
7720 if (N.getOpcode() == ISD::SHL)
7721 FromHi = false;
7722 else if (N.getOpcode() == ISD::SRL)
7723 FromHi = true;
7724 else
7725 return false;
7726
7727 if (!isa<ConstantSDNode>(N.getOperand(1)))
7728 return false;
7729
7730 ShiftAmount = N->getConstantOperandVal(1);
7731 Src = N->getOperand(0);
7732 return true;
7733}
7734
7735/// EXTR instruction extracts a contiguous chunk of bits from two existing
7736/// registers viewed as a high/low pair. This function looks for the pattern:
7737/// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an
7738/// EXTR. Can't quite be done in TableGen because the two immediates aren't
7739/// independent.
7740static SDValue tryCombineToEXTR(SDNode *N,
7741 TargetLowering::DAGCombinerInfo &DCI) {
7742 SelectionDAG &DAG = DCI.DAG;
7743 SDLoc DL(N);
7744 EVT VT = N->getValueType(0);
7745
7746 assert(N->getOpcode() == ISD::OR && "Unexpected root");
7747
7748 if (VT != MVT::i32 && VT != MVT::i64)
7749 return SDValue();
7750
7751 SDValue LHS;
7752 uint32_t ShiftLHS = 0;
7753 bool LHSFromHi = 0;
7754 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
7755 return SDValue();
7756
7757 SDValue RHS;
7758 uint32_t ShiftRHS = 0;
7759 bool RHSFromHi = 0;
7760 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
7761 return SDValue();
7762
7763 // If they're both trying to come from the high part of the register, they're
7764 // not really an EXTR.
7765 if (LHSFromHi == RHSFromHi)
7766 return SDValue();
7767
7768 if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
7769 return SDValue();
7770
7771 if (LHSFromHi) {
7772 std::swap(LHS, RHS);
7773 std::swap(ShiftLHS, ShiftRHS);
7774 }
7775
7776 return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007777 DAG.getConstant(ShiftRHS, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00007778}
7779
7780static SDValue tryCombineToBSL(SDNode *N,
7781 TargetLowering::DAGCombinerInfo &DCI) {
7782 EVT VT = N->getValueType(0);
7783 SelectionDAG &DAG = DCI.DAG;
7784 SDLoc DL(N);
7785
7786 if (!VT.isVector())
7787 return SDValue();
7788
7789 SDValue N0 = N->getOperand(0);
7790 if (N0.getOpcode() != ISD::AND)
7791 return SDValue();
7792
7793 SDValue N1 = N->getOperand(1);
7794 if (N1.getOpcode() != ISD::AND)
7795 return SDValue();
7796
7797 // We only have to look for constant vectors here since the general, variable
7798 // case can be handled in TableGen.
7799 unsigned Bits = VT.getVectorElementType().getSizeInBits();
7800 uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
7801 for (int i = 1; i >= 0; --i)
7802 for (int j = 1; j >= 0; --j) {
7803 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
7804 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
7805 if (!BVN0 || !BVN1)
7806 continue;
7807
7808 bool FoundMatch = true;
7809 for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
7810 ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
7811 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
7812 if (!CN0 || !CN1 ||
7813 CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
7814 FoundMatch = false;
7815 break;
7816 }
7817 }
7818
7819 if (FoundMatch)
7820 return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
7821 N0->getOperand(1 - i), N1->getOperand(1 - j));
7822 }
7823
7824 return SDValue();
7825}
7826
7827static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
7828 const AArch64Subtarget *Subtarget) {
7829 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
7830 if (!EnableAArch64ExtrGeneration)
7831 return SDValue();
7832 SelectionDAG &DAG = DCI.DAG;
7833 EVT VT = N->getValueType(0);
7834
7835 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7836 return SDValue();
7837
7838 SDValue Res = tryCombineToEXTR(N, DCI);
7839 if (Res.getNode())
7840 return Res;
7841
7842 Res = tryCombineToBSL(N, DCI);
7843 if (Res.getNode())
7844 return Res;
7845
7846 return SDValue();
7847}
7848
7849static SDValue performBitcastCombine(SDNode *N,
7850 TargetLowering::DAGCombinerInfo &DCI,
7851 SelectionDAG &DAG) {
7852 // Wait 'til after everything is legalized to try this. That way we have
7853 // legal vector types and such.
7854 if (DCI.isBeforeLegalizeOps())
7855 return SDValue();
7856
7857 // Remove extraneous bitcasts around an extract_subvector.
7858 // For example,
7859 // (v4i16 (bitconvert
7860 // (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
7861 // becomes
7862 // (extract_subvector ((v8i16 ...), (i64 4)))
7863
7864 // Only interested in 64-bit vectors as the ultimate result.
7865 EVT VT = N->getValueType(0);
7866 if (!VT.isVector())
7867 return SDValue();
7868 if (VT.getSimpleVT().getSizeInBits() != 64)
7869 return SDValue();
7870 // Is the operand an extract_subvector starting at the beginning or halfway
7871 // point of the vector? A low half may also come through as an
7872 // EXTRACT_SUBREG, so look for that, too.
7873 SDValue Op0 = N->getOperand(0);
7874 if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
7875 !(Op0->isMachineOpcode() &&
7876 Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
7877 return SDValue();
7878 uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
7879 if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
7880 if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
7881 return SDValue();
7882 } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
7883 if (idx != AArch64::dsub)
7884 return SDValue();
7885 // The dsub reference is equivalent to a lane zero subvector reference.
7886 idx = 0;
7887 }
7888 // Look through the bitcast of the input to the extract.
7889 if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
7890 return SDValue();
7891 SDValue Source = Op0->getOperand(0)->getOperand(0);
7892 // If the source type has twice the number of elements as our destination
7893 // type, we know this is an extract of the high or low half of the vector.
7894 EVT SVT = Source->getValueType(0);
7895 if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
7896 return SDValue();
7897
7898 DEBUG(dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
7899
7900 // Create the simplified form to just extract the low or high half of the
7901 // vector directly rather than bothering with the bitcasts.
7902 SDLoc dl(N);
7903 unsigned NumElements = VT.getVectorNumElements();
7904 if (idx) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007905 SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00007906 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
7907 } else {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007908 SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00007909 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
7910 Source, SubReg),
7911 0);
7912 }
7913}
7914
7915static SDValue performConcatVectorsCombine(SDNode *N,
7916 TargetLowering::DAGCombinerInfo &DCI,
7917 SelectionDAG &DAG) {
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00007918 SDLoc dl(N);
7919 EVT VT = N->getValueType(0);
7920 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
7921
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00007922 // Optimize concat_vectors of truncated vectors, where the intermediate
7923 // type is illegal, to avoid said illegality, e.g.,
7924 // (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
7925 // (v2i16 (truncate (v2i64)))))
7926 // ->
Ahmed Bougachae6bb09a2015-03-21 01:08:39 +00007927 // (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
7928 // (v4i32 (bitcast (v2i64))),
7929 // <0, 2, 4, 6>)))
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00007930 // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
7931 // on both input and result type, so we might generate worse code.
7932 // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
7933 if (N->getNumOperands() == 2 &&
7934 N0->getOpcode() == ISD::TRUNCATE &&
7935 N1->getOpcode() == ISD::TRUNCATE) {
7936 SDValue N00 = N0->getOperand(0);
7937 SDValue N10 = N1->getOperand(0);
7938 EVT N00VT = N00.getValueType();
7939
7940 if (N00VT == N10.getValueType() &&
7941 (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
7942 N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
Ahmed Bougachae6bb09a2015-03-21 01:08:39 +00007943 MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
7944 SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
7945 for (size_t i = 0; i < Mask.size(); ++i)
7946 Mask[i] = i * 2;
7947 return DAG.getNode(ISD::TRUNCATE, dl, VT,
7948 DAG.getVectorShuffle(
7949 MidVT, dl,
7950 DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
7951 DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00007952 }
7953 }
7954
Tim Northover3b0846e2014-05-24 12:50:23 +00007955 // Wait 'til after everything is legalized to try this. That way we have
7956 // legal vector types and such.
7957 if (DCI.isBeforeLegalizeOps())
7958 return SDValue();
7959
Tim Northover3b0846e2014-05-24 12:50:23 +00007960 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
7961 // splat. The indexed instructions are going to be expecting a DUPLANE64, so
7962 // canonicalise to that.
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00007963 if (N0 == N1 && VT.getVectorNumElements() == 2) {
Tim Northover3b0846e2014-05-24 12:50:23 +00007964 assert(VT.getVectorElementType().getSizeInBits() == 64);
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00007965 return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007966 DAG.getConstant(0, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00007967 }
7968
7969 // Canonicalise concat_vectors so that the right-hand vector has as few
7970 // bit-casts as possible before its real operation. The primary matching
7971 // destination for these operations will be the narrowing "2" instructions,
7972 // which depend on the operation being performed on this right-hand vector.
7973 // For example,
7974 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS))))
7975 // becomes
7976 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
7977
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00007978 if (N1->getOpcode() != ISD::BITCAST)
Tim Northover3b0846e2014-05-24 12:50:23 +00007979 return SDValue();
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00007980 SDValue RHS = N1->getOperand(0);
Tim Northover3b0846e2014-05-24 12:50:23 +00007981 MVT RHSTy = RHS.getValueType().getSimpleVT();
7982 // If the RHS is not a vector, this is not the pattern we're looking for.
7983 if (!RHSTy.isVector())
7984 return SDValue();
7985
7986 DEBUG(dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
7987
7988 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
7989 RHSTy.getVectorNumElements() * 2);
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00007990 return DAG.getNode(ISD::BITCAST, dl, VT,
7991 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
7992 DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
7993 RHS));
Tim Northover3b0846e2014-05-24 12:50:23 +00007994}
7995
7996static SDValue tryCombineFixedPointConvert(SDNode *N,
7997 TargetLowering::DAGCombinerInfo &DCI,
7998 SelectionDAG &DAG) {
7999 // Wait 'til after everything is legalized to try this. That way we have
8000 // legal vector types and such.
8001 if (DCI.isBeforeLegalizeOps())
8002 return SDValue();
8003 // Transform a scalar conversion of a value from a lane extract into a
8004 // lane extract of a vector conversion. E.g., from foo1 to foo2:
8005 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
8006 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
8007 //
8008 // The second form interacts better with instruction selection and the
8009 // register allocator to avoid cross-class register copies that aren't
8010 // coalescable due to a lane reference.
8011
8012 // Check the operand and see if it originates from a lane extract.
8013 SDValue Op1 = N->getOperand(1);
8014 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8015 // Yep, no additional predication needed. Perform the transform.
8016 SDValue IID = N->getOperand(0);
8017 SDValue Shift = N->getOperand(2);
8018 SDValue Vec = Op1.getOperand(0);
8019 SDValue Lane = Op1.getOperand(1);
8020 EVT ResTy = N->getValueType(0);
8021 EVT VecResTy;
8022 SDLoc DL(N);
8023
8024 // The vector width should be 128 bits by the time we get here, even
8025 // if it started as 64 bits (the extract_vector handling will have
8026 // done so).
8027 assert(Vec.getValueType().getSizeInBits() == 128 &&
8028 "unexpected vector size on extract_vector_elt!");
8029 if (Vec.getValueType() == MVT::v4i32)
8030 VecResTy = MVT::v4f32;
8031 else if (Vec.getValueType() == MVT::v2i64)
8032 VecResTy = MVT::v2f64;
8033 else
Craig Topper2a30d782014-06-18 05:05:13 +00008034 llvm_unreachable("unexpected vector type!");
Tim Northover3b0846e2014-05-24 12:50:23 +00008035
8036 SDValue Convert =
8037 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
8038 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
8039 }
8040 return SDValue();
8041}
8042
8043// AArch64 high-vector "long" operations are formed by performing the non-high
8044// version on an extract_subvector of each operand which gets the high half:
8045//
8046// (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
8047//
8048// However, there are cases which don't have an extract_high explicitly, but
8049// have another operation that can be made compatible with one for free. For
8050// example:
8051//
8052// (dupv64 scalar) --> (extract_high (dup128 scalar))
8053//
8054// This routine does the actual conversion of such DUPs, once outer routines
8055// have determined that everything else is in order.
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008056// It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
8057// similarly here.
Tim Northover3b0846e2014-05-24 12:50:23 +00008058static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00008059 switch (N.getOpcode()) {
8060 case AArch64ISD::DUP:
Tim Northover3b0846e2014-05-24 12:50:23 +00008061 case AArch64ISD::DUPLANE8:
8062 case AArch64ISD::DUPLANE16:
8063 case AArch64ISD::DUPLANE32:
8064 case AArch64ISD::DUPLANE64:
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008065 case AArch64ISD::MOVI:
8066 case AArch64ISD::MOVIshift:
8067 case AArch64ISD::MOVIedit:
8068 case AArch64ISD::MOVImsl:
8069 case AArch64ISD::MVNIshift:
8070 case AArch64ISD::MVNImsl:
Tim Northover3b0846e2014-05-24 12:50:23 +00008071 break;
8072 default:
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008073 // FMOV could be supported, but isn't very useful, as it would only occur
8074 // if you passed a bitcast' floating point immediate to an eligible long
8075 // integer op (addl, smull, ...).
Tim Northover3b0846e2014-05-24 12:50:23 +00008076 return SDValue();
8077 }
8078
8079 MVT NarrowTy = N.getSimpleValueType();
8080 if (!NarrowTy.is64BitVector())
8081 return SDValue();
8082
8083 MVT ElementTy = NarrowTy.getVectorElementType();
8084 unsigned NumElems = NarrowTy.getVectorNumElements();
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008085 MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
Tim Northover3b0846e2014-05-24 12:50:23 +00008086
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008087 SDLoc dl(N);
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008088 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
8089 DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008090 DAG.getConstant(NumElems, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008091}
8092
8093static bool isEssentiallyExtractSubvector(SDValue N) {
8094 if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
8095 return true;
8096
8097 return N.getOpcode() == ISD::BITCAST &&
8098 N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
8099}
8100
8101/// \brief Helper structure to keep track of ISD::SET_CC operands.
8102struct GenericSetCCInfo {
8103 const SDValue *Opnd0;
8104 const SDValue *Opnd1;
8105 ISD::CondCode CC;
8106};
8107
8108/// \brief Helper structure to keep track of a SET_CC lowered into AArch64 code.
8109struct AArch64SetCCInfo {
8110 const SDValue *Cmp;
8111 AArch64CC::CondCode CC;
8112};
8113
8114/// \brief Helper structure to keep track of SetCC information.
8115union SetCCInfo {
8116 GenericSetCCInfo Generic;
8117 AArch64SetCCInfo AArch64;
8118};
8119
8120/// \brief Helper structure to be able to read SetCC information. If set to
8121/// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
8122/// GenericSetCCInfo.
8123struct SetCCInfoAndKind {
8124 SetCCInfo Info;
8125 bool IsAArch64;
8126};
8127
8128/// \brief Check whether or not \p Op is a SET_CC operation, either a generic or
8129/// an
8130/// AArch64 lowered one.
8131/// \p SetCCInfo is filled accordingly.
8132/// \post SetCCInfo is meanginfull only when this function returns true.
8133/// \return True when Op is a kind of SET_CC operation.
8134static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
8135 // If this is a setcc, this is straight forward.
8136 if (Op.getOpcode() == ISD::SETCC) {
8137 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
8138 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
8139 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8140 SetCCInfo.IsAArch64 = false;
8141 return true;
8142 }
8143 // Otherwise, check if this is a matching csel instruction.
8144 // In other words:
8145 // - csel 1, 0, cc
8146 // - csel 0, 1, !cc
8147 if (Op.getOpcode() != AArch64ISD::CSEL)
8148 return false;
8149 // Set the information about the operands.
8150 // TODO: we want the operands of the Cmp not the csel
8151 SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
8152 SetCCInfo.IsAArch64 = true;
8153 SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
8154 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
8155
8156 // Check that the operands matches the constraints:
8157 // (1) Both operands must be constants.
8158 // (2) One must be 1 and the other must be 0.
8159 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
8160 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8161
8162 // Check (1).
8163 if (!TValue || !FValue)
8164 return false;
8165
8166 // Check (2).
8167 if (!TValue->isOne()) {
8168 // Update the comparison when we are interested in !cc.
8169 std::swap(TValue, FValue);
8170 SetCCInfo.Info.AArch64.CC =
8171 AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
8172 }
8173 return TValue->isOne() && FValue->isNullValue();
8174}
8175
8176// Returns true if Op is setcc or zext of setcc.
8177static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
8178 if (isSetCC(Op, Info))
8179 return true;
8180 return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
8181 isSetCC(Op->getOperand(0), Info));
8182}
8183
8184// The folding we want to perform is:
8185// (add x, [zext] (setcc cc ...) )
8186// -->
8187// (csel x, (add x, 1), !cc ...)
8188//
8189// The latter will get matched to a CSINC instruction.
8190static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
8191 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
8192 SDValue LHS = Op->getOperand(0);
8193 SDValue RHS = Op->getOperand(1);
8194 SetCCInfoAndKind InfoAndKind;
8195
8196 // If neither operand is a SET_CC, give up.
8197 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
8198 std::swap(LHS, RHS);
8199 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
8200 return SDValue();
8201 }
8202
8203 // FIXME: This could be generatized to work for FP comparisons.
8204 EVT CmpVT = InfoAndKind.IsAArch64
8205 ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
8206 : InfoAndKind.Info.Generic.Opnd0->getValueType();
8207 if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
8208 return SDValue();
8209
8210 SDValue CCVal;
8211 SDValue Cmp;
8212 SDLoc dl(Op);
8213 if (InfoAndKind.IsAArch64) {
8214 CCVal = DAG.getConstant(
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008215 AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
8216 MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00008217 Cmp = *InfoAndKind.Info.AArch64.Cmp;
8218 } else
8219 Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
8220 *InfoAndKind.Info.Generic.Opnd1,
8221 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
8222 CCVal, DAG, dl);
8223
8224 EVT VT = Op->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008225 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
Tim Northover3b0846e2014-05-24 12:50:23 +00008226 return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
8227}
8228
8229// The basic add/sub long vector instructions have variants with "2" on the end
8230// which act on the high-half of their inputs. They are normally matched by
8231// patterns like:
8232//
8233// (add (zeroext (extract_high LHS)),
8234// (zeroext (extract_high RHS)))
8235// -> uaddl2 vD, vN, vM
8236//
8237// However, if one of the extracts is something like a duplicate, this
8238// instruction can still be used profitably. This function puts the DAG into a
8239// more appropriate form for those patterns to trigger.
8240static SDValue performAddSubLongCombine(SDNode *N,
8241 TargetLowering::DAGCombinerInfo &DCI,
8242 SelectionDAG &DAG) {
8243 if (DCI.isBeforeLegalizeOps())
8244 return SDValue();
8245
8246 MVT VT = N->getSimpleValueType(0);
8247 if (!VT.is128BitVector()) {
8248 if (N->getOpcode() == ISD::ADD)
8249 return performSetccAddFolding(N, DAG);
8250 return SDValue();
8251 }
8252
8253 // Make sure both branches are extended in the same way.
8254 SDValue LHS = N->getOperand(0);
8255 SDValue RHS = N->getOperand(1);
8256 if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
8257 LHS.getOpcode() != ISD::SIGN_EXTEND) ||
8258 LHS.getOpcode() != RHS.getOpcode())
8259 return SDValue();
8260
8261 unsigned ExtType = LHS.getOpcode();
8262
8263 // It's not worth doing if at least one of the inputs isn't already an
8264 // extract, but we don't know which it'll be so we have to try both.
8265 if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
8266 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
8267 if (!RHS.getNode())
8268 return SDValue();
8269
8270 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
8271 } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
8272 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
8273 if (!LHS.getNode())
8274 return SDValue();
8275
8276 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
8277 }
8278
8279 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
8280}
8281
8282// Massage DAGs which we can use the high-half "long" operations on into
8283// something isel will recognize better. E.g.
8284//
8285// (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
8286// (aarch64_neon_umull (extract_high (v2i64 vec)))
8287// (extract_high (v2i64 (dup128 scalar)))))
8288//
Hal Finkelcd8664c2015-12-11 23:11:52 +00008289static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
Tim Northover3b0846e2014-05-24 12:50:23 +00008290 TargetLowering::DAGCombinerInfo &DCI,
8291 SelectionDAG &DAG) {
8292 if (DCI.isBeforeLegalizeOps())
8293 return SDValue();
8294
Hal Finkelcd8664c2015-12-11 23:11:52 +00008295 SDValue LHS = N->getOperand(1);
8296 SDValue RHS = N->getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00008297 assert(LHS.getValueType().is64BitVector() &&
8298 RHS.getValueType().is64BitVector() &&
8299 "unexpected shape for long operation");
8300
8301 // Either node could be a DUP, but it's not worth doing both of them (you'd
8302 // just as well use the non-high version) so look for a corresponding extract
8303 // operation on the other "wing".
8304 if (isEssentiallyExtractSubvector(LHS)) {
8305 RHS = tryExtendDUPToExtractHigh(RHS, DAG);
8306 if (!RHS.getNode())
8307 return SDValue();
8308 } else if (isEssentiallyExtractSubvector(RHS)) {
8309 LHS = tryExtendDUPToExtractHigh(LHS, DAG);
8310 if (!LHS.getNode())
8311 return SDValue();
8312 }
8313
Hal Finkelcd8664c2015-12-11 23:11:52 +00008314 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
8315 N->getOperand(0), LHS, RHS);
Tim Northover3b0846e2014-05-24 12:50:23 +00008316}
8317
8318static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
8319 MVT ElemTy = N->getSimpleValueType(0).getScalarType();
8320 unsigned ElemBits = ElemTy.getSizeInBits();
8321
8322 int64_t ShiftAmount;
8323 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
8324 APInt SplatValue, SplatUndef;
8325 unsigned SplatBitSize;
8326 bool HasAnyUndefs;
8327 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
8328 HasAnyUndefs, ElemBits) ||
8329 SplatBitSize != ElemBits)
8330 return SDValue();
8331
8332 ShiftAmount = SplatValue.getSExtValue();
8333 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
8334 ShiftAmount = CVN->getSExtValue();
8335 } else
8336 return SDValue();
8337
8338 unsigned Opcode;
8339 bool IsRightShift;
8340 switch (IID) {
8341 default:
8342 llvm_unreachable("Unknown shift intrinsic");
8343 case Intrinsic::aarch64_neon_sqshl:
8344 Opcode = AArch64ISD::SQSHL_I;
8345 IsRightShift = false;
8346 break;
8347 case Intrinsic::aarch64_neon_uqshl:
8348 Opcode = AArch64ISD::UQSHL_I;
8349 IsRightShift = false;
8350 break;
8351 case Intrinsic::aarch64_neon_srshl:
8352 Opcode = AArch64ISD::SRSHR_I;
8353 IsRightShift = true;
8354 break;
8355 case Intrinsic::aarch64_neon_urshl:
8356 Opcode = AArch64ISD::URSHR_I;
8357 IsRightShift = true;
8358 break;
8359 case Intrinsic::aarch64_neon_sqshlu:
8360 Opcode = AArch64ISD::SQSHLU_I;
8361 IsRightShift = false;
8362 break;
8363 }
8364
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008365 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
8366 SDLoc dl(N);
8367 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8368 DAG.getConstant(-ShiftAmount, dl, MVT::i32));
8369 } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
8370 SDLoc dl(N);
8371 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8372 DAG.getConstant(ShiftAmount, dl, MVT::i32));
8373 }
Tim Northover3b0846e2014-05-24 12:50:23 +00008374
8375 return SDValue();
8376}
8377
8378// The CRC32[BH] instructions ignore the high bits of their data operand. Since
8379// the intrinsics must be legal and take an i32, this means there's almost
8380// certainly going to be a zext in the DAG which we can eliminate.
8381static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
8382 SDValue AndN = N->getOperand(2);
8383 if (AndN.getOpcode() != ISD::AND)
8384 return SDValue();
8385
8386 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
8387 if (!CMask || CMask->getZExtValue() != Mask)
8388 return SDValue();
8389
8390 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
8391 N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
8392}
8393
Ahmed Bougachafab58922015-03-10 20:45:38 +00008394static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
8395 SelectionDAG &DAG) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008396 SDLoc dl(N);
8397 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
8398 DAG.getNode(Opc, dl,
Ahmed Bougachafab58922015-03-10 20:45:38 +00008399 N->getOperand(1).getSimpleValueType(),
8400 N->getOperand(1)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008401 DAG.getConstant(0, dl, MVT::i64));
Ahmed Bougachafab58922015-03-10 20:45:38 +00008402}
8403
Tim Northover3b0846e2014-05-24 12:50:23 +00008404static SDValue performIntrinsicCombine(SDNode *N,
8405 TargetLowering::DAGCombinerInfo &DCI,
8406 const AArch64Subtarget *Subtarget) {
8407 SelectionDAG &DAG = DCI.DAG;
8408 unsigned IID = getIntrinsicID(N);
8409 switch (IID) {
8410 default:
8411 break;
8412 case Intrinsic::aarch64_neon_vcvtfxs2fp:
8413 case Intrinsic::aarch64_neon_vcvtfxu2fp:
8414 return tryCombineFixedPointConvert(N, DCI, DAG);
Ahmed Bougachafab58922015-03-10 20:45:38 +00008415 case Intrinsic::aarch64_neon_saddv:
8416 return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
8417 case Intrinsic::aarch64_neon_uaddv:
8418 return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
8419 case Intrinsic::aarch64_neon_sminv:
8420 return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
8421 case Intrinsic::aarch64_neon_uminv:
8422 return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
8423 case Intrinsic::aarch64_neon_smaxv:
8424 return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
8425 case Intrinsic::aarch64_neon_umaxv:
8426 return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00008427 case Intrinsic::aarch64_neon_fmax:
James Molloyedf38f02015-08-11 12:06:33 +00008428 return DAG.getNode(ISD::FMAXNAN, SDLoc(N), N->getValueType(0),
Tim Northover3b0846e2014-05-24 12:50:23 +00008429 N->getOperand(1), N->getOperand(2));
8430 case Intrinsic::aarch64_neon_fmin:
James Molloyedf38f02015-08-11 12:06:33 +00008431 return DAG.getNode(ISD::FMINNAN, SDLoc(N), N->getValueType(0),
Tim Northover3b0846e2014-05-24 12:50:23 +00008432 N->getOperand(1), N->getOperand(2));
James Molloyb7b2a1e2015-08-11 12:06:37 +00008433 case Intrinsic::aarch64_neon_fmaxnm:
8434 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
8435 N->getOperand(1), N->getOperand(2));
8436 case Intrinsic::aarch64_neon_fminnm:
8437 return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
8438 N->getOperand(1), N->getOperand(2));
Tim Northover3b0846e2014-05-24 12:50:23 +00008439 case Intrinsic::aarch64_neon_smull:
8440 case Intrinsic::aarch64_neon_umull:
8441 case Intrinsic::aarch64_neon_pmull:
8442 case Intrinsic::aarch64_neon_sqdmull:
Hal Finkelcd8664c2015-12-11 23:11:52 +00008443 return tryCombineLongOpWithDup(IID, N, DCI, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00008444 case Intrinsic::aarch64_neon_sqshl:
8445 case Intrinsic::aarch64_neon_uqshl:
8446 case Intrinsic::aarch64_neon_sqshlu:
8447 case Intrinsic::aarch64_neon_srshl:
8448 case Intrinsic::aarch64_neon_urshl:
8449 return tryCombineShiftImm(IID, N, DAG);
8450 case Intrinsic::aarch64_crc32b:
8451 case Intrinsic::aarch64_crc32cb:
8452 return tryCombineCRC32(0xff, N, DAG);
8453 case Intrinsic::aarch64_crc32h:
8454 case Intrinsic::aarch64_crc32ch:
8455 return tryCombineCRC32(0xffff, N, DAG);
8456 }
8457 return SDValue();
8458}
8459
8460static SDValue performExtendCombine(SDNode *N,
8461 TargetLowering::DAGCombinerInfo &DCI,
8462 SelectionDAG &DAG) {
8463 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
8464 // we can convert that DUP into another extract_high (of a bigger DUP), which
8465 // helps the backend to decide that an sabdl2 would be useful, saving a real
8466 // extract_high operation.
8467 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
Hal Finkelcd8664c2015-12-11 23:11:52 +00008468 N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
Tim Northover3b0846e2014-05-24 12:50:23 +00008469 SDNode *ABDNode = N->getOperand(0).getNode();
Hal Finkelcd8664c2015-12-11 23:11:52 +00008470 unsigned IID = getIntrinsicID(ABDNode);
8471 if (IID == Intrinsic::aarch64_neon_sabd ||
8472 IID == Intrinsic::aarch64_neon_uabd) {
8473 SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
8474 if (!NewABD.getNode())
8475 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00008476
Hal Finkelcd8664c2015-12-11 23:11:52 +00008477 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
8478 NewABD);
8479 }
Tim Northover3b0846e2014-05-24 12:50:23 +00008480 }
8481
8482 // This is effectively a custom type legalization for AArch64.
8483 //
8484 // Type legalization will split an extend of a small, legal, type to a larger
8485 // illegal type by first splitting the destination type, often creating
8486 // illegal source types, which then get legalized in isel-confusing ways,
8487 // leading to really terrible codegen. E.g.,
8488 // %result = v8i32 sext v8i8 %value
8489 // becomes
8490 // %losrc = extract_subreg %value, ...
8491 // %hisrc = extract_subreg %value, ...
8492 // %lo = v4i32 sext v4i8 %losrc
8493 // %hi = v4i32 sext v4i8 %hisrc
8494 // Things go rapidly downhill from there.
8495 //
8496 // For AArch64, the [sz]ext vector instructions can only go up one element
8497 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
8498 // take two instructions.
8499 //
8500 // This implies that the most efficient way to do the extend from v8i8
8501 // to two v4i32 values is to first extend the v8i8 to v8i16, then do
8502 // the normal splitting to happen for the v8i16->v8i32.
8503
8504 // This is pre-legalization to catch some cases where the default
8505 // type legalization will create ill-tempered code.
8506 if (!DCI.isBeforeLegalizeOps())
8507 return SDValue();
8508
8509 // We're only interested in cleaning things up for non-legal vector types
8510 // here. If both the source and destination are legal, things will just
8511 // work naturally without any fiddling.
Matthew Simpson13dddb02015-12-17 21:29:47 +00008512 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00008513 EVT ResVT = N->getValueType(0);
8514 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
8515 return SDValue();
8516 // If the vector type isn't a simple VT, it's beyond the scope of what
8517 // we're worried about here. Let legalization do its thing and hope for
8518 // the best.
Jim Grosbachec2b0d02014-08-28 22:08:28 +00008519 SDValue Src = N->getOperand(0);
8520 EVT SrcVT = Src->getValueType(0);
8521 if (!ResVT.isSimple() || !SrcVT.isSimple())
Tim Northover3b0846e2014-05-24 12:50:23 +00008522 return SDValue();
8523
Tim Northover3b0846e2014-05-24 12:50:23 +00008524 // If the source VT is a 64-bit vector, we can play games and get the
8525 // better results we want.
8526 if (SrcVT.getSizeInBits() != 64)
8527 return SDValue();
8528
8529 unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits();
8530 unsigned ElementCount = SrcVT.getVectorNumElements();
8531 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
8532 SDLoc DL(N);
8533 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
8534
8535 // Now split the rest of the operation into two halves, each with a 64
8536 // bit source.
8537 EVT LoVT, HiVT;
8538 SDValue Lo, Hi;
8539 unsigned NumElements = ResVT.getVectorNumElements();
8540 assert(!(NumElements & 1) && "Splitting vector, but not in half!");
8541 LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
8542 ResVT.getVectorElementType(), NumElements / 2);
8543
8544 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
8545 LoVT.getVectorNumElements());
8546 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008547 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008548 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008549 DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008550 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
8551 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
8552
8553 // Now combine the parts back together so we still have a single result
8554 // like the combiner expects.
8555 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
8556}
8557
8558/// Replace a splat of a scalar to a vector store by scalar stores of the scalar
8559/// value. The load store optimizer pass will merge them to store pair stores.
8560/// This has better performance than a splat of the scalar followed by a split
8561/// vector store. Even if the stores are not merged it is four stores vs a dup,
8562/// followed by an ext.b and two stores.
8563static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode *St) {
8564 SDValue StVal = St->getValue();
8565 EVT VT = StVal.getValueType();
8566
8567 // Don't replace floating point stores, they possibly won't be transformed to
8568 // stp because of the store pair suppress pass.
8569 if (VT.isFloatingPoint())
8570 return SDValue();
8571
8572 // Check for insert vector elements.
8573 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
8574 return SDValue();
8575
8576 // We can express a splat as store pair(s) for 2 or 4 elements.
8577 unsigned NumVecElts = VT.getVectorNumElements();
8578 if (NumVecElts != 4 && NumVecElts != 2)
8579 return SDValue();
8580 SDValue SplatVal = StVal.getOperand(1);
8581 unsigned RemainInsertElts = NumVecElts - 1;
8582
8583 // Check that this is a splat.
8584 while (--RemainInsertElts) {
8585 SDValue NextInsertElt = StVal.getOperand(0);
8586 if (NextInsertElt.getOpcode() != ISD::INSERT_VECTOR_ELT)
8587 return SDValue();
8588 if (NextInsertElt.getOperand(1) != SplatVal)
8589 return SDValue();
8590 StVal = NextInsertElt;
8591 }
8592 unsigned OrigAlignment = St->getAlignment();
8593 unsigned EltOffset = NumVecElts == 4 ? 4 : 8;
8594 unsigned Alignment = std::min(OrigAlignment, EltOffset);
8595
8596 // Create scalar stores. This is at least as good as the code sequence for a
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00008597 // split unaligned store which is a dup.s, ext.b, and two stores.
Tim Northover3b0846e2014-05-24 12:50:23 +00008598 // Most of the time the three stores should be replaced by store pair
8599 // instructions (stp).
8600 SDLoc DL(St);
8601 SDValue BasePtr = St->getBasePtr();
8602 SDValue NewST1 =
8603 DAG.getStore(St->getChain(), DL, SplatVal, BasePtr, St->getPointerInfo(),
8604 St->isVolatile(), St->isNonTemporal(), St->getAlignment());
8605
8606 unsigned Offset = EltOffset;
8607 while (--NumVecElts) {
8608 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008609 DAG.getConstant(Offset, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008610 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
8611 St->getPointerInfo(), St->isVolatile(),
8612 St->isNonTemporal(), Alignment);
8613 Offset += EltOffset;
8614 }
8615 return NewST1;
8616}
8617
Tim Northover339c83e2015-11-10 00:44:23 +00008618static SDValue split16BStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
8619 SelectionDAG &DAG,
8620 const AArch64Subtarget *Subtarget) {
Tim Northover3b0846e2014-05-24 12:50:23 +00008621 if (!DCI.isBeforeLegalize())
8622 return SDValue();
8623
8624 StoreSDNode *S = cast<StoreSDNode>(N);
8625 if (S->isVolatile())
8626 return SDValue();
8627
Sanjay Patelbbbf9a12015-09-25 21:49:48 +00008628 // FIXME: The logic for deciding if an unaligned store should be split should
8629 // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
8630 // a call to that function here.
8631
Tim Northover3b0846e2014-05-24 12:50:23 +00008632 // Cyclone has bad performance on unaligned 16B stores when crossing line and
Sanjay Patel08efcd92015-01-28 22:37:32 +00008633 // page boundaries. We want to split such stores.
Tim Northover3b0846e2014-05-24 12:50:23 +00008634 if (!Subtarget->isCyclone())
8635 return SDValue();
8636
Sanjay Patel924879a2015-08-04 15:49:57 +00008637 // Don't split at -Oz.
8638 if (DAG.getMachineFunction().getFunction()->optForMinSize())
Tim Northover3b0846e2014-05-24 12:50:23 +00008639 return SDValue();
8640
8641 SDValue StVal = S->getValue();
8642 EVT VT = StVal.getValueType();
8643
8644 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
8645 // those up regresses performance on micro-benchmarks and olden/bh.
8646 if (!VT.isVector() || VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
8647 return SDValue();
8648
8649 // Split unaligned 16B stores. They are terrible for performance.
8650 // Don't split stores with alignment of 1 or 2. Code that uses clang vector
8651 // extensions can use this to mark that it does not want splitting to happen
8652 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
8653 // eliminating alignment hazards is only 1 in 8 for alignment of 2.
8654 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
8655 S->getAlignment() <= 2)
8656 return SDValue();
8657
8658 // If we get a splat of a scalar convert this vector store to a store of
8659 // scalars. They will be merged into store pairs thereby removing two
8660 // instructions.
Ahmed Bougacha239d6352015-08-04 00:48:02 +00008661 if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, S))
Tim Northover3b0846e2014-05-24 12:50:23 +00008662 return ReplacedSplat;
8663
8664 SDLoc DL(S);
8665 unsigned NumElts = VT.getVectorNumElements() / 2;
8666 // Split VT into two.
8667 EVT HalfVT =
8668 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
8669 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008670 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008671 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008672 DAG.getConstant(NumElts, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008673 SDValue BasePtr = S->getBasePtr();
8674 SDValue NewST1 =
8675 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
8676 S->isVolatile(), S->isNonTemporal(), S->getAlignment());
8677 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008678 DAG.getConstant(8, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008679 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
8680 S->getPointerInfo(), S->isVolatile(), S->isNonTemporal(),
8681 S->getAlignment());
8682}
8683
8684/// Target-specific DAG combine function for post-increment LD1 (lane) and
8685/// post-increment LD1R.
8686static SDValue performPostLD1Combine(SDNode *N,
8687 TargetLowering::DAGCombinerInfo &DCI,
8688 bool IsLaneOp) {
8689 if (DCI.isBeforeLegalizeOps())
8690 return SDValue();
8691
8692 SelectionDAG &DAG = DCI.DAG;
8693 EVT VT = N->getValueType(0);
8694
8695 unsigned LoadIdx = IsLaneOp ? 1 : 0;
8696 SDNode *LD = N->getOperand(LoadIdx).getNode();
8697 // If it is not LOAD, can not do such combine.
8698 if (LD->getOpcode() != ISD::LOAD)
8699 return SDValue();
8700
8701 LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
8702 EVT MemVT = LoadSDN->getMemoryVT();
8703 // Check if memory operand is the same type as the vector element.
8704 if (MemVT != VT.getVectorElementType())
8705 return SDValue();
8706
8707 // Check if there are other uses. If so, do not combine as it will introduce
8708 // an extra load.
8709 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
8710 ++UI) {
8711 if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
8712 continue;
8713 if (*UI != N)
8714 return SDValue();
8715 }
8716
8717 SDValue Addr = LD->getOperand(1);
8718 SDValue Vector = N->getOperand(0);
8719 // Search for a use of the address operand that is an increment.
8720 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
8721 Addr.getNode()->use_end(); UI != UE; ++UI) {
8722 SDNode *User = *UI;
8723 if (User->getOpcode() != ISD::ADD
8724 || UI.getUse().getResNo() != Addr.getResNo())
8725 continue;
8726
8727 // Check that the add is independent of the load. Otherwise, folding it
8728 // would create a cycle.
8729 if (User->isPredecessorOf(LD) || LD->isPredecessorOf(User))
8730 continue;
8731 // Also check that add is not used in the vector operand. This would also
8732 // create a cycle.
8733 if (User->isPredecessorOf(Vector.getNode()))
8734 continue;
8735
8736 // If the increment is a constant, it must match the memory ref size.
8737 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8738 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8739 uint32_t IncVal = CInc->getZExtValue();
8740 unsigned NumBytes = VT.getScalarSizeInBits() / 8;
8741 if (IncVal != NumBytes)
8742 continue;
8743 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
8744 }
8745
Ahmed Bougacha2448ef52015-04-17 21:02:30 +00008746 // Finally, check that the vector doesn't depend on the load.
8747 // Again, this would create a cycle.
8748 // The load depending on the vector is fine, as that's the case for the
8749 // LD1*post we'll eventually generate anyway.
8750 if (LoadSDN->isPredecessorOf(Vector.getNode()))
8751 continue;
8752
Tim Northover3b0846e2014-05-24 12:50:23 +00008753 SmallVector<SDValue, 8> Ops;
8754 Ops.push_back(LD->getOperand(0)); // Chain
8755 if (IsLaneOp) {
8756 Ops.push_back(Vector); // The vector to be inserted
8757 Ops.push_back(N->getOperand(2)); // The lane to be inserted in the vector
8758 }
8759 Ops.push_back(Addr);
8760 Ops.push_back(Inc);
8761
8762 EVT Tys[3] = { VT, MVT::i64, MVT::Other };
Craig Toppere1d12942014-08-27 05:25:25 +00008763 SDVTList SDTys = DAG.getVTList(Tys);
Tim Northover3b0846e2014-05-24 12:50:23 +00008764 unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
8765 SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
8766 MemVT,
8767 LoadSDN->getMemOperand());
8768
8769 // Update the uses.
Ahmed Bougacha4c2b0782015-02-19 23:13:10 +00008770 SmallVector<SDValue, 2> NewResults;
Tim Northover3b0846e2014-05-24 12:50:23 +00008771 NewResults.push_back(SDValue(LD, 0)); // The result of load
8772 NewResults.push_back(SDValue(UpdN.getNode(), 2)); // Chain
8773 DCI.CombineTo(LD, NewResults);
8774 DCI.CombineTo(N, SDValue(UpdN.getNode(), 0)); // Dup/Inserted Result
8775 DCI.CombineTo(User, SDValue(UpdN.getNode(), 1)); // Write back register
8776
8777 break;
8778 }
8779 return SDValue();
8780}
8781
Tim Northover339c83e2015-11-10 00:44:23 +00008782/// Simplify \Addr given that the top byte of it is ignored by HW during
8783/// address translation.
8784static bool performTBISimplification(SDValue Addr,
8785 TargetLowering::DAGCombinerInfo &DCI,
8786 SelectionDAG &DAG) {
8787 APInt DemandedMask = APInt::getLowBitsSet(64, 56);
8788 APInt KnownZero, KnownOne;
8789 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
8790 DCI.isBeforeLegalizeOps());
8791 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8792 if (TLI.SimplifyDemandedBits(Addr, DemandedMask, KnownZero, KnownOne, TLO)) {
8793 DCI.CommitTargetLoweringOpt(TLO);
8794 return true;
8795 }
8796 return false;
8797}
8798
8799static SDValue performSTORECombine(SDNode *N,
8800 TargetLowering::DAGCombinerInfo &DCI,
8801 SelectionDAG &DAG,
8802 const AArch64Subtarget *Subtarget) {
8803 SDValue Split = split16BStores(N, DCI, DAG, Subtarget);
8804 if (Split.getNode())
8805 return Split;
8806
8807 if (Subtarget->supportsAddressTopByteIgnored() &&
8808 performTBISimplification(N->getOperand(2), DCI, DAG))
8809 return SDValue(N, 0);
8810
8811 return SDValue();
8812}
8813
8814 /// This function handles the log2-shuffle pattern produced by the
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008815/// LoopVectorizer for the across vector reduction. It consists of
8816/// log2(NumVectorElements) steps and, in each step, 2^(s) elements
8817/// are reduced, where s is an induction variable from 0 to
8818/// log2(NumVectorElements).
8819static SDValue tryMatchAcrossLaneShuffleForReduction(SDNode *N, SDValue OpV,
8820 unsigned Op,
8821 SelectionDAG &DAG) {
8822 EVT VTy = OpV->getOperand(0).getValueType();
8823 if (!VTy.isVector())
Chad Rosier6c36eff2015-09-03 18:13:57 +00008824 return SDValue();
8825
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008826 int NumVecElts = VTy.getVectorNumElements();
Jun Bum Lim0aace132015-10-09 14:11:25 +00008827 if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) {
8828 if (NumVecElts != 4)
8829 return SDValue();
8830 } else {
8831 if (NumVecElts != 4 && NumVecElts != 8 && NumVecElts != 16)
8832 return SDValue();
8833 }
Chad Rosier6c36eff2015-09-03 18:13:57 +00008834
8835 int NumExpectedSteps = APInt(8, NumVecElts).logBase2();
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008836 SDValue PreOp = OpV;
Chad Rosier6c36eff2015-09-03 18:13:57 +00008837 // Iterate over each step of the across vector reduction.
8838 for (int CurStep = 0; CurStep != NumExpectedSteps; ++CurStep) {
Chad Rosier6c36eff2015-09-03 18:13:57 +00008839 SDValue CurOp = PreOp.getOperand(0);
8840 SDValue Shuffle = PreOp.getOperand(1);
8841 if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE) {
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008842 // Try to swap the 1st and 2nd operand as add and min/max instructions
8843 // are commutative.
Chad Rosier6c36eff2015-09-03 18:13:57 +00008844 CurOp = PreOp.getOperand(1);
8845 Shuffle = PreOp.getOperand(0);
8846 if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE)
8847 return SDValue();
8848 }
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008849
8850 // Check if the input vector is fed by the operator we want to handle,
8851 // except the last step; the very first input vector is not necessarily
8852 // the same operator we are handling.
8853 if (CurOp.getOpcode() != Op && (CurStep != (NumExpectedSteps - 1)))
8854 return SDValue();
8855
Chad Rosier6c36eff2015-09-03 18:13:57 +00008856 // Check if it forms one step of the across vector reduction.
8857 // E.g.,
8858 // %cur = add %1, %0
8859 // %shuffle = vector_shuffle %cur, <2, 3, u, u>
8860 // %pre = add %cur, %shuffle
8861 if (Shuffle.getOperand(0) != CurOp)
8862 return SDValue();
8863
8864 int NumMaskElts = 1 << CurStep;
8865 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Shuffle)->getMask();
8866 // Check mask values in each step.
8867 // We expect the shuffle mask in each step follows a specific pattern
8868 // denoted here by the <M, U> form, where M is a sequence of integers
8869 // starting from NumMaskElts, increasing by 1, and the number integers
8870 // in M should be NumMaskElts. U is a sequence of UNDEFs and the number
8871 // of undef in U should be NumVecElts - NumMaskElts.
8872 // E.g., for <8 x i16>, mask values in each step should be :
8873 // step 0 : <1,u,u,u,u,u,u,u>
8874 // step 1 : <2,3,u,u,u,u,u,u>
8875 // step 2 : <4,5,6,7,u,u,u,u>
8876 for (int i = 0; i < NumVecElts; ++i)
8877 if ((i < NumMaskElts && Mask[i] != (NumMaskElts + i)) ||
8878 (i >= NumMaskElts && !(Mask[i] < 0)))
8879 return SDValue();
8880
8881 PreOp = CurOp;
8882 }
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008883 unsigned Opcode;
Jun Bum Lim0aace132015-10-09 14:11:25 +00008884 bool IsIntrinsic = false;
8885
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008886 switch (Op) {
8887 default:
8888 llvm_unreachable("Unexpected operator for across vector reduction");
8889 case ISD::ADD:
8890 Opcode = AArch64ISD::UADDV;
8891 break;
8892 case ISD::SMAX:
8893 Opcode = AArch64ISD::SMAXV;
8894 break;
8895 case ISD::UMAX:
8896 Opcode = AArch64ISD::UMAXV;
8897 break;
8898 case ISD::SMIN:
8899 Opcode = AArch64ISD::SMINV;
8900 break;
8901 case ISD::UMIN:
8902 Opcode = AArch64ISD::UMINV;
8903 break;
Jun Bum Lim0aace132015-10-09 14:11:25 +00008904 case ISD::FMAXNUM:
8905 Opcode = Intrinsic::aarch64_neon_fmaxnmv;
8906 IsIntrinsic = true;
8907 break;
8908 case ISD::FMINNUM:
8909 Opcode = Intrinsic::aarch64_neon_fminnmv;
8910 IsIntrinsic = true;
8911 break;
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008912 }
Chad Rosier6c36eff2015-09-03 18:13:57 +00008913 SDLoc DL(N);
Jun Bum Lim0aace132015-10-09 14:11:25 +00008914
8915 return IsIntrinsic
8916 ? DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, N->getValueType(0),
8917 DAG.getConstant(Opcode, DL, MVT::i32), PreOp)
8918 : DAG.getNode(
8919 ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0),
8920 DAG.getNode(Opcode, DL, PreOp.getSimpleValueType(), PreOp),
8921 DAG.getConstant(0, DL, MVT::i64));
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008922}
8923
8924/// Target-specific DAG combine for the across vector min/max reductions.
8925/// This function specifically handles the final clean-up step of the vector
8926/// min/max reductions produced by the LoopVectorizer. It is the log2-shuffle
8927/// pattern, which narrows down and finds the final min/max value from all
8928/// elements of the vector.
8929/// For example, for a <16 x i8> vector :
8930/// svn0 = vector_shuffle %0, undef<8,9,10,11,12,13,14,15,u,u,u,u,u,u,u,u>
8931/// %smax0 = smax %arr, svn0
8932/// %svn1 = vector_shuffle %smax0, undef<4,5,6,7,u,u,u,u,u,u,u,u,u,u,u,u>
8933/// %smax1 = smax %smax0, %svn1
8934/// %svn2 = vector_shuffle %smax1, undef<2,3,u,u,u,u,u,u,u,u,u,u,u,u,u,u>
8935/// %smax2 = smax %smax1, svn2
8936/// %svn3 = vector_shuffle %smax2, undef<1,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u>
8937/// %sc = setcc %smax2, %svn3, gt
8938/// %n0 = extract_vector_elt %sc, #0
8939/// %n1 = extract_vector_elt %smax2, #0
8940/// %n2 = extract_vector_elt $smax2, #1
8941/// %result = select %n0, %n1, n2
8942/// becomes :
8943/// %1 = smaxv %0
8944/// %result = extract_vector_elt %1, 0
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008945static SDValue
8946performAcrossLaneMinMaxReductionCombine(SDNode *N, SelectionDAG &DAG,
8947 const AArch64Subtarget *Subtarget) {
8948 if (!Subtarget->hasNEON())
8949 return SDValue();
8950
8951 SDValue N0 = N->getOperand(0);
8952 SDValue IfTrue = N->getOperand(1);
8953 SDValue IfFalse = N->getOperand(2);
8954
8955 // Check if the SELECT merges up the final result of the min/max
8956 // from a vector.
8957 if (N0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
8958 IfTrue.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
8959 IfFalse.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8960 return SDValue();
8961
8962 // Expect N0 is fed by SETCC.
8963 SDValue SetCC = N0.getOperand(0);
8964 EVT SetCCVT = SetCC.getValueType();
8965 if (SetCC.getOpcode() != ISD::SETCC || !SetCCVT.isVector() ||
8966 SetCCVT.getVectorElementType() != MVT::i1)
8967 return SDValue();
8968
8969 SDValue VectorOp = SetCC.getOperand(0);
8970 unsigned Op = VectorOp->getOpcode();
8971 // Check if the input vector is fed by the operator we want to handle.
Jun Bum Lim0aace132015-10-09 14:11:25 +00008972 if (Op != ISD::SMAX && Op != ISD::UMAX && Op != ISD::SMIN &&
8973 Op != ISD::UMIN && Op != ISD::FMAXNUM && Op != ISD::FMINNUM)
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008974 return SDValue();
8975
8976 EVT VTy = VectorOp.getValueType();
8977 if (!VTy.isVector())
8978 return SDValue();
8979
Jun Bum Lim0aace132015-10-09 14:11:25 +00008980 if (VTy.getSizeInBits() < 64)
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008981 return SDValue();
8982
Jun Bum Lim0aace132015-10-09 14:11:25 +00008983 EVT EltTy = VTy.getVectorElementType();
8984 if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) {
8985 if (EltTy != MVT::f32)
8986 return SDValue();
8987 } else {
8988 if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8)
8989 return SDValue();
8990 }
8991
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008992 // Check if extracting from the same vector.
8993 // For example,
8994 // %sc = setcc %vector, %svn1, gt
8995 // %n0 = extract_vector_elt %sc, #0
8996 // %n1 = extract_vector_elt %vector, #0
8997 // %n2 = extract_vector_elt $vector, #1
8998 if (!(VectorOp == IfTrue->getOperand(0) &&
8999 VectorOp == IfFalse->getOperand(0)))
9000 return SDValue();
9001
9002 // Check if the condition code is matched with the operator type.
9003 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get();
9004 if ((Op == ISD::SMAX && CC != ISD::SETGT && CC != ISD::SETGE) ||
9005 (Op == ISD::UMAX && CC != ISD::SETUGT && CC != ISD::SETUGE) ||
9006 (Op == ISD::SMIN && CC != ISD::SETLT && CC != ISD::SETLE) ||
Jun Bum Lim0aace132015-10-09 14:11:25 +00009007 (Op == ISD::UMIN && CC != ISD::SETULT && CC != ISD::SETULE) ||
9008 (Op == ISD::FMAXNUM && CC != ISD::SETOGT && CC != ISD::SETOGE &&
9009 CC != ISD::SETUGT && CC != ISD::SETUGE && CC != ISD::SETGT &&
9010 CC != ISD::SETGE) ||
9011 (Op == ISD::FMINNUM && CC != ISD::SETOLT && CC != ISD::SETOLE &&
9012 CC != ISD::SETULT && CC != ISD::SETULE && CC != ISD::SETLT &&
9013 CC != ISD::SETLE))
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009014 return SDValue();
9015
9016 // Expect to check only lane 0 from the vector SETCC.
Artyom Skrobov314ee042015-11-25 19:41:11 +00009017 if (!isNullConstant(N0.getOperand(1)))
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009018 return SDValue();
9019
9020 // Expect to extract the true value from lane 0.
Artyom Skrobov314ee042015-11-25 19:41:11 +00009021 if (!isNullConstant(IfTrue.getOperand(1)))
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009022 return SDValue();
9023
9024 // Expect to extract the false value from lane 1.
Artyom Skrobov314ee042015-11-25 19:41:11 +00009025 if (!isOneConstant(IfFalse.getOperand(1)))
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009026 return SDValue();
9027
9028 return tryMatchAcrossLaneShuffleForReduction(N, SetCC, Op, DAG);
9029}
9030
9031/// Target-specific DAG combine for the across vector add reduction.
9032/// This function specifically handles the final clean-up step of the vector
9033/// add reduction produced by the LoopVectorizer. It is the log2-shuffle
9034/// pattern, which adds all elements of a vector together.
9035/// For example, for a <4 x i32> vector :
9036/// %1 = vector_shuffle %0, <2,3,u,u>
9037/// %2 = add %0, %1
9038/// %3 = vector_shuffle %2, <1,u,u,u>
9039/// %4 = add %2, %3
9040/// %result = extract_vector_elt %4, 0
9041/// becomes :
9042/// %0 = uaddv %0
9043/// %result = extract_vector_elt %0, 0
9044static SDValue
9045performAcrossLaneAddReductionCombine(SDNode *N, SelectionDAG &DAG,
9046 const AArch64Subtarget *Subtarget) {
9047 if (!Subtarget->hasNEON())
9048 return SDValue();
9049 SDValue N0 = N->getOperand(0);
9050 SDValue N1 = N->getOperand(1);
9051
9052 // Check if the input vector is fed by the ADD.
9053 if (N0->getOpcode() != ISD::ADD)
9054 return SDValue();
9055
9056 // The vector extract idx must constant zero because we only expect the final
9057 // result of the reduction is placed in lane 0.
Artyom Skrobov314ee042015-11-25 19:41:11 +00009058 if (!isNullConstant(N1))
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009059 return SDValue();
9060
9061 EVT VTy = N0.getValueType();
9062 if (!VTy.isVector())
9063 return SDValue();
9064
9065 EVT EltTy = VTy.getVectorElementType();
9066 if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8)
9067 return SDValue();
9068
Jun Bum Lim0aace132015-10-09 14:11:25 +00009069 if (VTy.getSizeInBits() < 64)
9070 return SDValue();
9071
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009072 return tryMatchAcrossLaneShuffleForReduction(N, N0, ISD::ADD, DAG);
Chad Rosier6c36eff2015-09-03 18:13:57 +00009073}
9074
Tim Northover3b0846e2014-05-24 12:50:23 +00009075/// Target-specific DAG combine function for NEON load/store intrinsics
9076/// to merge base address updates.
9077static SDValue performNEONPostLDSTCombine(SDNode *N,
9078 TargetLowering::DAGCombinerInfo &DCI,
9079 SelectionDAG &DAG) {
9080 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9081 return SDValue();
9082
9083 unsigned AddrOpIdx = N->getNumOperands() - 1;
9084 SDValue Addr = N->getOperand(AddrOpIdx);
9085
9086 // Search for a use of the address operand that is an increment.
9087 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9088 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9089 SDNode *User = *UI;
9090 if (User->getOpcode() != ISD::ADD ||
9091 UI.getUse().getResNo() != Addr.getResNo())
9092 continue;
9093
9094 // Check that the add is independent of the load/store. Otherwise, folding
9095 // it would create a cycle.
9096 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9097 continue;
9098
9099 // Find the new opcode for the updating load/store.
9100 bool IsStore = false;
9101 bool IsLaneOp = false;
9102 bool IsDupOp = false;
9103 unsigned NewOpc = 0;
9104 unsigned NumVecs = 0;
9105 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9106 switch (IntNo) {
9107 default: llvm_unreachable("unexpected intrinsic for Neon base update");
9108 case Intrinsic::aarch64_neon_ld2: NewOpc = AArch64ISD::LD2post;
9109 NumVecs = 2; break;
9110 case Intrinsic::aarch64_neon_ld3: NewOpc = AArch64ISD::LD3post;
9111 NumVecs = 3; break;
9112 case Intrinsic::aarch64_neon_ld4: NewOpc = AArch64ISD::LD4post;
9113 NumVecs = 4; break;
9114 case Intrinsic::aarch64_neon_st2: NewOpc = AArch64ISD::ST2post;
9115 NumVecs = 2; IsStore = true; break;
9116 case Intrinsic::aarch64_neon_st3: NewOpc = AArch64ISD::ST3post;
9117 NumVecs = 3; IsStore = true; break;
9118 case Intrinsic::aarch64_neon_st4: NewOpc = AArch64ISD::ST4post;
9119 NumVecs = 4; IsStore = true; break;
9120 case Intrinsic::aarch64_neon_ld1x2: NewOpc = AArch64ISD::LD1x2post;
9121 NumVecs = 2; break;
9122 case Intrinsic::aarch64_neon_ld1x3: NewOpc = AArch64ISD::LD1x3post;
9123 NumVecs = 3; break;
9124 case Intrinsic::aarch64_neon_ld1x4: NewOpc = AArch64ISD::LD1x4post;
9125 NumVecs = 4; break;
9126 case Intrinsic::aarch64_neon_st1x2: NewOpc = AArch64ISD::ST1x2post;
9127 NumVecs = 2; IsStore = true; break;
9128 case Intrinsic::aarch64_neon_st1x3: NewOpc = AArch64ISD::ST1x3post;
9129 NumVecs = 3; IsStore = true; break;
9130 case Intrinsic::aarch64_neon_st1x4: NewOpc = AArch64ISD::ST1x4post;
9131 NumVecs = 4; IsStore = true; break;
9132 case Intrinsic::aarch64_neon_ld2r: NewOpc = AArch64ISD::LD2DUPpost;
9133 NumVecs = 2; IsDupOp = true; break;
9134 case Intrinsic::aarch64_neon_ld3r: NewOpc = AArch64ISD::LD3DUPpost;
9135 NumVecs = 3; IsDupOp = true; break;
9136 case Intrinsic::aarch64_neon_ld4r: NewOpc = AArch64ISD::LD4DUPpost;
9137 NumVecs = 4; IsDupOp = true; break;
9138 case Intrinsic::aarch64_neon_ld2lane: NewOpc = AArch64ISD::LD2LANEpost;
9139 NumVecs = 2; IsLaneOp = true; break;
9140 case Intrinsic::aarch64_neon_ld3lane: NewOpc = AArch64ISD::LD3LANEpost;
9141 NumVecs = 3; IsLaneOp = true; break;
9142 case Intrinsic::aarch64_neon_ld4lane: NewOpc = AArch64ISD::LD4LANEpost;
9143 NumVecs = 4; IsLaneOp = true; break;
9144 case Intrinsic::aarch64_neon_st2lane: NewOpc = AArch64ISD::ST2LANEpost;
9145 NumVecs = 2; IsStore = true; IsLaneOp = true; break;
9146 case Intrinsic::aarch64_neon_st3lane: NewOpc = AArch64ISD::ST3LANEpost;
9147 NumVecs = 3; IsStore = true; IsLaneOp = true; break;
9148 case Intrinsic::aarch64_neon_st4lane: NewOpc = AArch64ISD::ST4LANEpost;
9149 NumVecs = 4; IsStore = true; IsLaneOp = true; break;
9150 }
9151
9152 EVT VecTy;
9153 if (IsStore)
9154 VecTy = N->getOperand(2).getValueType();
9155 else
9156 VecTy = N->getValueType(0);
9157
9158 // If the increment is a constant, it must match the memory ref size.
9159 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9160 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9161 uint32_t IncVal = CInc->getZExtValue();
9162 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9163 if (IsLaneOp || IsDupOp)
9164 NumBytes /= VecTy.getVectorNumElements();
9165 if (IncVal != NumBytes)
9166 continue;
9167 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
9168 }
9169 SmallVector<SDValue, 8> Ops;
9170 Ops.push_back(N->getOperand(0)); // Incoming chain
9171 // Load lane and store have vector list as input.
9172 if (IsLaneOp || IsStore)
9173 for (unsigned i = 2; i < AddrOpIdx; ++i)
9174 Ops.push_back(N->getOperand(i));
9175 Ops.push_back(Addr); // Base register
9176 Ops.push_back(Inc);
9177
9178 // Return Types.
9179 EVT Tys[6];
9180 unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
9181 unsigned n;
9182 for (n = 0; n < NumResultVecs; ++n)
9183 Tys[n] = VecTy;
9184 Tys[n++] = MVT::i64; // Type of write back register
9185 Tys[n] = MVT::Other; // Type of the chain
Craig Toppere1d12942014-08-27 05:25:25 +00009186 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
Tim Northover3b0846e2014-05-24 12:50:23 +00009187
9188 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9189 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
9190 MemInt->getMemoryVT(),
9191 MemInt->getMemOperand());
9192
9193 // Update the uses.
9194 std::vector<SDValue> NewResults;
9195 for (unsigned i = 0; i < NumResultVecs; ++i) {
9196 NewResults.push_back(SDValue(UpdN.getNode(), i));
9197 }
9198 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
9199 DCI.CombineTo(N, NewResults);
9200 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9201
9202 break;
9203 }
9204 return SDValue();
9205}
9206
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009207// Checks to see if the value is the prescribed width and returns information
9208// about its extension mode.
9209static
9210bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
9211 ExtType = ISD::NON_EXTLOAD;
9212 switch(V.getNode()->getOpcode()) {
9213 default:
9214 return false;
9215 case ISD::LOAD: {
9216 LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
9217 if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
9218 || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
9219 ExtType = LoadNode->getExtensionType();
9220 return true;
9221 }
9222 return false;
9223 }
9224 case ISD::AssertSext: {
9225 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9226 if ((TypeNode->getVT() == MVT::i8 && width == 8)
9227 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9228 ExtType = ISD::SEXTLOAD;
9229 return true;
9230 }
9231 return false;
9232 }
9233 case ISD::AssertZext: {
9234 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9235 if ((TypeNode->getVT() == MVT::i8 && width == 8)
9236 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9237 ExtType = ISD::ZEXTLOAD;
9238 return true;
9239 }
9240 return false;
9241 }
9242 case ISD::Constant:
9243 case ISD::TargetConstant: {
Reid Kleckner39ad7c92014-08-29 22:14:26 +00009244 if (std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
Aaron Ballman8ca53882014-09-02 12:19:02 +00009245 1LL << (width - 1))
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009246 return true;
9247 return false;
9248 }
9249 }
9250
9251 return true;
9252}
9253
9254// This function does a whole lot of voodoo to determine if the tests are
9255// equivalent without and with a mask. Essentially what happens is that given a
9256// DAG resembling:
9257//
9258// +-------------+ +-------------+ +-------------+ +-------------+
9259// | Input | | AddConstant | | CompConstant| | CC |
9260// +-------------+ +-------------+ +-------------+ +-------------+
9261// | | | |
9262// V V | +----------+
9263// +-------------+ +----+ | |
9264// | ADD | |0xff| | |
9265// +-------------+ +----+ | |
9266// | | | |
9267// V V | |
9268// +-------------+ | |
9269// | AND | | |
9270// +-------------+ | |
9271// | | |
9272// +-----+ | |
9273// | | |
9274// V V V
9275// +-------------+
9276// | CMP |
9277// +-------------+
9278//
9279// The AND node may be safely removed for some combinations of inputs. In
9280// particular we need to take into account the extension type of the Input,
9281// the exact values of AddConstant, CompConstant, and CC, along with the nominal
9282// width of the input (this can work for any width inputs, the above graph is
9283// specific to 8 bits.
9284//
9285// The specific equations were worked out by generating output tables for each
9286// AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
9287// problem was simplified by working with 4 bit inputs, which means we only
9288// needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
9289// extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
9290// patterns present in both extensions (0,7). For every distinct set of
9291// AddConstant and CompConstants bit patterns we can consider the masked and
9292// unmasked versions to be equivalent if the result of this function is true for
9293// all 16 distinct bit patterns of for the current extension type of Input (w0).
9294//
9295// sub w8, w0, w1
9296// and w10, w8, #0x0f
9297// cmp w8, w2
9298// cset w9, AArch64CC
9299// cmp w10, w2
9300// cset w11, AArch64CC
9301// cmp w9, w11
9302// cset w0, eq
9303// ret
9304//
9305// Since the above function shows when the outputs are equivalent it defines
9306// when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
9307// would be expensive to run during compiles. The equations below were written
9308// in a test harness that confirmed they gave equivalent outputs to the above
9309// for all inputs function, so they can be used determine if the removal is
9310// legal instead.
9311//
9312// isEquivalentMaskless() is the code for testing if the AND can be removed
9313// factored out of the DAG recognition as the DAG can take several forms.
9314
9315static
9316bool isEquivalentMaskless(unsigned CC, unsigned width,
9317 ISD::LoadExtType ExtType, signed AddConstant,
9318 signed CompConstant) {
9319 // By being careful about our equations and only writing the in term
9320 // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
9321 // make them generally applicable to all bit widths.
9322 signed MaxUInt = (1 << width);
9323
9324 // For the purposes of these comparisons sign extending the type is
9325 // equivalent to zero extending the add and displacing it by half the integer
9326 // width. Provided we are careful and make sure our equations are valid over
9327 // the whole range we can just adjust the input and avoid writing equations
9328 // for sign extended inputs.
9329 if (ExtType == ISD::SEXTLOAD)
9330 AddConstant -= (1 << (width-1));
9331
9332 switch(CC) {
9333 case AArch64CC::LE:
9334 case AArch64CC::GT: {
9335 if ((AddConstant == 0) ||
9336 (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
9337 (AddConstant >= 0 && CompConstant < 0) ||
9338 (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
9339 return true;
9340 } break;
9341 case AArch64CC::LT:
9342 case AArch64CC::GE: {
9343 if ((AddConstant == 0) ||
9344 (AddConstant >= 0 && CompConstant <= 0) ||
9345 (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
9346 return true;
9347 } break;
9348 case AArch64CC::HI:
9349 case AArch64CC::LS: {
9350 if ((AddConstant >= 0 && CompConstant < 0) ||
9351 (AddConstant <= 0 && CompConstant >= -1 &&
9352 CompConstant < AddConstant + MaxUInt))
9353 return true;
9354 } break;
9355 case AArch64CC::PL:
9356 case AArch64CC::MI: {
9357 if ((AddConstant == 0) ||
9358 (AddConstant > 0 && CompConstant <= 0) ||
9359 (AddConstant < 0 && CompConstant <= AddConstant))
9360 return true;
9361 } break;
9362 case AArch64CC::LO:
9363 case AArch64CC::HS: {
9364 if ((AddConstant >= 0 && CompConstant <= 0) ||
9365 (AddConstant <= 0 && CompConstant >= 0 &&
9366 CompConstant <= AddConstant + MaxUInt))
9367 return true;
9368 } break;
9369 case AArch64CC::EQ:
9370 case AArch64CC::NE: {
9371 if ((AddConstant > 0 && CompConstant < 0) ||
9372 (AddConstant < 0 && CompConstant >= 0 &&
9373 CompConstant < AddConstant + MaxUInt) ||
9374 (AddConstant >= 0 && CompConstant >= 0 &&
9375 CompConstant >= AddConstant) ||
9376 (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
9377
9378 return true;
9379 } break;
9380 case AArch64CC::VS:
9381 case AArch64CC::VC:
9382 case AArch64CC::AL:
9383 case AArch64CC::NV:
9384 return true;
9385 case AArch64CC::Invalid:
9386 break;
9387 }
9388
9389 return false;
9390}
9391
9392static
9393SDValue performCONDCombine(SDNode *N,
9394 TargetLowering::DAGCombinerInfo &DCI,
9395 SelectionDAG &DAG, unsigned CCIndex,
9396 unsigned CmpIndex) {
9397 unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
9398 SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
9399 unsigned CondOpcode = SubsNode->getOpcode();
9400
9401 if (CondOpcode != AArch64ISD::SUBS)
9402 return SDValue();
9403
9404 // There is a SUBS feeding this condition. Is it fed by a mask we can
9405 // use?
9406
9407 SDNode *AndNode = SubsNode->getOperand(0).getNode();
9408 unsigned MaskBits = 0;
9409
9410 if (AndNode->getOpcode() != ISD::AND)
9411 return SDValue();
9412
9413 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
9414 uint32_t CNV = CN->getZExtValue();
9415 if (CNV == 255)
9416 MaskBits = 8;
9417 else if (CNV == 65535)
9418 MaskBits = 16;
9419 }
9420
9421 if (!MaskBits)
9422 return SDValue();
9423
9424 SDValue AddValue = AndNode->getOperand(0);
9425
9426 if (AddValue.getOpcode() != ISD::ADD)
9427 return SDValue();
9428
9429 // The basic dag structure is correct, grab the inputs and validate them.
9430
9431 SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
9432 SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
9433 SDValue SubsInputValue = SubsNode->getOperand(1);
9434
9435 // The mask is present and the provenance of all the values is a smaller type,
9436 // lets see if the mask is superfluous.
9437
9438 if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
9439 !isa<ConstantSDNode>(SubsInputValue.getNode()))
9440 return SDValue();
9441
9442 ISD::LoadExtType ExtType;
9443
9444 if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
9445 !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
9446 !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
9447 return SDValue();
9448
9449 if(!isEquivalentMaskless(CC, MaskBits, ExtType,
9450 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
9451 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
9452 return SDValue();
9453
9454 // The AND is not necessary, remove it.
9455
9456 SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
9457 SubsNode->getValueType(1));
9458 SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
9459
9460 SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
9461 DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
9462
9463 return SDValue(N, 0);
9464}
9465
Tim Northover3b0846e2014-05-24 12:50:23 +00009466// Optimize compare with zero and branch.
9467static SDValue performBRCONDCombine(SDNode *N,
9468 TargetLowering::DAGCombinerInfo &DCI,
9469 SelectionDAG &DAG) {
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009470 SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3);
9471 if (NV.getNode())
9472 N = NV.getNode();
Tim Northover3b0846e2014-05-24 12:50:23 +00009473 SDValue Chain = N->getOperand(0);
9474 SDValue Dest = N->getOperand(1);
9475 SDValue CCVal = N->getOperand(2);
9476 SDValue Cmp = N->getOperand(3);
9477
9478 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
9479 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
9480 if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
9481 return SDValue();
9482
9483 unsigned CmpOpc = Cmp.getOpcode();
9484 if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
9485 return SDValue();
9486
9487 // Only attempt folding if there is only one use of the flag and no use of the
9488 // value.
9489 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
9490 return SDValue();
9491
9492 SDValue LHS = Cmp.getOperand(0);
9493 SDValue RHS = Cmp.getOperand(1);
9494
9495 assert(LHS.getValueType() == RHS.getValueType() &&
9496 "Expected the value type to be the same for both operands!");
9497 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
9498 return SDValue();
9499
Artyom Skrobov314ee042015-11-25 19:41:11 +00009500 if (isNullConstant(LHS))
Tim Northover3b0846e2014-05-24 12:50:23 +00009501 std::swap(LHS, RHS);
9502
Artyom Skrobov314ee042015-11-25 19:41:11 +00009503 if (!isNullConstant(RHS))
Tim Northover3b0846e2014-05-24 12:50:23 +00009504 return SDValue();
9505
9506 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
9507 LHS.getOpcode() == ISD::SRL)
9508 return SDValue();
9509
9510 // Fold the compare into the branch instruction.
9511 SDValue BR;
9512 if (CC == AArch64CC::EQ)
9513 BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9514 else
9515 BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9516
9517 // Do not add new nodes to DAG combiner worklist.
9518 DCI.CombineTo(N, BR, false);
9519
9520 return SDValue();
9521}
9522
Geoff Berry9e934b02016-01-04 18:55:47 +00009523// Optimize some simple tbz/tbnz cases. Returns the new operand and bit to test
9524// as well as whether the test should be inverted. This code is required to
9525// catch these cases (as opposed to standard dag combines) because
9526// AArch64ISD::TBZ is matched during legalization.
9527static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert,
9528 SelectionDAG &DAG) {
9529
9530 if (!Op->hasOneUse())
9531 return Op;
9532
9533 // We don't handle undef/constant-fold cases below, as they should have
9534 // already been taken care of (e.g. and of 0, test of undefined shifted bits,
9535 // etc.)
9536
9537 // (tbz (trunc x), b) -> (tbz x, b)
9538 // This case is just here to enable more of the below cases to be caught.
9539 if (Op->getOpcode() == ISD::TRUNCATE &&
9540 Bit < Op->getValueType(0).getSizeInBits()) {
9541 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9542 }
9543
9544 if (Op->getNumOperands() != 2)
9545 return Op;
9546
9547 auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
9548 if (!C)
9549 return Op;
9550
9551 switch (Op->getOpcode()) {
9552 default:
9553 return Op;
9554
9555 // (tbz (and x, m), b) -> (tbz x, b)
9556 case ISD::AND:
9557 if ((C->getZExtValue() >> Bit) & 1)
9558 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9559 return Op;
9560
9561 // (tbz (shl x, c), b) -> (tbz x, b-c)
9562 case ISD::SHL:
9563 if (C->getZExtValue() <= Bit &&
9564 (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
9565 Bit = Bit - C->getZExtValue();
9566 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9567 }
9568 return Op;
9569
9570 // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
9571 case ISD::SRA:
9572 Bit = Bit + C->getZExtValue();
9573 if (Bit >= Op->getValueType(0).getSizeInBits())
9574 Bit = Op->getValueType(0).getSizeInBits() - 1;
9575 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9576
9577 // (tbz (srl x, c), b) -> (tbz x, b+c)
9578 case ISD::SRL:
9579 if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
9580 Bit = Bit + C->getZExtValue();
9581 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9582 }
9583 return Op;
9584
9585 // (tbz (xor x, -1), b) -> (tbnz x, b)
9586 case ISD::XOR:
9587 if ((C->getZExtValue() >> Bit) & 1)
9588 Invert = !Invert;
9589 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9590 }
9591}
9592
9593// Optimize test single bit zero/non-zero and branch.
9594static SDValue performTBZCombine(SDNode *N,
9595 TargetLowering::DAGCombinerInfo &DCI,
9596 SelectionDAG &DAG) {
9597 unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
9598 bool Invert = false;
9599 SDValue TestSrc = N->getOperand(1);
9600 SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG);
9601
9602 if (TestSrc == NewTestSrc)
9603 return SDValue();
9604
9605 unsigned NewOpc = N->getOpcode();
9606 if (Invert) {
9607 if (NewOpc == AArch64ISD::TBZ)
9608 NewOpc = AArch64ISD::TBNZ;
9609 else {
9610 assert(NewOpc == AArch64ISD::TBNZ);
9611 NewOpc = AArch64ISD::TBZ;
9612 }
9613 }
9614
9615 SDLoc DL(N);
9616 return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc,
9617 DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3));
9618}
9619
Tim Northover3b0846e2014-05-24 12:50:23 +00009620// vselect (v1i1 setcc) ->
9621// vselect (v1iXX setcc) (XX is the size of the compared operand type)
9622// FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
9623// condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
9624// such VSELECT.
9625static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
9626 SDValue N0 = N->getOperand(0);
9627 EVT CCVT = N0.getValueType();
9628
9629 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
9630 CCVT.getVectorElementType() != MVT::i1)
9631 return SDValue();
9632
9633 EVT ResVT = N->getValueType(0);
9634 EVT CmpVT = N0.getOperand(0).getValueType();
9635 // Only combine when the result type is of the same size as the compared
9636 // operands.
9637 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
9638 return SDValue();
9639
9640 SDValue IfTrue = N->getOperand(1);
9641 SDValue IfFalse = N->getOperand(2);
9642 SDValue SetCC =
9643 DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
9644 N0.getOperand(0), N0.getOperand(1),
9645 cast<CondCodeSDNode>(N0.getOperand(2))->get());
9646 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
9647 IfTrue, IfFalse);
9648}
9649
9650/// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
9651/// the compare-mask instructions rather than going via NZCV, even if LHS and
9652/// RHS are really scalar. This replaces any scalar setcc in the above pattern
9653/// with a vector one followed by a DUP shuffle on the result.
Ahmed Bougachac004c602015-04-27 21:43:12 +00009654static SDValue performSelectCombine(SDNode *N,
9655 TargetLowering::DAGCombinerInfo &DCI) {
9656 SelectionDAG &DAG = DCI.DAG;
Tim Northover3b0846e2014-05-24 12:50:23 +00009657 SDValue N0 = N->getOperand(0);
9658 EVT ResVT = N->getValueType(0);
Tim Northover3c0915e2014-08-29 15:34:58 +00009659
Ahmed Bougachac004c602015-04-27 21:43:12 +00009660 if (N0.getOpcode() != ISD::SETCC)
Tim Northover3c0915e2014-08-29 15:34:58 +00009661 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00009662
Ahmed Bougachac004c602015-04-27 21:43:12 +00009663 // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
9664 // scalar SetCCResultType. We also don't expect vectors, because we assume
9665 // that selects fed by vector SETCCs are canonicalized to VSELECT.
9666 assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
9667 "Scalar-SETCC feeding SELECT has unexpected result type!");
9668
Tim Northoverc1c05ae2014-08-29 13:05:18 +00009669 // If NumMaskElts == 0, the comparison is larger than select result. The
9670 // largest real NEON comparison is 64-bits per lane, which means the result is
9671 // at most 32-bits and an illegal vector. Just bail out for now.
Tim Northover3c0915e2014-08-29 15:34:58 +00009672 EVT SrcVT = N0.getOperand(0).getValueType();
Ahmed Bougachad0ce0582014-12-01 20:59:00 +00009673
9674 // Don't try to do this optimization when the setcc itself has i1 operands.
9675 // There are no legal vectors of i1, so this would be pointless.
9676 if (SrcVT == MVT::i1)
9677 return SDValue();
9678
Tim Northover3c0915e2014-08-29 15:34:58 +00009679 int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
Tim Northoverc1c05ae2014-08-29 13:05:18 +00009680 if (!ResVT.isVector() || NumMaskElts == 0)
Tim Northover3b0846e2014-05-24 12:50:23 +00009681 return SDValue();
9682
Tim Northoverc1c05ae2014-08-29 13:05:18 +00009683 SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
Tim Northover3b0846e2014-05-24 12:50:23 +00009684 EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
9685
Ahmed Bougacha89bba612015-04-27 21:01:20 +00009686 // Also bail out if the vector CCVT isn't the same size as ResVT.
9687 // This can happen if the SETCC operand size doesn't divide the ResVT size
9688 // (e.g., f64 vs v3f32).
9689 if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
9690 return SDValue();
9691
Ahmed Bougachac004c602015-04-27 21:43:12 +00009692 // Make sure we didn't create illegal types, if we're not supposed to.
9693 assert(DCI.isBeforeLegalize() ||
9694 DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
9695
Tim Northover3b0846e2014-05-24 12:50:23 +00009696 // First perform a vector comparison, where lane 0 is the one we're interested
9697 // in.
Tim Northoverc1c05ae2014-08-29 13:05:18 +00009698 SDLoc DL(N0);
Tim Northover3b0846e2014-05-24 12:50:23 +00009699 SDValue LHS =
9700 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
9701 SDValue RHS =
9702 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
9703 SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
9704
9705 // Now duplicate the comparison mask we want across all other lanes.
9706 SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
9707 SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask.data());
Tim Northoverc1c05ae2014-08-29 13:05:18 +00009708 Mask = DAG.getNode(ISD::BITCAST, DL,
9709 ResVT.changeVectorElementTypeToInteger(), Mask);
Tim Northover3b0846e2014-05-24 12:50:23 +00009710
9711 return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
9712}
9713
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009714/// Get rid of unnecessary NVCASTs (that don't change the type).
9715static SDValue performNVCASTCombine(SDNode *N) {
9716 if (N->getValueType(0) == N->getOperand(0).getValueType())
9717 return N->getOperand(0);
9718
9719 return SDValue();
9720}
9721
Tim Northover3b0846e2014-05-24 12:50:23 +00009722SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
9723 DAGCombinerInfo &DCI) const {
9724 SelectionDAG &DAG = DCI.DAG;
9725 switch (N->getOpcode()) {
9726 default:
9727 break;
9728 case ISD::ADD:
9729 case ISD::SUB:
9730 return performAddSubLongCombine(N, DCI, DAG);
9731 case ISD::XOR:
9732 return performXorCombine(N, DAG, DCI, Subtarget);
9733 case ISD::MUL:
9734 return performMulCombine(N, DAG, DCI, Subtarget);
9735 case ISD::SINT_TO_FP:
9736 case ISD::UINT_TO_FP:
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00009737 return performIntToFpCombine(N, DAG, Subtarget);
Chad Rosierfa30c9b2015-10-07 17:39:18 +00009738 case ISD::FP_TO_SINT:
9739 case ISD::FP_TO_UINT:
9740 return performFpToIntCombine(N, DAG, Subtarget);
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00009741 case ISD::FDIV:
9742 return performFDivCombine(N, DAG, Subtarget);
Tim Northover3b0846e2014-05-24 12:50:23 +00009743 case ISD::OR:
9744 return performORCombine(N, DCI, Subtarget);
9745 case ISD::INTRINSIC_WO_CHAIN:
9746 return performIntrinsicCombine(N, DCI, Subtarget);
9747 case ISD::ANY_EXTEND:
9748 case ISD::ZERO_EXTEND:
9749 case ISD::SIGN_EXTEND:
9750 return performExtendCombine(N, DCI, DAG);
9751 case ISD::BITCAST:
9752 return performBitcastCombine(N, DCI, DAG);
9753 case ISD::CONCAT_VECTORS:
9754 return performConcatVectorsCombine(N, DCI, DAG);
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009755 case ISD::SELECT: {
9756 SDValue RV = performSelectCombine(N, DCI);
9757 if (!RV.getNode())
9758 RV = performAcrossLaneMinMaxReductionCombine(N, DAG, Subtarget);
9759 return RV;
9760 }
Tim Northover3b0846e2014-05-24 12:50:23 +00009761 case ISD::VSELECT:
9762 return performVSelectCombine(N, DCI.DAG);
Tim Northover339c83e2015-11-10 00:44:23 +00009763 case ISD::LOAD:
9764 if (performTBISimplification(N->getOperand(1), DCI, DAG))
9765 return SDValue(N, 0);
9766 break;
Tim Northover3b0846e2014-05-24 12:50:23 +00009767 case ISD::STORE:
9768 return performSTORECombine(N, DCI, DAG, Subtarget);
9769 case AArch64ISD::BRCOND:
9770 return performBRCONDCombine(N, DCI, DAG);
Geoff Berry9e934b02016-01-04 18:55:47 +00009771 case AArch64ISD::TBNZ:
9772 case AArch64ISD::TBZ:
9773 return performTBZCombine(N, DCI, DAG);
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009774 case AArch64ISD::CSEL:
9775 return performCONDCombine(N, DCI, DAG, 2, 3);
Tim Northover3b0846e2014-05-24 12:50:23 +00009776 case AArch64ISD::DUP:
9777 return performPostLD1Combine(N, DCI, false);
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009778 case AArch64ISD::NVCAST:
9779 return performNVCASTCombine(N);
Tim Northover3b0846e2014-05-24 12:50:23 +00009780 case ISD::INSERT_VECTOR_ELT:
9781 return performPostLD1Combine(N, DCI, true);
Chad Rosier6c36eff2015-09-03 18:13:57 +00009782 case ISD::EXTRACT_VECTOR_ELT:
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009783 return performAcrossLaneAddReductionCombine(N, DAG, Subtarget);
Tim Northover3b0846e2014-05-24 12:50:23 +00009784 case ISD::INTRINSIC_VOID:
9785 case ISD::INTRINSIC_W_CHAIN:
9786 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9787 case Intrinsic::aarch64_neon_ld2:
9788 case Intrinsic::aarch64_neon_ld3:
9789 case Intrinsic::aarch64_neon_ld4:
9790 case Intrinsic::aarch64_neon_ld1x2:
9791 case Intrinsic::aarch64_neon_ld1x3:
9792 case Intrinsic::aarch64_neon_ld1x4:
9793 case Intrinsic::aarch64_neon_ld2lane:
9794 case Intrinsic::aarch64_neon_ld3lane:
9795 case Intrinsic::aarch64_neon_ld4lane:
9796 case Intrinsic::aarch64_neon_ld2r:
9797 case Intrinsic::aarch64_neon_ld3r:
9798 case Intrinsic::aarch64_neon_ld4r:
9799 case Intrinsic::aarch64_neon_st2:
9800 case Intrinsic::aarch64_neon_st3:
9801 case Intrinsic::aarch64_neon_st4:
9802 case Intrinsic::aarch64_neon_st1x2:
9803 case Intrinsic::aarch64_neon_st1x3:
9804 case Intrinsic::aarch64_neon_st1x4:
9805 case Intrinsic::aarch64_neon_st2lane:
9806 case Intrinsic::aarch64_neon_st3lane:
9807 case Intrinsic::aarch64_neon_st4lane:
9808 return performNEONPostLDSTCombine(N, DCI, DAG);
9809 default:
9810 break;
9811 }
9812 }
9813 return SDValue();
9814}
9815
9816// Check if the return value is used as only a return value, as otherwise
9817// we can't perform a tail-call. In particular, we need to check for
9818// target ISD nodes that are returns and any other "odd" constructs
9819// that the generic analysis code won't necessarily catch.
9820bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
9821 SDValue &Chain) const {
9822 if (N->getNumValues() != 1)
9823 return false;
9824 if (!N->hasNUsesOfValue(1, 0))
9825 return false;
9826
9827 SDValue TCChain = Chain;
9828 SDNode *Copy = *N->use_begin();
9829 if (Copy->getOpcode() == ISD::CopyToReg) {
9830 // If the copy has a glue operand, we conservatively assume it isn't safe to
9831 // perform a tail call.
9832 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
9833 MVT::Glue)
9834 return false;
9835 TCChain = Copy->getOperand(0);
9836 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
9837 return false;
9838
9839 bool HasRet = false;
9840 for (SDNode *Node : Copy->uses()) {
9841 if (Node->getOpcode() != AArch64ISD::RET_FLAG)
9842 return false;
9843 HasRet = true;
9844 }
9845
9846 if (!HasRet)
9847 return false;
9848
9849 Chain = TCChain;
9850 return true;
9851}
9852
9853// Return whether the an instruction can potentially be optimized to a tail
9854// call. This will cause the optimizers to attempt to move, or duplicate,
9855// return instructions to help enable tail call optimizations for this
9856// instruction.
9857bool AArch64TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
9858 if (!CI->isTailCall())
9859 return false;
9860
9861 return true;
9862}
9863
9864bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
9865 SDValue &Offset,
9866 ISD::MemIndexedMode &AM,
9867 bool &IsInc,
9868 SelectionDAG &DAG) const {
9869 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
9870 return false;
9871
9872 Base = Op->getOperand(0);
9873 // All of the indexed addressing mode instructions take a signed
9874 // 9 bit immediate offset.
9875 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
9876 int64_t RHSC = (int64_t)RHS->getZExtValue();
9877 if (RHSC >= 256 || RHSC <= -256)
9878 return false;
9879 IsInc = (Op->getOpcode() == ISD::ADD);
9880 Offset = Op->getOperand(1);
9881 return true;
9882 }
9883 return false;
9884}
9885
9886bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
9887 SDValue &Offset,
9888 ISD::MemIndexedMode &AM,
9889 SelectionDAG &DAG) const {
9890 EVT VT;
9891 SDValue Ptr;
9892 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9893 VT = LD->getMemoryVT();
9894 Ptr = LD->getBasePtr();
9895 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9896 VT = ST->getMemoryVT();
9897 Ptr = ST->getBasePtr();
9898 } else
9899 return false;
9900
9901 bool IsInc;
9902 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
9903 return false;
9904 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
9905 return true;
9906}
9907
9908bool AArch64TargetLowering::getPostIndexedAddressParts(
9909 SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
9910 ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
9911 EVT VT;
9912 SDValue Ptr;
9913 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9914 VT = LD->getMemoryVT();
9915 Ptr = LD->getBasePtr();
9916 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9917 VT = ST->getMemoryVT();
9918 Ptr = ST->getBasePtr();
9919 } else
9920 return false;
9921
9922 bool IsInc;
9923 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
9924 return false;
9925 // Post-indexing updates the base, so it's not a valid transform
9926 // if that's not the same as the load's pointer.
9927 if (Ptr != Base)
9928 return false;
9929 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
9930 return true;
9931}
9932
Tim Northoverf8bfe212014-07-18 13:07:05 +00009933static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
9934 SelectionDAG &DAG) {
Tim Northoverf8bfe212014-07-18 13:07:05 +00009935 SDLoc DL(N);
9936 SDValue Op = N->getOperand(0);
Ahmed Bougacha87946322014-12-01 20:52:32 +00009937
9938 if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
9939 return;
9940
Tim Northoverf8bfe212014-07-18 13:07:05 +00009941 Op = SDValue(
9942 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
9943 DAG.getUNDEF(MVT::i32), Op,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009944 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
Tim Northoverf8bfe212014-07-18 13:07:05 +00009945 0);
9946 Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
9947 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
9948}
9949
Charlie Turner434d4592015-10-16 15:38:25 +00009950static void ReplaceReductionResults(SDNode *N,
9951 SmallVectorImpl<SDValue> &Results,
9952 SelectionDAG &DAG, unsigned InterOp,
9953 unsigned AcrossOp) {
9954 EVT LoVT, HiVT;
9955 SDValue Lo, Hi;
9956 SDLoc dl(N);
9957 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
9958 std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
9959 SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
9960 SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
9961 Results.push_back(SplitVal);
9962}
9963
Tim Northover3b0846e2014-05-24 12:50:23 +00009964void AArch64TargetLowering::ReplaceNodeResults(
9965 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
9966 switch (N->getOpcode()) {
9967 default:
9968 llvm_unreachable("Don't know how to custom expand this");
Tim Northoverf8bfe212014-07-18 13:07:05 +00009969 case ISD::BITCAST:
9970 ReplaceBITCASTResults(N, Results, DAG);
9971 return;
Charlie Turner434d4592015-10-16 15:38:25 +00009972 case AArch64ISD::SADDV:
9973 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
9974 return;
9975 case AArch64ISD::UADDV:
9976 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
9977 return;
9978 case AArch64ISD::SMINV:
9979 ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
9980 return;
9981 case AArch64ISD::UMINV:
9982 ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
9983 return;
9984 case AArch64ISD::SMAXV:
9985 ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
9986 return;
9987 case AArch64ISD::UMAXV:
9988 ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
9989 return;
Tim Northover3b0846e2014-05-24 12:50:23 +00009990 case ISD::FP_TO_UINT:
9991 case ISD::FP_TO_SINT:
9992 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
9993 // Let normal code take care of it by not adding anything to Results.
9994 return;
9995 }
9996}
9997
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +00009998bool AArch64TargetLowering::useLoadStackGuardNode() const {
9999 return true;
10000}
10001
Sanjay Patel1dd15592015-07-28 23:05:48 +000010002unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
Hao Liu44e5d7a2014-11-21 06:39:58 +000010003 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
10004 // reciprocal if there are three or more FDIVs.
Sanjay Patel1dd15592015-07-28 23:05:48 +000010005 return 3;
Hao Liu44e5d7a2014-11-21 06:39:58 +000010006}
10007
Chandler Carruth9d010ff2014-07-03 00:23:43 +000010008TargetLoweringBase::LegalizeTypeAction
10009AArch64TargetLowering::getPreferredVectorAction(EVT VT) const {
10010 MVT SVT = VT.getSimpleVT();
10011 // During type legalization, we prefer to widen v1i8, v1i16, v1i32 to v8i8,
10012 // v4i16, v2i32 instead of to promote.
10013 if (SVT == MVT::v1i8 || SVT == MVT::v1i16 || SVT == MVT::v1i32
10014 || SVT == MVT::v1f32)
10015 return TypeWidenVector;
10016
10017 return TargetLoweringBase::getPreferredVectorAction(VT);
10018}
10019
Robin Morisseted3d48f2014-09-03 21:29:59 +000010020// Loads and stores less than 128-bits are already atomic; ones above that
10021// are doomed anyway, so defer to the default libcall and blame the OS when
10022// things go wrong.
10023bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
10024 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
10025 return Size == 128;
10026}
10027
10028// Loads and stores less than 128-bits are already atomic; ones above that
10029// are doomed anyway, so defer to the default libcall and blame the OS when
10030// things go wrong.
Ahmed Bougacha52468672015-09-11 17:08:28 +000010031TargetLowering::AtomicExpansionKind
10032AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
Robin Morisseted3d48f2014-09-03 21:29:59 +000010033 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
Ahmed Bougacha52468672015-09-11 17:08:28 +000010034 return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
Robin Morisseted3d48f2014-09-03 21:29:59 +000010035}
10036
10037// For the real atomic operations, we have ldxr/stxr up to 128 bits,
Ahmed Bougacha52468672015-09-11 17:08:28 +000010038TargetLowering::AtomicExpansionKind
JF Bastienf14889e2015-03-04 15:47:57 +000010039AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
Robin Morisseted3d48f2014-09-03 21:29:59 +000010040 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
Ahmed Bougacha9d677132015-09-11 17:08:17 +000010041 return Size <= 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
Robin Morisseted3d48f2014-09-03 21:29:59 +000010042}
10043
Ahmed Bougacha52468672015-09-11 17:08:28 +000010044bool AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
10045 AtomicCmpXchgInst *AI) const {
Robin Morisset25c8e312014-09-17 00:06:58 +000010046 return true;
10047}
10048
Tim Northover3b0846e2014-05-24 12:50:23 +000010049Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
10050 AtomicOrdering Ord) const {
10051 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10052 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
Robin Morissetb155f522014-08-18 16:48:58 +000010053 bool IsAcquire = isAtLeastAcquire(Ord);
Tim Northover3b0846e2014-05-24 12:50:23 +000010054
10055 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
10056 // intrinsic must return {i64, i64} and we have to recombine them into a
10057 // single i128 here.
10058 if (ValTy->getPrimitiveSizeInBits() == 128) {
10059 Intrinsic::ID Int =
10060 IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
10061 Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int);
10062
10063 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10064 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
10065
10066 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
10067 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
10068 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
10069 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
10070 return Builder.CreateOr(
10071 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
10072 }
10073
10074 Type *Tys[] = { Addr->getType() };
10075 Intrinsic::ID Int =
10076 IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
10077 Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int, Tys);
10078
10079 return Builder.CreateTruncOrBitCast(
10080 Builder.CreateCall(Ldxr, Addr),
10081 cast<PointerType>(Addr->getType())->getElementType());
10082}
10083
Ahmed Bougacha07a844d2015-09-22 17:21:44 +000010084void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
10085 IRBuilder<> &Builder) const {
10086 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10087 Builder.CreateCall(
10088 llvm::Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
10089}
10090
Tim Northover3b0846e2014-05-24 12:50:23 +000010091Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
10092 Value *Val, Value *Addr,
10093 AtomicOrdering Ord) const {
10094 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
Robin Morissetb155f522014-08-18 16:48:58 +000010095 bool IsRelease = isAtLeastRelease(Ord);
Tim Northover3b0846e2014-05-24 12:50:23 +000010096
10097 // Since the intrinsics must have legal type, the i128 intrinsics take two
10098 // parameters: "i64, i64". We must marshal Val into the appropriate form
10099 // before the call.
10100 if (Val->getType()->getPrimitiveSizeInBits() == 128) {
10101 Intrinsic::ID Int =
10102 IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
10103 Function *Stxr = Intrinsic::getDeclaration(M, Int);
10104 Type *Int64Ty = Type::getInt64Ty(M->getContext());
10105
10106 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
10107 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
10108 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
David Blaikieff6409d2015-05-18 22:13:54 +000010109 return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
Tim Northover3b0846e2014-05-24 12:50:23 +000010110 }
10111
10112 Intrinsic::ID Int =
10113 IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
10114 Type *Tys[] = { Addr->getType() };
10115 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
10116
David Blaikieff6409d2015-05-18 22:13:54 +000010117 return Builder.CreateCall(Stxr,
10118 {Builder.CreateZExtOrBitCast(
10119 Val, Stxr->getFunctionType()->getParamType(0)),
10120 Addr});
Tim Northover3b0846e2014-05-24 12:50:23 +000010121}
Tim Northover3c55cca2014-11-27 21:02:42 +000010122
10123bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
10124 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
10125 return Ty->isArrayTy();
10126}
Matthias Braunaf7d7702015-07-16 20:02:37 +000010127
10128bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
10129 EVT) const {
10130 return false;
10131}
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000010132
10133Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
10134 if (!Subtarget->isTargetAndroid())
10135 return TargetLowering::getSafeStackPointerLocation(IRB);
10136
10137 // Android provides a fixed TLS slot for the SafeStack pointer. See the
10138 // definition of TLS_SLOT_SAFESTACK in
10139 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
10140 const unsigned TlsOffset = 0x48;
10141 Module *M = IRB.GetInsertBlock()->getParent()->getParent();
10142 Function *ThreadPointerFunc =
10143 Intrinsic::getDeclaration(M, Intrinsic::aarch64_thread_pointer);
10144 return IRB.CreatePointerCast(
10145 IRB.CreateConstGEP1_32(IRB.CreateCall(ThreadPointerFunc), TlsOffset),
10146 Type::getInt8PtrTy(IRB.getContext())->getPointerTo(0));
10147}
Manman Rencbe4f942015-12-16 21:04:19 +000010148
10149void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
10150 // Update IsSplitCSR in AArch64unctionInfo.
10151 AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>();
10152 AFI->setIsSplitCSR(true);
10153}
10154
10155void AArch64TargetLowering::insertCopiesSplitCSR(
10156 MachineBasicBlock *Entry,
10157 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
10158 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
10159 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
10160 if (!IStart)
10161 return;
10162
10163 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10164 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
Manman Ren4632e8e2016-01-15 20:13:28 +000010165 MachineBasicBlock::iterator MBBI = Entry->begin();
Manman Rencbe4f942015-12-16 21:04:19 +000010166 for (const MCPhysReg *I = IStart; *I; ++I) {
10167 const TargetRegisterClass *RC = nullptr;
10168 if (AArch64::GPR64RegClass.contains(*I))
10169 RC = &AArch64::GPR64RegClass;
10170 else if (AArch64::FPR64RegClass.contains(*I))
10171 RC = &AArch64::FPR64RegClass;
10172 else
10173 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
10174
10175 unsigned NewVR = MRI->createVirtualRegister(RC);
10176 // Create copy from CSR to a virtual register.
10177 // FIXME: this currently does not emit CFI pseudo-instructions, it works
10178 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
10179 // nounwind. If we want to generalize this later, we may need to emit
10180 // CFI pseudo-instructions.
10181 assert(Entry->getParent()->getFunction()->hasFnAttribute(
10182 Attribute::NoUnwind) &&
10183 "Function should be nounwind in insertCopiesSplitCSR!");
10184 Entry->addLiveIn(*I);
Manman Ren4632e8e2016-01-15 20:13:28 +000010185 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
Manman Rencbe4f942015-12-16 21:04:19 +000010186 .addReg(*I);
10187
Manman Ren4632e8e2016-01-15 20:13:28 +000010188 // Insert the copy-back instructions right before the terminator.
Manman Rencbe4f942015-12-16 21:04:19 +000010189 for (auto *Exit : Exits)
Manman Ren4632e8e2016-01-15 20:13:28 +000010190 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
10191 TII->get(TargetOpcode::COPY), *I)
Manman Rencbe4f942015-12-16 21:04:19 +000010192 .addReg(NewVR);
10193 }
10194}