blob: 91e8ba18e34a67373c0e916e33647c6e4eeaced1 [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
Alexey Samsonovf17f03e2014-08-19 18:40:39 +000043namespace {
Tim Northover3b0846e2014-05-24 12:50:23 +000044enum AlignMode {
45 StrictAlign,
46 NoStrictAlign
47};
Alexey Samsonovf17f03e2014-08-19 18:40:39 +000048}
Tim Northover3b0846e2014-05-24 12:50:23 +000049
50static cl::opt<AlignMode>
51Align(cl::desc("Load/store alignment support"),
52 cl::Hidden, cl::init(NoStrictAlign),
53 cl::values(
54 clEnumValN(StrictAlign, "aarch64-strict-align",
55 "Disallow all unaligned memory accesses"),
56 clEnumValN(NoStrictAlign, "aarch64-no-strict-align",
57 "Allow unaligned memory accesses"),
58 clEnumValEnd));
59
60// Place holder until extr generation is tested fully.
61static cl::opt<bool>
62EnableAArch64ExtrGeneration("aarch64-extr-generation", cl::Hidden,
63 cl::desc("Allow AArch64 (or (shift)(shift))->extract"),
64 cl::init(true));
65
66static cl::opt<bool>
67EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden,
Kristof Beylsaea84612015-03-04 09:12:08 +000068 cl::desc("Allow AArch64 SLI/SRI formation"),
69 cl::init(false));
70
71// FIXME: The necessary dtprel relocations don't seem to be supported
72// well in the GNU bfd and gold linkers at the moment. Therefore, by
73// default, for now, fall back to GeneralDynamic code generation.
74cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration(
75 "aarch64-elf-ldtls-generation", cl::Hidden,
76 cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
77 cl::init(false));
Tim Northover3b0846e2014-05-24 12:50:23 +000078
Matthias Braunaf7d7702015-07-16 20:02:37 +000079/// Value type used for condition codes.
80static const MVT MVT_CC = MVT::i32;
81
Eric Christopher905f12d2015-01-29 00:19:42 +000082AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
83 const AArch64Subtarget &STI)
84 : TargetLowering(TM), Subtarget(&STI) {
Tim Northover3b0846e2014-05-24 12:50:23 +000085
86 // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
87 // we have to make something up. Arbitrarily, choose ZeroOrOne.
88 setBooleanContents(ZeroOrOneBooleanContent);
89 // When comparing vectors the result sets the different elements in the
90 // vector to all-one or all-zero.
91 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
92
93 // Set up the register classes.
94 addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
95 addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
96
97 if (Subtarget->hasFPARMv8()) {
98 addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
99 addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
100 addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
101 addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
102 }
103
104 if (Subtarget->hasNEON()) {
105 addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
106 addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
107 // Someone set us up the NEON.
108 addDRTypeForNEON(MVT::v2f32);
109 addDRTypeForNEON(MVT::v8i8);
110 addDRTypeForNEON(MVT::v4i16);
111 addDRTypeForNEON(MVT::v2i32);
112 addDRTypeForNEON(MVT::v1i64);
113 addDRTypeForNEON(MVT::v1f64);
Oliver Stannard89d15422014-08-27 16:16:04 +0000114 addDRTypeForNEON(MVT::v4f16);
Tim Northover3b0846e2014-05-24 12:50:23 +0000115
116 addQRTypeForNEON(MVT::v4f32);
117 addQRTypeForNEON(MVT::v2f64);
118 addQRTypeForNEON(MVT::v16i8);
119 addQRTypeForNEON(MVT::v8i16);
120 addQRTypeForNEON(MVT::v4i32);
121 addQRTypeForNEON(MVT::v2i64);
Oliver Stannard89d15422014-08-27 16:16:04 +0000122 addQRTypeForNEON(MVT::v8f16);
Tim Northover3b0846e2014-05-24 12:50:23 +0000123 }
124
125 // Compute derived properties from the register classes
Eric Christopher23a3a7c2015-02-26 00:00:24 +0000126 computeRegisterProperties(Subtarget->getRegisterInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +0000127
128 // Provide all sorts of operation actions
129 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
130 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
131 setOperationAction(ISD::SETCC, MVT::i32, Custom);
132 setOperationAction(ISD::SETCC, MVT::i64, Custom);
133 setOperationAction(ISD::SETCC, MVT::f32, Custom);
134 setOperationAction(ISD::SETCC, MVT::f64, Custom);
135 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
136 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
137 setOperationAction(ISD::BR_CC, MVT::i64, Custom);
138 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
139 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
140 setOperationAction(ISD::SELECT, MVT::i32, Custom);
141 setOperationAction(ISD::SELECT, MVT::i64, Custom);
142 setOperationAction(ISD::SELECT, MVT::f32, Custom);
143 setOperationAction(ISD::SELECT, MVT::f64, Custom);
144 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
145 setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
146 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
147 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
148 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
149 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
150
151 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
152 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
153 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
154
155 setOperationAction(ISD::FREM, MVT::f32, Expand);
156 setOperationAction(ISD::FREM, MVT::f64, Expand);
157 setOperationAction(ISD::FREM, MVT::f80, Expand);
158
159 // Custom lowering hooks are needed for XOR
160 // to fold it into CSINC/CSINV.
161 setOperationAction(ISD::XOR, MVT::i32, Custom);
162 setOperationAction(ISD::XOR, MVT::i64, Custom);
163
164 // Virtually no operation on f128 is legal, but LLVM can't expand them when
165 // there's a valid register class, so we need custom operations in most cases.
166 setOperationAction(ISD::FABS, MVT::f128, Expand);
167 setOperationAction(ISD::FADD, MVT::f128, Custom);
168 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
169 setOperationAction(ISD::FCOS, MVT::f128, Expand);
170 setOperationAction(ISD::FDIV, MVT::f128, Custom);
171 setOperationAction(ISD::FMA, MVT::f128, Expand);
172 setOperationAction(ISD::FMUL, MVT::f128, Custom);
173 setOperationAction(ISD::FNEG, MVT::f128, Expand);
174 setOperationAction(ISD::FPOW, MVT::f128, Expand);
175 setOperationAction(ISD::FREM, MVT::f128, Expand);
176 setOperationAction(ISD::FRINT, MVT::f128, Expand);
177 setOperationAction(ISD::FSIN, MVT::f128, Expand);
178 setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
179 setOperationAction(ISD::FSQRT, MVT::f128, Expand);
180 setOperationAction(ISD::FSUB, MVT::f128, Custom);
181 setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
182 setOperationAction(ISD::SETCC, MVT::f128, Custom);
183 setOperationAction(ISD::BR_CC, MVT::f128, Custom);
184 setOperationAction(ISD::SELECT, MVT::f128, Custom);
185 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
186 setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
187
188 // Lowering for many of the conversions is actually specified by the non-f128
189 // type. The LowerXXX function will be trivial when f128 isn't involved.
190 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
191 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
192 setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
193 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
194 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
195 setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
196 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
197 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
198 setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
199 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
200 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
201 setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
202 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
203 setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
204
205 // Variable arguments.
206 setOperationAction(ISD::VASTART, MVT::Other, Custom);
207 setOperationAction(ISD::VAARG, MVT::Other, Custom);
208 setOperationAction(ISD::VACOPY, MVT::Other, Custom);
209 setOperationAction(ISD::VAEND, MVT::Other, Expand);
210
211 // Variable-sized objects.
212 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
213 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
214 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
215
216 // Exception handling.
217 // FIXME: These are guesses. Has this been defined yet?
218 setExceptionPointerRegister(AArch64::X0);
219 setExceptionSelectorRegister(AArch64::X1);
220
221 // Constant pool entries
222 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
223
224 // BlockAddress
225 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
226
227 // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
228 setOperationAction(ISD::ADDC, MVT::i32, Custom);
229 setOperationAction(ISD::ADDE, MVT::i32, Custom);
230 setOperationAction(ISD::SUBC, MVT::i32, Custom);
231 setOperationAction(ISD::SUBE, MVT::i32, Custom);
232 setOperationAction(ISD::ADDC, MVT::i64, Custom);
233 setOperationAction(ISD::ADDE, MVT::i64, Custom);
234 setOperationAction(ISD::SUBC, MVT::i64, Custom);
235 setOperationAction(ISD::SUBE, MVT::i64, Custom);
236
237 // AArch64 lacks both left-rotate and popcount instructions.
238 setOperationAction(ISD::ROTL, MVT::i32, Expand);
239 setOperationAction(ISD::ROTL, MVT::i64, Expand);
240
241 // AArch64 doesn't have {U|S}MUL_LOHI.
242 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
243 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
244
245
246 // Expand the undefined-at-zero variants to cttz/ctlz to their defined-at-zero
247 // counterparts, which AArch64 supports directly.
248 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
249 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
250 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
251 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
252
253 setOperationAction(ISD::CTPOP, MVT::i32, Custom);
254 setOperationAction(ISD::CTPOP, MVT::i64, Custom);
255
256 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
257 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
258 setOperationAction(ISD::SREM, MVT::i32, Expand);
259 setOperationAction(ISD::SREM, MVT::i64, Expand);
260 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
261 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
262 setOperationAction(ISD::UREM, MVT::i32, Expand);
263 setOperationAction(ISD::UREM, MVT::i64, Expand);
264
265 // Custom lower Add/Sub/Mul with overflow.
266 setOperationAction(ISD::SADDO, MVT::i32, Custom);
267 setOperationAction(ISD::SADDO, MVT::i64, Custom);
268 setOperationAction(ISD::UADDO, MVT::i32, Custom);
269 setOperationAction(ISD::UADDO, MVT::i64, Custom);
270 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
271 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
272 setOperationAction(ISD::USUBO, MVT::i32, Custom);
273 setOperationAction(ISD::USUBO, MVT::i64, Custom);
274 setOperationAction(ISD::SMULO, MVT::i32, Custom);
275 setOperationAction(ISD::SMULO, MVT::i64, Custom);
276 setOperationAction(ISD::UMULO, MVT::i32, Custom);
277 setOperationAction(ISD::UMULO, MVT::i64, Custom);
278
279 setOperationAction(ISD::FSIN, MVT::f32, Expand);
280 setOperationAction(ISD::FSIN, MVT::f64, Expand);
281 setOperationAction(ISD::FCOS, MVT::f32, Expand);
282 setOperationAction(ISD::FCOS, MVT::f64, Expand);
283 setOperationAction(ISD::FPOW, MVT::f32, Expand);
284 setOperationAction(ISD::FPOW, MVT::f64, Expand);
285 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
286 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
287
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +0000288 // f16 is a storage-only type, always promote it to f32.
289 setOperationAction(ISD::SETCC, MVT::f16, Promote);
290 setOperationAction(ISD::BR_CC, MVT::f16, Promote);
291 setOperationAction(ISD::SELECT_CC, MVT::f16, Promote);
292 setOperationAction(ISD::SELECT, MVT::f16, Promote);
293 setOperationAction(ISD::FADD, MVT::f16, Promote);
294 setOperationAction(ISD::FSUB, MVT::f16, Promote);
295 setOperationAction(ISD::FMUL, MVT::f16, Promote);
296 setOperationAction(ISD::FDIV, MVT::f16, Promote);
297 setOperationAction(ISD::FREM, MVT::f16, Promote);
298 setOperationAction(ISD::FMA, MVT::f16, Promote);
299 setOperationAction(ISD::FNEG, MVT::f16, Promote);
300 setOperationAction(ISD::FABS, MVT::f16, Promote);
301 setOperationAction(ISD::FCEIL, MVT::f16, Promote);
302 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote);
303 setOperationAction(ISD::FCOS, MVT::f16, Promote);
304 setOperationAction(ISD::FFLOOR, MVT::f16, Promote);
305 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote);
306 setOperationAction(ISD::FPOW, MVT::f16, Promote);
307 setOperationAction(ISD::FPOWI, MVT::f16, Promote);
308 setOperationAction(ISD::FRINT, MVT::f16, Promote);
309 setOperationAction(ISD::FSIN, MVT::f16, Promote);
310 setOperationAction(ISD::FSINCOS, MVT::f16, Promote);
311 setOperationAction(ISD::FSQRT, MVT::f16, Promote);
312 setOperationAction(ISD::FEXP, MVT::f16, Promote);
313 setOperationAction(ISD::FEXP2, MVT::f16, Promote);
314 setOperationAction(ISD::FLOG, MVT::f16, Promote);
315 setOperationAction(ISD::FLOG2, MVT::f16, Promote);
316 setOperationAction(ISD::FLOG10, MVT::f16, Promote);
317 setOperationAction(ISD::FROUND, MVT::f16, Promote);
318 setOperationAction(ISD::FTRUNC, MVT::f16, Promote);
319 setOperationAction(ISD::FMINNUM, MVT::f16, Promote);
320 setOperationAction(ISD::FMAXNUM, MVT::f16, Promote);
Oliver Stannardf5469be2014-08-18 14:22:39 +0000321
Oliver Stannard89d15422014-08-27 16:16:04 +0000322 // v4f16 is also a storage-only type, so promote it to v4f32 when that is
323 // known to be safe.
324 setOperationAction(ISD::FADD, MVT::v4f16, Promote);
325 setOperationAction(ISD::FSUB, MVT::v4f16, Promote);
326 setOperationAction(ISD::FMUL, MVT::v4f16, Promote);
327 setOperationAction(ISD::FDIV, MVT::v4f16, Promote);
328 setOperationAction(ISD::FP_EXTEND, MVT::v4f16, Promote);
329 setOperationAction(ISD::FP_ROUND, MVT::v4f16, Promote);
330 AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32);
331 AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32);
332 AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32);
333 AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32);
334 AddPromotedToType(ISD::FP_EXTEND, MVT::v4f16, MVT::v4f32);
335 AddPromotedToType(ISD::FP_ROUND, MVT::v4f16, MVT::v4f32);
336
337 // Expand all other v4f16 operations.
338 // FIXME: We could generate better code by promoting some operations to
339 // a pair of v4f32s
340 setOperationAction(ISD::FABS, MVT::v4f16, Expand);
341 setOperationAction(ISD::FCEIL, MVT::v4f16, Expand);
342 setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand);
343 setOperationAction(ISD::FCOS, MVT::v4f16, Expand);
344 setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand);
345 setOperationAction(ISD::FMA, MVT::v4f16, Expand);
346 setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand);
347 setOperationAction(ISD::FNEG, MVT::v4f16, Expand);
348 setOperationAction(ISD::FPOW, MVT::v4f16, Expand);
349 setOperationAction(ISD::FPOWI, MVT::v4f16, Expand);
350 setOperationAction(ISD::FREM, MVT::v4f16, Expand);
351 setOperationAction(ISD::FROUND, MVT::v4f16, Expand);
352 setOperationAction(ISD::FRINT, MVT::v4f16, Expand);
353 setOperationAction(ISD::FSIN, MVT::v4f16, Expand);
354 setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand);
355 setOperationAction(ISD::FSQRT, MVT::v4f16, Expand);
356 setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand);
357 setOperationAction(ISD::SETCC, MVT::v4f16, Expand);
358 setOperationAction(ISD::BR_CC, MVT::v4f16, Expand);
359 setOperationAction(ISD::SELECT, MVT::v4f16, Expand);
360 setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand);
361 setOperationAction(ISD::FEXP, MVT::v4f16, Expand);
362 setOperationAction(ISD::FEXP2, MVT::v4f16, Expand);
363 setOperationAction(ISD::FLOG, MVT::v4f16, Expand);
364 setOperationAction(ISD::FLOG2, MVT::v4f16, Expand);
365 setOperationAction(ISD::FLOG10, MVT::v4f16, Expand);
366
367
368 // v8f16 is also a storage-only type, so expand it.
369 setOperationAction(ISD::FABS, MVT::v8f16, Expand);
370 setOperationAction(ISD::FADD, MVT::v8f16, Expand);
371 setOperationAction(ISD::FCEIL, MVT::v8f16, Expand);
372 setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand);
373 setOperationAction(ISD::FCOS, MVT::v8f16, Expand);
374 setOperationAction(ISD::FDIV, MVT::v8f16, Expand);
375 setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand);
376 setOperationAction(ISD::FMA, MVT::v8f16, Expand);
377 setOperationAction(ISD::FMUL, MVT::v8f16, Expand);
378 setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand);
379 setOperationAction(ISD::FNEG, MVT::v8f16, Expand);
380 setOperationAction(ISD::FPOW, MVT::v8f16, Expand);
381 setOperationAction(ISD::FPOWI, MVT::v8f16, Expand);
382 setOperationAction(ISD::FREM, MVT::v8f16, Expand);
383 setOperationAction(ISD::FROUND, MVT::v8f16, Expand);
384 setOperationAction(ISD::FRINT, MVT::v8f16, Expand);
385 setOperationAction(ISD::FSIN, MVT::v8f16, Expand);
386 setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
387 setOperationAction(ISD::FSQRT, MVT::v8f16, Expand);
388 setOperationAction(ISD::FSUB, MVT::v8f16, Expand);
389 setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand);
390 setOperationAction(ISD::SETCC, MVT::v8f16, Expand);
391 setOperationAction(ISD::BR_CC, MVT::v8f16, Expand);
392 setOperationAction(ISD::SELECT, MVT::v8f16, Expand);
393 setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand);
394 setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand);
395 setOperationAction(ISD::FEXP, MVT::v8f16, Expand);
396 setOperationAction(ISD::FEXP2, MVT::v8f16, Expand);
397 setOperationAction(ISD::FLOG, MVT::v8f16, Expand);
398 setOperationAction(ISD::FLOG2, MVT::v8f16, Expand);
399 setOperationAction(ISD::FLOG10, MVT::v8f16, Expand);
400
Tim Northover3b0846e2014-05-24 12:50:23 +0000401 // AArch64 has implementations of a lot of rounding-like FP operations.
Benjamin Kramer57a3d082015-03-08 16:07:39 +0000402 for (MVT Ty : {MVT::f32, MVT::f64}) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000403 setOperationAction(ISD::FFLOOR, Ty, Legal);
404 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
405 setOperationAction(ISD::FCEIL, Ty, Legal);
406 setOperationAction(ISD::FRINT, Ty, Legal);
407 setOperationAction(ISD::FTRUNC, Ty, Legal);
408 setOperationAction(ISD::FROUND, Ty, Legal);
409 }
410
411 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
412
413 if (Subtarget->isTargetMachO()) {
414 // For iOS, we don't want to the normal expansion of a libcall to
415 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
416 // traffic.
417 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
418 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
419 } else {
420 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
421 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
422 }
423
Juergen Ributzka23266502014-12-10 19:43:32 +0000424 // Make floating-point constants legal for the large code model, so they don't
425 // become loads from the constant pool.
426 if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
427 setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
428 setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
429 }
430
Tim Northover3b0846e2014-05-24 12:50:23 +0000431 // AArch64 does not have floating-point extending loads, i1 sign-extending
432 // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000433 for (MVT VT : MVT::fp_valuetypes()) {
434 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
435 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
436 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
437 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
438 }
439 for (MVT VT : MVT::integer_valuetypes())
440 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
441
Tim Northover3b0846e2014-05-24 12:50:23 +0000442 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
443 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
444 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
445 setTruncStoreAction(MVT::f128, MVT::f80, Expand);
446 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
447 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
448 setTruncStoreAction(MVT::f128, MVT::f16, Expand);
Tim Northoverf8bfe212014-07-18 13:07:05 +0000449
450 setOperationAction(ISD::BITCAST, MVT::i16, Custom);
451 setOperationAction(ISD::BITCAST, MVT::f16, Custom);
452
Tim Northover3b0846e2014-05-24 12:50:23 +0000453 // Indexed loads and stores are supported.
454 for (unsigned im = (unsigned)ISD::PRE_INC;
455 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
456 setIndexedLoadAction(im, MVT::i8, Legal);
457 setIndexedLoadAction(im, MVT::i16, Legal);
458 setIndexedLoadAction(im, MVT::i32, Legal);
459 setIndexedLoadAction(im, MVT::i64, Legal);
460 setIndexedLoadAction(im, MVT::f64, Legal);
461 setIndexedLoadAction(im, MVT::f32, Legal);
462 setIndexedStoreAction(im, MVT::i8, Legal);
463 setIndexedStoreAction(im, MVT::i16, Legal);
464 setIndexedStoreAction(im, MVT::i32, Legal);
465 setIndexedStoreAction(im, MVT::i64, Legal);
466 setIndexedStoreAction(im, MVT::f64, Legal);
467 setIndexedStoreAction(im, MVT::f32, Legal);
468 }
469
470 // Trap.
471 setOperationAction(ISD::TRAP, MVT::Other, Legal);
472
473 // We combine OR nodes for bitfield operations.
474 setTargetDAGCombine(ISD::OR);
475
476 // Vector add and sub nodes may conceal a high-half opportunity.
477 // Also, try to fold ADD into CSINC/CSINV..
478 setTargetDAGCombine(ISD::ADD);
479 setTargetDAGCombine(ISD::SUB);
480
481 setTargetDAGCombine(ISD::XOR);
482 setTargetDAGCombine(ISD::SINT_TO_FP);
483 setTargetDAGCombine(ISD::UINT_TO_FP);
484
485 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
486
487 setTargetDAGCombine(ISD::ANY_EXTEND);
488 setTargetDAGCombine(ISD::ZERO_EXTEND);
489 setTargetDAGCombine(ISD::SIGN_EXTEND);
490 setTargetDAGCombine(ISD::BITCAST);
491 setTargetDAGCombine(ISD::CONCAT_VECTORS);
492 setTargetDAGCombine(ISD::STORE);
493
494 setTargetDAGCombine(ISD::MUL);
495
496 setTargetDAGCombine(ISD::SELECT);
497 setTargetDAGCombine(ISD::VSELECT);
Artyom Skrobova70dfe12015-05-14 12:59:46 +0000498 setTargetDAGCombine(ISD::SELECT_CC);
Tim Northover3b0846e2014-05-24 12:50:23 +0000499
500 setTargetDAGCombine(ISD::INTRINSIC_VOID);
501 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
502 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
503
504 MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 8;
505 MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 4;
506 MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = 4;
507
508 setStackPointerRegisterToSaveRestore(AArch64::SP);
509
510 setSchedulingPreference(Sched::Hybrid);
511
512 // Enable TBZ/TBNZ
513 MaskAndBranchFoldingIsLegal = true;
Quentin Colombet6843ac42015-03-31 20:52:32 +0000514 EnableExtLdPromotion = true;
Tim Northover3b0846e2014-05-24 12:50:23 +0000515
516 setMinFunctionAlignment(2);
517
518 RequireStrictAlign = (Align == StrictAlign);
519
520 setHasExtractBitsInsn(true);
521
522 if (Subtarget->hasNEON()) {
523 // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
524 // silliness like this:
525 setOperationAction(ISD::FABS, MVT::v1f64, Expand);
526 setOperationAction(ISD::FADD, MVT::v1f64, Expand);
527 setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
528 setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
529 setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
530 setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
531 setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
532 setOperationAction(ISD::FMA, MVT::v1f64, Expand);
533 setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
534 setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
535 setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
536 setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
537 setOperationAction(ISD::FREM, MVT::v1f64, Expand);
538 setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
539 setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
540 setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
541 setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
542 setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
543 setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
544 setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
545 setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
546 setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
547 setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
548 setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
549 setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
550
551 setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
552 setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
553 setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
554 setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
555 setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
556
557 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
558
559 // AArch64 doesn't have a direct vector ->f32 conversion instructions for
560 // elements smaller than i32, so promote the input to i32 first.
561 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Promote);
562 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Promote);
563 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Promote);
564 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Promote);
Pirama Arumuga Nainarb1881532015-04-23 17:16:27 +0000565 // i8 and i16 vector elements also need promotion to i32 for v8i8 or v8i16
566 // -> v8f16 conversions.
567 setOperationAction(ISD::SINT_TO_FP, MVT::v8i8, Promote);
568 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Promote);
569 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
570 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Promote);
Tim Northover3b0846e2014-05-24 12:50:23 +0000571 // Similarly, there is no direct i32 -> f64 vector conversion instruction.
572 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
573 setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
574 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
575 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
Pirama Arumuga Nainarb1881532015-04-23 17:16:27 +0000576 // Or, direct i32 -> f16 vector conversion. Set it so custom, so the
577 // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
578 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
579 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000580
581 // AArch64 doesn't have MUL.2d:
582 setOperationAction(ISD::MUL, MVT::v2i64, Expand);
Chad Rosierd9d0f862014-10-08 02:31:24 +0000583 // Custom handling for some quad-vector types to detect MULL.
584 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
585 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
586 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
587
Tim Northover3b0846e2014-05-24 12:50:23 +0000588 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
589 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
590 // Likewise, narrowing and extending vector loads/stores aren't handled
591 // directly.
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000592 for (MVT VT : MVT::vector_valuetypes()) {
593 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000594
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000595 setOperationAction(ISD::MULHS, VT, Expand);
596 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
597 setOperationAction(ISD::MULHU, VT, Expand);
598 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000599
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000600 setOperationAction(ISD::BSWAP, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000601
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000602 for (MVT InnerVT : MVT::vector_valuetypes()) {
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000603 setTruncStoreAction(VT, InnerVT, Expand);
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000604 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
605 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
606 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
607 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000608 }
609
610 // AArch64 has implementations of a lot of rounding-like FP operations.
Benjamin Kramer57a3d082015-03-08 16:07:39 +0000611 for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000612 setOperationAction(ISD::FFLOOR, Ty, Legal);
613 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
614 setOperationAction(ISD::FCEIL, Ty, Legal);
615 setOperationAction(ISD::FRINT, Ty, Legal);
616 setOperationAction(ISD::FTRUNC, Ty, Legal);
617 setOperationAction(ISD::FROUND, Ty, Legal);
618 }
619 }
James Molloyf089ab72014-08-06 10:42:18 +0000620
621 // Prefer likely predicted branches to selects on out-of-order cores.
622 if (Subtarget->isCortexA57())
623 PredictableSelectIsExpensive = true;
Tim Northover3b0846e2014-05-24 12:50:23 +0000624}
625
626void AArch64TargetLowering::addTypeForNEON(EVT VT, EVT PromotedBitwiseVT) {
Jiangning Liu08f4cda2014-08-29 01:31:42 +0000627 if (VT == MVT::v2f32 || VT == MVT::v4f16) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000628 setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
629 AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i32);
630
631 setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
632 AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i32);
Jiangning Liu08f4cda2014-08-29 01:31:42 +0000633 } else if (VT == MVT::v2f64 || VT == MVT::v4f32 || VT == MVT::v8f16) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000634 setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
635 AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i64);
636
637 setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
638 AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i64);
639 }
640
641 // Mark vector float intrinsics as expand.
642 if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
643 setOperationAction(ISD::FSIN, VT.getSimpleVT(), Expand);
644 setOperationAction(ISD::FCOS, VT.getSimpleVT(), Expand);
645 setOperationAction(ISD::FPOWI, VT.getSimpleVT(), Expand);
646 setOperationAction(ISD::FPOW, VT.getSimpleVT(), Expand);
647 setOperationAction(ISD::FLOG, VT.getSimpleVT(), Expand);
648 setOperationAction(ISD::FLOG2, VT.getSimpleVT(), Expand);
649 setOperationAction(ISD::FLOG10, VT.getSimpleVT(), Expand);
650 setOperationAction(ISD::FEXP, VT.getSimpleVT(), Expand);
651 setOperationAction(ISD::FEXP2, VT.getSimpleVT(), Expand);
652 }
653
654 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT.getSimpleVT(), Custom);
655 setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getSimpleVT(), Custom);
656 setOperationAction(ISD::BUILD_VECTOR, VT.getSimpleVT(), Custom);
657 setOperationAction(ISD::VECTOR_SHUFFLE, VT.getSimpleVT(), Custom);
658 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT.getSimpleVT(), Custom);
659 setOperationAction(ISD::SRA, VT.getSimpleVT(), Custom);
660 setOperationAction(ISD::SRL, VT.getSimpleVT(), Custom);
661 setOperationAction(ISD::SHL, VT.getSimpleVT(), Custom);
662 setOperationAction(ISD::AND, VT.getSimpleVT(), Custom);
663 setOperationAction(ISD::OR, VT.getSimpleVT(), Custom);
664 setOperationAction(ISD::SETCC, VT.getSimpleVT(), Custom);
665 setOperationAction(ISD::CONCAT_VECTORS, VT.getSimpleVT(), Legal);
666
667 setOperationAction(ISD::SELECT, VT.getSimpleVT(), Expand);
668 setOperationAction(ISD::SELECT_CC, VT.getSimpleVT(), Expand);
669 setOperationAction(ISD::VSELECT, VT.getSimpleVT(), Expand);
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000670 for (MVT InnerVT : MVT::all_valuetypes())
671 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT.getSimpleVT(), Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000672
673 // CNT supports only B element sizes.
674 if (VT != MVT::v8i8 && VT != MVT::v16i8)
675 setOperationAction(ISD::CTPOP, VT.getSimpleVT(), Expand);
676
677 setOperationAction(ISD::UDIV, VT.getSimpleVT(), Expand);
678 setOperationAction(ISD::SDIV, VT.getSimpleVT(), Expand);
679 setOperationAction(ISD::UREM, VT.getSimpleVT(), Expand);
680 setOperationAction(ISD::SREM, VT.getSimpleVT(), Expand);
681 setOperationAction(ISD::FREM, VT.getSimpleVT(), Expand);
682
683 setOperationAction(ISD::FP_TO_SINT, VT.getSimpleVT(), Custom);
684 setOperationAction(ISD::FP_TO_UINT, VT.getSimpleVT(), Custom);
685
James Molloycfb04432015-05-15 16:15:57 +0000686 // [SU][MIN|MAX] are available for all NEON types apart from i64.
687 if (!VT.isFloatingPoint() &&
688 VT.getSimpleVT() != MVT::v2i64 && VT.getSimpleVT() != MVT::v1i64)
689 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
690 setOperationAction(Opcode, VT.getSimpleVT(), Legal);
691
Tim Northover3b0846e2014-05-24 12:50:23 +0000692 if (Subtarget->isLittleEndian()) {
693 for (unsigned im = (unsigned)ISD::PRE_INC;
694 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
695 setIndexedLoadAction(im, VT.getSimpleVT(), Legal);
696 setIndexedStoreAction(im, VT.getSimpleVT(), Legal);
697 }
698 }
699}
700
701void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
702 addRegisterClass(VT, &AArch64::FPR64RegClass);
703 addTypeForNEON(VT, MVT::v2i32);
704}
705
706void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
707 addRegisterClass(VT, &AArch64::FPR128RegClass);
708 addTypeForNEON(VT, MVT::v4i32);
709}
710
Mehdi Amini44ede332015-07-09 02:09:04 +0000711EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
712 EVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +0000713 if (!VT.isVector())
714 return MVT::i32;
715 return VT.changeVectorElementTypeToInteger();
716}
717
718/// computeKnownBitsForTargetNode - Determine which of the bits specified in
719/// Mask are known to be either zero or one and return them in the
720/// KnownZero/KnownOne bitsets.
721void AArch64TargetLowering::computeKnownBitsForTargetNode(
722 const SDValue Op, APInt &KnownZero, APInt &KnownOne,
723 const SelectionDAG &DAG, unsigned Depth) const {
724 switch (Op.getOpcode()) {
725 default:
726 break;
727 case AArch64ISD::CSEL: {
728 APInt KnownZero2, KnownOne2;
729 DAG.computeKnownBits(Op->getOperand(0), KnownZero, KnownOne, Depth + 1);
730 DAG.computeKnownBits(Op->getOperand(1), KnownZero2, KnownOne2, Depth + 1);
731 KnownZero &= KnownZero2;
732 KnownOne &= KnownOne2;
733 break;
734 }
735 case ISD::INTRINSIC_W_CHAIN: {
736 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
737 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
738 switch (IntID) {
739 default: return;
740 case Intrinsic::aarch64_ldaxr:
741 case Intrinsic::aarch64_ldxr: {
742 unsigned BitWidth = KnownOne.getBitWidth();
743 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
744 unsigned MemBits = VT.getScalarType().getSizeInBits();
745 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
746 return;
747 }
748 }
749 break;
750 }
751 case ISD::INTRINSIC_WO_CHAIN:
752 case ISD::INTRINSIC_VOID: {
753 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
754 switch (IntNo) {
755 default:
756 break;
757 case Intrinsic::aarch64_neon_umaxv:
758 case Intrinsic::aarch64_neon_uminv: {
759 // Figure out the datatype of the vector operand. The UMINV instruction
760 // will zero extend the result, so we can mark as known zero all the
761 // bits larger than the element datatype. 32-bit or larget doesn't need
762 // this as those are legal types and will be handled by isel directly.
763 MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
764 unsigned BitWidth = KnownZero.getBitWidth();
765 if (VT == MVT::v8i8 || VT == MVT::v16i8) {
766 assert(BitWidth >= 8 && "Unexpected width!");
767 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
768 KnownZero |= Mask;
769 } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
770 assert(BitWidth >= 16 && "Unexpected width!");
771 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
772 KnownZero |= Mask;
773 }
774 break;
775 } break;
776 }
777 }
778 }
779}
780
Mehdi Aminieaabc512015-07-09 15:12:23 +0000781MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
782 EVT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +0000783 return MVT::i64;
784}
785
Tim Northover3b0846e2014-05-24 12:50:23 +0000786FastISel *
787AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
788 const TargetLibraryInfo *libInfo) const {
789 return AArch64::createFastISel(funcInfo, libInfo);
790}
791
792const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
Matthias Braund04893f2015-05-07 21:33:59 +0000793 switch ((AArch64ISD::NodeType)Opcode) {
794 case AArch64ISD::FIRST_NUMBER: break;
Tim Northover3b0846e2014-05-24 12:50:23 +0000795 case AArch64ISD::CALL: return "AArch64ISD::CALL";
796 case AArch64ISD::ADRP: return "AArch64ISD::ADRP";
797 case AArch64ISD::ADDlow: return "AArch64ISD::ADDlow";
798 case AArch64ISD::LOADgot: return "AArch64ISD::LOADgot";
799 case AArch64ISD::RET_FLAG: return "AArch64ISD::RET_FLAG";
800 case AArch64ISD::BRCOND: return "AArch64ISD::BRCOND";
801 case AArch64ISD::CSEL: return "AArch64ISD::CSEL";
802 case AArch64ISD::FCSEL: return "AArch64ISD::FCSEL";
803 case AArch64ISD::CSINV: return "AArch64ISD::CSINV";
804 case AArch64ISD::CSNEG: return "AArch64ISD::CSNEG";
805 case AArch64ISD::CSINC: return "AArch64ISD::CSINC";
806 case AArch64ISD::THREAD_POINTER: return "AArch64ISD::THREAD_POINTER";
Kristof Beylsaea84612015-03-04 09:12:08 +0000807 case AArch64ISD::TLSDESC_CALLSEQ: return "AArch64ISD::TLSDESC_CALLSEQ";
Tim Northover3b0846e2014-05-24 12:50:23 +0000808 case AArch64ISD::ADC: return "AArch64ISD::ADC";
809 case AArch64ISD::SBC: return "AArch64ISD::SBC";
810 case AArch64ISD::ADDS: return "AArch64ISD::ADDS";
811 case AArch64ISD::SUBS: return "AArch64ISD::SUBS";
812 case AArch64ISD::ADCS: return "AArch64ISD::ADCS";
813 case AArch64ISD::SBCS: return "AArch64ISD::SBCS";
814 case AArch64ISD::ANDS: return "AArch64ISD::ANDS";
Matthias Braunaf7d7702015-07-16 20:02:37 +0000815 case AArch64ISD::CCMP: return "AArch64ISD::CCMP";
816 case AArch64ISD::CCMN: return "AArch64ISD::CCMN";
817 case AArch64ISD::FCCMP: return "AArch64ISD::FCCMP";
Tim Northover3b0846e2014-05-24 12:50:23 +0000818 case AArch64ISD::FCMP: return "AArch64ISD::FCMP";
819 case AArch64ISD::FMIN: return "AArch64ISD::FMIN";
820 case AArch64ISD::FMAX: return "AArch64ISD::FMAX";
821 case AArch64ISD::DUP: return "AArch64ISD::DUP";
822 case AArch64ISD::DUPLANE8: return "AArch64ISD::DUPLANE8";
823 case AArch64ISD::DUPLANE16: return "AArch64ISD::DUPLANE16";
824 case AArch64ISD::DUPLANE32: return "AArch64ISD::DUPLANE32";
825 case AArch64ISD::DUPLANE64: return "AArch64ISD::DUPLANE64";
826 case AArch64ISD::MOVI: return "AArch64ISD::MOVI";
827 case AArch64ISD::MOVIshift: return "AArch64ISD::MOVIshift";
828 case AArch64ISD::MOVIedit: return "AArch64ISD::MOVIedit";
829 case AArch64ISD::MOVImsl: return "AArch64ISD::MOVImsl";
830 case AArch64ISD::FMOV: return "AArch64ISD::FMOV";
831 case AArch64ISD::MVNIshift: return "AArch64ISD::MVNIshift";
832 case AArch64ISD::MVNImsl: return "AArch64ISD::MVNImsl";
833 case AArch64ISD::BICi: return "AArch64ISD::BICi";
834 case AArch64ISD::ORRi: return "AArch64ISD::ORRi";
835 case AArch64ISD::BSL: return "AArch64ISD::BSL";
836 case AArch64ISD::NEG: return "AArch64ISD::NEG";
837 case AArch64ISD::EXTR: return "AArch64ISD::EXTR";
838 case AArch64ISD::ZIP1: return "AArch64ISD::ZIP1";
839 case AArch64ISD::ZIP2: return "AArch64ISD::ZIP2";
840 case AArch64ISD::UZP1: return "AArch64ISD::UZP1";
841 case AArch64ISD::UZP2: return "AArch64ISD::UZP2";
842 case AArch64ISD::TRN1: return "AArch64ISD::TRN1";
843 case AArch64ISD::TRN2: return "AArch64ISD::TRN2";
844 case AArch64ISD::REV16: return "AArch64ISD::REV16";
845 case AArch64ISD::REV32: return "AArch64ISD::REV32";
846 case AArch64ISD::REV64: return "AArch64ISD::REV64";
847 case AArch64ISD::EXT: return "AArch64ISD::EXT";
848 case AArch64ISD::VSHL: return "AArch64ISD::VSHL";
849 case AArch64ISD::VLSHR: return "AArch64ISD::VLSHR";
850 case AArch64ISD::VASHR: return "AArch64ISD::VASHR";
851 case AArch64ISD::CMEQ: return "AArch64ISD::CMEQ";
852 case AArch64ISD::CMGE: return "AArch64ISD::CMGE";
853 case AArch64ISD::CMGT: return "AArch64ISD::CMGT";
854 case AArch64ISD::CMHI: return "AArch64ISD::CMHI";
855 case AArch64ISD::CMHS: return "AArch64ISD::CMHS";
856 case AArch64ISD::FCMEQ: return "AArch64ISD::FCMEQ";
857 case AArch64ISD::FCMGE: return "AArch64ISD::FCMGE";
858 case AArch64ISD::FCMGT: return "AArch64ISD::FCMGT";
859 case AArch64ISD::CMEQz: return "AArch64ISD::CMEQz";
860 case AArch64ISD::CMGEz: return "AArch64ISD::CMGEz";
861 case AArch64ISD::CMGTz: return "AArch64ISD::CMGTz";
862 case AArch64ISD::CMLEz: return "AArch64ISD::CMLEz";
863 case AArch64ISD::CMLTz: return "AArch64ISD::CMLTz";
864 case AArch64ISD::FCMEQz: return "AArch64ISD::FCMEQz";
865 case AArch64ISD::FCMGEz: return "AArch64ISD::FCMGEz";
866 case AArch64ISD::FCMGTz: return "AArch64ISD::FCMGTz";
867 case AArch64ISD::FCMLEz: return "AArch64ISD::FCMLEz";
868 case AArch64ISD::FCMLTz: return "AArch64ISD::FCMLTz";
Ahmed Bougachafab58922015-03-10 20:45:38 +0000869 case AArch64ISD::SADDV: return "AArch64ISD::SADDV";
870 case AArch64ISD::UADDV: return "AArch64ISD::UADDV";
871 case AArch64ISD::SMINV: return "AArch64ISD::SMINV";
872 case AArch64ISD::UMINV: return "AArch64ISD::UMINV";
873 case AArch64ISD::SMAXV: return "AArch64ISD::SMAXV";
874 case AArch64ISD::UMAXV: return "AArch64ISD::UMAXV";
Tim Northover3b0846e2014-05-24 12:50:23 +0000875 case AArch64ISD::NOT: return "AArch64ISD::NOT";
876 case AArch64ISD::BIT: return "AArch64ISD::BIT";
877 case AArch64ISD::CBZ: return "AArch64ISD::CBZ";
878 case AArch64ISD::CBNZ: return "AArch64ISD::CBNZ";
879 case AArch64ISD::TBZ: return "AArch64ISD::TBZ";
880 case AArch64ISD::TBNZ: return "AArch64ISD::TBNZ";
881 case AArch64ISD::TC_RETURN: return "AArch64ISD::TC_RETURN";
Matthias Braund04893f2015-05-07 21:33:59 +0000882 case AArch64ISD::PREFETCH: return "AArch64ISD::PREFETCH";
Tim Northover3b0846e2014-05-24 12:50:23 +0000883 case AArch64ISD::SITOF: return "AArch64ISD::SITOF";
884 case AArch64ISD::UITOF: return "AArch64ISD::UITOF";
Asiri Rathnayake530b3ed2014-10-01 09:59:45 +0000885 case AArch64ISD::NVCAST: return "AArch64ISD::NVCAST";
Tim Northover3b0846e2014-05-24 12:50:23 +0000886 case AArch64ISD::SQSHL_I: return "AArch64ISD::SQSHL_I";
887 case AArch64ISD::UQSHL_I: return "AArch64ISD::UQSHL_I";
888 case AArch64ISD::SRSHR_I: return "AArch64ISD::SRSHR_I";
889 case AArch64ISD::URSHR_I: return "AArch64ISD::URSHR_I";
890 case AArch64ISD::SQSHLU_I: return "AArch64ISD::SQSHLU_I";
891 case AArch64ISD::WrapperLarge: return "AArch64ISD::WrapperLarge";
892 case AArch64ISD::LD2post: return "AArch64ISD::LD2post";
893 case AArch64ISD::LD3post: return "AArch64ISD::LD3post";
894 case AArch64ISD::LD4post: return "AArch64ISD::LD4post";
895 case AArch64ISD::ST2post: return "AArch64ISD::ST2post";
896 case AArch64ISD::ST3post: return "AArch64ISD::ST3post";
897 case AArch64ISD::ST4post: return "AArch64ISD::ST4post";
898 case AArch64ISD::LD1x2post: return "AArch64ISD::LD1x2post";
899 case AArch64ISD::LD1x3post: return "AArch64ISD::LD1x3post";
900 case AArch64ISD::LD1x4post: return "AArch64ISD::LD1x4post";
901 case AArch64ISD::ST1x2post: return "AArch64ISD::ST1x2post";
902 case AArch64ISD::ST1x3post: return "AArch64ISD::ST1x3post";
903 case AArch64ISD::ST1x4post: return "AArch64ISD::ST1x4post";
904 case AArch64ISD::LD1DUPpost: return "AArch64ISD::LD1DUPpost";
905 case AArch64ISD::LD2DUPpost: return "AArch64ISD::LD2DUPpost";
906 case AArch64ISD::LD3DUPpost: return "AArch64ISD::LD3DUPpost";
907 case AArch64ISD::LD4DUPpost: return "AArch64ISD::LD4DUPpost";
908 case AArch64ISD::LD1LANEpost: return "AArch64ISD::LD1LANEpost";
909 case AArch64ISD::LD2LANEpost: return "AArch64ISD::LD2LANEpost";
910 case AArch64ISD::LD3LANEpost: return "AArch64ISD::LD3LANEpost";
911 case AArch64ISD::LD4LANEpost: return "AArch64ISD::LD4LANEpost";
912 case AArch64ISD::ST2LANEpost: return "AArch64ISD::ST2LANEpost";
913 case AArch64ISD::ST3LANEpost: return "AArch64ISD::ST3LANEpost";
914 case AArch64ISD::ST4LANEpost: return "AArch64ISD::ST4LANEpost";
Chad Rosierd9d0f862014-10-08 02:31:24 +0000915 case AArch64ISD::SMULL: return "AArch64ISD::SMULL";
916 case AArch64ISD::UMULL: return "AArch64ISD::UMULL";
Tim Northover3b0846e2014-05-24 12:50:23 +0000917 }
Matthias Braund04893f2015-05-07 21:33:59 +0000918 return nullptr;
Tim Northover3b0846e2014-05-24 12:50:23 +0000919}
920
921MachineBasicBlock *
922AArch64TargetLowering::EmitF128CSEL(MachineInstr *MI,
923 MachineBasicBlock *MBB) const {
924 // We materialise the F128CSEL pseudo-instruction as some control flow and a
925 // phi node:
926
927 // OrigBB:
928 // [... previous instrs leading to comparison ...]
929 // b.ne TrueBB
930 // b EndBB
931 // TrueBB:
932 // ; Fallthrough
933 // EndBB:
934 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
935
Tim Northover3b0846e2014-05-24 12:50:23 +0000936 MachineFunction *MF = MBB->getParent();
Eric Christopher905f12d2015-01-29 00:19:42 +0000937 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +0000938 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
939 DebugLoc DL = MI->getDebugLoc();
940 MachineFunction::iterator It = MBB;
941 ++It;
942
943 unsigned DestReg = MI->getOperand(0).getReg();
944 unsigned IfTrueReg = MI->getOperand(1).getReg();
945 unsigned IfFalseReg = MI->getOperand(2).getReg();
946 unsigned CondCode = MI->getOperand(3).getImm();
947 bool NZCVKilled = MI->getOperand(4).isKill();
948
949 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
950 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
951 MF->insert(It, TrueBB);
952 MF->insert(It, EndBB);
953
954 // Transfer rest of current basic-block to EndBB
955 EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
956 MBB->end());
957 EndBB->transferSuccessorsAndUpdatePHIs(MBB);
958
959 BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
960 BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
961 MBB->addSuccessor(TrueBB);
962 MBB->addSuccessor(EndBB);
963
964 // TrueBB falls through to the end.
965 TrueBB->addSuccessor(EndBB);
966
967 if (!NZCVKilled) {
968 TrueBB->addLiveIn(AArch64::NZCV);
969 EndBB->addLiveIn(AArch64::NZCV);
970 }
971
972 BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
973 .addReg(IfTrueReg)
974 .addMBB(TrueBB)
975 .addReg(IfFalseReg)
976 .addMBB(MBB);
977
978 MI->eraseFromParent();
979 return EndBB;
980}
981
982MachineBasicBlock *
983AArch64TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
984 MachineBasicBlock *BB) const {
985 switch (MI->getOpcode()) {
986 default:
987#ifndef NDEBUG
988 MI->dump();
989#endif
Craig Topper35b2f752014-06-19 06:10:58 +0000990 llvm_unreachable("Unexpected instruction for custom inserter!");
Tim Northover3b0846e2014-05-24 12:50:23 +0000991
992 case AArch64::F128CSEL:
993 return EmitF128CSEL(MI, BB);
994
995 case TargetOpcode::STACKMAP:
996 case TargetOpcode::PATCHPOINT:
997 return emitPatchPoint(MI, BB);
998 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000999}
1000
1001//===----------------------------------------------------------------------===//
1002// AArch64 Lowering private implementation.
1003//===----------------------------------------------------------------------===//
1004
1005//===----------------------------------------------------------------------===//
1006// Lowering Code
1007//===----------------------------------------------------------------------===//
1008
1009/// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1010/// CC
1011static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1012 switch (CC) {
1013 default:
1014 llvm_unreachable("Unknown condition code!");
1015 case ISD::SETNE:
1016 return AArch64CC::NE;
1017 case ISD::SETEQ:
1018 return AArch64CC::EQ;
1019 case ISD::SETGT:
1020 return AArch64CC::GT;
1021 case ISD::SETGE:
1022 return AArch64CC::GE;
1023 case ISD::SETLT:
1024 return AArch64CC::LT;
1025 case ISD::SETLE:
1026 return AArch64CC::LE;
1027 case ISD::SETUGT:
1028 return AArch64CC::HI;
1029 case ISD::SETUGE:
1030 return AArch64CC::HS;
1031 case ISD::SETULT:
1032 return AArch64CC::LO;
1033 case ISD::SETULE:
1034 return AArch64CC::LS;
1035 }
1036}
1037
1038/// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1039static void changeFPCCToAArch64CC(ISD::CondCode CC,
1040 AArch64CC::CondCode &CondCode,
1041 AArch64CC::CondCode &CondCode2) {
1042 CondCode2 = AArch64CC::AL;
1043 switch (CC) {
1044 default:
1045 llvm_unreachable("Unknown FP condition!");
1046 case ISD::SETEQ:
1047 case ISD::SETOEQ:
1048 CondCode = AArch64CC::EQ;
1049 break;
1050 case ISD::SETGT:
1051 case ISD::SETOGT:
1052 CondCode = AArch64CC::GT;
1053 break;
1054 case ISD::SETGE:
1055 case ISD::SETOGE:
1056 CondCode = AArch64CC::GE;
1057 break;
1058 case ISD::SETOLT:
1059 CondCode = AArch64CC::MI;
1060 break;
1061 case ISD::SETOLE:
1062 CondCode = AArch64CC::LS;
1063 break;
1064 case ISD::SETONE:
1065 CondCode = AArch64CC::MI;
1066 CondCode2 = AArch64CC::GT;
1067 break;
1068 case ISD::SETO:
1069 CondCode = AArch64CC::VC;
1070 break;
1071 case ISD::SETUO:
1072 CondCode = AArch64CC::VS;
1073 break;
1074 case ISD::SETUEQ:
1075 CondCode = AArch64CC::EQ;
1076 CondCode2 = AArch64CC::VS;
1077 break;
1078 case ISD::SETUGT:
1079 CondCode = AArch64CC::HI;
1080 break;
1081 case ISD::SETUGE:
1082 CondCode = AArch64CC::PL;
1083 break;
1084 case ISD::SETLT:
1085 case ISD::SETULT:
1086 CondCode = AArch64CC::LT;
1087 break;
1088 case ISD::SETLE:
1089 case ISD::SETULE:
1090 CondCode = AArch64CC::LE;
1091 break;
1092 case ISD::SETNE:
1093 case ISD::SETUNE:
1094 CondCode = AArch64CC::NE;
1095 break;
1096 }
1097}
1098
1099/// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1100/// CC usable with the vector instructions. Fewer operations are available
1101/// without a real NZCV register, so we have to use less efficient combinations
1102/// to get the same effect.
1103static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1104 AArch64CC::CondCode &CondCode,
1105 AArch64CC::CondCode &CondCode2,
1106 bool &Invert) {
1107 Invert = false;
1108 switch (CC) {
1109 default:
1110 // Mostly the scalar mappings work fine.
1111 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1112 break;
1113 case ISD::SETUO:
1114 Invert = true; // Fallthrough
1115 case ISD::SETO:
1116 CondCode = AArch64CC::MI;
1117 CondCode2 = AArch64CC::GE;
1118 break;
1119 case ISD::SETUEQ:
1120 case ISD::SETULT:
1121 case ISD::SETULE:
1122 case ISD::SETUGT:
1123 case ISD::SETUGE:
1124 // All of the compare-mask comparisons are ordered, but we can switch
1125 // between the two by a double inversion. E.g. ULE == !OGT.
1126 Invert = true;
1127 changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1128 break;
1129 }
1130}
1131
1132static bool isLegalArithImmed(uint64_t C) {
1133 // Matches AArch64DAGToDAGISel::SelectArithImmed().
1134 return (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1135}
1136
1137static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1138 SDLoc dl, SelectionDAG &DAG) {
1139 EVT VT = LHS.getValueType();
1140
1141 if (VT.isFloatingPoint())
1142 return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
1143
1144 // The CMP instruction is just an alias for SUBS, and representing it as
1145 // SUBS means that it's possible to get CSE with subtract operations.
1146 // A later phase can perform the optimization of setting the destination
1147 // register to WZR/XZR if it ends up being unused.
1148 unsigned Opcode = AArch64ISD::SUBS;
1149
1150 if (RHS.getOpcode() == ISD::SUB && isa<ConstantSDNode>(RHS.getOperand(0)) &&
1151 cast<ConstantSDNode>(RHS.getOperand(0))->getZExtValue() == 0 &&
1152 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1153 // We'd like to combine a (CMP op1, (sub 0, op2) into a CMN instruction on
1154 // the grounds that "op1 - (-op2) == op1 + op2". However, the C and V flags
1155 // can be set differently by this operation. It comes down to whether
1156 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1157 // everything is fine. If not then the optimization is wrong. Thus general
1158 // comparisons are only valid if op2 != 0.
1159
1160 // So, finally, the only LLVM-native comparisons that don't mention C and V
1161 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1162 // the absence of information about op2.
1163 Opcode = AArch64ISD::ADDS;
1164 RHS = RHS.getOperand(1);
1165 } else if (LHS.getOpcode() == ISD::AND && isa<ConstantSDNode>(RHS) &&
1166 cast<ConstantSDNode>(RHS)->getZExtValue() == 0 &&
1167 !isUnsignedIntSetCC(CC)) {
1168 // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1169 // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1170 // of the signed comparisons.
1171 Opcode = AArch64ISD::ANDS;
1172 RHS = LHS.getOperand(1);
1173 LHS = LHS.getOperand(0);
1174 }
1175
Matthias Braunaf7d7702015-07-16 20:02:37 +00001176 return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
Tim Northover3b0846e2014-05-24 12:50:23 +00001177 .getValue(1);
1178}
1179
Matthias Braunaf7d7702015-07-16 20:02:37 +00001180/// \defgroup AArch64CCMP CMP;CCMP matching
1181///
1182/// These functions deal with the formation of CMP;CCMP;... sequences.
1183/// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1184/// a comparison. They set the NZCV flags to a predefined value if their
1185/// predicate is false. This allows to express arbitrary conjunctions, for
1186/// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B))))"
1187/// expressed as:
1188/// cmp A
1189/// ccmp B, inv(CB), CA
1190/// check for CB flags
1191///
1192/// In general we can create code for arbitrary "... (and (and A B) C)"
1193/// sequences. We can also implement some "or" expressions, because "(or A B)"
1194/// is equivalent to "not (and (not A) (not B))" and we can implement some
1195/// negation operations:
1196/// We can negate the results of a single comparison by inverting the flags
1197/// used when the predicate fails and inverting the flags tested in the next
1198/// instruction; We can also negate the results of the whole previous
1199/// conditional compare sequence by inverting the flags tested in the next
1200/// instruction. However there is no way to negate the result of a partial
1201/// sequence.
1202///
1203/// Therefore on encountering an "or" expression we can negate the subtree on
1204/// one side and have to be able to push the negate to the leafs of the subtree
1205/// on the other side (see also the comments in code). As complete example:
1206/// "or (or (setCA (cmp A)) (setCB (cmp B)))
1207/// (and (setCC (cmp C)) (setCD (cmp D)))"
1208/// is transformed to
1209/// "not (and (not (and (setCC (cmp C)) (setCC (cmp D))))
1210/// (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1211/// and implemented as:
1212/// cmp C
1213/// ccmp D, inv(CD), CC
1214/// ccmp A, CA, inv(CD)
1215/// ccmp B, CB, inv(CA)
1216/// check for CB flags
1217/// A counterexample is "or (and A B) (and C D)" which cannot be implemented
1218/// by conditional compare sequences.
1219/// @{
1220
1221/// Create a conditional comparison; Use CCMP, CCMN or FCCMP as apropriate.
1222static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1223 ISD::CondCode CC, SDValue CCOp,
1224 SDValue Condition, unsigned NZCV,
1225 SDLoc DL, SelectionDAG &DAG) {
1226 unsigned Opcode = 0;
1227 if (LHS.getValueType().isFloatingPoint())
1228 Opcode = AArch64ISD::FCCMP;
1229 else if (RHS.getOpcode() == ISD::SUB) {
1230 SDValue SubOp0 = RHS.getOperand(0);
1231 if (const ConstantSDNode *SubOp0C = dyn_cast<ConstantSDNode>(SubOp0))
1232 if (SubOp0C->isNullValue() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1233 // See emitComparison() on why we can only do this for SETEQ and SETNE.
1234 Opcode = AArch64ISD::CCMN;
1235 RHS = RHS.getOperand(1);
1236 }
1237 }
1238 if (Opcode == 0)
1239 Opcode = AArch64ISD::CCMP;
1240
1241 SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1242 return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1243}
1244
1245/// Returns true if @p Val is a tree of AND/OR/SETCC operations.
1246/// CanPushNegate is set to true if we can push a negate operation through
1247/// the tree in a was that we are left with AND operations and negate operations
1248/// at the leafs only. i.e. "not (or (or x y) z)" can be changed to
1249/// "and (and (not x) (not y)) (not z)"; "not (or (and x y) z)" cannot be
1250/// brought into such a form.
1251static bool isConjunctionDisjunctionTree(const SDValue Val, bool &CanPushNegate,
1252 unsigned Depth = 0) {
1253 if (!Val.hasOneUse())
1254 return false;
1255 unsigned Opcode = Val->getOpcode();
1256 if (Opcode == ISD::SETCC) {
1257 CanPushNegate = true;
1258 return true;
1259 }
1260 // Protect against stack overflow.
1261 if (Depth > 15)
1262 return false;
1263 if (Opcode == ISD::AND || Opcode == ISD::OR) {
1264 SDValue O0 = Val->getOperand(0);
1265 SDValue O1 = Val->getOperand(1);
1266 bool CanPushNegateL;
1267 if (!isConjunctionDisjunctionTree(O0, CanPushNegateL, Depth+1))
1268 return false;
1269 bool CanPushNegateR;
1270 if (!isConjunctionDisjunctionTree(O1, CanPushNegateR, Depth+1))
1271 return false;
1272 // We cannot push a negate through an AND operation (it would become an OR),
1273 // we can however change a (not (or x y)) to (and (not x) (not y)) if we can
1274 // push the negate through the x/y subtrees.
1275 CanPushNegate = (Opcode == ISD::OR) && CanPushNegateL && CanPushNegateR;
1276 return true;
1277 }
1278 return false;
1279}
1280
1281/// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1282/// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1283/// Tries to transform the given i1 producing node @p Val to a series compare
1284/// and conditional compare operations. @returns an NZCV flags producing node
1285/// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1286/// transformation was not possible.
1287/// On recursive invocations @p PushNegate may be set to true to have negation
1288/// effects pushed to the tree leafs; @p Predicate is an NZCV flag predicate
1289/// for the comparisons in the current subtree; @p Depth limits the search
1290/// depth to avoid stack overflow.
1291static SDValue emitConjunctionDisjunctionTree(SelectionDAG &DAG, SDValue Val,
1292 AArch64CC::CondCode &OutCC, bool PushNegate = false,
1293 SDValue CCOp = SDValue(), AArch64CC::CondCode Predicate = AArch64CC::AL,
1294 unsigned Depth = 0) {
1295 // We're at a tree leaf, produce a conditional comparison operation.
1296 unsigned Opcode = Val->getOpcode();
1297 if (Opcode == ISD::SETCC) {
1298 SDValue LHS = Val->getOperand(0);
1299 SDValue RHS = Val->getOperand(1);
1300 ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1301 bool isInteger = LHS.getValueType().isInteger();
1302 if (PushNegate)
1303 CC = getSetCCInverse(CC, isInteger);
1304 SDLoc DL(Val);
1305 // Determine OutCC and handle FP special case.
1306 if (isInteger) {
1307 OutCC = changeIntCCToAArch64CC(CC);
1308 } else {
1309 assert(LHS.getValueType().isFloatingPoint());
1310 AArch64CC::CondCode ExtraCC;
1311 changeFPCCToAArch64CC(CC, OutCC, ExtraCC);
1312 // Surpisingly some floating point conditions can't be tested with a
1313 // single condition code. Construct an additional comparison in this case.
1314 // See comment below on how we deal with OR conditions.
1315 if (ExtraCC != AArch64CC::AL) {
1316 SDValue ExtraCmp;
1317 if (!CCOp.getNode())
1318 ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
1319 else {
1320 SDValue ConditionOp = DAG.getConstant(Predicate, DL, MVT_CC);
1321 // Note that we want the inverse of ExtraCC, so NZCV is not inversed.
1322 unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(ExtraCC);
1323 ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, ConditionOp,
1324 NZCV, DL, DAG);
1325 }
1326 CCOp = ExtraCmp;
1327 Predicate = AArch64CC::getInvertedCondCode(ExtraCC);
1328 OutCC = AArch64CC::getInvertedCondCode(OutCC);
1329 }
1330 }
1331
1332 // Produce a normal comparison if we are first in the chain
1333 if (!CCOp.getNode())
1334 return emitComparison(LHS, RHS, CC, DL, DAG);
1335 // Otherwise produce a ccmp.
1336 SDValue ConditionOp = DAG.getConstant(Predicate, DL, MVT_CC);
1337 AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1338 unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
1339 return emitConditionalComparison(LHS, RHS, CC, CCOp, ConditionOp, NZCV, DL,
1340 DAG);
1341 } else if (Opcode != ISD::AND && Opcode != ISD::OR)
1342 return SDValue();
1343
1344 assert((Opcode == ISD::OR || !PushNegate)
1345 && "Can only push negate through OR operation");
1346
1347 // Check if both sides can be transformed.
1348 SDValue LHS = Val->getOperand(0);
1349 SDValue RHS = Val->getOperand(1);
1350 bool CanPushNegateL;
1351 if (!isConjunctionDisjunctionTree(LHS, CanPushNegateL, Depth+1))
1352 return SDValue();
1353 bool CanPushNegateR;
1354 if (!isConjunctionDisjunctionTree(RHS, CanPushNegateR, Depth+1))
1355 return SDValue();
1356
1357 // Do we need to negate our operands?
1358 bool NegateOperands = Opcode == ISD::OR;
1359 // We can negate the results of all previous operations by inverting the
1360 // predicate flags giving us a free negation for one side. For the other side
1361 // we need to be able to push the negation to the leafs of the tree.
1362 if (NegateOperands) {
1363 if (!CanPushNegateL && !CanPushNegateR)
1364 return SDValue();
1365 // Order the side where we can push the negate through to LHS.
1366 if (!CanPushNegateL && CanPushNegateR) {
1367 std::swap(LHS, RHS);
1368 CanPushNegateL = true;
1369 }
1370 }
1371
1372 // Emit RHS. If we want to negate the tree we only need to push a negate
1373 // through if we are already in a PushNegate case, otherwise we can negate
1374 // the "flags to test" afterwards.
1375 AArch64CC::CondCode RHSCC;
1376 SDValue CmpR = emitConjunctionDisjunctionTree(DAG, RHS, RHSCC, PushNegate,
1377 CCOp, Predicate, Depth+1);
1378 if (NegateOperands && !PushNegate)
1379 RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
1380 // Emit LHS. We must push the negate through if we need to negate it.
1381 SDValue CmpL = emitConjunctionDisjunctionTree(DAG, LHS, OutCC, NegateOperands,
1382 CmpR, RHSCC, Depth+1);
1383 // If we transformed an OR to and AND then we have to negate the result
1384 // (or absorb a PushNegate resulting in a double negation).
1385 if (Opcode == ISD::OR && !PushNegate)
1386 OutCC = AArch64CC::getInvertedCondCode(OutCC);
1387 return CmpL;
1388}
1389
1390/// @}
1391
Tim Northover3b0846e2014-05-24 12:50:23 +00001392static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1393 SDValue &AArch64cc, SelectionDAG &DAG, SDLoc dl) {
1394 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1395 EVT VT = RHS.getValueType();
1396 uint64_t C = RHSC->getZExtValue();
1397 if (!isLegalArithImmed(C)) {
1398 // Constant does not fit, try adjusting it by one?
1399 switch (CC) {
1400 default:
1401 break;
1402 case ISD::SETLT:
1403 case ISD::SETGE:
1404 if ((VT == MVT::i32 && C != 0x80000000 &&
1405 isLegalArithImmed((uint32_t)(C - 1))) ||
1406 (VT == MVT::i64 && C != 0x80000000ULL &&
1407 isLegalArithImmed(C - 1ULL))) {
1408 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1409 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001410 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001411 }
1412 break;
1413 case ISD::SETULT:
1414 case ISD::SETUGE:
1415 if ((VT == MVT::i32 && C != 0 &&
1416 isLegalArithImmed((uint32_t)(C - 1))) ||
1417 (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1418 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1419 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001420 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001421 }
1422 break;
1423 case ISD::SETLE:
1424 case ISD::SETGT:
Oliver Stannard269a275c2014-11-03 15:28:40 +00001425 if ((VT == MVT::i32 && C != INT32_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001426 isLegalArithImmed((uint32_t)(C + 1))) ||
Oliver Stannard269a275c2014-11-03 15:28:40 +00001427 (VT == MVT::i64 && C != INT64_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001428 isLegalArithImmed(C + 1ULL))) {
1429 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1430 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001431 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001432 }
1433 break;
1434 case ISD::SETULE:
1435 case ISD::SETUGT:
Oliver Stannard269a275c2014-11-03 15:28:40 +00001436 if ((VT == MVT::i32 && C != UINT32_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001437 isLegalArithImmed((uint32_t)(C + 1))) ||
Oliver Stannard269a275c2014-11-03 15:28:40 +00001438 (VT == MVT::i64 && C != UINT64_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001439 isLegalArithImmed(C + 1ULL))) {
1440 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1441 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001442 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001443 }
1444 break;
1445 }
1446 }
1447 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001448 SDValue Cmp;
1449 AArch64CC::CondCode AArch64CC;
David Xuee978202014-08-28 04:59:53 +00001450 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001451 const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
1452
1453 // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
1454 // For the i8 operand, the largest immediate is 255, so this can be easily
1455 // encoded in the compare instruction. For the i16 operand, however, the
1456 // largest immediate cannot be encoded in the compare.
1457 // Therefore, use a sign extending load and cmn to avoid materializing the
1458 // -1 constant. For example,
1459 // movz w1, #65535
1460 // ldrh w0, [x0, #0]
1461 // cmp w0, w1
1462 // >
1463 // ldrsh w0, [x0, #0]
1464 // cmn w0, #1
1465 // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
1466 // if and only if (sext LHS) == (sext RHS). The checks are in place to
1467 // ensure both the LHS and RHS are truely zero extended and to make sure the
1468 // transformation is profitable.
1469 if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
1470 cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
1471 cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
1472 LHS.getNode()->hasNUsesOfValue(1, 0)) {
1473 int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
1474 if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
1475 SDValue SExt =
1476 DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
1477 DAG.getValueType(MVT::i16));
1478 Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
1479 RHS.getValueType()),
1480 CC, dl, DAG);
1481 AArch64CC = changeIntCCToAArch64CC(CC);
1482 }
1483 }
1484
1485 if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
1486 if ((Cmp = emitConjunctionDisjunctionTree(DAG, LHS, AArch64CC))) {
1487 if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
1488 AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
David Xuee978202014-08-28 04:59:53 +00001489 }
1490 }
1491 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001492
1493 if (!Cmp) {
1494 Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
1495 AArch64CC = changeIntCCToAArch64CC(CC);
1496 }
1497 AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
Tim Northover3b0846e2014-05-24 12:50:23 +00001498 return Cmp;
1499}
1500
1501static std::pair<SDValue, SDValue>
1502getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
1503 assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
1504 "Unsupported value type");
1505 SDValue Value, Overflow;
1506 SDLoc DL(Op);
1507 SDValue LHS = Op.getOperand(0);
1508 SDValue RHS = Op.getOperand(1);
1509 unsigned Opc = 0;
1510 switch (Op.getOpcode()) {
1511 default:
1512 llvm_unreachable("Unknown overflow instruction!");
1513 case ISD::SADDO:
1514 Opc = AArch64ISD::ADDS;
1515 CC = AArch64CC::VS;
1516 break;
1517 case ISD::UADDO:
1518 Opc = AArch64ISD::ADDS;
1519 CC = AArch64CC::HS;
1520 break;
1521 case ISD::SSUBO:
1522 Opc = AArch64ISD::SUBS;
1523 CC = AArch64CC::VS;
1524 break;
1525 case ISD::USUBO:
1526 Opc = AArch64ISD::SUBS;
1527 CC = AArch64CC::LO;
1528 break;
1529 // Multiply needs a little bit extra work.
1530 case ISD::SMULO:
1531 case ISD::UMULO: {
1532 CC = AArch64CC::NE;
David Blaikie186d2cb2015-03-24 16:24:01 +00001533 bool IsSigned = Op.getOpcode() == ISD::SMULO;
Tim Northover3b0846e2014-05-24 12:50:23 +00001534 if (Op.getValueType() == MVT::i32) {
1535 unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1536 // For a 32 bit multiply with overflow check we want the instruction
1537 // selector to generate a widening multiply (SMADDL/UMADDL). For that we
1538 // need to generate the following pattern:
1539 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
1540 LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
1541 RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
1542 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1543 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001544 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001545 // On AArch64 the upper 32 bits are always zero extended for a 32 bit
1546 // operation. We need to clear out the upper 32 bits, because we used a
1547 // widening multiply that wrote all 64 bits. In the end this should be a
1548 // noop.
1549 Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
1550 if (IsSigned) {
1551 // The signed overflow check requires more than just a simple check for
1552 // any bit set in the upper 32 bits of the result. These bits could be
1553 // just the sign bits of a negative number. To perform the overflow
1554 // check we have to arithmetic shift right the 32nd bit of the result by
1555 // 31 bits. Then we compare the result to the upper 32 bits.
1556 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001557 DAG.getConstant(32, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001558 UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
1559 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001560 DAG.getConstant(31, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001561 // It is important that LowerBits is last, otherwise the arithmetic
1562 // shift will not be folded into the compare (SUBS).
1563 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
1564 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1565 .getValue(1);
1566 } else {
1567 // The overflow check for unsigned multiply is easy. We only need to
1568 // check if any of the upper 32 bits are set. This can be done with a
1569 // CMP (shifted register). For that we need to generate the following
1570 // pattern:
1571 // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
1572 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001573 DAG.getConstant(32, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001574 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1575 Overflow =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001576 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1577 DAG.getConstant(0, DL, MVT::i64),
Tim Northover3b0846e2014-05-24 12:50:23 +00001578 UpperBits).getValue(1);
1579 }
1580 break;
1581 }
1582 assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
1583 // For the 64 bit multiply
1584 Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1585 if (IsSigned) {
1586 SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
1587 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001588 DAG.getConstant(63, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001589 // It is important that LowerBits is last, otherwise the arithmetic
1590 // shift will not be folded into the compare (SUBS).
1591 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1592 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1593 .getValue(1);
1594 } else {
1595 SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
1596 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1597 Overflow =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001598 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1599 DAG.getConstant(0, DL, MVT::i64),
Tim Northover3b0846e2014-05-24 12:50:23 +00001600 UpperBits).getValue(1);
1601 }
1602 break;
1603 }
1604 } // switch (...)
1605
1606 if (Opc) {
1607 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
1608
1609 // Emit the AArch64 operation with overflow check.
1610 Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
1611 Overflow = Value.getValue(1);
1612 }
1613 return std::make_pair(Value, Overflow);
1614}
1615
1616SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
1617 RTLIB::Libcall Call) const {
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00001618 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
Tim Northover3b0846e2014-05-24 12:50:23 +00001619 return makeLibCall(DAG, Call, MVT::f128, &Ops[0], Ops.size(), false,
1620 SDLoc(Op)).first;
1621}
1622
1623static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
1624 SDValue Sel = Op.getOperand(0);
1625 SDValue Other = Op.getOperand(1);
1626
1627 // If neither operand is a SELECT_CC, give up.
1628 if (Sel.getOpcode() != ISD::SELECT_CC)
1629 std::swap(Sel, Other);
1630 if (Sel.getOpcode() != ISD::SELECT_CC)
1631 return Op;
1632
1633 // The folding we want to perform is:
1634 // (xor x, (select_cc a, b, cc, 0, -1) )
1635 // -->
1636 // (csel x, (xor x, -1), cc ...)
1637 //
1638 // The latter will get matched to a CSINV instruction.
1639
1640 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
1641 SDValue LHS = Sel.getOperand(0);
1642 SDValue RHS = Sel.getOperand(1);
1643 SDValue TVal = Sel.getOperand(2);
1644 SDValue FVal = Sel.getOperand(3);
1645 SDLoc dl(Sel);
1646
1647 // FIXME: This could be generalized to non-integer comparisons.
1648 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
1649 return Op;
1650
1651 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
1652 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
1653
Eric Christopher572e03a2015-06-19 01:53:21 +00001654 // The values aren't constants, this isn't the pattern we're looking for.
Tim Northover3b0846e2014-05-24 12:50:23 +00001655 if (!CFVal || !CTVal)
1656 return Op;
1657
1658 // We can commute the SELECT_CC by inverting the condition. This
1659 // might be needed to make this fit into a CSINV pattern.
1660 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
1661 std::swap(TVal, FVal);
1662 std::swap(CTVal, CFVal);
1663 CC = ISD::getSetCCInverse(CC, true);
1664 }
1665
1666 // If the constants line up, perform the transform!
1667 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
1668 SDValue CCVal;
1669 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
1670
1671 FVal = Other;
1672 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001673 DAG.getConstant(-1ULL, dl, Other.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00001674
1675 return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
1676 CCVal, Cmp);
1677 }
1678
1679 return Op;
1680}
1681
1682static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
1683 EVT VT = Op.getValueType();
1684
1685 // Let legalize expand this if it isn't a legal type yet.
1686 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
1687 return SDValue();
1688
1689 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
1690
1691 unsigned Opc;
1692 bool ExtraOp = false;
1693 switch (Op.getOpcode()) {
1694 default:
Craig Topper2a30d782014-06-18 05:05:13 +00001695 llvm_unreachable("Invalid code");
Tim Northover3b0846e2014-05-24 12:50:23 +00001696 case ISD::ADDC:
1697 Opc = AArch64ISD::ADDS;
1698 break;
1699 case ISD::SUBC:
1700 Opc = AArch64ISD::SUBS;
1701 break;
1702 case ISD::ADDE:
1703 Opc = AArch64ISD::ADCS;
1704 ExtraOp = true;
1705 break;
1706 case ISD::SUBE:
1707 Opc = AArch64ISD::SBCS;
1708 ExtraOp = true;
1709 break;
1710 }
1711
1712 if (!ExtraOp)
1713 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
1714 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
1715 Op.getOperand(2));
1716}
1717
1718static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
1719 // Let legalize expand this if it isn't a legal type yet.
1720 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
1721 return SDValue();
1722
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001723 SDLoc dl(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00001724 AArch64CC::CondCode CC;
1725 // The actual operation that sets the overflow or carry flag.
1726 SDValue Value, Overflow;
1727 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
1728
1729 // We use 0 and 1 as false and true values.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001730 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
1731 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00001732
1733 // We use an inverted condition, because the conditional select is inverted
1734 // too. This will allow it to be selected to a single instruction:
1735 // CSINC Wd, WZR, WZR, invert(cond).
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001736 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
1737 Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
Tim Northover3b0846e2014-05-24 12:50:23 +00001738 CCVal, Overflow);
1739
1740 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001741 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
Tim Northover3b0846e2014-05-24 12:50:23 +00001742}
1743
1744// Prefetch operands are:
1745// 1: Address to prefetch
1746// 2: bool isWrite
1747// 3: int locality (0 = no locality ... 3 = extreme locality)
1748// 4: bool isDataCache
1749static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
1750 SDLoc DL(Op);
1751 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
1752 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
Yi Konge56de692014-08-05 12:46:47 +00001753 unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00001754
1755 bool IsStream = !Locality;
1756 // When the locality number is set
1757 if (Locality) {
1758 // The front-end should have filtered out the out-of-range values
1759 assert(Locality <= 3 && "Prefetch locality out-of-range");
1760 // The locality degree is the opposite of the cache speed.
1761 // Put the number the other way around.
1762 // The encoding starts at 0 for level 1
1763 Locality = 3 - Locality;
1764 }
1765
1766 // built the mask value encoding the expected behavior.
1767 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit
Yi Konge56de692014-08-05 12:46:47 +00001768 (!IsData << 3) | // IsDataCache bit
Tim Northover3b0846e2014-05-24 12:50:23 +00001769 (Locality << 1) | // Cache level bits
1770 (unsigned)IsStream; // Stream bit
1771 return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001772 DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00001773}
1774
1775SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
1776 SelectionDAG &DAG) const {
1777 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
1778
1779 RTLIB::Libcall LC;
1780 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
1781
1782 return LowerF128Call(Op, DAG, LC);
1783}
1784
1785SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
1786 SelectionDAG &DAG) const {
1787 if (Op.getOperand(0).getValueType() != MVT::f128) {
1788 // It's legal except when f128 is involved
1789 return Op;
1790 }
1791
1792 RTLIB::Libcall LC;
1793 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
1794
1795 // FP_ROUND node has a second operand indicating whether it is known to be
1796 // precise. That doesn't take part in the LibCall so we can't directly use
1797 // LowerF128Call.
1798 SDValue SrcVal = Op.getOperand(0);
1799 return makeLibCall(DAG, LC, Op.getValueType(), &SrcVal, 1,
1800 /*isSigned*/ false, SDLoc(Op)).first;
1801}
1802
1803static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
1804 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1805 // Any additional optimization in this function should be recorded
1806 // in the cost tables.
1807 EVT InVT = Op.getOperand(0).getValueType();
1808 EVT VT = Op.getValueType();
1809
Tim Northoverdbecc3b2014-06-15 09:27:15 +00001810 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001811 SDLoc dl(Op);
1812 SDValue Cv =
1813 DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
1814 Op.getOperand(0));
1815 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
Tim Northoverdbecc3b2014-06-15 09:27:15 +00001816 }
1817
1818 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001819 SDLoc dl(Op);
Oliver Stannard89d15422014-08-27 16:16:04 +00001820 MVT ExtVT =
1821 MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
1822 VT.getVectorNumElements());
1823 SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
Tim Northover3b0846e2014-05-24 12:50:23 +00001824 return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
1825 }
1826
1827 // Type changing conversions are illegal.
Tim Northoverdbecc3b2014-06-15 09:27:15 +00001828 return Op;
Tim Northover3b0846e2014-05-24 12:50:23 +00001829}
1830
1831SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
1832 SelectionDAG &DAG) const {
1833 if (Op.getOperand(0).getValueType().isVector())
1834 return LowerVectorFP_TO_INT(Op, DAG);
1835
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00001836 // f16 conversions are promoted to f32.
1837 if (Op.getOperand(0).getValueType() == MVT::f16) {
1838 SDLoc dl(Op);
1839 return DAG.getNode(
1840 Op.getOpcode(), dl, Op.getValueType(),
1841 DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
1842 }
1843
Tim Northover3b0846e2014-05-24 12:50:23 +00001844 if (Op.getOperand(0).getValueType() != MVT::f128) {
1845 // It's legal except when f128 is involved
1846 return Op;
1847 }
1848
1849 RTLIB::Libcall LC;
1850 if (Op.getOpcode() == ISD::FP_TO_SINT)
1851 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
1852 else
1853 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
1854
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00001855 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
Tim Northover3b0846e2014-05-24 12:50:23 +00001856 return makeLibCall(DAG, LC, Op.getValueType(), &Ops[0], Ops.size(), false,
1857 SDLoc(Op)).first;
1858}
1859
1860static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
1861 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1862 // Any additional optimization in this function should be recorded
1863 // in the cost tables.
1864 EVT VT = Op.getValueType();
1865 SDLoc dl(Op);
1866 SDValue In = Op.getOperand(0);
1867 EVT InVT = In.getValueType();
1868
Tim Northoveref0d7602014-06-15 09:27:06 +00001869 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
1870 MVT CastVT =
1871 MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
1872 InVT.getVectorNumElements());
1873 In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001874 return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
Tim Northover3b0846e2014-05-24 12:50:23 +00001875 }
1876
Tim Northoveref0d7602014-06-15 09:27:06 +00001877 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
1878 unsigned CastOpc =
1879 Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1880 EVT CastVT = VT.changeVectorElementTypeToInteger();
1881 In = DAG.getNode(CastOpc, dl, CastVT, In);
1882 return DAG.getNode(Op.getOpcode(), dl, VT, In);
Tim Northover3b0846e2014-05-24 12:50:23 +00001883 }
1884
Tim Northoveref0d7602014-06-15 09:27:06 +00001885 return Op;
Tim Northover3b0846e2014-05-24 12:50:23 +00001886}
1887
1888SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
1889 SelectionDAG &DAG) const {
1890 if (Op.getValueType().isVector())
1891 return LowerVectorINT_TO_FP(Op, DAG);
1892
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00001893 // f16 conversions are promoted to f32.
1894 if (Op.getValueType() == MVT::f16) {
1895 SDLoc dl(Op);
1896 return DAG.getNode(
1897 ISD::FP_ROUND, dl, MVT::f16,
1898 DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001899 DAG.getIntPtrConstant(0, dl));
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00001900 }
1901
Tim Northover3b0846e2014-05-24 12:50:23 +00001902 // i128 conversions are libcalls.
1903 if (Op.getOperand(0).getValueType() == MVT::i128)
1904 return SDValue();
1905
1906 // Other conversions are legal, unless it's to the completely software-based
1907 // fp128.
1908 if (Op.getValueType() != MVT::f128)
1909 return Op;
1910
1911 RTLIB::Libcall LC;
1912 if (Op.getOpcode() == ISD::SINT_TO_FP)
1913 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
1914 else
1915 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
1916
1917 return LowerF128Call(Op, DAG, LC);
1918}
1919
1920SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
1921 SelectionDAG &DAG) const {
1922 // For iOS, we want to call an alternative entry point: __sincos_stret,
1923 // which returns the values in two S / D registers.
1924 SDLoc dl(Op);
1925 SDValue Arg = Op.getOperand(0);
1926 EVT ArgVT = Arg.getValueType();
1927 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
1928
1929 ArgListTy Args;
1930 ArgListEntry Entry;
1931
1932 Entry.Node = Arg;
1933 Entry.Ty = ArgTy;
1934 Entry.isSExt = false;
1935 Entry.isZExt = false;
1936 Args.push_back(Entry);
1937
1938 const char *LibcallName =
1939 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
Mehdi Amini44ede332015-07-09 02:09:04 +00001940 SDValue Callee =
1941 DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00001942
Reid Kleckner343c3952014-11-20 23:51:47 +00001943 StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
Tim Northover3b0846e2014-05-24 12:50:23 +00001944 TargetLowering::CallLoweringInfo CLI(DAG);
1945 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
Juergen Ributzka3bd03c72014-07-01 22:01:54 +00001946 .setCallee(CallingConv::Fast, RetTy, Callee, std::move(Args), 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00001947
1948 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1949 return CallResult.first;
1950}
1951
Tim Northoverf8bfe212014-07-18 13:07:05 +00001952static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
1953 if (Op.getValueType() != MVT::f16)
1954 return SDValue();
1955
1956 assert(Op.getOperand(0).getValueType() == MVT::i16);
1957 SDLoc DL(Op);
1958
1959 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
1960 Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
1961 return SDValue(
1962 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001963 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
Tim Northoverf8bfe212014-07-18 13:07:05 +00001964 0);
1965}
1966
Chad Rosierd9d0f862014-10-08 02:31:24 +00001967static EVT getExtensionTo64Bits(const EVT &OrigVT) {
1968 if (OrigVT.getSizeInBits() >= 64)
1969 return OrigVT;
1970
1971 assert(OrigVT.isSimple() && "Expecting a simple value type");
1972
1973 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
1974 switch (OrigSimpleTy) {
1975 default: llvm_unreachable("Unexpected Vector Type");
1976 case MVT::v2i8:
1977 case MVT::v2i16:
1978 return MVT::v2i32;
1979 case MVT::v4i8:
1980 return MVT::v4i16;
1981 }
1982}
1983
1984static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
1985 const EVT &OrigTy,
1986 const EVT &ExtTy,
1987 unsigned ExtOpcode) {
1988 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
1989 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
1990 // 64-bits we need to insert a new extension so that it will be 64-bits.
1991 assert(ExtTy.is128BitVector() && "Unexpected extension size");
1992 if (OrigTy.getSizeInBits() >= 64)
1993 return N;
1994
1995 // Must extend size to at least 64 bits to be used as an operand for VMULL.
1996 EVT NewVT = getExtensionTo64Bits(OrigTy);
1997
1998 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
1999}
2000
2001static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2002 bool isSigned) {
2003 EVT VT = N->getValueType(0);
2004
2005 if (N->getOpcode() != ISD::BUILD_VECTOR)
2006 return false;
2007
Pete Cooper3af9a252015-06-26 18:17:36 +00002008 for (const SDValue &Elt : N->op_values()) {
Chad Rosierd9d0f862014-10-08 02:31:24 +00002009 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
2010 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
2011 unsigned HalfSize = EltSize / 2;
2012 if (isSigned) {
2013 if (!isIntN(HalfSize, C->getSExtValue()))
2014 return false;
2015 } else {
2016 if (!isUIntN(HalfSize, C->getZExtValue()))
2017 return false;
2018 }
2019 continue;
2020 }
2021 return false;
2022 }
2023
2024 return true;
2025}
2026
2027static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2028 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2029 return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2030 N->getOperand(0)->getValueType(0),
2031 N->getValueType(0),
2032 N->getOpcode());
2033
2034 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2035 EVT VT = N->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002036 SDLoc dl(N);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002037 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
2038 unsigned NumElts = VT.getVectorNumElements();
2039 MVT TruncVT = MVT::getIntegerVT(EltSize);
2040 SmallVector<SDValue, 8> Ops;
2041 for (unsigned i = 0; i != NumElts; ++i) {
2042 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2043 const APInt &CInt = C->getAPIntValue();
2044 // Element types smaller than 32 bits are not legal, so use i32 elements.
2045 // The values are implicitly truncated so sext vs. zext doesn't matter.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002046 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
Chad Rosierd9d0f862014-10-08 02:31:24 +00002047 }
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002048 return DAG.getNode(ISD::BUILD_VECTOR, dl,
Chad Rosierd9d0f862014-10-08 02:31:24 +00002049 MVT::getVectorVT(TruncVT, NumElts), Ops);
2050}
2051
2052static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
2053 if (N->getOpcode() == ISD::SIGN_EXTEND)
2054 return true;
2055 if (isExtendedBUILD_VECTOR(N, DAG, true))
2056 return true;
2057 return false;
2058}
2059
2060static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
2061 if (N->getOpcode() == ISD::ZERO_EXTEND)
2062 return true;
2063 if (isExtendedBUILD_VECTOR(N, DAG, false))
2064 return true;
2065 return false;
2066}
2067
2068static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2069 unsigned Opcode = N->getOpcode();
2070 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2071 SDNode *N0 = N->getOperand(0).getNode();
2072 SDNode *N1 = N->getOperand(1).getNode();
2073 return N0->hasOneUse() && N1->hasOneUse() &&
2074 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2075 }
2076 return false;
2077}
2078
2079static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2080 unsigned Opcode = N->getOpcode();
2081 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2082 SDNode *N0 = N->getOperand(0).getNode();
2083 SDNode *N1 = N->getOperand(1).getNode();
2084 return N0->hasOneUse() && N1->hasOneUse() &&
2085 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2086 }
2087 return false;
2088}
2089
2090static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2091 // Multiplications are only custom-lowered for 128-bit vectors so that
2092 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
2093 EVT VT = Op.getValueType();
2094 assert(VT.is128BitVector() && VT.isInteger() &&
2095 "unexpected type for custom-lowering ISD::MUL");
2096 SDNode *N0 = Op.getOperand(0).getNode();
2097 SDNode *N1 = Op.getOperand(1).getNode();
2098 unsigned NewOpc = 0;
2099 bool isMLA = false;
2100 bool isN0SExt = isSignExtended(N0, DAG);
2101 bool isN1SExt = isSignExtended(N1, DAG);
2102 if (isN0SExt && isN1SExt)
2103 NewOpc = AArch64ISD::SMULL;
2104 else {
2105 bool isN0ZExt = isZeroExtended(N0, DAG);
2106 bool isN1ZExt = isZeroExtended(N1, DAG);
2107 if (isN0ZExt && isN1ZExt)
2108 NewOpc = AArch64ISD::UMULL;
2109 else if (isN1SExt || isN1ZExt) {
2110 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2111 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2112 if (isN1SExt && isAddSubSExt(N0, DAG)) {
2113 NewOpc = AArch64ISD::SMULL;
2114 isMLA = true;
2115 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2116 NewOpc = AArch64ISD::UMULL;
2117 isMLA = true;
2118 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2119 std::swap(N0, N1);
2120 NewOpc = AArch64ISD::UMULL;
2121 isMLA = true;
2122 }
2123 }
2124
2125 if (!NewOpc) {
2126 if (VT == MVT::v2i64)
2127 // Fall through to expand this. It is not legal.
2128 return SDValue();
2129 else
2130 // Other vector multiplications are legal.
2131 return Op;
2132 }
2133 }
2134
2135 // Legalize to a S/UMULL instruction
2136 SDLoc DL(Op);
2137 SDValue Op0;
2138 SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2139 if (!isMLA) {
2140 Op0 = skipExtensionForVectorMULL(N0, DAG);
2141 assert(Op0.getValueType().is64BitVector() &&
2142 Op1.getValueType().is64BitVector() &&
2143 "unexpected types for extended operands to VMULL");
2144 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2145 }
2146 // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2147 // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2148 // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2149 SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2150 SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2151 EVT Op1VT = Op1.getValueType();
2152 return DAG.getNode(N0->getOpcode(), DL, VT,
2153 DAG.getNode(NewOpc, DL, VT,
2154 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2155 DAG.getNode(NewOpc, DL, VT,
2156 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2157}
Tim Northoverf8bfe212014-07-18 13:07:05 +00002158
Tim Northover3b0846e2014-05-24 12:50:23 +00002159SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
2160 SelectionDAG &DAG) const {
2161 switch (Op.getOpcode()) {
2162 default:
2163 llvm_unreachable("unimplemented operand");
2164 return SDValue();
Tim Northoverf8bfe212014-07-18 13:07:05 +00002165 case ISD::BITCAST:
2166 return LowerBITCAST(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002167 case ISD::GlobalAddress:
2168 return LowerGlobalAddress(Op, DAG);
2169 case ISD::GlobalTLSAddress:
2170 return LowerGlobalTLSAddress(Op, DAG);
2171 case ISD::SETCC:
2172 return LowerSETCC(Op, DAG);
2173 case ISD::BR_CC:
2174 return LowerBR_CC(Op, DAG);
2175 case ISD::SELECT:
2176 return LowerSELECT(Op, DAG);
2177 case ISD::SELECT_CC:
2178 return LowerSELECT_CC(Op, DAG);
2179 case ISD::JumpTable:
2180 return LowerJumpTable(Op, DAG);
2181 case ISD::ConstantPool:
2182 return LowerConstantPool(Op, DAG);
2183 case ISD::BlockAddress:
2184 return LowerBlockAddress(Op, DAG);
2185 case ISD::VASTART:
2186 return LowerVASTART(Op, DAG);
2187 case ISD::VACOPY:
2188 return LowerVACOPY(Op, DAG);
2189 case ISD::VAARG:
2190 return LowerVAARG(Op, DAG);
2191 case ISD::ADDC:
2192 case ISD::ADDE:
2193 case ISD::SUBC:
2194 case ISD::SUBE:
2195 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
2196 case ISD::SADDO:
2197 case ISD::UADDO:
2198 case ISD::SSUBO:
2199 case ISD::USUBO:
2200 case ISD::SMULO:
2201 case ISD::UMULO:
2202 return LowerXALUO(Op, DAG);
2203 case ISD::FADD:
2204 return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
2205 case ISD::FSUB:
2206 return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
2207 case ISD::FMUL:
2208 return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
2209 case ISD::FDIV:
2210 return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
2211 case ISD::FP_ROUND:
2212 return LowerFP_ROUND(Op, DAG);
2213 case ISD::FP_EXTEND:
2214 return LowerFP_EXTEND(Op, DAG);
2215 case ISD::FRAMEADDR:
2216 return LowerFRAMEADDR(Op, DAG);
2217 case ISD::RETURNADDR:
2218 return LowerRETURNADDR(Op, DAG);
2219 case ISD::INSERT_VECTOR_ELT:
2220 return LowerINSERT_VECTOR_ELT(Op, DAG);
2221 case ISD::EXTRACT_VECTOR_ELT:
2222 return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2223 case ISD::BUILD_VECTOR:
2224 return LowerBUILD_VECTOR(Op, DAG);
2225 case ISD::VECTOR_SHUFFLE:
2226 return LowerVECTOR_SHUFFLE(Op, DAG);
2227 case ISD::EXTRACT_SUBVECTOR:
2228 return LowerEXTRACT_SUBVECTOR(Op, DAG);
2229 case ISD::SRA:
2230 case ISD::SRL:
2231 case ISD::SHL:
2232 return LowerVectorSRA_SRL_SHL(Op, DAG);
2233 case ISD::SHL_PARTS:
2234 return LowerShiftLeftParts(Op, DAG);
2235 case ISD::SRL_PARTS:
2236 case ISD::SRA_PARTS:
2237 return LowerShiftRightParts(Op, DAG);
2238 case ISD::CTPOP:
2239 return LowerCTPOP(Op, DAG);
2240 case ISD::FCOPYSIGN:
2241 return LowerFCOPYSIGN(Op, DAG);
2242 case ISD::AND:
2243 return LowerVectorAND(Op, DAG);
2244 case ISD::OR:
2245 return LowerVectorOR(Op, DAG);
2246 case ISD::XOR:
2247 return LowerXOR(Op, DAG);
2248 case ISD::PREFETCH:
2249 return LowerPREFETCH(Op, DAG);
2250 case ISD::SINT_TO_FP:
2251 case ISD::UINT_TO_FP:
2252 return LowerINT_TO_FP(Op, DAG);
2253 case ISD::FP_TO_SINT:
2254 case ISD::FP_TO_UINT:
2255 return LowerFP_TO_INT(Op, DAG);
2256 case ISD::FSINCOS:
2257 return LowerFSINCOS(Op, DAG);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002258 case ISD::MUL:
2259 return LowerMUL(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002260 }
2261}
2262
2263/// getFunctionAlignment - Return the Log2 alignment of this function.
2264unsigned AArch64TargetLowering::getFunctionAlignment(const Function *F) const {
2265 return 2;
2266}
2267
2268//===----------------------------------------------------------------------===//
2269// Calling Convention Implementation
2270//===----------------------------------------------------------------------===//
2271
2272#include "AArch64GenCallingConv.inc"
2273
Robin Morisset039781e2014-08-29 21:53:01 +00002274/// Selects the correct CCAssignFn for a given CallingConvention value.
Tim Northover3b0846e2014-05-24 12:50:23 +00002275CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2276 bool IsVarArg) const {
2277 switch (CC) {
2278 default:
2279 llvm_unreachable("Unsupported calling convention.");
2280 case CallingConv::WebKit_JS:
2281 return CC_AArch64_WebKit_JS;
Greg Fitzgeraldfa78d082015-01-19 17:40:05 +00002282 case CallingConv::GHC:
2283 return CC_AArch64_GHC;
Tim Northover3b0846e2014-05-24 12:50:23 +00002284 case CallingConv::C:
2285 case CallingConv::Fast:
2286 if (!Subtarget->isTargetDarwin())
2287 return CC_AArch64_AAPCS;
2288 return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
2289 }
2290}
2291
2292SDValue AArch64TargetLowering::LowerFormalArguments(
2293 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2294 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2295 SmallVectorImpl<SDValue> &InVals) const {
2296 MachineFunction &MF = DAG.getMachineFunction();
2297 MachineFrameInfo *MFI = MF.getFrameInfo();
2298
2299 // Assign locations to all of the incoming arguments.
2300 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002301 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2302 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002303
2304 // At this point, Ins[].VT may already be promoted to i32. To correctly
2305 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2306 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2307 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
2308 // we use a special version of AnalyzeFormalArguments to pass in ValVT and
2309 // LocVT.
2310 unsigned NumArgs = Ins.size();
2311 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2312 unsigned CurArgIdx = 0;
2313 for (unsigned i = 0; i != NumArgs; ++i) {
2314 MVT ValVT = Ins[i].VT;
Andrew Trick05938a52015-02-16 18:10:47 +00002315 if (Ins[i].isOrigArg()) {
2316 std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
2317 CurArgIdx = Ins[i].getOrigArgIndex();
Tim Northover3b0846e2014-05-24 12:50:23 +00002318
Andrew Trick05938a52015-02-16 18:10:47 +00002319 // Get type of the original argument.
Mehdi Amini44ede332015-07-09 02:09:04 +00002320 EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
2321 /*AllowUnknown*/ true);
Andrew Trick05938a52015-02-16 18:10:47 +00002322 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
2323 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2324 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2325 ValVT = MVT::i8;
2326 else if (ActualMVT == MVT::i16)
2327 ValVT = MVT::i16;
2328 }
Tim Northover3b0846e2014-05-24 12:50:23 +00002329 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2330 bool Res =
Tim Northover47e003c2014-05-26 17:21:53 +00002331 AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00002332 assert(!Res && "Call operand has unhandled type");
2333 (void)Res;
2334 }
2335 assert(ArgLocs.size() == Ins.size());
2336 SmallVector<SDValue, 16> ArgValues;
2337 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2338 CCValAssign &VA = ArgLocs[i];
2339
2340 if (Ins[i].Flags.isByVal()) {
2341 // Byval is used for HFAs in the PCS, but the system should work in a
2342 // non-compliant manner for larger structs.
Mehdi Amini44ede332015-07-09 02:09:04 +00002343 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00002344 int Size = Ins[i].Flags.getByValSize();
2345 unsigned NumRegs = (Size + 7) / 8;
2346
2347 // FIXME: This works on big-endian for composite byvals, which are the common
2348 // case. It should also work for fundamental types too.
2349 unsigned FrameIdx =
2350 MFI->CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
Mehdi Amini44ede332015-07-09 02:09:04 +00002351 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00002352 InVals.push_back(FrameIdxN);
2353
2354 continue;
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002355 }
2356
2357 if (VA.isRegLoc()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00002358 // Arguments stored in registers.
2359 EVT RegVT = VA.getLocVT();
2360
2361 SDValue ArgValue;
2362 const TargetRegisterClass *RC;
2363
2364 if (RegVT == MVT::i32)
2365 RC = &AArch64::GPR32RegClass;
2366 else if (RegVT == MVT::i64)
2367 RC = &AArch64::GPR64RegClass;
Oliver Stannard6eda6ff2014-07-11 13:33:46 +00002368 else if (RegVT == MVT::f16)
2369 RC = &AArch64::FPR16RegClass;
Tim Northover3b0846e2014-05-24 12:50:23 +00002370 else if (RegVT == MVT::f32)
2371 RC = &AArch64::FPR32RegClass;
2372 else if (RegVT == MVT::f64 || RegVT.is64BitVector())
2373 RC = &AArch64::FPR64RegClass;
2374 else if (RegVT == MVT::f128 || RegVT.is128BitVector())
2375 RC = &AArch64::FPR128RegClass;
2376 else
2377 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2378
2379 // Transform the arguments in physical registers into virtual ones.
2380 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2381 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2382
2383 // If this is an 8, 16 or 32-bit value, it is really passed promoted
2384 // to 64 bits. Insert an assert[sz]ext to capture this, then
2385 // truncate to the right size.
2386 switch (VA.getLocInfo()) {
2387 default:
2388 llvm_unreachable("Unknown loc info!");
2389 case CCValAssign::Full:
2390 break;
2391 case CCValAssign::BCvt:
2392 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
2393 break;
Tim Northover47e003c2014-05-26 17:21:53 +00002394 case CCValAssign::AExt:
Tim Northover3b0846e2014-05-24 12:50:23 +00002395 case CCValAssign::SExt:
Tim Northover3b0846e2014-05-24 12:50:23 +00002396 case CCValAssign::ZExt:
Tim Northover47e003c2014-05-26 17:21:53 +00002397 // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
2398 // nodes after our lowering.
2399 assert(RegVT == Ins[i].VT && "incorrect register location selected");
Tim Northover3b0846e2014-05-24 12:50:23 +00002400 break;
2401 }
2402
2403 InVals.push_back(ArgValue);
2404
2405 } else { // VA.isRegLoc()
2406 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
2407 unsigned ArgOffset = VA.getLocMemOffset();
Amara Emerson82da7d02014-08-15 14:29:57 +00002408 unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
Tim Northover3b0846e2014-05-24 12:50:23 +00002409
2410 uint32_t BEAlign = 0;
Tim Northover293d4142014-12-03 17:49:26 +00002411 if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
2412 !Ins[i].Flags.isInConsecutiveRegs())
Tim Northover3b0846e2014-05-24 12:50:23 +00002413 BEAlign = 8 - ArgSize;
2414
2415 int FI = MFI->CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
2416
2417 // Create load nodes to retrieve arguments from the stack.
Mehdi Amini44ede332015-07-09 02:09:04 +00002418 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00002419 SDValue ArgValue;
2420
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002421 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
Tim Northover47e003c2014-05-26 17:21:53 +00002422 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002423 MVT MemVT = VA.getValVT();
2424
Tim Northover47e003c2014-05-26 17:21:53 +00002425 switch (VA.getLocInfo()) {
2426 default:
2427 break;
Tim Northover6890add2014-06-03 13:54:53 +00002428 case CCValAssign::BCvt:
2429 MemVT = VA.getLocVT();
2430 break;
Tim Northover47e003c2014-05-26 17:21:53 +00002431 case CCValAssign::SExt:
2432 ExtType = ISD::SEXTLOAD;
2433 break;
2434 case CCValAssign::ZExt:
2435 ExtType = ISD::ZEXTLOAD;
2436 break;
2437 case CCValAssign::AExt:
2438 ExtType = ISD::EXTLOAD;
2439 break;
Tim Northover3b0846e2014-05-24 12:50:23 +00002440 }
2441
Tim Northover6890add2014-06-03 13:54:53 +00002442 ArgValue = DAG.getExtLoad(ExtType, DL, VA.getLocVT(), Chain, FIN,
Tim Northover47e003c2014-05-26 17:21:53 +00002443 MachinePointerInfo::getFixedStack(FI),
Benjamin Kramer2e52f022014-10-04 22:44:29 +00002444 MemVT, false, false, false, 0);
Tim Northover47e003c2014-05-26 17:21:53 +00002445
Tim Northover3b0846e2014-05-24 12:50:23 +00002446 InVals.push_back(ArgValue);
2447 }
2448 }
2449
2450 // varargs
2451 if (isVarArg) {
2452 if (!Subtarget->isTargetDarwin()) {
2453 // The AAPCS variadic function ABI is identical to the non-variadic
2454 // one. As a result there may be more arguments in registers and we should
2455 // save them for future reference.
2456 saveVarArgRegisters(CCInfo, DAG, DL, Chain);
2457 }
2458
2459 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
2460 // This will point to the next argument passed via stack.
2461 unsigned StackOffset = CCInfo.getNextStackOffset();
2462 // We currently pass all varargs at 8-byte alignment.
2463 StackOffset = ((StackOffset + 7) & ~7);
2464 AFI->setVarArgsStackIndex(MFI->CreateFixedObject(4, StackOffset, true));
2465 }
2466
2467 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2468 unsigned StackArgSize = CCInfo.getNextStackOffset();
2469 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2470 if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
2471 // This is a non-standard ABI so by fiat I say we're allowed to make full
2472 // use of the stack area to be popped, which must be aligned to 16 bytes in
2473 // any case:
2474 StackArgSize = RoundUpToAlignment(StackArgSize, 16);
2475
2476 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
2477 // a multiple of 16.
2478 FuncInfo->setArgumentStackToRestore(StackArgSize);
2479
2480 // This realignment carries over to the available bytes below. Our own
2481 // callers will guarantee the space is free by giving an aligned value to
2482 // CALLSEQ_START.
2483 }
2484 // Even if we're not expected to free up the space, it's useful to know how
2485 // much is there while considering tail calls (because we can reuse it).
2486 FuncInfo->setBytesInStackArgArea(StackArgSize);
2487
2488 return Chain;
2489}
2490
2491void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
2492 SelectionDAG &DAG, SDLoc DL,
2493 SDValue &Chain) const {
2494 MachineFunction &MF = DAG.getMachineFunction();
2495 MachineFrameInfo *MFI = MF.getFrameInfo();
2496 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Mehdi Amini44ede332015-07-09 02:09:04 +00002497 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00002498
2499 SmallVector<SDValue, 8> MemOps;
2500
2501 static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
2502 AArch64::X3, AArch64::X4, AArch64::X5,
2503 AArch64::X6, AArch64::X7 };
2504 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
Tim Northover3b6b7ca2015-02-21 02:11:17 +00002505 unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
Tim Northover3b0846e2014-05-24 12:50:23 +00002506
2507 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
2508 int GPRIdx = 0;
2509 if (GPRSaveSize != 0) {
2510 GPRIdx = MFI->CreateStackObject(GPRSaveSize, 8, false);
2511
Mehdi Amini44ede332015-07-09 02:09:04 +00002512 SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00002513
2514 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
2515 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
2516 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
2517 SDValue Store =
2518 DAG.getStore(Val.getValue(1), DL, Val, FIN,
2519 MachinePointerInfo::getStack(i * 8), false, false, 0);
2520 MemOps.push_back(Store);
Mehdi Amini44ede332015-07-09 02:09:04 +00002521 FIN =
2522 DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00002523 }
2524 }
2525 FuncInfo->setVarArgsGPRIndex(GPRIdx);
2526 FuncInfo->setVarArgsGPRSize(GPRSaveSize);
2527
2528 if (Subtarget->hasFPARMv8()) {
2529 static const MCPhysReg FPRArgRegs[] = {
2530 AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
2531 AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
2532 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
Tim Northover3b6b7ca2015-02-21 02:11:17 +00002533 unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
Tim Northover3b0846e2014-05-24 12:50:23 +00002534
2535 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
2536 int FPRIdx = 0;
2537 if (FPRSaveSize != 0) {
2538 FPRIdx = MFI->CreateStackObject(FPRSaveSize, 16, false);
2539
Mehdi Amini44ede332015-07-09 02:09:04 +00002540 SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00002541
2542 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
2543 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
2544 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
2545
2546 SDValue Store =
2547 DAG.getStore(Val.getValue(1), DL, Val, FIN,
2548 MachinePointerInfo::getStack(i * 16), false, false, 0);
2549 MemOps.push_back(Store);
Mehdi Amini44ede332015-07-09 02:09:04 +00002550 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
2551 DAG.getConstant(16, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00002552 }
2553 }
2554 FuncInfo->setVarArgsFPRIndex(FPRIdx);
2555 FuncInfo->setVarArgsFPRSize(FPRSaveSize);
2556 }
2557
2558 if (!MemOps.empty()) {
2559 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
2560 }
2561}
2562
2563/// LowerCallResult - Lower the result values of a call into the
2564/// appropriate copies out of appropriate physical registers.
2565SDValue AArch64TargetLowering::LowerCallResult(
2566 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
2567 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2568 SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
2569 SDValue ThisVal) const {
2570 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
2571 ? RetCC_AArch64_WebKit_JS
2572 : RetCC_AArch64_AAPCS;
2573 // Assign locations to each value returned by this call.
2574 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002575 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2576 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002577 CCInfo.AnalyzeCallResult(Ins, RetCC);
2578
2579 // Copy all of the result registers out of their specified physreg.
2580 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2581 CCValAssign VA = RVLocs[i];
2582
2583 // Pass 'this' value directly from the argument to return value, to avoid
2584 // reg unit interference
2585 if (i == 0 && isThisReturn) {
2586 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
2587 "unexpected return calling convention register assignment");
2588 InVals.push_back(ThisVal);
2589 continue;
2590 }
2591
2592 SDValue Val =
2593 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2594 Chain = Val.getValue(1);
2595 InFlag = Val.getValue(2);
2596
2597 switch (VA.getLocInfo()) {
2598 default:
2599 llvm_unreachable("Unknown loc info!");
2600 case CCValAssign::Full:
2601 break;
2602 case CCValAssign::BCvt:
2603 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2604 break;
2605 }
2606
2607 InVals.push_back(Val);
2608 }
2609
2610 return Chain;
2611}
2612
2613bool AArch64TargetLowering::isEligibleForTailCallOptimization(
2614 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
2615 bool isCalleeStructRet, bool isCallerStructRet,
2616 const SmallVectorImpl<ISD::OutputArg> &Outs,
2617 const SmallVectorImpl<SDValue> &OutVals,
2618 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2619 // For CallingConv::C this function knows whether the ABI needs
2620 // changing. That's not true for other conventions so they will have to opt in
2621 // manually.
2622 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
2623 return false;
2624
2625 const MachineFunction &MF = DAG.getMachineFunction();
2626 const Function *CallerF = MF.getFunction();
2627 CallingConv::ID CallerCC = CallerF->getCallingConv();
2628 bool CCMatch = CallerCC == CalleeCC;
2629
2630 // Byval parameters hand the function a pointer directly into the stack area
2631 // we want to reuse during a tail call. Working around this *is* possible (see
2632 // X86) but less efficient and uglier in LowerCall.
2633 for (Function::const_arg_iterator i = CallerF->arg_begin(),
2634 e = CallerF->arg_end();
2635 i != e; ++i)
2636 if (i->hasByValAttr())
2637 return false;
2638
2639 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2640 if (IsTailCallConvention(CalleeCC) && CCMatch)
2641 return true;
2642 return false;
2643 }
2644
Oliver Stannard12993dd2014-08-18 12:42:15 +00002645 // Externally-defined functions with weak linkage should not be
2646 // tail-called on AArch64 when the OS does not support dynamic
2647 // pre-emption of symbols, as the AAELF spec requires normal calls
2648 // to undefined weak functions to be replaced with a NOP or jump to the
2649 // next instruction. The behaviour of branch instructions in this
2650 // situation (as used for tail calls) is implementation-defined, so we
2651 // cannot rely on the linker replacing the tail call with a return.
2652 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2653 const GlobalValue *GV = G->getGlobal();
Daniel Sandersc81f4502015-06-16 15:44:21 +00002654 const Triple &TT = getTargetMachine().getTargetTriple();
Saleem Abdulrasool67f72992015-01-03 21:35:00 +00002655 if (GV->hasExternalWeakLinkage() &&
2656 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
Oliver Stannard12993dd2014-08-18 12:42:15 +00002657 return false;
2658 }
2659
Tim Northover3b0846e2014-05-24 12:50:23 +00002660 // Now we search for cases where we can use a tail call without changing the
2661 // ABI. Sibcall is used in some places (particularly gcc) to refer to this
2662 // concept.
2663
2664 // I want anyone implementing a new calling convention to think long and hard
2665 // about this assert.
2666 assert((!isVarArg || CalleeCC == CallingConv::C) &&
2667 "Unexpected variadic calling convention");
2668
2669 if (isVarArg && !Outs.empty()) {
2670 // At least two cases here: if caller is fastcc then we can't have any
2671 // memory arguments (we'd be expected to clean up the stack afterwards). If
2672 // caller is C then we could potentially use its argument area.
2673
2674 // FIXME: for now we take the most conservative of these in both cases:
2675 // disallow all variadic memory operands.
2676 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002677 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2678 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002679
2680 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
2681 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
2682 if (!ArgLocs[i].isRegLoc())
2683 return false;
2684 }
2685
2686 // If the calling conventions do not match, then we'd better make sure the
2687 // results are returned in the same way as what the caller expects.
2688 if (!CCMatch) {
2689 SmallVector<CCValAssign, 16> RVLocs1;
Eric Christopherb5217502014-08-06 18:45:26 +00002690 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2691 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002692 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForCall(CalleeCC, isVarArg));
2693
2694 SmallVector<CCValAssign, 16> RVLocs2;
Eric Christopherb5217502014-08-06 18:45:26 +00002695 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2696 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002697 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForCall(CallerCC, isVarArg));
2698
2699 if (RVLocs1.size() != RVLocs2.size())
2700 return false;
2701 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2702 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2703 return false;
2704 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2705 return false;
2706 if (RVLocs1[i].isRegLoc()) {
2707 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2708 return false;
2709 } else {
2710 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2711 return false;
2712 }
2713 }
2714 }
2715
2716 // Nothing more to check if the callee is taking no arguments
2717 if (Outs.empty())
2718 return true;
2719
2720 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002721 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2722 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002723
2724 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2725
2726 const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2727
2728 // If the stack arguments for this call would fit into our own save area then
2729 // the call can be made tail.
2730 return CCInfo.getNextStackOffset() <= FuncInfo->getBytesInStackArgArea();
2731}
2732
2733SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
2734 SelectionDAG &DAG,
2735 MachineFrameInfo *MFI,
2736 int ClobberedFI) const {
2737 SmallVector<SDValue, 8> ArgChains;
2738 int64_t FirstByte = MFI->getObjectOffset(ClobberedFI);
2739 int64_t LastByte = FirstByte + MFI->getObjectSize(ClobberedFI) - 1;
2740
2741 // Include the original chain at the beginning of the list. When this is
2742 // used by target LowerCall hooks, this helps legalize find the
2743 // CALLSEQ_BEGIN node.
2744 ArgChains.push_back(Chain);
2745
2746 // Add a chain value for each stack argument corresponding
2747 for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
2748 UE = DAG.getEntryNode().getNode()->use_end();
2749 U != UE; ++U)
2750 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
2751 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
2752 if (FI->getIndex() < 0) {
2753 int64_t InFirstByte = MFI->getObjectOffset(FI->getIndex());
2754 int64_t InLastByte = InFirstByte;
2755 InLastByte += MFI->getObjectSize(FI->getIndex()) - 1;
2756
2757 if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
2758 (FirstByte <= InFirstByte && InFirstByte <= LastByte))
2759 ArgChains.push_back(SDValue(L, 1));
2760 }
2761
2762 // Build a tokenfactor for all the chains.
2763 return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
2764}
2765
2766bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
2767 bool TailCallOpt) const {
2768 return CallCC == CallingConv::Fast && TailCallOpt;
2769}
2770
2771bool AArch64TargetLowering::IsTailCallConvention(CallingConv::ID CallCC) const {
2772 return CallCC == CallingConv::Fast;
2773}
2774
2775/// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
2776/// and add input and output parameter nodes.
2777SDValue
2778AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
2779 SmallVectorImpl<SDValue> &InVals) const {
2780 SelectionDAG &DAG = CLI.DAG;
2781 SDLoc &DL = CLI.DL;
2782 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2783 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2784 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2785 SDValue Chain = CLI.Chain;
2786 SDValue Callee = CLI.Callee;
2787 bool &IsTailCall = CLI.IsTailCall;
2788 CallingConv::ID CallConv = CLI.CallConv;
2789 bool IsVarArg = CLI.IsVarArg;
2790
2791 MachineFunction &MF = DAG.getMachineFunction();
2792 bool IsStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
2793 bool IsThisReturn = false;
2794
2795 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2796 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2797 bool IsSibCall = false;
2798
2799 if (IsTailCall) {
2800 // Check if it's really possible to do a tail call.
2801 IsTailCall = isEligibleForTailCallOptimization(
2802 Callee, CallConv, IsVarArg, IsStructRet,
2803 MF.getFunction()->hasStructRetAttr(), Outs, OutVals, Ins, DAG);
2804 if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
2805 report_fatal_error("failed to perform tail call elimination on a call "
2806 "site marked musttail");
2807
2808 // A sibling call is one where we're under the usual C ABI and not planning
2809 // to change that but can still do a tail call:
2810 if (!TailCallOpt && IsTailCall)
2811 IsSibCall = true;
2812
2813 if (IsTailCall)
2814 ++NumTailCalls;
2815 }
2816
2817 // Analyze operands of the call, assigning locations to each operand.
2818 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002819 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
2820 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002821
2822 if (IsVarArg) {
2823 // Handle fixed and variable vector arguments differently.
2824 // Variable vector arguments always go into memory.
2825 unsigned NumArgs = Outs.size();
2826
2827 for (unsigned i = 0; i != NumArgs; ++i) {
2828 MVT ArgVT = Outs[i].VT;
2829 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2830 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
2831 /*IsVarArg=*/ !Outs[i].IsFixed);
2832 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
2833 assert(!Res && "Call operand has unhandled type");
2834 (void)Res;
2835 }
2836 } else {
2837 // At this point, Outs[].VT may already be promoted to i32. To correctly
2838 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2839 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2840 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
2841 // we use a special version of AnalyzeCallOperands to pass in ValVT and
2842 // LocVT.
2843 unsigned NumArgs = Outs.size();
2844 for (unsigned i = 0; i != NumArgs; ++i) {
2845 MVT ValVT = Outs[i].VT;
2846 // Get type of the original argument.
Mehdi Amini44ede332015-07-09 02:09:04 +00002847 EVT ActualVT = getValueType(DAG.getDataLayout(),
2848 CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
Tim Northover3b0846e2014-05-24 12:50:23 +00002849 /*AllowUnknown*/ true);
2850 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
2851 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2852 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
Tim Northover3b0846e2014-05-24 12:50:23 +00002853 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
Tim Northover47e003c2014-05-26 17:21:53 +00002854 ValVT = MVT::i8;
Tim Northover3b0846e2014-05-24 12:50:23 +00002855 else if (ActualMVT == MVT::i16)
Tim Northover47e003c2014-05-26 17:21:53 +00002856 ValVT = MVT::i16;
Tim Northover3b0846e2014-05-24 12:50:23 +00002857
2858 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
Tim Northover47e003c2014-05-26 17:21:53 +00002859 bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00002860 assert(!Res && "Call operand has unhandled type");
2861 (void)Res;
2862 }
2863 }
2864
2865 // Get a count of how many bytes are to be pushed on the stack.
2866 unsigned NumBytes = CCInfo.getNextStackOffset();
2867
2868 if (IsSibCall) {
2869 // Since we're not changing the ABI to make this a tail call, the memory
2870 // operands are already available in the caller's incoming argument space.
2871 NumBytes = 0;
2872 }
2873
2874 // FPDiff is the byte offset of the call's argument area from the callee's.
2875 // Stores to callee stack arguments will be placed in FixedStackSlots offset
2876 // by this amount for a tail call. In a sibling call it must be 0 because the
2877 // caller will deallocate the entire stack and the callee still expects its
2878 // arguments to begin at SP+0. Completely unused for non-tail calls.
2879 int FPDiff = 0;
2880
2881 if (IsTailCall && !IsSibCall) {
2882 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
2883
2884 // Since callee will pop argument stack as a tail call, we must keep the
2885 // popped size 16-byte aligned.
2886 NumBytes = RoundUpToAlignment(NumBytes, 16);
2887
2888 // FPDiff will be negative if this tail call requires more space than we
2889 // would automatically have in our incoming argument space. Positive if we
2890 // can actually shrink the stack.
2891 FPDiff = NumReusableBytes - NumBytes;
2892
2893 // The stack pointer must be 16-byte aligned at all times it's used for a
2894 // memory operation, which in practice means at *all* times and in
2895 // particular across call boundaries. Therefore our own arguments started at
2896 // a 16-byte aligned SP and the delta applied for the tail call should
2897 // satisfy the same constraint.
2898 assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
2899 }
2900
2901 // Adjust the stack pointer for the new arguments...
2902 // These operations are automatically eliminated by the prolog/epilog pass
2903 if (!IsSibCall)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002904 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, DL,
2905 true),
2906 DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00002907
Mehdi Amini44ede332015-07-09 02:09:04 +00002908 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
2909 getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00002910
2911 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2912 SmallVector<SDValue, 8> MemOpChains;
Mehdi Amini44ede332015-07-09 02:09:04 +00002913 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00002914
2915 // Walk the register/memloc assignments, inserting copies/loads.
2916 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
2917 ++i, ++realArgIdx) {
2918 CCValAssign &VA = ArgLocs[i];
2919 SDValue Arg = OutVals[realArgIdx];
2920 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2921
2922 // Promote the value if needed.
2923 switch (VA.getLocInfo()) {
2924 default:
2925 llvm_unreachable("Unknown loc info!");
2926 case CCValAssign::Full:
2927 break;
2928 case CCValAssign::SExt:
2929 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2930 break;
2931 case CCValAssign::ZExt:
2932 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2933 break;
2934 case CCValAssign::AExt:
Tim Northover68ae5032014-05-26 17:22:07 +00002935 if (Outs[realArgIdx].ArgVT == MVT::i1) {
2936 // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
2937 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
2938 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
2939 }
Tim Northover3b0846e2014-05-24 12:50:23 +00002940 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2941 break;
2942 case CCValAssign::BCvt:
2943 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2944 break;
2945 case CCValAssign::FPExt:
2946 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
2947 break;
2948 }
2949
2950 if (VA.isRegLoc()) {
2951 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i64) {
2952 assert(VA.getLocVT() == MVT::i64 &&
2953 "unexpected calling convention register assignment");
2954 assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
2955 "unexpected use of 'returned'");
2956 IsThisReturn = true;
2957 }
2958 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2959 } else {
2960 assert(VA.isMemLoc());
2961
2962 SDValue DstAddr;
2963 MachinePointerInfo DstInfo;
2964
2965 // FIXME: This works on big-endian for composite byvals, which are the
2966 // common case. It should also work for fundamental types too.
2967 uint32_t BEAlign = 0;
2968 unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
Amara Emerson82da7d02014-08-15 14:29:57 +00002969 : VA.getValVT().getSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00002970 OpSize = (OpSize + 7) / 8;
Tim Northover293d4142014-12-03 17:49:26 +00002971 if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
2972 !Flags.isInConsecutiveRegs()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00002973 if (OpSize < 8)
2974 BEAlign = 8 - OpSize;
2975 }
2976 unsigned LocMemOffset = VA.getLocMemOffset();
2977 int32_t Offset = LocMemOffset + BEAlign;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002978 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
Mehdi Amini44ede332015-07-09 02:09:04 +00002979 PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
Tim Northover3b0846e2014-05-24 12:50:23 +00002980
2981 if (IsTailCall) {
2982 Offset = Offset + FPDiff;
2983 int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2984
Mehdi Amini44ede332015-07-09 02:09:04 +00002985 DstAddr = DAG.getFrameIndex(FI, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00002986 DstInfo = MachinePointerInfo::getFixedStack(FI);
2987
2988 // Make sure any stack arguments overlapping with where we're storing
2989 // are loaded before this eventual operation. Otherwise they'll be
2990 // clobbered.
2991 Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
2992 } else {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002993 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00002994
Mehdi Amini44ede332015-07-09 02:09:04 +00002995 DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
Tim Northover3b0846e2014-05-24 12:50:23 +00002996 DstInfo = MachinePointerInfo::getStack(LocMemOffset);
2997 }
2998
2999 if (Outs[i].Flags.isByVal()) {
3000 SDValue SizeNode =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003001 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00003002 SDValue Cpy = DAG.getMemcpy(
3003 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
Krzysztof Parzyszeka46c36b2015-04-13 17:16:45 +00003004 /*isVol = */ false, /*AlwaysInline = */ false,
3005 /*isTailCall = */ false,
3006 DstInfo, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00003007
3008 MemOpChains.push_back(Cpy);
3009 } else {
3010 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
3011 // promoted to a legal register type i32, we should truncate Arg back to
3012 // i1/i8/i16.
Tim Northover6890add2014-06-03 13:54:53 +00003013 if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
3014 VA.getValVT() == MVT::i16)
3015 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
Tim Northover3b0846e2014-05-24 12:50:23 +00003016
3017 SDValue Store =
3018 DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, false, false, 0);
3019 MemOpChains.push_back(Store);
3020 }
3021 }
3022 }
3023
3024 if (!MemOpChains.empty())
3025 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3026
3027 // Build a sequence of copy-to-reg nodes chained together with token chain
3028 // and flag operands which copy the outgoing args into the appropriate regs.
3029 SDValue InFlag;
3030 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3031 Chain = DAG.getCopyToReg(Chain, DL, RegsToPass[i].first,
3032 RegsToPass[i].second, InFlag);
3033 InFlag = Chain.getValue(1);
3034 }
3035
3036 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3037 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3038 // node so that legalize doesn't hack it.
3039 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3040 Subtarget->isTargetMachO()) {
3041 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3042 const GlobalValue *GV = G->getGlobal();
3043 bool InternalLinkage = GV->hasInternalLinkage();
3044 if (InternalLinkage)
Mehdi Amini44ede332015-07-09 02:09:04 +00003045 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00003046 else {
Mehdi Amini44ede332015-07-09 02:09:04 +00003047 Callee =
3048 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT);
3049 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
Tim Northover3b0846e2014-05-24 12:50:23 +00003050 }
3051 } else if (ExternalSymbolSDNode *S =
3052 dyn_cast<ExternalSymbolSDNode>(Callee)) {
3053 const char *Sym = S->getSymbol();
Mehdi Amini44ede332015-07-09 02:09:04 +00003054 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
3055 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
Tim Northover3b0846e2014-05-24 12:50:23 +00003056 }
3057 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3058 const GlobalValue *GV = G->getGlobal();
Mehdi Amini44ede332015-07-09 02:09:04 +00003059 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00003060 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3061 const char *Sym = S->getSymbol();
Mehdi Amini44ede332015-07-09 02:09:04 +00003062 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00003063 }
3064
3065 // We don't usually want to end the call-sequence here because we would tidy
3066 // the frame up *after* the call, however in the ABI-changing tail-call case
3067 // we've carefully laid out the parameters so that when sp is reset they'll be
3068 // in the correct location.
3069 if (IsTailCall && !IsSibCall) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003070 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3071 DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003072 InFlag = Chain.getValue(1);
3073 }
3074
3075 std::vector<SDValue> Ops;
3076 Ops.push_back(Chain);
3077 Ops.push_back(Callee);
3078
3079 if (IsTailCall) {
3080 // Each tail call may have to adjust the stack by a different amount, so
3081 // this information must travel along with the operation for eventual
3082 // consumption by emitEpilogue.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003083 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00003084 }
3085
3086 // Add argument registers to the end of the list so that they are known live
3087 // into the call.
3088 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3089 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3090 RegsToPass[i].second.getValueType()));
3091
3092 // Add a register mask operand representing the call-preserved registers.
3093 const uint32_t *Mask;
Eric Christopher905f12d2015-01-29 00:19:42 +00003094 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00003095 if (IsThisReturn) {
3096 // For 'this' returns, use the X0-preserving mask if applicable
Eric Christopher9deb75d2015-03-11 22:42:13 +00003097 Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003098 if (!Mask) {
3099 IsThisReturn = false;
Eric Christopher9deb75d2015-03-11 22:42:13 +00003100 Mask = TRI->getCallPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003101 }
3102 } else
Eric Christopher9deb75d2015-03-11 22:42:13 +00003103 Mask = TRI->getCallPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003104
3105 assert(Mask && "Missing call preserved mask for calling convention");
3106 Ops.push_back(DAG.getRegisterMask(Mask));
3107
3108 if (InFlag.getNode())
3109 Ops.push_back(InFlag);
3110
3111 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3112
3113 // If we're doing a tall call, use a TC_RETURN here rather than an
3114 // actual call instruction.
Arnold Schwaighoferf54b73d2015-05-08 23:52:00 +00003115 if (IsTailCall) {
3116 MF.getFrameInfo()->setHasTailCall();
Tim Northover3b0846e2014-05-24 12:50:23 +00003117 return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
Arnold Schwaighoferf54b73d2015-05-08 23:52:00 +00003118 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003119
3120 // Returns a chain and a flag for retval copy to use.
3121 Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
3122 InFlag = Chain.getValue(1);
3123
3124 uint64_t CalleePopBytes = DoesCalleeRestoreStack(CallConv, TailCallOpt)
3125 ? RoundUpToAlignment(NumBytes, 16)
3126 : 0;
3127
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003128 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3129 DAG.getIntPtrConstant(CalleePopBytes, DL, true),
Tim Northover3b0846e2014-05-24 12:50:23 +00003130 InFlag, DL);
3131 if (!Ins.empty())
3132 InFlag = Chain.getValue(1);
3133
3134 // Handle result values, copying them out of physregs into vregs that we
3135 // return.
3136 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3137 InVals, IsThisReturn,
3138 IsThisReturn ? OutVals[0] : SDValue());
3139}
3140
3141bool AArch64TargetLowering::CanLowerReturn(
3142 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
3143 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
3144 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3145 ? RetCC_AArch64_WebKit_JS
3146 : RetCC_AArch64_AAPCS;
3147 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003148 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
Tim Northover3b0846e2014-05-24 12:50:23 +00003149 return CCInfo.CheckReturn(Outs, RetCC);
3150}
3151
3152SDValue
3153AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3154 bool isVarArg,
3155 const SmallVectorImpl<ISD::OutputArg> &Outs,
3156 const SmallVectorImpl<SDValue> &OutVals,
3157 SDLoc DL, SelectionDAG &DAG) const {
3158 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3159 ? RetCC_AArch64_WebKit_JS
3160 : RetCC_AArch64_AAPCS;
3161 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003162 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3163 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00003164 CCInfo.AnalyzeReturn(Outs, RetCC);
3165
3166 // Copy the result values into the output registers.
3167 SDValue Flag;
3168 SmallVector<SDValue, 4> RetOps(1, Chain);
3169 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
3170 ++i, ++realRVLocIdx) {
3171 CCValAssign &VA = RVLocs[i];
3172 assert(VA.isRegLoc() && "Can only return in registers!");
3173 SDValue Arg = OutVals[realRVLocIdx];
3174
3175 switch (VA.getLocInfo()) {
3176 default:
3177 llvm_unreachable("Unknown loc info!");
3178 case CCValAssign::Full:
Tim Northover68ae5032014-05-26 17:22:07 +00003179 if (Outs[i].ArgVT == MVT::i1) {
3180 // AAPCS requires i1 to be zero-extended to i8 by the producer of the
3181 // value. This is strictly redundant on Darwin (which uses "zeroext
3182 // i1"), but will be optimised out before ISel.
3183 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3184 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3185 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003186 break;
3187 case CCValAssign::BCvt:
3188 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3189 break;
3190 }
3191
3192 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
3193 Flag = Chain.getValue(1);
3194 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3195 }
3196
3197 RetOps[0] = Chain; // Update chain.
3198
3199 // Add the flag if we have it.
3200 if (Flag.getNode())
3201 RetOps.push_back(Flag);
3202
3203 return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
3204}
3205
3206//===----------------------------------------------------------------------===//
3207// Other Lowering Code
3208//===----------------------------------------------------------------------===//
3209
3210SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
3211 SelectionDAG &DAG) const {
Mehdi Amini44ede332015-07-09 02:09:04 +00003212 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003213 SDLoc DL(Op);
Asiri Rathnayake369c0302014-09-10 13:54:38 +00003214 const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
3215 const GlobalValue *GV = GN->getGlobal();
Tim Northover3b0846e2014-05-24 12:50:23 +00003216 unsigned char OpFlags =
3217 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
3218
3219 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
3220 "unexpected offset in global node");
3221
3222 // This also catched the large code model case for Darwin.
3223 if ((OpFlags & AArch64II::MO_GOT) != 0) {
3224 SDValue GotAddr = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
3225 // FIXME: Once remat is capable of dealing with instructions with register
3226 // operands, expand this into two nodes instead of using a wrapper node.
3227 return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
3228 }
3229
Asiri Rathnayake369c0302014-09-10 13:54:38 +00003230 if ((OpFlags & AArch64II::MO_CONSTPOOL) != 0) {
3231 assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
3232 "use of MO_CONSTPOOL only supported on small model");
3233 SDValue Hi = DAG.getTargetConstantPool(GV, PtrVT, 0, 0, AArch64II::MO_PAGE);
3234 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3235 unsigned char LoFlags = AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
3236 SDValue Lo = DAG.getTargetConstantPool(GV, PtrVT, 0, 0, LoFlags);
3237 SDValue PoolAddr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3238 SDValue GlobalAddr = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), PoolAddr,
3239 MachinePointerInfo::getConstantPool(),
3240 /*isVolatile=*/ false,
3241 /*isNonTemporal=*/ true,
3242 /*isInvariant=*/ true, 8);
3243 if (GN->getOffset() != 0)
3244 return DAG.getNode(ISD::ADD, DL, PtrVT, GlobalAddr,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003245 DAG.getConstant(GN->getOffset(), DL, PtrVT));
Asiri Rathnayake369c0302014-09-10 13:54:38 +00003246 return GlobalAddr;
3247 }
3248
Tim Northover3b0846e2014-05-24 12:50:23 +00003249 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
3250 const unsigned char MO_NC = AArch64II::MO_NC;
3251 return DAG.getNode(
3252 AArch64ISD::WrapperLarge, DL, PtrVT,
3253 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G3),
3254 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
3255 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
3256 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
3257 } else {
3258 // Use ADRP/ADD or ADRP/LDR for everything else: the small model on ELF and
3259 // the only correct model on Darwin.
3260 SDValue Hi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
3261 OpFlags | AArch64II::MO_PAGE);
3262 unsigned char LoFlags = OpFlags | AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
3263 SDValue Lo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, LoFlags);
3264
3265 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3266 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3267 }
3268}
3269
3270/// \brief Convert a TLS address reference into the correct sequence of loads
3271/// and calls to compute the variable's address (for Darwin, currently) and
3272/// return an SDValue containing the final node.
3273
3274/// Darwin only has one TLS scheme which must be capable of dealing with the
3275/// fully general situation, in the worst case. This means:
3276/// + "extern __thread" declaration.
3277/// + Defined in a possibly unknown dynamic library.
3278///
3279/// The general system is that each __thread variable has a [3 x i64] descriptor
3280/// which contains information used by the runtime to calculate the address. The
3281/// only part of this the compiler needs to know about is the first xword, which
3282/// contains a function pointer that must be called with the address of the
3283/// entire descriptor in "x0".
3284///
3285/// Since this descriptor may be in a different unit, in general even the
3286/// descriptor must be accessed via an indirect load. The "ideal" code sequence
3287/// is:
3288/// adrp x0, _var@TLVPPAGE
3289/// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor
3290/// ldr x1, [x0] ; x1 contains 1st entry of descriptor,
3291/// ; the function pointer
3292/// blr x1 ; Uses descriptor address in x0
3293/// ; Address of _var is now in x0.
3294///
3295/// If the address of _var's descriptor *is* known to the linker, then it can
3296/// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
3297/// a slight efficiency gain.
3298SDValue
3299AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
3300 SelectionDAG &DAG) const {
3301 assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
3302
3303 SDLoc DL(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00003304 MVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003305 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3306
3307 SDValue TLVPAddr =
3308 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3309 SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
3310
3311 // The first entry in the descriptor is a function pointer that we must call
3312 // to obtain the address of the variable.
3313 SDValue Chain = DAG.getEntryNode();
3314 SDValue FuncTLVGet =
3315 DAG.getLoad(MVT::i64, DL, Chain, DescAddr, MachinePointerInfo::getGOT(),
3316 false, true, true, 8);
3317 Chain = FuncTLVGet.getValue(1);
3318
3319 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3320 MFI->setAdjustsStack(true);
3321
3322 // TLS calls preserve all registers except those that absolutely must be
3323 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
3324 // silly).
Eric Christopher6c901622015-01-28 03:51:33 +00003325 const uint32_t *Mask =
Eric Christopher905f12d2015-01-29 00:19:42 +00003326 Subtarget->getRegisterInfo()->getTLSCallPreservedMask();
Tim Northover3b0846e2014-05-24 12:50:23 +00003327
3328 // Finally, we can make the call. This is just a degenerate version of a
3329 // normal AArch64 call node: x0 takes the address of the descriptor, and
3330 // returns the address of the variable in this thread.
3331 Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
3332 Chain =
3333 DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3334 Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
3335 DAG.getRegisterMask(Mask), Chain.getValue(1));
3336 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
3337}
3338
3339/// When accessing thread-local variables under either the general-dynamic or
3340/// local-dynamic system, we make a "TLS-descriptor" call. The variable will
3341/// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
Kristof Beylsaea84612015-03-04 09:12:08 +00003342/// is a function pointer to carry out the resolution.
Tim Northover3b0846e2014-05-24 12:50:23 +00003343///
Kristof Beylsaea84612015-03-04 09:12:08 +00003344/// The sequence is:
3345/// adrp x0, :tlsdesc:var
3346/// ldr x1, [x0, #:tlsdesc_lo12:var]
3347/// add x0, x0, #:tlsdesc_lo12:var
3348/// .tlsdesccall var
3349/// blr x1
3350/// (TPIDR_EL0 offset now in x0)
Tim Northover3b0846e2014-05-24 12:50:23 +00003351///
Kristof Beylsaea84612015-03-04 09:12:08 +00003352/// The above sequence must be produced unscheduled, to enable the linker to
3353/// optimize/relax this sequence.
3354/// Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
3355/// above sequence, and expanded really late in the compilation flow, to ensure
3356/// the sequence is produced as per above.
3357SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr, SDLoc DL,
3358 SelectionDAG &DAG) const {
Mehdi Amini44ede332015-07-09 02:09:04 +00003359 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003360
Kristof Beylsaea84612015-03-04 09:12:08 +00003361 SDValue Chain = DAG.getEntryNode();
Tim Northover3b0846e2014-05-24 12:50:23 +00003362 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
Kristof Beylsaea84612015-03-04 09:12:08 +00003363
3364 SmallVector<SDValue, 2> Ops;
3365 Ops.push_back(Chain);
3366 Ops.push_back(SymAddr);
3367
3368 Chain = DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, Ops);
3369 SDValue Glue = Chain.getValue(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00003370
3371 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
3372}
3373
3374SDValue
3375AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
3376 SelectionDAG &DAG) const {
3377 assert(Subtarget->isTargetELF() && "This function expects an ELF target");
3378 assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
3379 "ELF TLS only supported in small memory model");
Kristof Beylsaea84612015-03-04 09:12:08 +00003380 // Different choices can be made for the maximum size of the TLS area for a
3381 // module. For the small address model, the default TLS size is 16MiB and the
3382 // maximum TLS size is 4GiB.
3383 // FIXME: add -mtls-size command line option and make it control the 16MiB
3384 // vs. 4GiB code sequence generation.
Tim Northover3b0846e2014-05-24 12:50:23 +00003385 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3386
3387 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
Kristof Beylsaea84612015-03-04 09:12:08 +00003388 if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
3389 if (Model == TLSModel::LocalDynamic)
3390 Model = TLSModel::GeneralDynamic;
3391 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003392
3393 SDValue TPOff;
Mehdi Amini44ede332015-07-09 02:09:04 +00003394 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003395 SDLoc DL(Op);
3396 const GlobalValue *GV = GA->getGlobal();
3397
3398 SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
3399
3400 if (Model == TLSModel::LocalExec) {
3401 SDValue HiVar = DAG.getTargetGlobalAddress(
Kristof Beylsaea84612015-03-04 09:12:08 +00003402 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
Tim Northover3b0846e2014-05-24 12:50:23 +00003403 SDValue LoVar = DAG.getTargetGlobalAddress(
3404 GV, DL, PtrVT, 0,
Kristof Beylsaea84612015-03-04 09:12:08 +00003405 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
Tim Northover3b0846e2014-05-24 12:50:23 +00003406
Kristof Beylsaea84612015-03-04 09:12:08 +00003407 SDValue TPWithOff_lo =
3408 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003409 HiVar,
3410 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003411 0);
3412 SDValue TPWithOff =
3413 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003414 LoVar,
3415 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003416 0);
3417 return TPWithOff;
Tim Northover3b0846e2014-05-24 12:50:23 +00003418 } else if (Model == TLSModel::InitialExec) {
3419 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3420 TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
3421 } else if (Model == TLSModel::LocalDynamic) {
3422 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
3423 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
3424 // the beginning of the module's TLS region, followed by a DTPREL offset
3425 // calculation.
3426
3427 // These accesses will need deduplicating if there's more than one.
3428 AArch64FunctionInfo *MFI =
3429 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
3430 MFI->incNumLocalDynamicTLSAccesses();
3431
Tim Northover3b0846e2014-05-24 12:50:23 +00003432 // The call needs a relocation too for linker relaxation. It doesn't make
3433 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3434 // the address.
3435 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
3436 AArch64II::MO_TLS);
3437
3438 // Now we can calculate the offset from TPIDR_EL0 to this module's
3439 // thread-local area.
Kristof Beylsaea84612015-03-04 09:12:08 +00003440 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00003441
3442 // Now use :dtprel_whatever: operations to calculate this variable's offset
3443 // in its thread-storage area.
3444 SDValue HiVar = DAG.getTargetGlobalAddress(
Kristof Beylsaea84612015-03-04 09:12:08 +00003445 GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
Tim Northover3b0846e2014-05-24 12:50:23 +00003446 SDValue LoVar = DAG.getTargetGlobalAddress(
3447 GV, DL, MVT::i64, 0,
Tim Northover3b0846e2014-05-24 12:50:23 +00003448 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3449
Kristof Beylsaea84612015-03-04 09:12:08 +00003450 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003451 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003452 0);
3453 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003454 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003455 0);
3456 } else if (Model == TLSModel::GeneralDynamic) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003457 // The call needs a relocation too for linker relaxation. It doesn't make
3458 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3459 // the address.
3460 SDValue SymAddr =
3461 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3462
3463 // Finally we can make a call to calculate the offset from tpidr_el0.
Kristof Beylsaea84612015-03-04 09:12:08 +00003464 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00003465 } else
3466 llvm_unreachable("Unsupported ELF TLS access model");
3467
3468 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
3469}
3470
3471SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
3472 SelectionDAG &DAG) const {
3473 if (Subtarget->isTargetDarwin())
3474 return LowerDarwinGlobalTLSAddress(Op, DAG);
3475 else if (Subtarget->isTargetELF())
3476 return LowerELFGlobalTLSAddress(Op, DAG);
3477
3478 llvm_unreachable("Unexpected platform trying to use TLS");
3479}
3480SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3481 SDValue Chain = Op.getOperand(0);
3482 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3483 SDValue LHS = Op.getOperand(2);
3484 SDValue RHS = Op.getOperand(3);
3485 SDValue Dest = Op.getOperand(4);
3486 SDLoc dl(Op);
3487
3488 // Handle f128 first, since lowering it will result in comparing the return
3489 // value of a libcall against zero, which is just what the rest of LowerBR_CC
3490 // is expecting to deal with.
3491 if (LHS.getValueType() == MVT::f128) {
3492 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3493
3494 // If softenSetCCOperands returned a scalar, we need to compare the result
3495 // against zero to select between true and false values.
3496 if (!RHS.getNode()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003497 RHS = DAG.getConstant(0, dl, LHS.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00003498 CC = ISD::SETNE;
3499 }
3500 }
3501
3502 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
3503 // instruction.
3504 unsigned Opc = LHS.getOpcode();
3505 if (LHS.getResNo() == 1 && isa<ConstantSDNode>(RHS) &&
3506 cast<ConstantSDNode>(RHS)->isOne() &&
3507 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3508 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
3509 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
3510 "Unexpected condition code.");
3511 // Only lower legal XALUO ops.
3512 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
3513 return SDValue();
3514
3515 // The actual operation with overflow check.
3516 AArch64CC::CondCode OFCC;
3517 SDValue Value, Overflow;
3518 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
3519
3520 if (CC == ISD::SETNE)
3521 OFCC = getInvertedCondCode(OFCC);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003522 SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003523
Ahmed Bougachadf956a22015-02-06 23:15:39 +00003524 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3525 Overflow);
Tim Northover3b0846e2014-05-24 12:50:23 +00003526 }
3527
3528 if (LHS.getValueType().isInteger()) {
3529 assert((LHS.getValueType() == RHS.getValueType()) &&
3530 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3531
3532 // If the RHS of the comparison is zero, we can potentially fold this
3533 // to a specialized branch.
3534 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
3535 if (RHSC && RHSC->getZExtValue() == 0) {
3536 if (CC == ISD::SETEQ) {
3537 // See if we can use a TBZ to fold in an AND as well.
3538 // TBZ has a smaller branch displacement than CBZ. If the offset is
3539 // out of bounds, a late MI-layer pass rewrites branches.
3540 // 403.gcc is an example that hits this case.
3541 if (LHS.getOpcode() == ISD::AND &&
3542 isa<ConstantSDNode>(LHS.getOperand(1)) &&
3543 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3544 SDValue Test = LHS.getOperand(0);
3545 uint64_t Mask = LHS.getConstantOperandVal(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00003546 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003547 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3548 Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00003549 }
3550
3551 return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
3552 } else if (CC == ISD::SETNE) {
3553 // See if we can use a TBZ to fold in an AND as well.
3554 // TBZ has a smaller branch displacement than CBZ. If the offset is
3555 // out of bounds, a late MI-layer pass rewrites branches.
3556 // 403.gcc is an example that hits this case.
3557 if (LHS.getOpcode() == ISD::AND &&
3558 isa<ConstantSDNode>(LHS.getOperand(1)) &&
3559 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3560 SDValue Test = LHS.getOperand(0);
3561 uint64_t Mask = LHS.getConstantOperandVal(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00003562 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003563 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3564 Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00003565 }
3566
3567 return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
Chad Rosier579c02c2014-08-01 14:48:56 +00003568 } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
3569 // Don't combine AND since emitComparison converts the AND to an ANDS
3570 // (a.k.a. TST) and the test in the test bit and branch instruction
3571 // becomes redundant. This would also increase register pressure.
3572 uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
3573 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003574 DAG.getConstant(Mask, dl, MVT::i64), Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00003575 }
3576 }
Chad Rosier579c02c2014-08-01 14:48:56 +00003577 if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
3578 LHS.getOpcode() != ISD::AND) {
3579 // Don't combine AND since emitComparison converts the AND to an ANDS
3580 // (a.k.a. TST) and the test in the test bit and branch instruction
3581 // becomes redundant. This would also increase register pressure.
3582 uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
3583 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003584 DAG.getConstant(Mask, dl, MVT::i64), Dest);
Chad Rosier579c02c2014-08-01 14:48:56 +00003585 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003586
3587 SDValue CCVal;
3588 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3589 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3590 Cmp);
3591 }
3592
3593 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3594
3595 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
3596 // clean. Some of them require two branches to implement.
3597 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3598 AArch64CC::CondCode CC1, CC2;
3599 changeFPCCToAArch64CC(CC, CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003600 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003601 SDValue BR1 =
3602 DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
3603 if (CC2 != AArch64CC::AL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003604 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003605 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
3606 Cmp);
3607 }
3608
3609 return BR1;
3610}
3611
3612SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
3613 SelectionDAG &DAG) const {
3614 EVT VT = Op.getValueType();
3615 SDLoc DL(Op);
3616
3617 SDValue In1 = Op.getOperand(0);
3618 SDValue In2 = Op.getOperand(1);
3619 EVT SrcVT = In2.getValueType();
3620 if (SrcVT != VT) {
3621 if (SrcVT == MVT::f32 && VT == MVT::f64)
3622 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
3623 else if (SrcVT == MVT::f64 && VT == MVT::f32)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003624 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2,
3625 DAG.getIntPtrConstant(0, DL));
Tim Northover3b0846e2014-05-24 12:50:23 +00003626 else
3627 // FIXME: Src type is different, bail out for now. Can VT really be a
3628 // vector type?
3629 return SDValue();
3630 }
3631
3632 EVT VecVT;
3633 EVT EltVT;
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00003634 uint64_t EltMask;
3635 SDValue VecVal1, VecVal2;
Tim Northover3b0846e2014-05-24 12:50:23 +00003636 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
3637 EltVT = MVT::i32;
3638 VecVT = MVT::v4i32;
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00003639 EltMask = 0x80000000ULL;
Tim Northover3b0846e2014-05-24 12:50:23 +00003640
3641 if (!VT.isVector()) {
3642 VecVal1 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3643 DAG.getUNDEF(VecVT), In1);
3644 VecVal2 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3645 DAG.getUNDEF(VecVT), In2);
3646 } else {
3647 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3648 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3649 }
3650 } else if (VT == MVT::f64 || VT == MVT::v2f64) {
3651 EltVT = MVT::i64;
3652 VecVT = MVT::v2i64;
3653
Eric Christopher572e03a2015-06-19 01:53:21 +00003654 // We want to materialize a mask with the high bit set, but the AdvSIMD
Tim Northover3b0846e2014-05-24 12:50:23 +00003655 // immediate moves cannot materialize that in a single instruction for
3656 // 64-bit elements. Instead, materialize zero and then negate it.
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00003657 EltMask = 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00003658
3659 if (!VT.isVector()) {
3660 VecVal1 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3661 DAG.getUNDEF(VecVT), In1);
3662 VecVal2 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3663 DAG.getUNDEF(VecVT), In2);
3664 } else {
3665 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3666 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3667 }
3668 } else {
3669 llvm_unreachable("Invalid type for copysign!");
3670 }
3671
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003672 SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00003673
3674 // If we couldn't materialize the mask above, then the mask vector will be
3675 // the zero vector, and we need to negate it here.
3676 if (VT == MVT::f64 || VT == MVT::v2f64) {
3677 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
3678 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
3679 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
3680 }
3681
3682 SDValue Sel =
3683 DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
3684
3685 if (VT == MVT::f32)
3686 return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
3687 else if (VT == MVT::f64)
3688 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
3689 else
3690 return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
3691}
3692
3693SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
Duncan P. N. Exon Smith003bb7d2015-02-14 02:09:06 +00003694 if (DAG.getMachineFunction().getFunction()->hasFnAttribute(
3695 Attribute::NoImplicitFloat))
Tim Northover3b0846e2014-05-24 12:50:23 +00003696 return SDValue();
3697
Weiming Zhao7a2d1562014-11-19 00:29:14 +00003698 if (!Subtarget->hasNEON())
3699 return SDValue();
3700
Tim Northover3b0846e2014-05-24 12:50:23 +00003701 // While there is no integer popcount instruction, it can
3702 // be more efficiently lowered to the following sequence that uses
3703 // AdvSIMD registers/instructions as long as the copies to/from
3704 // the AdvSIMD registers are cheap.
3705 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd
3706 // CNT V0.8B, V0.8B // 8xbyte pop-counts
3707 // ADDV B0, V0.8B // sum 8xbyte pop-counts
3708 // UMOV X0, V0.B[0] // copy byte result back to integer reg
3709 SDValue Val = Op.getOperand(0);
3710 SDLoc DL(Op);
3711 EVT VT = Op.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00003712
Hao Liue0335d72015-01-30 02:13:53 +00003713 if (VT == MVT::i32)
3714 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
3715 Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
Tim Northover3b0846e2014-05-24 12:50:23 +00003716
Hao Liue0335d72015-01-30 02:13:53 +00003717 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
Tim Northover3b0846e2014-05-24 12:50:23 +00003718 SDValue UaddLV = DAG.getNode(
3719 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003720 DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
Tim Northover3b0846e2014-05-24 12:50:23 +00003721
3722 if (VT == MVT::i64)
3723 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
3724 return UaddLV;
3725}
3726
3727SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3728
3729 if (Op.getValueType().isVector())
3730 return LowerVSETCC(Op, DAG);
3731
3732 SDValue LHS = Op.getOperand(0);
3733 SDValue RHS = Op.getOperand(1);
3734 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3735 SDLoc dl(Op);
3736
3737 // We chose ZeroOrOneBooleanContents, so use zero and one.
3738 EVT VT = Op.getValueType();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003739 SDValue TVal = DAG.getConstant(1, dl, VT);
3740 SDValue FVal = DAG.getConstant(0, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00003741
3742 // Handle f128 first, since one possible outcome is a normal integer
3743 // comparison which gets picked up by the next if statement.
3744 if (LHS.getValueType() == MVT::f128) {
3745 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3746
3747 // If softenSetCCOperands returned a scalar, use it.
3748 if (!RHS.getNode()) {
3749 assert(LHS.getValueType() == Op.getValueType() &&
3750 "Unexpected setcc expansion!");
3751 return LHS;
3752 }
3753 }
3754
3755 if (LHS.getValueType().isInteger()) {
3756 SDValue CCVal;
3757 SDValue Cmp =
3758 getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
3759
3760 // Note that we inverted the condition above, so we reverse the order of
3761 // the true and false operands here. This will allow the setcc to be
3762 // matched to a single CSINC instruction.
3763 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
3764 }
3765
3766 // Now we know we're dealing with FP values.
3767 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3768
3769 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
3770 // and do the comparison.
3771 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3772
3773 AArch64CC::CondCode CC1, CC2;
3774 changeFPCCToAArch64CC(CC, CC1, CC2);
3775 if (CC2 == AArch64CC::AL) {
3776 changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003777 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003778
3779 // Note that we inverted the condition above, so we reverse the order of
3780 // the true and false operands here. This will allow the setcc to be
3781 // matched to a single CSINC instruction.
3782 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
3783 } else {
3784 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
3785 // totally clean. Some of them require two CSELs to implement. As is in
3786 // this case, we emit the first CSEL and then emit a second using the output
3787 // of the first as the RHS. We're effectively OR'ing the two CC's together.
3788
3789 // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003790 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003791 SDValue CS1 =
3792 DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3793
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003794 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003795 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3796 }
3797}
3798
3799/// A SELECT_CC operation is really some kind of max or min if both values being
3800/// compared are, in some sense, equal to the results in either case. However,
3801/// it is permissible to compare f32 values and produce directly extended f64
3802/// values.
3803///
3804/// Extending the comparison operands would also be allowed, but is less likely
3805/// to happen in practice since their use is right here. Note that truncate
3806/// operations would *not* be semantically equivalent.
3807static bool selectCCOpsAreFMaxCompatible(SDValue Cmp, SDValue Result) {
3808 if (Cmp == Result)
Artyom Skrobova70dfe12015-05-14 12:59:46 +00003809 return (Cmp.getValueType() == MVT::f32 ||
3810 Cmp.getValueType() == MVT::f64);
Tim Northover3b0846e2014-05-24 12:50:23 +00003811
3812 ConstantFPSDNode *CCmp = dyn_cast<ConstantFPSDNode>(Cmp);
3813 ConstantFPSDNode *CResult = dyn_cast<ConstantFPSDNode>(Result);
3814 if (CCmp && CResult && Cmp.getValueType() == MVT::f32 &&
3815 Result.getValueType() == MVT::f64) {
3816 bool Lossy;
3817 APFloat CmpVal = CCmp->getValueAPF();
3818 CmpVal.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &Lossy);
3819 return CResult->getValueAPF().bitwiseIsEqual(CmpVal);
3820 }
3821
3822 return Result->getOpcode() == ISD::FP_EXTEND && Result->getOperand(0) == Cmp;
3823}
3824
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00003825SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
3826 SDValue RHS, SDValue TVal,
3827 SDValue FVal, SDLoc dl,
Tim Northover3b0846e2014-05-24 12:50:23 +00003828 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00003829 // Handle f128 first, because it will result in a comparison of some RTLIB
3830 // call result against zero.
3831 if (LHS.getValueType() == MVT::f128) {
3832 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3833
3834 // If softenSetCCOperands returned a scalar, we need to compare the result
3835 // against zero to select between true and false values.
3836 if (!RHS.getNode()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003837 RHS = DAG.getConstant(0, dl, LHS.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00003838 CC = ISD::SETNE;
3839 }
3840 }
3841
3842 // Handle integers first.
3843 if (LHS.getValueType().isInteger()) {
3844 assert((LHS.getValueType() == RHS.getValueType()) &&
3845 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3846
3847 unsigned Opcode = AArch64ISD::CSEL;
3848
3849 // If both the TVal and the FVal are constants, see if we can swap them in
3850 // order to for a CSINV or CSINC out of them.
3851 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
3852 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
3853
3854 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
3855 std::swap(TVal, FVal);
3856 std::swap(CTVal, CFVal);
3857 CC = ISD::getSetCCInverse(CC, true);
3858 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
3859 std::swap(TVal, FVal);
3860 std::swap(CTVal, CFVal);
3861 CC = ISD::getSetCCInverse(CC, true);
3862 } else if (TVal.getOpcode() == ISD::XOR) {
3863 // If TVal is a NOT we want to swap TVal and FVal so that we can match
3864 // with a CSINV rather than a CSEL.
3865 ConstantSDNode *CVal = dyn_cast<ConstantSDNode>(TVal.getOperand(1));
3866
3867 if (CVal && CVal->isAllOnesValue()) {
3868 std::swap(TVal, FVal);
3869 std::swap(CTVal, CFVal);
3870 CC = ISD::getSetCCInverse(CC, true);
3871 }
3872 } else if (TVal.getOpcode() == ISD::SUB) {
3873 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
3874 // that we can match with a CSNEG rather than a CSEL.
3875 ConstantSDNode *CVal = dyn_cast<ConstantSDNode>(TVal.getOperand(0));
3876
3877 if (CVal && CVal->isNullValue()) {
3878 std::swap(TVal, FVal);
3879 std::swap(CTVal, CFVal);
3880 CC = ISD::getSetCCInverse(CC, true);
3881 }
3882 } else if (CTVal && CFVal) {
3883 const int64_t TrueVal = CTVal->getSExtValue();
3884 const int64_t FalseVal = CFVal->getSExtValue();
3885 bool Swap = false;
3886
3887 // If both TVal and FVal are constants, see if FVal is the
3888 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
3889 // instead of a CSEL in that case.
3890 if (TrueVal == ~FalseVal) {
3891 Opcode = AArch64ISD::CSINV;
3892 } else if (TrueVal == -FalseVal) {
3893 Opcode = AArch64ISD::CSNEG;
3894 } else if (TVal.getValueType() == MVT::i32) {
3895 // If our operands are only 32-bit wide, make sure we use 32-bit
3896 // arithmetic for the check whether we can use CSINC. This ensures that
3897 // the addition in the check will wrap around properly in case there is
3898 // an overflow (which would not be the case if we do the check with
3899 // 64-bit arithmetic).
3900 const uint32_t TrueVal32 = CTVal->getZExtValue();
3901 const uint32_t FalseVal32 = CFVal->getZExtValue();
3902
3903 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
3904 Opcode = AArch64ISD::CSINC;
3905
3906 if (TrueVal32 > FalseVal32) {
3907 Swap = true;
3908 }
3909 }
3910 // 64-bit check whether we can use CSINC.
3911 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
3912 Opcode = AArch64ISD::CSINC;
3913
3914 if (TrueVal > FalseVal) {
3915 Swap = true;
3916 }
3917 }
3918
3919 // Swap TVal and FVal if necessary.
3920 if (Swap) {
3921 std::swap(TVal, FVal);
3922 std::swap(CTVal, CFVal);
3923 CC = ISD::getSetCCInverse(CC, true);
3924 }
3925
3926 if (Opcode != AArch64ISD::CSEL) {
3927 // Drop FVal since we can get its value by simply inverting/negating
3928 // TVal.
3929 FVal = TVal;
3930 }
3931 }
3932
3933 SDValue CCVal;
3934 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3935
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00003936 EVT VT = TVal.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00003937 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
3938 }
3939
3940 // Now we know we're dealing with FP values.
3941 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3942 assert(LHS.getValueType() == RHS.getValueType());
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00003943 EVT VT = TVal.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00003944 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3945
3946 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
3947 // clean. Some of them require two CSELs to implement.
3948 AArch64CC::CondCode CC1, CC2;
3949 changeFPCCToAArch64CC(CC, CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003950 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003951 SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3952
3953 // If we need a second CSEL, emit it, using the output of the first as the
3954 // RHS. We're effectively OR'ing the two CC's together.
3955 if (CC2 != AArch64CC::AL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003956 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003957 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3958 }
3959
3960 // Otherwise, return the output of the first CSEL.
3961 return CS1;
3962}
3963
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00003964SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
3965 SelectionDAG &DAG) const {
3966 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
3967 SDValue LHS = Op.getOperand(0);
3968 SDValue RHS = Op.getOperand(1);
3969 SDValue TVal = Op.getOperand(2);
3970 SDValue FVal = Op.getOperand(3);
3971 SDLoc DL(Op);
3972 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
3973}
3974
3975SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
3976 SelectionDAG &DAG) const {
3977 SDValue CCVal = Op->getOperand(0);
3978 SDValue TVal = Op->getOperand(1);
3979 SDValue FVal = Op->getOperand(2);
3980 SDLoc DL(Op);
3981
3982 unsigned Opc = CCVal.getOpcode();
3983 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
3984 // instruction.
3985 if (CCVal.getResNo() == 1 &&
3986 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3987 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
3988 // Only lower legal XALUO ops.
3989 if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
3990 return SDValue();
3991
3992 AArch64CC::CondCode OFCC;
3993 SDValue Value, Overflow;
3994 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003995 SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00003996
3997 return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
3998 CCVal, Overflow);
3999 }
4000
4001 // Lower it the same way as we would lower a SELECT_CC node.
4002 ISD::CondCode CC;
4003 SDValue LHS, RHS;
4004 if (CCVal.getOpcode() == ISD::SETCC) {
4005 LHS = CCVal.getOperand(0);
4006 RHS = CCVal.getOperand(1);
4007 CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
4008 } else {
4009 LHS = CCVal;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004010 RHS = DAG.getConstant(0, DL, CCVal.getValueType());
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004011 CC = ISD::SETNE;
4012 }
4013 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4014}
4015
Tim Northover3b0846e2014-05-24 12:50:23 +00004016SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
4017 SelectionDAG &DAG) const {
4018 // Jump table entries as PC relative offsets. No additional tweaking
4019 // is necessary here. Just get the address of the jump table.
4020 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00004021 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004022 SDLoc DL(Op);
4023
4024 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4025 !Subtarget->isTargetMachO()) {
4026 const unsigned char MO_NC = AArch64II::MO_NC;
4027 return DAG.getNode(
4028 AArch64ISD::WrapperLarge, DL, PtrVT,
4029 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G3),
4030 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G2 | MO_NC),
4031 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G1 | MO_NC),
4032 DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4033 AArch64II::MO_G0 | MO_NC));
4034 }
4035
4036 SDValue Hi =
4037 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_PAGE);
4038 SDValue Lo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4039 AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4040 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4041 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4042}
4043
4044SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
4045 SelectionDAG &DAG) const {
4046 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00004047 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004048 SDLoc DL(Op);
4049
4050 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4051 // Use the GOT for the large code model on iOS.
4052 if (Subtarget->isTargetMachO()) {
4053 SDValue GotAddr = DAG.getTargetConstantPool(
4054 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4055 AArch64II::MO_GOT);
4056 return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
4057 }
4058
4059 const unsigned char MO_NC = AArch64II::MO_NC;
4060 return DAG.getNode(
4061 AArch64ISD::WrapperLarge, DL, PtrVT,
4062 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4063 CP->getOffset(), AArch64II::MO_G3),
4064 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4065 CP->getOffset(), AArch64II::MO_G2 | MO_NC),
4066 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4067 CP->getOffset(), AArch64II::MO_G1 | MO_NC),
4068 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4069 CP->getOffset(), AArch64II::MO_G0 | MO_NC));
4070 } else {
4071 // Use ADRP/ADD or ADRP/LDR for everything else: the small memory model on
4072 // ELF, the only valid one on Darwin.
4073 SDValue Hi =
4074 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4075 CP->getOffset(), AArch64II::MO_PAGE);
4076 SDValue Lo = DAG.getTargetConstantPool(
4077 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4078 AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4079
4080 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4081 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4082 }
4083}
4084
4085SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
4086 SelectionDAG &DAG) const {
4087 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
Mehdi Amini44ede332015-07-09 02:09:04 +00004088 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004089 SDLoc DL(Op);
4090 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4091 !Subtarget->isTargetMachO()) {
4092 const unsigned char MO_NC = AArch64II::MO_NC;
4093 return DAG.getNode(
4094 AArch64ISD::WrapperLarge, DL, PtrVT,
4095 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G3),
4096 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
4097 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
4098 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
4099 } else {
4100 SDValue Hi = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGE);
4101 SDValue Lo = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGEOFF |
4102 AArch64II::MO_NC);
4103 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4104 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4105 }
4106}
4107
4108SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
4109 SelectionDAG &DAG) const {
4110 AArch64FunctionInfo *FuncInfo =
4111 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4112
4113 SDLoc DL(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00004114 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
4115 getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00004116 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4117 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
4118 MachinePointerInfo(SV), false, false, 0);
4119}
4120
4121SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
4122 SelectionDAG &DAG) const {
4123 // The layout of the va_list struct is specified in the AArch64 Procedure Call
4124 // Standard, section B.3.
4125 MachineFunction &MF = DAG.getMachineFunction();
4126 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Mehdi Amini44ede332015-07-09 02:09:04 +00004127 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004128 SDLoc DL(Op);
4129
4130 SDValue Chain = Op.getOperand(0);
4131 SDValue VAList = Op.getOperand(1);
4132 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4133 SmallVector<SDValue, 4> MemOps;
4134
4135 // void *__stack at offset 0
Mehdi Amini44ede332015-07-09 02:09:04 +00004136 SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004137 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
4138 MachinePointerInfo(SV), false, false, 8));
4139
4140 // void *__gr_top at offset 8
4141 int GPRSize = FuncInfo->getVarArgsGPRSize();
4142 if (GPRSize > 0) {
4143 SDValue GRTop, GRTopAddr;
4144
Mehdi Amini44ede332015-07-09 02:09:04 +00004145 GRTopAddr =
4146 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004147
Mehdi Amini44ede332015-07-09 02:09:04 +00004148 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
4149 GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
4150 DAG.getConstant(GPRSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004151
4152 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
4153 MachinePointerInfo(SV, 8), false, false, 8));
4154 }
4155
4156 // void *__vr_top at offset 16
4157 int FPRSize = FuncInfo->getVarArgsFPRSize();
4158 if (FPRSize > 0) {
4159 SDValue VRTop, VRTopAddr;
Mehdi Amini44ede332015-07-09 02:09:04 +00004160 VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4161 DAG.getConstant(16, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004162
Mehdi Amini44ede332015-07-09 02:09:04 +00004163 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
4164 VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
4165 DAG.getConstant(FPRSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004166
4167 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
4168 MachinePointerInfo(SV, 16), false, false, 8));
4169 }
4170
4171 // int __gr_offs at offset 24
Mehdi Amini44ede332015-07-09 02:09:04 +00004172 SDValue GROffsAddr =
4173 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004174 MemOps.push_back(DAG.getStore(Chain, DL,
4175 DAG.getConstant(-GPRSize, DL, MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00004176 GROffsAddr, MachinePointerInfo(SV, 24), false,
4177 false, 4));
4178
4179 // int __vr_offs at offset 28
Mehdi Amini44ede332015-07-09 02:09:04 +00004180 SDValue VROffsAddr =
4181 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004182 MemOps.push_back(DAG.getStore(Chain, DL,
4183 DAG.getConstant(-FPRSize, DL, MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00004184 VROffsAddr, MachinePointerInfo(SV, 28), false,
4185 false, 4));
4186
4187 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
4188}
4189
4190SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
4191 SelectionDAG &DAG) const {
4192 return Subtarget->isTargetDarwin() ? LowerDarwin_VASTART(Op, DAG)
4193 : LowerAAPCS_VASTART(Op, DAG);
4194}
4195
4196SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
4197 SelectionDAG &DAG) const {
4198 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
4199 // pointer.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004200 SDLoc DL(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00004201 unsigned VaListSize = Subtarget->isTargetDarwin() ? 8 : 32;
4202 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4203 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4204
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004205 return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1),
4206 Op.getOperand(2),
4207 DAG.getConstant(VaListSize, DL, MVT::i32),
Krzysztof Parzyszeka46c36b2015-04-13 17:16:45 +00004208 8, false, false, false, MachinePointerInfo(DestSV),
Tim Northover3b0846e2014-05-24 12:50:23 +00004209 MachinePointerInfo(SrcSV));
4210}
4211
4212SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
4213 assert(Subtarget->isTargetDarwin() &&
4214 "automatic va_arg instruction only works on Darwin");
4215
4216 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4217 EVT VT = Op.getValueType();
4218 SDLoc DL(Op);
4219 SDValue Chain = Op.getOperand(0);
4220 SDValue Addr = Op.getOperand(1);
4221 unsigned Align = Op.getConstantOperandVal(3);
Mehdi Amini44ede332015-07-09 02:09:04 +00004222 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004223
Mehdi Amini44ede332015-07-09 02:09:04 +00004224 SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V),
4225 false, false, false, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00004226 Chain = VAList.getValue(1);
4227
4228 if (Align > 8) {
4229 assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
Mehdi Amini44ede332015-07-09 02:09:04 +00004230 VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4231 DAG.getConstant(Align - 1, DL, PtrVT));
4232 VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
4233 DAG.getConstant(-(int64_t)Align, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004234 }
4235
4236 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
Mehdi Amini44ede332015-07-09 02:09:04 +00004237 uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
Tim Northover3b0846e2014-05-24 12:50:23 +00004238
4239 // Scalar integer and FP values smaller than 64 bits are implicitly extended
4240 // up to 64 bits. At the very least, we have to increase the striding of the
4241 // vaargs list to match this, and for FP values we need to introduce
4242 // FP_ROUND nodes as well.
4243 if (VT.isInteger() && !VT.isVector())
4244 ArgSize = 8;
4245 bool NeedFPTrunc = false;
4246 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
4247 ArgSize = 8;
4248 NeedFPTrunc = true;
4249 }
4250
4251 // Increment the pointer, VAList, to the next vaarg
Mehdi Amini44ede332015-07-09 02:09:04 +00004252 SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4253 DAG.getConstant(ArgSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004254 // Store the incremented VAList to the legalized pointer
4255 SDValue APStore = DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V),
4256 false, false, 0);
4257
4258 // Load the actual argument out of the pointer VAList
4259 if (NeedFPTrunc) {
4260 // Load the value as an f64.
4261 SDValue WideFP = DAG.getLoad(MVT::f64, DL, APStore, VAList,
4262 MachinePointerInfo(), false, false, false, 0);
4263 // Round the value down to an f32.
4264 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004265 DAG.getIntPtrConstant(1, DL));
Tim Northover3b0846e2014-05-24 12:50:23 +00004266 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
4267 // Merge the rounded value with the chain output of the load.
4268 return DAG.getMergeValues(Ops, DL);
4269 }
4270
4271 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo(), false,
4272 false, false, 0);
4273}
4274
4275SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
4276 SelectionDAG &DAG) const {
4277 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4278 MFI->setFrameAddressIsTaken(true);
4279
4280 EVT VT = Op.getValueType();
4281 SDLoc DL(Op);
4282 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4283 SDValue FrameAddr =
4284 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
4285 while (Depth--)
4286 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
4287 MachinePointerInfo(), false, false, false, 0);
4288 return FrameAddr;
4289}
4290
4291// FIXME? Maybe this could be a TableGen attribute on some registers and
4292// this table could be generated automatically from RegInfo.
Pat Gavlina717f252015-07-09 17:40:29 +00004293unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT,
4294 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004295 unsigned Reg = StringSwitch<unsigned>(RegName)
4296 .Case("sp", AArch64::SP)
4297 .Default(0);
4298 if (Reg)
4299 return Reg;
Luke Cheeseman85fd06d2015-06-01 12:02:47 +00004300 report_fatal_error(Twine("Invalid register name \""
4301 + StringRef(RegName) + "\"."));
Tim Northover3b0846e2014-05-24 12:50:23 +00004302}
4303
4304SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
4305 SelectionDAG &DAG) const {
4306 MachineFunction &MF = DAG.getMachineFunction();
4307 MachineFrameInfo *MFI = MF.getFrameInfo();
4308 MFI->setReturnAddressIsTaken(true);
4309
4310 EVT VT = Op.getValueType();
4311 SDLoc DL(Op);
4312 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4313 if (Depth) {
4314 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
Mehdi Amini44ede332015-07-09 02:09:04 +00004315 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00004316 return DAG.getLoad(VT, DL, DAG.getEntryNode(),
4317 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
4318 MachinePointerInfo(), false, false, false, 0);
4319 }
4320
4321 // Return LR, which contains the return address. Mark it an implicit live-in.
4322 unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
4323 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4324}
4325
4326/// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4327/// i64 values and take a 2 x i64 value to shift plus a shift amount.
4328SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
4329 SelectionDAG &DAG) const {
4330 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4331 EVT VT = Op.getValueType();
4332 unsigned VTBits = VT.getSizeInBits();
4333 SDLoc dl(Op);
4334 SDValue ShOpLo = Op.getOperand(0);
4335 SDValue ShOpHi = Op.getOperand(1);
4336 SDValue ShAmt = Op.getOperand(2);
4337 SDValue ARMcc;
4338 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4339
4340 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4341
4342 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004343 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
Tim Northover3b0846e2014-05-24 12:50:23 +00004344 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4345 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004346 DAG.getConstant(VTBits, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00004347 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4348
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004349 SDValue Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64),
Tim Northover3b0846e2014-05-24 12:50:23 +00004350 ISD::SETGE, dl, DAG);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004351 SDValue CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004352
4353 SDValue FalseValLo = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4354 SDValue TrueValLo = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4355 SDValue Lo =
4356 DAG.getNode(AArch64ISD::CSEL, dl, VT, TrueValLo, FalseValLo, CCVal, Cmp);
4357
4358 // AArch64 shifts larger than the register width are wrapped rather than
4359 // clamped, so we can't just emit "hi >> x".
4360 SDValue FalseValHi = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4361 SDValue TrueValHi = Opc == ISD::SRA
4362 ? DAG.getNode(Opc, dl, VT, ShOpHi,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004363 DAG.getConstant(VTBits - 1, dl,
4364 MVT::i64))
4365 : DAG.getConstant(0, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004366 SDValue Hi =
4367 DAG.getNode(AArch64ISD::CSEL, dl, VT, TrueValHi, FalseValHi, CCVal, Cmp);
4368
4369 SDValue Ops[2] = { Lo, Hi };
4370 return DAG.getMergeValues(Ops, dl);
4371}
4372
4373/// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4374/// i64 values and take a 2 x i64 value to shift plus a shift amount.
4375SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
4376 SelectionDAG &DAG) const {
4377 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4378 EVT VT = Op.getValueType();
4379 unsigned VTBits = VT.getSizeInBits();
4380 SDLoc dl(Op);
4381 SDValue ShOpLo = Op.getOperand(0);
4382 SDValue ShOpHi = Op.getOperand(1);
4383 SDValue ShAmt = Op.getOperand(2);
4384 SDValue ARMcc;
4385
4386 assert(Op.getOpcode() == ISD::SHL_PARTS);
4387 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004388 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
Tim Northover3b0846e2014-05-24 12:50:23 +00004389 SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4390 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004391 DAG.getConstant(VTBits, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00004392 SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4393 SDValue Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4394
4395 SDValue FalseVal = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4396
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004397 SDValue Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64),
Tim Northover3b0846e2014-05-24 12:50:23 +00004398 ISD::SETGE, dl, DAG);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004399 SDValue CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004400 SDValue Hi =
4401 DAG.getNode(AArch64ISD::CSEL, dl, VT, Tmp3, FalseVal, CCVal, Cmp);
4402
4403 // AArch64 shifts of larger than register sizes are wrapped rather than
4404 // clamped, so we can't just emit "lo << a" if a is too big.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004405 SDValue TrueValLo = DAG.getConstant(0, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004406 SDValue FalseValLo = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4407 SDValue Lo =
4408 DAG.getNode(AArch64ISD::CSEL, dl, VT, TrueValLo, FalseValLo, CCVal, Cmp);
4409
4410 SDValue Ops[2] = { Lo, Hi };
4411 return DAG.getMergeValues(Ops, dl);
4412}
4413
4414bool AArch64TargetLowering::isOffsetFoldingLegal(
4415 const GlobalAddressSDNode *GA) const {
4416 // The AArch64 target doesn't support folding offsets into global addresses.
4417 return false;
4418}
4419
4420bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4421 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
4422 // FIXME: We should be able to handle f128 as well with a clever lowering.
4423 if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32))
4424 return true;
4425
4426 if (VT == MVT::f64)
4427 return AArch64_AM::getFP64Imm(Imm) != -1;
4428 else if (VT == MVT::f32)
4429 return AArch64_AM::getFP32Imm(Imm) != -1;
4430 return false;
4431}
4432
4433//===----------------------------------------------------------------------===//
4434// AArch64 Optimization Hooks
4435//===----------------------------------------------------------------------===//
4436
4437//===----------------------------------------------------------------------===//
4438// AArch64 Inline Assembly Support
4439//===----------------------------------------------------------------------===//
4440
4441// Table of Constraints
4442// TODO: This is the current set of constraints supported by ARM for the
4443// compiler, not all of them may make sense, e.g. S may be difficult to support.
4444//
4445// r - A general register
4446// w - An FP/SIMD register of some size in the range v0-v31
4447// x - An FP/SIMD register of some size in the range v0-v15
4448// I - Constant that can be used with an ADD instruction
4449// J - Constant that can be used with a SUB instruction
4450// K - Constant that can be used with a 32-bit logical instruction
4451// L - Constant that can be used with a 64-bit logical instruction
4452// M - Constant that can be used as a 32-bit MOV immediate
4453// N - Constant that can be used as a 64-bit MOV immediate
4454// Q - A memory reference with base register and no offset
4455// S - A symbolic address
4456// Y - Floating point constant zero
4457// Z - Integer constant zero
4458//
4459// Note that general register operands will be output using their 64-bit x
4460// register name, whatever the size of the variable, unless the asm operand
4461// is prefixed by the %w modifier. Floating-point and SIMD register operands
4462// will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
4463// %q modifier.
4464
4465/// getConstraintType - Given a constraint letter, return the type of
4466/// constraint it is for this target.
4467AArch64TargetLowering::ConstraintType
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00004468AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004469 if (Constraint.size() == 1) {
4470 switch (Constraint[0]) {
4471 default:
4472 break;
4473 case 'z':
4474 return C_Other;
4475 case 'x':
4476 case 'w':
4477 return C_RegisterClass;
4478 // An address with a single base register. Due to the way we
4479 // currently handle addresses it is the same as 'r'.
4480 case 'Q':
4481 return C_Memory;
4482 }
4483 }
4484 return TargetLowering::getConstraintType(Constraint);
4485}
4486
4487/// Examine constraint type and operand type and determine a weight value.
4488/// This object must already have been set up with the operand type
4489/// and the current alternative constraint selected.
4490TargetLowering::ConstraintWeight
4491AArch64TargetLowering::getSingleConstraintMatchWeight(
4492 AsmOperandInfo &info, const char *constraint) const {
4493 ConstraintWeight weight = CW_Invalid;
4494 Value *CallOperandVal = info.CallOperandVal;
4495 // If we don't have a value, we can't do a match,
4496 // but allow it at the lowest weight.
4497 if (!CallOperandVal)
4498 return CW_Default;
4499 Type *type = CallOperandVal->getType();
4500 // Look at the constraint type.
4501 switch (*constraint) {
4502 default:
4503 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
4504 break;
4505 case 'x':
4506 case 'w':
4507 if (type->isFloatingPointTy() || type->isVectorTy())
4508 weight = CW_Register;
4509 break;
4510 case 'z':
4511 weight = CW_Constant;
4512 break;
4513 }
4514 return weight;
4515}
4516
4517std::pair<unsigned, const TargetRegisterClass *>
4518AArch64TargetLowering::getRegForInlineAsmConstraint(
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00004519 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004520 if (Constraint.size() == 1) {
4521 switch (Constraint[0]) {
4522 case 'r':
4523 if (VT.getSizeInBits() == 64)
4524 return std::make_pair(0U, &AArch64::GPR64commonRegClass);
4525 return std::make_pair(0U, &AArch64::GPR32commonRegClass);
4526 case 'w':
4527 if (VT == MVT::f32)
4528 return std::make_pair(0U, &AArch64::FPR32RegClass);
4529 if (VT.getSizeInBits() == 64)
4530 return std::make_pair(0U, &AArch64::FPR64RegClass);
4531 if (VT.getSizeInBits() == 128)
4532 return std::make_pair(0U, &AArch64::FPR128RegClass);
4533 break;
4534 // The instructions that this constraint is designed for can
4535 // only take 128-bit registers so just use that regclass.
4536 case 'x':
4537 if (VT.getSizeInBits() == 128)
4538 return std::make_pair(0U, &AArch64::FPR128_loRegClass);
4539 break;
4540 }
4541 }
4542 if (StringRef("{cc}").equals_lower(Constraint))
4543 return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
4544
4545 // Use the default implementation in TargetLowering to convert the register
4546 // constraint into a member of a register class.
4547 std::pair<unsigned, const TargetRegisterClass *> Res;
Eric Christopher11e4df72015-02-26 22:38:43 +00004548 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004549
4550 // Not found as a standard register?
4551 if (!Res.second) {
4552 unsigned Size = Constraint.size();
4553 if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
4554 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00004555 int RegNo;
4556 bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
4557 if (!Failed && RegNo >= 0 && RegNo <= 31) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004558 // v0 - v31 are aliases of q0 - q31.
4559 // By default we'll emit v0-v31 for this unless there's a modifier where
4560 // we'll emit the correct register as well.
4561 Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
4562 Res.second = &AArch64::FPR128RegClass;
4563 }
4564 }
4565 }
4566
4567 return Res;
4568}
4569
4570/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
4571/// vector. If it is invalid, don't add anything to Ops.
4572void AArch64TargetLowering::LowerAsmOperandForConstraint(
4573 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
4574 SelectionDAG &DAG) const {
4575 SDValue Result;
4576
4577 // Currently only support length 1 constraints.
4578 if (Constraint.length() != 1)
4579 return;
4580
4581 char ConstraintLetter = Constraint[0];
4582 switch (ConstraintLetter) {
4583 default:
4584 break;
4585
4586 // This set of constraints deal with valid constants for various instructions.
4587 // Validate and return a target constant for them if we can.
4588 case 'z': {
4589 // 'z' maps to xzr or wzr so it needs an input of 0.
4590 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4591 if (!C || C->getZExtValue() != 0)
4592 return;
4593
4594 if (Op.getValueType() == MVT::i64)
4595 Result = DAG.getRegister(AArch64::XZR, MVT::i64);
4596 else
4597 Result = DAG.getRegister(AArch64::WZR, MVT::i32);
4598 break;
4599 }
4600
4601 case 'I':
4602 case 'J':
4603 case 'K':
4604 case 'L':
4605 case 'M':
4606 case 'N':
4607 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4608 if (!C)
4609 return;
4610
4611 // Grab the value and do some validation.
4612 uint64_t CVal = C->getZExtValue();
4613 switch (ConstraintLetter) {
4614 // The I constraint applies only to simple ADD or SUB immediate operands:
4615 // i.e. 0 to 4095 with optional shift by 12
4616 // The J constraint applies only to ADD or SUB immediates that would be
4617 // valid when negated, i.e. if [an add pattern] were to be output as a SUB
4618 // instruction [or vice versa], in other words -1 to -4095 with optional
4619 // left shift by 12.
4620 case 'I':
4621 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
4622 break;
4623 return;
4624 case 'J': {
4625 uint64_t NVal = -C->getSExtValue();
Tim Northover2c46beb2014-07-27 07:10:29 +00004626 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
4627 CVal = C->getSExtValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00004628 break;
Tim Northover2c46beb2014-07-27 07:10:29 +00004629 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004630 return;
4631 }
4632 // The K and L constraints apply *only* to logical immediates, including
4633 // what used to be the MOVI alias for ORR (though the MOVI alias has now
4634 // been removed and MOV should be used). So these constraints have to
4635 // distinguish between bit patterns that are valid 32-bit or 64-bit
4636 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
4637 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
4638 // versa.
4639 case 'K':
4640 if (AArch64_AM::isLogicalImmediate(CVal, 32))
4641 break;
4642 return;
4643 case 'L':
4644 if (AArch64_AM::isLogicalImmediate(CVal, 64))
4645 break;
4646 return;
4647 // The M and N constraints are a superset of K and L respectively, for use
4648 // with the MOV (immediate) alias. As well as the logical immediates they
4649 // also match 32 or 64-bit immediates that can be loaded either using a
4650 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
4651 // (M) or 64-bit 0x1234000000000000 (N) etc.
4652 // As a note some of this code is liberally stolen from the asm parser.
4653 case 'M': {
4654 if (!isUInt<32>(CVal))
4655 return;
4656 if (AArch64_AM::isLogicalImmediate(CVal, 32))
4657 break;
4658 if ((CVal & 0xFFFF) == CVal)
4659 break;
4660 if ((CVal & 0xFFFF0000ULL) == CVal)
4661 break;
4662 uint64_t NCVal = ~(uint32_t)CVal;
4663 if ((NCVal & 0xFFFFULL) == NCVal)
4664 break;
4665 if ((NCVal & 0xFFFF0000ULL) == NCVal)
4666 break;
4667 return;
4668 }
4669 case 'N': {
4670 if (AArch64_AM::isLogicalImmediate(CVal, 64))
4671 break;
4672 if ((CVal & 0xFFFFULL) == CVal)
4673 break;
4674 if ((CVal & 0xFFFF0000ULL) == CVal)
4675 break;
4676 if ((CVal & 0xFFFF00000000ULL) == CVal)
4677 break;
4678 if ((CVal & 0xFFFF000000000000ULL) == CVal)
4679 break;
4680 uint64_t NCVal = ~CVal;
4681 if ((NCVal & 0xFFFFULL) == NCVal)
4682 break;
4683 if ((NCVal & 0xFFFF0000ULL) == NCVal)
4684 break;
4685 if ((NCVal & 0xFFFF00000000ULL) == NCVal)
4686 break;
4687 if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
4688 break;
4689 return;
4690 }
4691 default:
4692 return;
4693 }
4694
4695 // All assembler immediates are 64-bit integers.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004696 Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00004697 break;
4698 }
4699
4700 if (Result.getNode()) {
4701 Ops.push_back(Result);
4702 return;
4703 }
4704
4705 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
4706}
4707
4708//===----------------------------------------------------------------------===//
4709// AArch64 Advanced SIMD Support
4710//===----------------------------------------------------------------------===//
4711
4712/// WidenVector - Given a value in the V64 register class, produce the
4713/// equivalent value in the V128 register class.
4714static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
4715 EVT VT = V64Reg.getValueType();
4716 unsigned NarrowSize = VT.getVectorNumElements();
4717 MVT EltTy = VT.getVectorElementType().getSimpleVT();
4718 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
4719 SDLoc DL(V64Reg);
4720
4721 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004722 V64Reg, DAG.getConstant(0, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00004723}
4724
4725/// getExtFactor - Determine the adjustment factor for the position when
4726/// generating an "extract from vector registers" instruction.
4727static unsigned getExtFactor(SDValue &V) {
4728 EVT EltType = V.getValueType().getVectorElementType();
4729 return EltType.getSizeInBits() / 8;
4730}
4731
4732/// NarrowVector - Given a value in the V128 register class, produce the
4733/// equivalent value in the V64 register class.
4734static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
4735 EVT VT = V128Reg.getValueType();
4736 unsigned WideSize = VT.getVectorNumElements();
4737 MVT EltTy = VT.getVectorElementType().getSimpleVT();
4738 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
4739 SDLoc DL(V128Reg);
4740
4741 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
4742}
4743
4744// Gather data to see if the operation can be modelled as a
4745// shuffle in combination with VEXTs.
4746SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
4747 SelectionDAG &DAG) const {
Kevin Qinf0ec9af2014-06-18 05:54:42 +00004748 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
Tim Northover3b0846e2014-05-24 12:50:23 +00004749 SDLoc dl(Op);
4750 EVT VT = Op.getValueType();
4751 unsigned NumElts = VT.getVectorNumElements();
4752
Tim Northover7324e842014-07-24 15:39:55 +00004753 struct ShuffleSourceInfo {
4754 SDValue Vec;
4755 unsigned MinElt;
4756 unsigned MaxElt;
Tim Northover3b0846e2014-05-24 12:50:23 +00004757
Tim Northover7324e842014-07-24 15:39:55 +00004758 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
4759 // be compatible with the shuffle we intend to construct. As a result
4760 // ShuffleVec will be some sliding window into the original Vec.
4761 SDValue ShuffleVec;
4762
4763 // Code should guarantee that element i in Vec starts at element "WindowBase
4764 // + i * WindowScale in ShuffleVec".
4765 int WindowBase;
4766 int WindowScale;
4767
4768 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
4769 ShuffleSourceInfo(SDValue Vec)
4770 : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
4771 WindowScale(1) {}
4772 };
4773
4774 // First gather all vectors used as an immediate source for this BUILD_VECTOR
4775 // node.
4776 SmallVector<ShuffleSourceInfo, 2> Sources;
Tim Northover3b0846e2014-05-24 12:50:23 +00004777 for (unsigned i = 0; i < NumElts; ++i) {
4778 SDValue V = Op.getOperand(i);
4779 if (V.getOpcode() == ISD::UNDEF)
4780 continue;
4781 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4782 // A shuffle can only come from building a vector from various
4783 // elements of other vectors.
4784 return SDValue();
4785 }
4786
Tim Northover7324e842014-07-24 15:39:55 +00004787 // Add this element source to the list if it's not already there.
Tim Northover3b0846e2014-05-24 12:50:23 +00004788 SDValue SourceVec = V.getOperand(0);
Tim Northover7324e842014-07-24 15:39:55 +00004789 auto Source = std::find(Sources.begin(), Sources.end(), SourceVec);
4790 if (Source == Sources.end())
James Molloyf497d552014-10-17 17:06:31 +00004791 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
Tim Northover3b0846e2014-05-24 12:50:23 +00004792
Tim Northover7324e842014-07-24 15:39:55 +00004793 // Update the minimum and maximum lane number seen.
4794 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4795 Source->MinElt = std::min(Source->MinElt, EltNo);
4796 Source->MaxElt = std::max(Source->MaxElt, EltNo);
Tim Northover3b0846e2014-05-24 12:50:23 +00004797 }
4798
4799 // Currently only do something sane when at most two source vectors
Tim Northover7324e842014-07-24 15:39:55 +00004800 // are involved.
4801 if (Sources.size() > 2)
Tim Northover3b0846e2014-05-24 12:50:23 +00004802 return SDValue();
4803
Kevin Qin9a2a2c52014-07-24 02:05:42 +00004804 // Find out the smallest element size among result and two sources, and use
4805 // it as element size to build the shuffle_vector.
4806 EVT SmallestEltTy = VT.getVectorElementType();
Tim Northover7324e842014-07-24 15:39:55 +00004807 for (auto &Source : Sources) {
4808 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00004809 if (SrcEltTy.bitsLT(SmallestEltTy)) {
4810 SmallestEltTy = SrcEltTy;
4811 }
4812 }
4813 unsigned ResMultiplier =
4814 VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00004815 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
4816 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
Tim Northover3b0846e2014-05-24 12:50:23 +00004817
Tim Northover7324e842014-07-24 15:39:55 +00004818 // If the source vector is too wide or too narrow, we may nevertheless be able
4819 // to construct a compatible shuffle either by concatenating it with UNDEF or
4820 // extracting a suitable range of elements.
4821 for (auto &Src : Sources) {
4822 EVT SrcVT = Src.ShuffleVec.getValueType();
Kevin Qinf0ec9af2014-06-18 05:54:42 +00004823
Tim Northover7324e842014-07-24 15:39:55 +00004824 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
Tim Northover3b0846e2014-05-24 12:50:23 +00004825 continue;
Tim Northover7324e842014-07-24 15:39:55 +00004826
4827 // This stage of the search produces a source with the same element type as
4828 // the original, but with a total width matching the BUILD_VECTOR output.
4829 EVT EltVT = SrcVT.getVectorElementType();
James Molloyf497d552014-10-17 17:06:31 +00004830 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
4831 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
Tim Northover7324e842014-07-24 15:39:55 +00004832
4833 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
4834 assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00004835 // We can pad out the smaller vector for free, so if it's part of a
4836 // shuffle...
Tim Northover7324e842014-07-24 15:39:55 +00004837 Src.ShuffleVec =
4838 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
4839 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00004840 continue;
4841 }
4842
Tim Northover7324e842014-07-24 15:39:55 +00004843 assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00004844
James Molloyf497d552014-10-17 17:06:31 +00004845 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004846 // Span too large for a VEXT to cope
4847 return SDValue();
4848 }
4849
James Molloyf497d552014-10-17 17:06:31 +00004850 if (Src.MinElt >= NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004851 // The extraction can just take the second half
Tim Northover7324e842014-07-24 15:39:55 +00004852 Src.ShuffleVec =
4853 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004854 DAG.getConstant(NumSrcElts, dl, MVT::i64));
James Molloyf497d552014-10-17 17:06:31 +00004855 Src.WindowBase = -NumSrcElts;
4856 } else if (Src.MaxElt < NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004857 // The extraction can just take the first half
Tim Northover5e84fe32014-12-06 00:33:37 +00004858 Src.ShuffleVec =
4859 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004860 DAG.getConstant(0, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00004861 } else {
4862 // An actual VEXT is needed
Tim Northover5e84fe32014-12-06 00:33:37 +00004863 SDValue VEXTSrc1 =
4864 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004865 DAG.getConstant(0, dl, MVT::i64));
Tim Northover7324e842014-07-24 15:39:55 +00004866 SDValue VEXTSrc2 =
4867 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004868 DAG.getConstant(NumSrcElts, dl, MVT::i64));
Tim Northover7324e842014-07-24 15:39:55 +00004869 unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
4870
4871 Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004872 VEXTSrc2,
4873 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover7324e842014-07-24 15:39:55 +00004874 Src.WindowBase = -Src.MinElt;
Tim Northover3b0846e2014-05-24 12:50:23 +00004875 }
4876 }
4877
Tim Northover7324e842014-07-24 15:39:55 +00004878 // Another possible incompatibility occurs from the vector element types. We
4879 // can fix this by bitcasting the source vectors to the same type we intend
4880 // for the shuffle.
4881 for (auto &Src : Sources) {
4882 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
4883 if (SrcEltTy == SmallestEltTy)
4884 continue;
4885 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
4886 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
4887 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
4888 Src.WindowBase *= Src.WindowScale;
4889 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004890
Tim Northover7324e842014-07-24 15:39:55 +00004891 // Final sanity check before we try to actually produce a shuffle.
4892 DEBUG(
4893 for (auto Src : Sources)
4894 assert(Src.ShuffleVec.getValueType() == ShuffleVT);
4895 );
4896
4897 // The stars all align, our next step is to produce the mask for the shuffle.
4898 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
4899 int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00004900 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004901 SDValue Entry = Op.getOperand(i);
Tim Northover7324e842014-07-24 15:39:55 +00004902 if (Entry.getOpcode() == ISD::UNDEF)
4903 continue;
Tim Northover3b0846e2014-05-24 12:50:23 +00004904
Tim Northover7324e842014-07-24 15:39:55 +00004905 auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0));
4906 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
4907
4908 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
4909 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
4910 // segment.
4911 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
4912 int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
4913 VT.getVectorElementType().getSizeInBits());
4914 int LanesDefined = BitsDefined / BitsPerShuffleLane;
4915
4916 // This source is expected to fill ResMultiplier lanes of the final shuffle,
4917 // starting at the appropriate offset.
4918 int *LaneMask = &Mask[i * ResMultiplier];
4919
4920 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
4921 ExtractBase += NumElts * (Src - Sources.begin());
4922 for (int j = 0; j < LanesDefined; ++j)
4923 LaneMask[j] = ExtractBase + j;
Tim Northover3b0846e2014-05-24 12:50:23 +00004924 }
4925
4926 // Final check before we try to produce nonsense...
Tim Northover7324e842014-07-24 15:39:55 +00004927 if (!isShuffleMaskLegal(Mask, ShuffleVT))
4928 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00004929
Tim Northover7324e842014-07-24 15:39:55 +00004930 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
4931 for (unsigned i = 0; i < Sources.size(); ++i)
4932 ShuffleOps[i] = Sources[i].ShuffleVec;
4933
4934 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
4935 ShuffleOps[1], &Mask[0]);
4936 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
Tim Northover3b0846e2014-05-24 12:50:23 +00004937}
4938
4939// check if an EXT instruction can handle the shuffle mask when the
4940// vector sources of the shuffle are the same.
4941static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
4942 unsigned NumElts = VT.getVectorNumElements();
4943
4944 // Assume that the first shuffle index is not UNDEF. Fail if it is.
4945 if (M[0] < 0)
4946 return false;
4947
4948 Imm = M[0];
4949
4950 // If this is a VEXT shuffle, the immediate value is the index of the first
4951 // element. The other shuffle indices must be the successive elements after
4952 // the first one.
4953 unsigned ExpectedElt = Imm;
4954 for (unsigned i = 1; i < NumElts; ++i) {
4955 // Increment the expected index. If it wraps around, just follow it
4956 // back to index zero and keep going.
4957 ++ExpectedElt;
4958 if (ExpectedElt == NumElts)
4959 ExpectedElt = 0;
4960
4961 if (M[i] < 0)
4962 continue; // ignore UNDEF indices
4963 if (ExpectedElt != static_cast<unsigned>(M[i]))
4964 return false;
4965 }
4966
4967 return true;
4968}
4969
4970// check if an EXT instruction can handle the shuffle mask when the
4971// vector sources of the shuffle are different.
4972static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
4973 unsigned &Imm) {
4974 // Look for the first non-undef element.
4975 const int *FirstRealElt = std::find_if(M.begin(), M.end(),
4976 [](int Elt) {return Elt >= 0;});
4977
4978 // Benefit form APInt to handle overflow when calculating expected element.
4979 unsigned NumElts = VT.getVectorNumElements();
4980 unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
4981 APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
4982 // The following shuffle indices must be the successive elements after the
4983 // first real element.
4984 const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
4985 [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
4986 if (FirstWrongElt != M.end())
4987 return false;
4988
4989 // The index of an EXT is the first element if it is not UNDEF.
4990 // Watch out for the beginning UNDEFs. The EXT index should be the expected
4991 // value of the first element. E.g.
4992 // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
4993 // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
4994 // ExpectedElt is the last mask index plus 1.
4995 Imm = ExpectedElt.getZExtValue();
4996
4997 // There are two difference cases requiring to reverse input vectors.
4998 // For example, for vector <4 x i32> we have the following cases,
4999 // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
5000 // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
5001 // For both cases, we finally use mask <5, 6, 7, 0>, which requires
5002 // to reverse two input vectors.
5003 if (Imm < NumElts)
5004 ReverseEXT = true;
5005 else
5006 Imm -= NumElts;
5007
5008 return true;
5009}
5010
5011/// isREVMask - Check if a vector shuffle corresponds to a REV
5012/// instruction with the specified blocksize. (The order of the elements
5013/// within each block of the vector is reversed.)
5014static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5015 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
5016 "Only possible block sizes for REV are: 16, 32, 64");
5017
5018 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5019 if (EltSz == 64)
5020 return false;
5021
5022 unsigned NumElts = VT.getVectorNumElements();
5023 unsigned BlockElts = M[0] + 1;
5024 // If the first shuffle index is UNDEF, be optimistic.
5025 if (M[0] < 0)
5026 BlockElts = BlockSize / EltSz;
5027
5028 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5029 return false;
5030
5031 for (unsigned i = 0; i < NumElts; ++i) {
5032 if (M[i] < 0)
5033 continue; // ignore UNDEF indices
5034 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
5035 return false;
5036 }
5037
5038 return true;
5039}
5040
5041static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5042 unsigned NumElts = VT.getVectorNumElements();
5043 WhichResult = (M[0] == 0 ? 0 : 1);
5044 unsigned Idx = WhichResult * NumElts / 2;
5045 for (unsigned i = 0; i != NumElts; i += 2) {
5046 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5047 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
5048 return false;
5049 Idx += 1;
5050 }
5051
5052 return true;
5053}
5054
5055static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5056 unsigned NumElts = VT.getVectorNumElements();
5057 WhichResult = (M[0] == 0 ? 0 : 1);
5058 for (unsigned i = 0; i != NumElts; ++i) {
5059 if (M[i] < 0)
5060 continue; // ignore UNDEF indices
5061 if ((unsigned)M[i] != 2 * i + WhichResult)
5062 return false;
5063 }
5064
5065 return true;
5066}
5067
5068static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5069 unsigned NumElts = VT.getVectorNumElements();
5070 WhichResult = (M[0] == 0 ? 0 : 1);
5071 for (unsigned i = 0; i < NumElts; i += 2) {
5072 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5073 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
5074 return false;
5075 }
5076 return true;
5077}
5078
5079/// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
5080/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5081/// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5082static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5083 unsigned NumElts = VT.getVectorNumElements();
5084 WhichResult = (M[0] == 0 ? 0 : 1);
5085 unsigned Idx = WhichResult * NumElts / 2;
5086 for (unsigned i = 0; i != NumElts; i += 2) {
5087 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5088 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
5089 return false;
5090 Idx += 1;
5091 }
5092
5093 return true;
5094}
5095
5096/// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
5097/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5098/// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5099static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5100 unsigned Half = VT.getVectorNumElements() / 2;
5101 WhichResult = (M[0] == 0 ? 0 : 1);
5102 for (unsigned j = 0; j != 2; ++j) {
5103 unsigned Idx = WhichResult;
5104 for (unsigned i = 0; i != Half; ++i) {
5105 int MIdx = M[i + j * Half];
5106 if (MIdx >= 0 && (unsigned)MIdx != Idx)
5107 return false;
5108 Idx += 2;
5109 }
5110 }
5111
5112 return true;
5113}
5114
5115/// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
5116/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5117/// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5118static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5119 unsigned NumElts = VT.getVectorNumElements();
5120 WhichResult = (M[0] == 0 ? 0 : 1);
5121 for (unsigned i = 0; i < NumElts; i += 2) {
5122 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5123 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
5124 return false;
5125 }
5126 return true;
5127}
5128
5129static bool isINSMask(ArrayRef<int> M, int NumInputElements,
5130 bool &DstIsLeft, int &Anomaly) {
5131 if (M.size() != static_cast<size_t>(NumInputElements))
5132 return false;
5133
5134 int NumLHSMatch = 0, NumRHSMatch = 0;
5135 int LastLHSMismatch = -1, LastRHSMismatch = -1;
5136
5137 for (int i = 0; i < NumInputElements; ++i) {
5138 if (M[i] == -1) {
5139 ++NumLHSMatch;
5140 ++NumRHSMatch;
5141 continue;
5142 }
5143
5144 if (M[i] == i)
5145 ++NumLHSMatch;
5146 else
5147 LastLHSMismatch = i;
5148
5149 if (M[i] == i + NumInputElements)
5150 ++NumRHSMatch;
5151 else
5152 LastRHSMismatch = i;
5153 }
5154
5155 if (NumLHSMatch == NumInputElements - 1) {
5156 DstIsLeft = true;
5157 Anomaly = LastLHSMismatch;
5158 return true;
5159 } else if (NumRHSMatch == NumInputElements - 1) {
5160 DstIsLeft = false;
5161 Anomaly = LastRHSMismatch;
5162 return true;
5163 }
5164
5165 return false;
5166}
5167
5168static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
5169 if (VT.getSizeInBits() != 128)
5170 return false;
5171
5172 unsigned NumElts = VT.getVectorNumElements();
5173
5174 for (int I = 0, E = NumElts / 2; I != E; I++) {
5175 if (Mask[I] != I)
5176 return false;
5177 }
5178
5179 int Offset = NumElts / 2;
5180 for (int I = NumElts / 2, E = NumElts; I != E; I++) {
5181 if (Mask[I] != I + SplitLHS * Offset)
5182 return false;
5183 }
5184
5185 return true;
5186}
5187
5188static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
5189 SDLoc DL(Op);
5190 EVT VT = Op.getValueType();
5191 SDValue V0 = Op.getOperand(0);
5192 SDValue V1 = Op.getOperand(1);
5193 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
5194
5195 if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
5196 VT.getVectorElementType() != V1.getValueType().getVectorElementType())
5197 return SDValue();
5198
5199 bool SplitV0 = V0.getValueType().getSizeInBits() == 128;
5200
5201 if (!isConcatMask(Mask, VT, SplitV0))
5202 return SDValue();
5203
5204 EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
5205 VT.getVectorNumElements() / 2);
5206 if (SplitV0) {
5207 V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005208 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005209 }
5210 if (V1.getValueType().getSizeInBits() == 128) {
5211 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005212 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005213 }
5214 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
5215}
5216
5217/// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5218/// the specified operations to build the shuffle.
5219static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5220 SDValue RHS, SelectionDAG &DAG,
5221 SDLoc dl) {
5222 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5223 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
5224 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
5225
5226 enum {
5227 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5228 OP_VREV,
5229 OP_VDUP0,
5230 OP_VDUP1,
5231 OP_VDUP2,
5232 OP_VDUP3,
5233 OP_VEXT1,
5234 OP_VEXT2,
5235 OP_VEXT3,
5236 OP_VUZPL, // VUZP, left result
5237 OP_VUZPR, // VUZP, right result
5238 OP_VZIPL, // VZIP, left result
5239 OP_VZIPR, // VZIP, right result
5240 OP_VTRNL, // VTRN, left result
5241 OP_VTRNR // VTRN, right result
5242 };
5243
5244 if (OpNum == OP_COPY) {
5245 if (LHSID == (1 * 9 + 2) * 9 + 3)
5246 return LHS;
5247 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
5248 return RHS;
5249 }
5250
5251 SDValue OpLHS, OpRHS;
5252 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5253 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5254 EVT VT = OpLHS.getValueType();
5255
5256 switch (OpNum) {
5257 default:
5258 llvm_unreachable("Unknown shuffle opcode!");
5259 case OP_VREV:
5260 // VREV divides the vector in half and swaps within the half.
5261 if (VT.getVectorElementType() == MVT::i32 ||
5262 VT.getVectorElementType() == MVT::f32)
5263 return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
5264 // vrev <4 x i16> -> REV32
Oliver Stannard89d15422014-08-27 16:16:04 +00005265 if (VT.getVectorElementType() == MVT::i16 ||
5266 VT.getVectorElementType() == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00005267 return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
5268 // vrev <4 x i8> -> REV16
5269 assert(VT.getVectorElementType() == MVT::i8);
5270 return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
5271 case OP_VDUP0:
5272 case OP_VDUP1:
5273 case OP_VDUP2:
5274 case OP_VDUP3: {
5275 EVT EltTy = VT.getVectorElementType();
5276 unsigned Opcode;
5277 if (EltTy == MVT::i8)
5278 Opcode = AArch64ISD::DUPLANE8;
Ahmed Bougacha941420d2015-04-16 23:57:07 +00005279 else if (EltTy == MVT::i16 || EltTy == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00005280 Opcode = AArch64ISD::DUPLANE16;
5281 else if (EltTy == MVT::i32 || EltTy == MVT::f32)
5282 Opcode = AArch64ISD::DUPLANE32;
5283 else if (EltTy == MVT::i64 || EltTy == MVT::f64)
5284 Opcode = AArch64ISD::DUPLANE64;
5285 else
5286 llvm_unreachable("Invalid vector element type?");
5287
5288 if (VT.getSizeInBits() == 64)
5289 OpLHS = WidenVector(OpLHS, DAG);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005290 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00005291 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
5292 }
5293 case OP_VEXT1:
5294 case OP_VEXT2:
5295 case OP_VEXT3: {
5296 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
5297 return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005298 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005299 }
5300 case OP_VUZPL:
5301 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
5302 OpRHS);
5303 case OP_VUZPR:
5304 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
5305 OpRHS);
5306 case OP_VZIPL:
5307 return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
5308 OpRHS);
5309 case OP_VZIPR:
5310 return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
5311 OpRHS);
5312 case OP_VTRNL:
5313 return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
5314 OpRHS);
5315 case OP_VTRNR:
5316 return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
5317 OpRHS);
5318 }
5319}
5320
5321static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
5322 SelectionDAG &DAG) {
5323 // Check to see if we can use the TBL instruction.
5324 SDValue V1 = Op.getOperand(0);
5325 SDValue V2 = Op.getOperand(1);
5326 SDLoc DL(Op);
5327
5328 EVT EltVT = Op.getValueType().getVectorElementType();
5329 unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
5330
5331 SmallVector<SDValue, 8> TBLMask;
5332 for (int Val : ShuffleMask) {
5333 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
5334 unsigned Offset = Byte + Val * BytesPerElt;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005335 TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005336 }
5337 }
5338
5339 MVT IndexVT = MVT::v8i8;
5340 unsigned IndexLen = 8;
5341 if (Op.getValueType().getSizeInBits() == 128) {
5342 IndexVT = MVT::v16i8;
5343 IndexLen = 16;
5344 }
5345
5346 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
5347 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
5348
5349 SDValue Shuffle;
5350 if (V2.getNode()->getOpcode() == ISD::UNDEF) {
5351 if (IndexLen == 8)
5352 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
5353 Shuffle = DAG.getNode(
5354 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005355 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
Tim Northover3b0846e2014-05-24 12:50:23 +00005356 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5357 makeArrayRef(TBLMask.data(), IndexLen)));
5358 } else {
5359 if (IndexLen == 8) {
5360 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
5361 Shuffle = DAG.getNode(
5362 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005363 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
Tim Northover3b0846e2014-05-24 12:50:23 +00005364 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5365 makeArrayRef(TBLMask.data(), IndexLen)));
5366 } else {
5367 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
5368 // cannot currently represent the register constraints on the input
5369 // table registers.
5370 // Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
5371 // DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5372 // &TBLMask[0], IndexLen));
5373 Shuffle = DAG.getNode(
5374 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005375 DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32),
5376 V1Cst, V2Cst,
Tim Northover3b0846e2014-05-24 12:50:23 +00005377 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5378 makeArrayRef(TBLMask.data(), IndexLen)));
5379 }
5380 }
5381 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
5382}
5383
5384static unsigned getDUPLANEOp(EVT EltType) {
5385 if (EltType == MVT::i8)
5386 return AArch64ISD::DUPLANE8;
Oliver Stannard89d15422014-08-27 16:16:04 +00005387 if (EltType == MVT::i16 || EltType == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00005388 return AArch64ISD::DUPLANE16;
5389 if (EltType == MVT::i32 || EltType == MVT::f32)
5390 return AArch64ISD::DUPLANE32;
5391 if (EltType == MVT::i64 || EltType == MVT::f64)
5392 return AArch64ISD::DUPLANE64;
5393
5394 llvm_unreachable("Invalid vector element type?");
5395}
5396
5397SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5398 SelectionDAG &DAG) const {
5399 SDLoc dl(Op);
5400 EVT VT = Op.getValueType();
5401
5402 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5403
5404 // Convert shuffles that are directly supported on NEON to target-specific
5405 // DAG nodes, instead of keeping them as shuffles and matching them again
5406 // during code selection. This is more efficient and avoids the possibility
5407 // of inconsistencies between legalization and selection.
5408 ArrayRef<int> ShuffleMask = SVN->getMask();
5409
5410 SDValue V1 = Op.getOperand(0);
5411 SDValue V2 = Op.getOperand(1);
5412
5413 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0],
5414 V1.getValueType().getSimpleVT())) {
5415 int Lane = SVN->getSplatIndex();
5416 // If this is undef splat, generate it via "just" vdup, if possible.
5417 if (Lane == -1)
5418 Lane = 0;
5419
5420 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
5421 return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
5422 V1.getOperand(0));
5423 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
5424 // constant. If so, we can just reference the lane's definition directly.
5425 if (V1.getOpcode() == ISD::BUILD_VECTOR &&
5426 !isa<ConstantSDNode>(V1.getOperand(Lane)))
5427 return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
5428
5429 // Otherwise, duplicate from the lane of the input vector.
5430 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
5431
5432 // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
5433 // to make a vector of the same size as this SHUFFLE. We can ignore the
5434 // extract entirely, and canonicalise the concat using WidenVector.
5435 if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
5436 Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
5437 V1 = V1.getOperand(0);
5438 } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
5439 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
5440 Lane -= Idx * VT.getVectorNumElements() / 2;
5441 V1 = WidenVector(V1.getOperand(Idx), DAG);
5442 } else if (VT.getSizeInBits() == 64)
5443 V1 = WidenVector(V1, DAG);
5444
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005445 return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005446 }
5447
5448 if (isREVMask(ShuffleMask, VT, 64))
5449 return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
5450 if (isREVMask(ShuffleMask, VT, 32))
5451 return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
5452 if (isREVMask(ShuffleMask, VT, 16))
5453 return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
5454
5455 bool ReverseEXT = false;
5456 unsigned Imm;
5457 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
5458 if (ReverseEXT)
5459 std::swap(V1, V2);
5460 Imm *= getExtFactor(V1);
5461 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005462 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005463 } else if (V2->getOpcode() == ISD::UNDEF &&
5464 isSingletonEXTMask(ShuffleMask, VT, Imm)) {
5465 Imm *= getExtFactor(V1);
5466 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005467 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005468 }
5469
5470 unsigned WhichResult;
5471 if (isZIPMask(ShuffleMask, VT, WhichResult)) {
5472 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5473 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5474 }
5475 if (isUZPMask(ShuffleMask, VT, WhichResult)) {
5476 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5477 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5478 }
5479 if (isTRNMask(ShuffleMask, VT, WhichResult)) {
5480 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5481 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5482 }
5483
5484 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5485 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5486 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5487 }
5488 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5489 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5490 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5491 }
5492 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5493 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5494 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5495 }
5496
5497 SDValue Concat = tryFormConcatFromShuffle(Op, DAG);
5498 if (Concat.getNode())
5499 return Concat;
5500
5501 bool DstIsLeft;
5502 int Anomaly;
5503 int NumInputElements = V1.getValueType().getVectorNumElements();
5504 if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
5505 SDValue DstVec = DstIsLeft ? V1 : V2;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005506 SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00005507
5508 SDValue SrcVec = V1;
5509 int SrcLane = ShuffleMask[Anomaly];
5510 if (SrcLane >= NumInputElements) {
5511 SrcVec = V2;
5512 SrcLane -= VT.getVectorNumElements();
5513 }
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005514 SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00005515
5516 EVT ScalarVT = VT.getVectorElementType();
Oliver Stannard89d15422014-08-27 16:16:04 +00005517
5518 if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00005519 ScalarVT = MVT::i32;
5520
5521 return DAG.getNode(
5522 ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5523 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
5524 DstLaneV);
5525 }
5526
5527 // If the shuffle is not directly supported and it has 4 elements, use
5528 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5529 unsigned NumElts = VT.getVectorNumElements();
5530 if (NumElts == 4) {
5531 unsigned PFIndexes[4];
5532 for (unsigned i = 0; i != 4; ++i) {
5533 if (ShuffleMask[i] < 0)
5534 PFIndexes[i] = 8;
5535 else
5536 PFIndexes[i] = ShuffleMask[i];
5537 }
5538
5539 // Compute the index in the perfect shuffle table.
5540 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
5541 PFIndexes[2] * 9 + PFIndexes[3];
5542 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5543 unsigned Cost = (PFEntry >> 30);
5544
5545 if (Cost <= 4)
5546 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5547 }
5548
5549 return GenerateTBL(Op, ShuffleMask, DAG);
5550}
5551
5552static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
5553 APInt &UndefBits) {
5554 EVT VT = BVN->getValueType(0);
5555 APInt SplatBits, SplatUndef;
5556 unsigned SplatBitSize;
5557 bool HasAnyUndefs;
5558 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5559 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
5560
5561 for (unsigned i = 0; i < NumSplats; ++i) {
5562 CnstBits <<= SplatBitSize;
5563 UndefBits <<= SplatBitSize;
5564 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
5565 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
5566 }
5567
5568 return true;
5569 }
5570
5571 return false;
5572}
5573
5574SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op,
5575 SelectionDAG &DAG) const {
5576 BuildVectorSDNode *BVN =
5577 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5578 SDValue LHS = Op.getOperand(0);
5579 SDLoc dl(Op);
5580 EVT VT = Op.getValueType();
5581
5582 if (!BVN)
5583 return Op;
5584
5585 APInt CnstBits(VT.getSizeInBits(), 0);
5586 APInt UndefBits(VT.getSizeInBits(), 0);
5587 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5588 // We only have BIC vector immediate instruction, which is and-not.
5589 CnstBits = ~CnstBits;
5590
5591 // We make use of a little bit of goto ickiness in order to avoid having to
5592 // duplicate the immediate matching logic for the undef toggled case.
5593 bool SecondTry = false;
5594 AttemptModImm:
5595
5596 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5597 CnstBits = CnstBits.zextOrTrunc(64);
5598 uint64_t CnstVal = CnstBits.getZExtValue();
5599
5600 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5601 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5602 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5603 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005604 DAG.getConstant(CnstVal, dl, MVT::i32),
5605 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005606 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005607 }
5608
5609 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5610 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5611 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5612 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005613 DAG.getConstant(CnstVal, dl, MVT::i32),
5614 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005615 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005616 }
5617
5618 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5619 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5620 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5621 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005622 DAG.getConstant(CnstVal, dl, MVT::i32),
5623 DAG.getConstant(16, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005624 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005625 }
5626
5627 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5628 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5629 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5630 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005631 DAG.getConstant(CnstVal, dl, MVT::i32),
5632 DAG.getConstant(24, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005633 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005634 }
5635
5636 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5637 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5638 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5639 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005640 DAG.getConstant(CnstVal, dl, MVT::i32),
5641 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005642 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005643 }
5644
5645 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5646 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5647 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5648 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005649 DAG.getConstant(CnstVal, dl, MVT::i32),
5650 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005651 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005652 }
5653 }
5654
5655 if (SecondTry)
5656 goto FailedModImm;
5657 SecondTry = true;
5658 CnstBits = ~UndefBits;
5659 goto AttemptModImm;
5660 }
5661
5662// We can always fall back to a non-immediate AND.
5663FailedModImm:
5664 return Op;
5665}
5666
5667// Specialized code to quickly find if PotentialBVec is a BuildVector that
5668// consists of only the same constant int value, returned in reference arg
5669// ConstVal
5670static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
5671 uint64_t &ConstVal) {
5672 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
5673 if (!Bvec)
5674 return false;
5675 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
5676 if (!FirstElt)
5677 return false;
5678 EVT VT = Bvec->getValueType(0);
5679 unsigned NumElts = VT.getVectorNumElements();
5680 for (unsigned i = 1; i < NumElts; ++i)
5681 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
5682 return false;
5683 ConstVal = FirstElt->getZExtValue();
5684 return true;
5685}
5686
5687static unsigned getIntrinsicID(const SDNode *N) {
5688 unsigned Opcode = N->getOpcode();
5689 switch (Opcode) {
5690 default:
5691 return Intrinsic::not_intrinsic;
5692 case ISD::INTRINSIC_WO_CHAIN: {
5693 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
5694 if (IID < Intrinsic::num_intrinsics)
5695 return IID;
5696 return Intrinsic::not_intrinsic;
5697 }
5698 }
5699}
5700
5701// Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
5702// to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
5703// BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
5704// Also, logical shift right -> sri, with the same structure.
5705static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
5706 EVT VT = N->getValueType(0);
5707
5708 if (!VT.isVector())
5709 return SDValue();
5710
5711 SDLoc DL(N);
5712
5713 // Is the first op an AND?
5714 const SDValue And = N->getOperand(0);
5715 if (And.getOpcode() != ISD::AND)
5716 return SDValue();
5717
5718 // Is the second op an shl or lshr?
5719 SDValue Shift = N->getOperand(1);
5720 // This will have been turned into: AArch64ISD::VSHL vector, #shift
5721 // or AArch64ISD::VLSHR vector, #shift
5722 unsigned ShiftOpc = Shift.getOpcode();
5723 if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
5724 return SDValue();
5725 bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
5726
5727 // Is the shift amount constant?
5728 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
5729 if (!C2node)
5730 return SDValue();
5731
5732 // Is the and mask vector all constant?
5733 uint64_t C1;
5734 if (!isAllConstantBuildVector(And.getOperand(1), C1))
5735 return SDValue();
5736
5737 // Is C1 == ~C2, taking into account how much one can shift elements of a
5738 // particular size?
5739 uint64_t C2 = C2node->getZExtValue();
5740 unsigned ElemSizeInBits = VT.getVectorElementType().getSizeInBits();
5741 if (C2 > ElemSizeInBits)
5742 return SDValue();
5743 unsigned ElemMask = (1 << ElemSizeInBits) - 1;
5744 if ((C1 & ElemMask) != (~C2 & ElemMask))
5745 return SDValue();
5746
5747 SDValue X = And.getOperand(0);
5748 SDValue Y = Shift.getOperand(0);
5749
5750 unsigned Intrin =
5751 IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
5752 SDValue ResultSLI =
5753 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005754 DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
5755 Shift.getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00005756
5757 DEBUG(dbgs() << "aarch64-lower: transformed: \n");
5758 DEBUG(N->dump(&DAG));
5759 DEBUG(dbgs() << "into: \n");
5760 DEBUG(ResultSLI->dump(&DAG));
5761
5762 ++NumShiftInserts;
5763 return ResultSLI;
5764}
5765
5766SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
5767 SelectionDAG &DAG) const {
5768 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
5769 if (EnableAArch64SlrGeneration) {
5770 SDValue Res = tryLowerToSLI(Op.getNode(), DAG);
5771 if (Res.getNode())
5772 return Res;
5773 }
5774
5775 BuildVectorSDNode *BVN =
5776 dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
5777 SDValue LHS = Op.getOperand(1);
5778 SDLoc dl(Op);
5779 EVT VT = Op.getValueType();
5780
5781 // OR commutes, so try swapping the operands.
5782 if (!BVN) {
5783 LHS = Op.getOperand(0);
5784 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5785 }
5786 if (!BVN)
5787 return Op;
5788
5789 APInt CnstBits(VT.getSizeInBits(), 0);
5790 APInt UndefBits(VT.getSizeInBits(), 0);
5791 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5792 // We make use of a little bit of goto ickiness in order to avoid having to
5793 // duplicate the immediate matching logic for the undef toggled case.
5794 bool SecondTry = false;
5795 AttemptModImm:
5796
5797 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5798 CnstBits = CnstBits.zextOrTrunc(64);
5799 uint64_t CnstVal = CnstBits.getZExtValue();
5800
5801 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5802 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5803 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5804 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005805 DAG.getConstant(CnstVal, dl, MVT::i32),
5806 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005807 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005808 }
5809
5810 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5811 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5812 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5813 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005814 DAG.getConstant(CnstVal, dl, MVT::i32),
5815 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005816 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005817 }
5818
5819 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5820 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5821 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5822 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005823 DAG.getConstant(CnstVal, dl, MVT::i32),
5824 DAG.getConstant(16, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005825 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005826 }
5827
5828 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5829 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5830 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5831 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005832 DAG.getConstant(CnstVal, dl, MVT::i32),
5833 DAG.getConstant(24, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005834 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005835 }
5836
5837 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5838 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5839 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5840 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005841 DAG.getConstant(CnstVal, dl, MVT::i32),
5842 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005843 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005844 }
5845
5846 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5847 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5848 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5849 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005850 DAG.getConstant(CnstVal, dl, MVT::i32),
5851 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005852 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005853 }
5854 }
5855
5856 if (SecondTry)
5857 goto FailedModImm;
5858 SecondTry = true;
5859 CnstBits = UndefBits;
5860 goto AttemptModImm;
5861 }
5862
5863// We can always fall back to a non-immediate OR.
5864FailedModImm:
5865 return Op;
5866}
5867
Kevin Qin4473c192014-07-07 02:45:40 +00005868// Normalize the operands of BUILD_VECTOR. The value of constant operands will
5869// be truncated to fit element width.
5870static SDValue NormalizeBuildVector(SDValue Op,
5871 SelectionDAG &DAG) {
5872 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
Tim Northover3b0846e2014-05-24 12:50:23 +00005873 SDLoc dl(Op);
5874 EVT VT = Op.getValueType();
Kevin Qin4473c192014-07-07 02:45:40 +00005875 EVT EltTy= VT.getVectorElementType();
5876
5877 if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
5878 return Op;
5879
5880 SmallVector<SDValue, 16> Ops;
5881 for (unsigned I = 0, E = VT.getVectorNumElements(); I != E; ++I) {
5882 SDValue Lane = Op.getOperand(I);
5883 if (Lane.getOpcode() == ISD::Constant) {
5884 APInt LowBits(EltTy.getSizeInBits(),
5885 cast<ConstantSDNode>(Lane)->getZExtValue());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005886 Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
Kevin Qin4473c192014-07-07 02:45:40 +00005887 }
5888 Ops.push_back(Lane);
5889 }
5890 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5891}
5892
5893SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
5894 SelectionDAG &DAG) const {
5895 SDLoc dl(Op);
5896 EVT VT = Op.getValueType();
5897 Op = NormalizeBuildVector(Op, DAG);
5898 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
Tim Northover3b0846e2014-05-24 12:50:23 +00005899
5900 APInt CnstBits(VT.getSizeInBits(), 0);
5901 APInt UndefBits(VT.getSizeInBits(), 0);
5902 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5903 // We make use of a little bit of goto ickiness in order to avoid having to
5904 // duplicate the immediate matching logic for the undef toggled case.
5905 bool SecondTry = false;
5906 AttemptModImm:
5907
5908 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5909 CnstBits = CnstBits.zextOrTrunc(64);
5910 uint64_t CnstVal = CnstBits.getZExtValue();
5911
5912 // Certain magic vector constants (used to express things like NOT
5913 // and NEG) are passed through unmodified. This allows codegen patterns
5914 // for these operations to match. Special-purpose patterns will lower
5915 // these immediates to MOVIs if it proves necessary.
5916 if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL))
5917 return Op;
5918
5919 // The many faces of MOVI...
5920 if (AArch64_AM::isAdvSIMDModImmType10(CnstVal)) {
5921 CnstVal = AArch64_AM::encodeAdvSIMDModImmType10(CnstVal);
5922 if (VT.getSizeInBits() == 128) {
5923 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::v2i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005924 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00005925 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005926 }
5927
5928 // Support the V64 version via subregister insertion.
5929 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::f64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005930 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00005931 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005932 }
5933
5934 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5935 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5936 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5937 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005938 DAG.getConstant(CnstVal, dl, MVT::i32),
5939 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00005940 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005941 }
5942
5943 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5944 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5945 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5946 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005947 DAG.getConstant(CnstVal, dl, MVT::i32),
5948 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00005949 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005950 }
5951
5952 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5953 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5954 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5955 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005956 DAG.getConstant(CnstVal, dl, MVT::i32),
5957 DAG.getConstant(16, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00005958 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005959 }
5960
5961 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5962 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5963 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5964 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005965 DAG.getConstant(CnstVal, dl, MVT::i32),
5966 DAG.getConstant(24, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00005967 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005968 }
5969
5970 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5971 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5972 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5973 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005974 DAG.getConstant(CnstVal, dl, MVT::i32),
5975 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00005976 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005977 }
5978
5979 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5980 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5981 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5982 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005983 DAG.getConstant(CnstVal, dl, MVT::i32),
5984 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00005985 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005986 }
5987
5988 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
5989 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
5990 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5991 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005992 DAG.getConstant(CnstVal, dl, MVT::i32),
5993 DAG.getConstant(264, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00005994 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005995 }
5996
5997 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
5998 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
5999 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6000 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006001 DAG.getConstant(CnstVal, dl, MVT::i32),
6002 DAG.getConstant(272, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006003 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006004 }
6005
6006 if (AArch64_AM::isAdvSIMDModImmType9(CnstVal)) {
6007 CnstVal = AArch64_AM::encodeAdvSIMDModImmType9(CnstVal);
6008 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
6009 SDValue Mov = DAG.getNode(AArch64ISD::MOVI, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006010 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006011 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006012 }
6013
6014 // The few faces of FMOV...
6015 if (AArch64_AM::isAdvSIMDModImmType11(CnstVal)) {
6016 CnstVal = AArch64_AM::encodeAdvSIMDModImmType11(CnstVal);
6017 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32;
6018 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006019 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006020 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006021 }
6022
6023 if (AArch64_AM::isAdvSIMDModImmType12(CnstVal) &&
6024 VT.getSizeInBits() == 128) {
6025 CnstVal = AArch64_AM::encodeAdvSIMDModImmType12(CnstVal);
6026 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MVT::v2f64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006027 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006028 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006029 }
6030
6031 // The many faces of MVNI...
6032 CnstVal = ~CnstVal;
6033 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6034 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6035 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6036 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006037 DAG.getConstant(CnstVal, dl, MVT::i32),
6038 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006039 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006040 }
6041
6042 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6043 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6044 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6045 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006046 DAG.getConstant(CnstVal, dl, MVT::i32),
6047 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006048 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006049 }
6050
6051 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6052 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6053 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6054 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006055 DAG.getConstant(CnstVal, dl, MVT::i32),
6056 DAG.getConstant(16, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006057 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006058 }
6059
6060 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6061 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6062 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6063 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006064 DAG.getConstant(CnstVal, dl, MVT::i32),
6065 DAG.getConstant(24, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006066 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006067 }
6068
6069 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6070 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6071 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6072 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006073 DAG.getConstant(CnstVal, dl, MVT::i32),
6074 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006075 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006076 }
6077
6078 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6079 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6080 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6081 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006082 DAG.getConstant(CnstVal, dl, MVT::i32),
6083 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006084 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006085 }
6086
6087 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6088 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6089 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6090 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006091 DAG.getConstant(CnstVal, dl, MVT::i32),
6092 DAG.getConstant(264, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006093 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006094 }
6095
6096 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6097 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6098 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6099 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006100 DAG.getConstant(CnstVal, dl, MVT::i32),
6101 DAG.getConstant(272, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006102 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006103 }
6104 }
6105
6106 if (SecondTry)
6107 goto FailedModImm;
6108 SecondTry = true;
6109 CnstBits = UndefBits;
6110 goto AttemptModImm;
6111 }
6112FailedModImm:
6113
6114 // Scan through the operands to find some interesting properties we can
6115 // exploit:
6116 // 1) If only one value is used, we can use a DUP, or
6117 // 2) if only the low element is not undef, we can just insert that, or
6118 // 3) if only one constant value is used (w/ some non-constant lanes),
6119 // we can splat the constant value into the whole vector then fill
6120 // in the non-constant lanes.
6121 // 4) FIXME: If different constant values are used, but we can intelligently
6122 // select the values we'll be overwriting for the non-constant
6123 // lanes such that we can directly materialize the vector
6124 // some other way (MOVI, e.g.), we can be sneaky.
6125 unsigned NumElts = VT.getVectorNumElements();
6126 bool isOnlyLowElement = true;
6127 bool usesOnlyOneValue = true;
6128 bool usesOnlyOneConstantValue = true;
6129 bool isConstant = true;
6130 unsigned NumConstantLanes = 0;
6131 SDValue Value;
6132 SDValue ConstantValue;
6133 for (unsigned i = 0; i < NumElts; ++i) {
6134 SDValue V = Op.getOperand(i);
6135 if (V.getOpcode() == ISD::UNDEF)
6136 continue;
6137 if (i > 0)
6138 isOnlyLowElement = false;
6139 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6140 isConstant = false;
6141
6142 if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
6143 ++NumConstantLanes;
6144 if (!ConstantValue.getNode())
6145 ConstantValue = V;
6146 else if (ConstantValue != V)
6147 usesOnlyOneConstantValue = false;
6148 }
6149
6150 if (!Value.getNode())
6151 Value = V;
6152 else if (V != Value)
6153 usesOnlyOneValue = false;
6154 }
6155
6156 if (!Value.getNode())
6157 return DAG.getUNDEF(VT);
6158
6159 if (isOnlyLowElement)
6160 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
6161
6162 // Use DUP for non-constant splats. For f32 constant splats, reduce to
6163 // i32 and try again.
6164 if (usesOnlyOneValue) {
6165 if (!isConstant) {
6166 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6167 Value.getValueType() != VT)
6168 return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
6169
6170 // This is actually a DUPLANExx operation, which keeps everything vectory.
6171
6172 // DUPLANE works on 128-bit vectors, widen it if necessary.
6173 SDValue Lane = Value.getOperand(1);
6174 Value = Value.getOperand(0);
6175 if (Value.getValueType().getSizeInBits() == 64)
6176 Value = WidenVector(Value, DAG);
6177
6178 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
6179 return DAG.getNode(Opcode, dl, VT, Value, Lane);
6180 }
6181
6182 if (VT.getVectorElementType().isFloatingPoint()) {
6183 SmallVector<SDValue, 8> Ops;
Pirama Arumuga Nainar12aeefc2015-03-17 23:10:29 +00006184 EVT EltTy = VT.getVectorElementType();
6185 assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
6186 "Unsupported floating-point vector type");
6187 MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00006188 for (unsigned i = 0; i < NumElts; ++i)
6189 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
6190 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
6191 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
6192 Val = LowerBUILD_VECTOR(Val, DAG);
6193 if (Val.getNode())
6194 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6195 }
6196 }
6197
6198 // If there was only one constant value used and for more than one lane,
6199 // start by splatting that value, then replace the non-constant lanes. This
6200 // is better than the default, which will perform a separate initialization
6201 // for each lane.
6202 if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
6203 SDValue Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
6204 // Now insert the non-constant lanes.
6205 for (unsigned i = 0; i < NumElts; ++i) {
6206 SDValue V = Op.getOperand(i);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006207 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006208 if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) {
6209 // Note that type legalization likely mucked about with the VT of the
6210 // source operand, so we may have to convert it here before inserting.
6211 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
6212 }
6213 }
6214 return Val;
6215 }
6216
6217 // If all elements are constants and the case above didn't get hit, fall back
6218 // to the default expansion, which will generate a load from the constant
6219 // pool.
6220 if (isConstant)
6221 return SDValue();
6222
6223 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6224 if (NumElts >= 4) {
6225 SDValue shuffle = ReconstructShuffle(Op, DAG);
6226 if (shuffle != SDValue())
6227 return shuffle;
6228 }
6229
6230 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6231 // know the default expansion would otherwise fall back on something even
6232 // worse. For a vector with one or two non-undef values, that's
6233 // scalar_to_vector for the elements followed by a shuffle (provided the
6234 // shuffle is valid for the target) and materialization element by element
6235 // on the stack followed by a load for everything else.
6236 if (!isConstant && !usesOnlyOneValue) {
6237 SDValue Vec = DAG.getUNDEF(VT);
6238 SDValue Op0 = Op.getOperand(0);
6239 unsigned ElemSize = VT.getVectorElementType().getSizeInBits();
6240 unsigned i = 0;
6241 // For 32 and 64 bit types, use INSERT_SUBREG for lane zero to
6242 // a) Avoid a RMW dependency on the full vector register, and
6243 // b) Allow the register coalescer to fold away the copy if the
6244 // value is already in an S or D register.
6245 if (Op0.getOpcode() != ISD::UNDEF && (ElemSize == 32 || ElemSize == 64)) {
6246 unsigned SubIdx = ElemSize == 32 ? AArch64::ssub : AArch64::dsub;
6247 MachineSDNode *N =
6248 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl, VT, Vec, Op0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006249 DAG.getTargetConstant(SubIdx, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006250 Vec = SDValue(N, 0);
6251 ++i;
6252 }
6253 for (; i < NumElts; ++i) {
6254 SDValue V = Op.getOperand(i);
6255 if (V.getOpcode() == ISD::UNDEF)
6256 continue;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006257 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006258 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6259 }
6260 return Vec;
6261 }
6262
6263 // Just use the default expansion. We failed to find a better alternative.
6264 return SDValue();
6265}
6266
6267SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
6268 SelectionDAG &DAG) const {
6269 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
6270
Tim Northovere4b8e132014-07-15 10:00:26 +00006271 // Check for non-constant or out of range lane.
6272 EVT VT = Op.getOperand(0).getValueType();
6273 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
6274 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
Tim Northover3b0846e2014-05-24 12:50:23 +00006275 return SDValue();
6276
Tim Northover3b0846e2014-05-24 12:50:23 +00006277
6278 // Insertion/extraction are legal for V128 types.
6279 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
Oliver Stannard89d15422014-08-27 16:16:04 +00006280 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6281 VT == MVT::v8f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006282 return Op;
6283
6284 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
Oliver Stannard89d15422014-08-27 16:16:04 +00006285 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006286 return SDValue();
6287
6288 // For V64 types, we perform insertion by expanding the value
6289 // to a V128 type and perform the insertion on that.
6290 SDLoc DL(Op);
6291 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6292 EVT WideTy = WideVec.getValueType();
6293
6294 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
6295 Op.getOperand(1), Op.getOperand(2));
6296 // Re-narrow the resultant vector.
6297 return NarrowVector(Node, DAG);
6298}
6299
6300SDValue
6301AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6302 SelectionDAG &DAG) const {
6303 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
6304
Tim Northovere4b8e132014-07-15 10:00:26 +00006305 // Check for non-constant or out of range lane.
6306 EVT VT = Op.getOperand(0).getValueType();
6307 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6308 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
Tim Northover3b0846e2014-05-24 12:50:23 +00006309 return SDValue();
6310
Tim Northover3b0846e2014-05-24 12:50:23 +00006311
6312 // Insertion/extraction are legal for V128 types.
6313 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
Oliver Stannard89d15422014-08-27 16:16:04 +00006314 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6315 VT == MVT::v8f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006316 return Op;
6317
6318 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
Oliver Stannard89d15422014-08-27 16:16:04 +00006319 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006320 return SDValue();
6321
6322 // For V64 types, we perform extraction by expanding the value
6323 // to a V128 type and perform the extraction on that.
6324 SDLoc DL(Op);
6325 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6326 EVT WideTy = WideVec.getValueType();
6327
6328 EVT ExtrTy = WideTy.getVectorElementType();
6329 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
6330 ExtrTy = MVT::i32;
6331
6332 // For extractions, we just return the result directly.
6333 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
6334 Op.getOperand(1));
6335}
6336
6337SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
6338 SelectionDAG &DAG) const {
6339 EVT VT = Op.getOperand(0).getValueType();
6340 SDLoc dl(Op);
6341 // Just in case...
6342 if (!VT.isVector())
6343 return SDValue();
6344
6345 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6346 if (!Cst)
6347 return SDValue();
6348 unsigned Val = Cst->getZExtValue();
6349
6350 unsigned Size = Op.getValueType().getSizeInBits();
6351 if (Val == 0) {
6352 switch (Size) {
6353 case 8:
6354 return DAG.getTargetExtractSubreg(AArch64::bsub, dl, Op.getValueType(),
6355 Op.getOperand(0));
6356 case 16:
6357 return DAG.getTargetExtractSubreg(AArch64::hsub, dl, Op.getValueType(),
6358 Op.getOperand(0));
6359 case 32:
6360 return DAG.getTargetExtractSubreg(AArch64::ssub, dl, Op.getValueType(),
6361 Op.getOperand(0));
6362 case 64:
6363 return DAG.getTargetExtractSubreg(AArch64::dsub, dl, Op.getValueType(),
6364 Op.getOperand(0));
6365 default:
6366 llvm_unreachable("Unexpected vector type in extract_subvector!");
6367 }
6368 }
6369 // If this is extracting the upper 64-bits of a 128-bit vector, we match
6370 // that directly.
6371 if (Size == 64 && Val * VT.getVectorElementType().getSizeInBits() == 64)
6372 return Op;
6373
6374 return SDValue();
6375}
6376
6377bool AArch64TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
6378 EVT VT) const {
6379 if (VT.getVectorNumElements() == 4 &&
6380 (VT.is128BitVector() || VT.is64BitVector())) {
6381 unsigned PFIndexes[4];
6382 for (unsigned i = 0; i != 4; ++i) {
6383 if (M[i] < 0)
6384 PFIndexes[i] = 8;
6385 else
6386 PFIndexes[i] = M[i];
6387 }
6388
6389 // Compute the index in the perfect shuffle table.
6390 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6391 PFIndexes[2] * 9 + PFIndexes[3];
6392 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6393 unsigned Cost = (PFEntry >> 30);
6394
6395 if (Cost <= 4)
6396 return true;
6397 }
6398
6399 bool DummyBool;
6400 int DummyInt;
6401 unsigned DummyUnsigned;
6402
6403 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
6404 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
6405 isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
6406 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
6407 isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
6408 isZIPMask(M, VT, DummyUnsigned) ||
6409 isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
6410 isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
6411 isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
6412 isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
6413 isConcatMask(M, VT, VT.getSizeInBits() == 128));
6414}
6415
6416/// getVShiftImm - Check if this is a valid build_vector for the immediate
6417/// operand of a vector shift operation, where all the elements of the
6418/// build_vector must have the same constant integer value.
6419static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
6420 // Ignore bit_converts.
6421 while (Op.getOpcode() == ISD::BITCAST)
6422 Op = Op.getOperand(0);
6423 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6424 APInt SplatBits, SplatUndef;
6425 unsigned SplatBitSize;
6426 bool HasAnyUndefs;
6427 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
6428 HasAnyUndefs, ElementBits) ||
6429 SplatBitSize > ElementBits)
6430 return false;
6431 Cnt = SplatBits.getSExtValue();
6432 return true;
6433}
6434
6435/// isVShiftLImm - Check if this is a valid build_vector for the immediate
6436/// operand of a vector shift left operation. That value must be in the range:
6437/// 0 <= Value < ElementBits for a left shift; or
6438/// 0 <= Value <= ElementBits for a long left shift.
6439static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
6440 assert(VT.isVector() && "vector shift count is not a vector type");
6441 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
6442 if (!getVShiftImm(Op, ElementBits, Cnt))
6443 return false;
6444 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
6445}
6446
6447/// isVShiftRImm - Check if this is a valid build_vector for the immediate
6448/// operand of a vector shift right operation. For a shift opcode, the value
6449/// is positive, but for an intrinsic the value count must be negative. The
6450/// absolute value must be in the range:
6451/// 1 <= |Value| <= ElementBits for a right shift; or
6452/// 1 <= |Value| <= ElementBits/2 for a narrow right shift.
6453static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
6454 int64_t &Cnt) {
6455 assert(VT.isVector() && "vector shift count is not a vector type");
6456 unsigned ElementBits = VT.getVectorElementType().getSizeInBits();
6457 if (!getVShiftImm(Op, ElementBits, Cnt))
6458 return false;
6459 if (isIntrinsic)
6460 Cnt = -Cnt;
6461 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
6462}
6463
6464SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
6465 SelectionDAG &DAG) const {
6466 EVT VT = Op.getValueType();
6467 SDLoc DL(Op);
6468 int64_t Cnt;
6469
6470 if (!Op.getOperand(1).getValueType().isVector())
6471 return Op;
6472 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6473
6474 switch (Op.getOpcode()) {
6475 default:
6476 llvm_unreachable("unexpected shift opcode");
6477
6478 case ISD::SHL:
6479 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006480 return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
6481 DAG.getConstant(Cnt, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006482 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006483 DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
6484 MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00006485 Op.getOperand(0), Op.getOperand(1));
6486 case ISD::SRA:
6487 case ISD::SRL:
6488 // Right shift immediate
6489 if (isVShiftRImm(Op.getOperand(1), VT, false, false, Cnt) &&
6490 Cnt < EltSize) {
6491 unsigned Opc =
6492 (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006493 return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
6494 DAG.getConstant(Cnt, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006495 }
6496
6497 // Right shift register. Note, there is not a shift right register
6498 // instruction, but the shift left register instruction takes a signed
6499 // value, where negative numbers specify a right shift.
6500 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
6501 : Intrinsic::aarch64_neon_ushl;
6502 // negate the shift amount
6503 SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
6504 SDValue NegShiftLeft =
6505 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006506 DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
6507 NegShift);
Tim Northover3b0846e2014-05-24 12:50:23 +00006508 return NegShiftLeft;
6509 }
6510
6511 return SDValue();
6512}
6513
6514static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
6515 AArch64CC::CondCode CC, bool NoNans, EVT VT,
6516 SDLoc dl, SelectionDAG &DAG) {
6517 EVT SrcVT = LHS.getValueType();
Tim Northover45aa89c2015-02-08 00:50:47 +00006518 assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
6519 "function only supposed to emit natural comparisons");
Tim Northover3b0846e2014-05-24 12:50:23 +00006520
6521 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
6522 APInt CnstBits(VT.getSizeInBits(), 0);
6523 APInt UndefBits(VT.getSizeInBits(), 0);
6524 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
6525 bool IsZero = IsCnst && (CnstBits == 0);
6526
6527 if (SrcVT.getVectorElementType().isFloatingPoint()) {
6528 switch (CC) {
6529 default:
6530 return SDValue();
6531 case AArch64CC::NE: {
6532 SDValue Fcmeq;
6533 if (IsZero)
6534 Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6535 else
6536 Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6537 return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
6538 }
6539 case AArch64CC::EQ:
6540 if (IsZero)
6541 return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6542 return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6543 case AArch64CC::GE:
6544 if (IsZero)
6545 return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
6546 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
6547 case AArch64CC::GT:
6548 if (IsZero)
6549 return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
6550 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
6551 case AArch64CC::LS:
6552 if (IsZero)
6553 return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
6554 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
6555 case AArch64CC::LT:
6556 if (!NoNans)
6557 return SDValue();
6558 // If we ignore NaNs then we can use to the MI implementation.
6559 // Fallthrough.
6560 case AArch64CC::MI:
6561 if (IsZero)
6562 return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
6563 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
6564 }
6565 }
6566
6567 switch (CC) {
6568 default:
6569 return SDValue();
6570 case AArch64CC::NE: {
6571 SDValue Cmeq;
6572 if (IsZero)
6573 Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6574 else
6575 Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6576 return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
6577 }
6578 case AArch64CC::EQ:
6579 if (IsZero)
6580 return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6581 return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6582 case AArch64CC::GE:
6583 if (IsZero)
6584 return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
6585 return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
6586 case AArch64CC::GT:
6587 if (IsZero)
6588 return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
6589 return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
6590 case AArch64CC::LE:
6591 if (IsZero)
6592 return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
6593 return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
6594 case AArch64CC::LS:
6595 return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
6596 case AArch64CC::LO:
6597 return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
6598 case AArch64CC::LT:
6599 if (IsZero)
6600 return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
6601 return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
6602 case AArch64CC::HI:
6603 return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
6604 case AArch64CC::HS:
6605 return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
6606 }
6607}
6608
6609SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
6610 SelectionDAG &DAG) const {
6611 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6612 SDValue LHS = Op.getOperand(0);
6613 SDValue RHS = Op.getOperand(1);
Tim Northover45aa89c2015-02-08 00:50:47 +00006614 EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
Tim Northover3b0846e2014-05-24 12:50:23 +00006615 SDLoc dl(Op);
6616
6617 if (LHS.getValueType().getVectorElementType().isInteger()) {
6618 assert(LHS.getValueType() == RHS.getValueType());
6619 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
Tim Northover45aa89c2015-02-08 00:50:47 +00006620 SDValue Cmp =
6621 EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
6622 return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00006623 }
6624
6625 assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
6626 LHS.getValueType().getVectorElementType() == MVT::f64);
6627
6628 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
6629 // clean. Some of them require two branches to implement.
6630 AArch64CC::CondCode CC1, CC2;
6631 bool ShouldInvert;
6632 changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
6633
6634 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
6635 SDValue Cmp =
Tim Northover45aa89c2015-02-08 00:50:47 +00006636 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00006637 if (!Cmp.getNode())
6638 return SDValue();
6639
6640 if (CC2 != AArch64CC::AL) {
6641 SDValue Cmp2 =
Tim Northover45aa89c2015-02-08 00:50:47 +00006642 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00006643 if (!Cmp2.getNode())
6644 return SDValue();
6645
Tim Northover45aa89c2015-02-08 00:50:47 +00006646 Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
Tim Northover3b0846e2014-05-24 12:50:23 +00006647 }
6648
Tim Northover45aa89c2015-02-08 00:50:47 +00006649 Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
6650
Tim Northover3b0846e2014-05-24 12:50:23 +00006651 if (ShouldInvert)
6652 return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
6653
6654 return Cmp;
6655}
6656
6657/// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
6658/// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
6659/// specified in the intrinsic calls.
6660bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
6661 const CallInst &I,
6662 unsigned Intrinsic) const {
Mehdi Aminia749f2a2015-07-09 02:09:52 +00006663 auto &DL = I.getModule()->getDataLayout();
Tim Northover3b0846e2014-05-24 12:50:23 +00006664 switch (Intrinsic) {
6665 case Intrinsic::aarch64_neon_ld2:
6666 case Intrinsic::aarch64_neon_ld3:
6667 case Intrinsic::aarch64_neon_ld4:
6668 case Intrinsic::aarch64_neon_ld1x2:
6669 case Intrinsic::aarch64_neon_ld1x3:
6670 case Intrinsic::aarch64_neon_ld1x4:
6671 case Intrinsic::aarch64_neon_ld2lane:
6672 case Intrinsic::aarch64_neon_ld3lane:
6673 case Intrinsic::aarch64_neon_ld4lane:
6674 case Intrinsic::aarch64_neon_ld2r:
6675 case Intrinsic::aarch64_neon_ld3r:
6676 case Intrinsic::aarch64_neon_ld4r: {
6677 Info.opc = ISD::INTRINSIC_W_CHAIN;
6678 // Conservatively set memVT to the entire set of vectors loaded.
Mehdi Aminia749f2a2015-07-09 02:09:52 +00006679 uint64_t NumElts = DL.getTypeAllocSize(I.getType()) / 8;
Tim Northover3b0846e2014-05-24 12:50:23 +00006680 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6681 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6682 Info.offset = 0;
6683 Info.align = 0;
6684 Info.vol = false; // volatile loads with NEON intrinsics not supported
6685 Info.readMem = true;
6686 Info.writeMem = false;
6687 return true;
6688 }
6689 case Intrinsic::aarch64_neon_st2:
6690 case Intrinsic::aarch64_neon_st3:
6691 case Intrinsic::aarch64_neon_st4:
6692 case Intrinsic::aarch64_neon_st1x2:
6693 case Intrinsic::aarch64_neon_st1x3:
6694 case Intrinsic::aarch64_neon_st1x4:
6695 case Intrinsic::aarch64_neon_st2lane:
6696 case Intrinsic::aarch64_neon_st3lane:
6697 case Intrinsic::aarch64_neon_st4lane: {
6698 Info.opc = ISD::INTRINSIC_VOID;
6699 // Conservatively set memVT to the entire set of vectors stored.
6700 unsigned NumElts = 0;
6701 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
6702 Type *ArgTy = I.getArgOperand(ArgI)->getType();
6703 if (!ArgTy->isVectorTy())
6704 break;
Mehdi Aminia749f2a2015-07-09 02:09:52 +00006705 NumElts += DL.getTypeAllocSize(ArgTy) / 8;
Tim Northover3b0846e2014-05-24 12:50:23 +00006706 }
6707 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6708 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6709 Info.offset = 0;
6710 Info.align = 0;
6711 Info.vol = false; // volatile stores with NEON intrinsics not supported
6712 Info.readMem = false;
6713 Info.writeMem = true;
6714 return true;
6715 }
6716 case Intrinsic::aarch64_ldaxr:
6717 case Intrinsic::aarch64_ldxr: {
6718 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
6719 Info.opc = ISD::INTRINSIC_W_CHAIN;
6720 Info.memVT = MVT::getVT(PtrTy->getElementType());
6721 Info.ptrVal = I.getArgOperand(0);
6722 Info.offset = 0;
Mehdi Aminia749f2a2015-07-09 02:09:52 +00006723 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
Tim Northover3b0846e2014-05-24 12:50:23 +00006724 Info.vol = true;
6725 Info.readMem = true;
6726 Info.writeMem = false;
6727 return true;
6728 }
6729 case Intrinsic::aarch64_stlxr:
6730 case Intrinsic::aarch64_stxr: {
6731 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
6732 Info.opc = ISD::INTRINSIC_W_CHAIN;
6733 Info.memVT = MVT::getVT(PtrTy->getElementType());
6734 Info.ptrVal = I.getArgOperand(1);
6735 Info.offset = 0;
Mehdi Aminia749f2a2015-07-09 02:09:52 +00006736 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
Tim Northover3b0846e2014-05-24 12:50:23 +00006737 Info.vol = true;
6738 Info.readMem = false;
6739 Info.writeMem = true;
6740 return true;
6741 }
6742 case Intrinsic::aarch64_ldaxp:
6743 case Intrinsic::aarch64_ldxp: {
6744 Info.opc = ISD::INTRINSIC_W_CHAIN;
6745 Info.memVT = MVT::i128;
6746 Info.ptrVal = I.getArgOperand(0);
6747 Info.offset = 0;
6748 Info.align = 16;
6749 Info.vol = true;
6750 Info.readMem = true;
6751 Info.writeMem = false;
6752 return true;
6753 }
6754 case Intrinsic::aarch64_stlxp:
6755 case Intrinsic::aarch64_stxp: {
6756 Info.opc = ISD::INTRINSIC_W_CHAIN;
6757 Info.memVT = MVT::i128;
6758 Info.ptrVal = I.getArgOperand(2);
6759 Info.offset = 0;
6760 Info.align = 16;
6761 Info.vol = true;
6762 Info.readMem = false;
6763 Info.writeMem = true;
6764 return true;
6765 }
6766 default:
6767 break;
6768 }
6769
6770 return false;
6771}
6772
6773// Truncations from 64-bit GPR to 32-bit GPR is free.
6774bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
6775 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6776 return false;
6777 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6778 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00006779 return NumBits1 > NumBits2;
Tim Northover3b0846e2014-05-24 12:50:23 +00006780}
6781bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
Hao Liu40914502014-05-29 09:19:07 +00006782 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00006783 return false;
6784 unsigned NumBits1 = VT1.getSizeInBits();
6785 unsigned NumBits2 = VT2.getSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00006786 return NumBits1 > NumBits2;
Tim Northover3b0846e2014-05-24 12:50:23 +00006787}
6788
Chad Rosier54390052015-02-23 19:15:16 +00006789/// Check if it is profitable to hoist instruction in then/else to if.
6790/// Not profitable if I and it's user can form a FMA instruction
6791/// because we prefer FMSUB/FMADD.
6792bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
6793 if (I->getOpcode() != Instruction::FMul)
6794 return true;
6795
6796 if (I->getNumUses() != 1)
6797 return true;
6798
6799 Instruction *User = I->user_back();
6800
6801 if (User &&
6802 !(User->getOpcode() == Instruction::FSub ||
6803 User->getOpcode() == Instruction::FAdd))
6804 return true;
6805
6806 const TargetOptions &Options = getTargetMachine().Options;
Mehdi Amini44ede332015-07-09 02:09:04 +00006807 const DataLayout &DL = I->getModule()->getDataLayout();
6808 EVT VT = getValueType(DL, User->getOperand(0)->getType());
Chad Rosier54390052015-02-23 19:15:16 +00006809
6810 if (isFMAFasterThanFMulAndFAdd(VT) &&
6811 isOperationLegalOrCustom(ISD::FMA, VT) &&
6812 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath))
6813 return false;
6814
6815 return true;
6816}
6817
Tim Northover3b0846e2014-05-24 12:50:23 +00006818// All 32-bit GPR operations implicitly zero the high-half of the corresponding
6819// 64-bit GPR.
6820bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
6821 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6822 return false;
6823 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6824 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00006825 return NumBits1 == 32 && NumBits2 == 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00006826}
6827bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
Hao Liu40914502014-05-29 09:19:07 +00006828 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00006829 return false;
6830 unsigned NumBits1 = VT1.getSizeInBits();
6831 unsigned NumBits2 = VT2.getSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00006832 return NumBits1 == 32 && NumBits2 == 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00006833}
6834
6835bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
6836 EVT VT1 = Val.getValueType();
6837 if (isZExtFree(VT1, VT2)) {
6838 return true;
6839 }
6840
6841 if (Val.getOpcode() != ISD::LOAD)
6842 return false;
6843
6844 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
Hao Liu40914502014-05-29 09:19:07 +00006845 return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
6846 VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
6847 VT1.getSizeInBits() <= 32);
Tim Northover3b0846e2014-05-24 12:50:23 +00006848}
6849
Quentin Colombet6843ac42015-03-31 20:52:32 +00006850bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
6851 if (isa<FPExtInst>(Ext))
6852 return false;
6853
6854 // Vector types are next free.
6855 if (Ext->getType()->isVectorTy())
6856 return false;
6857
6858 for (const Use &U : Ext->uses()) {
6859 // The extension is free if we can fold it with a left shift in an
6860 // addressing mode or an arithmetic operation: add, sub, and cmp.
6861
6862 // Is there a shift?
6863 const Instruction *Instr = cast<Instruction>(U.getUser());
6864
6865 // Is this a constant shift?
6866 switch (Instr->getOpcode()) {
6867 case Instruction::Shl:
6868 if (!isa<ConstantInt>(Instr->getOperand(1)))
6869 return false;
6870 break;
6871 case Instruction::GetElementPtr: {
6872 gep_type_iterator GTI = gep_type_begin(Instr);
Mehdi Aminia749f2a2015-07-09 02:09:52 +00006873 auto &DL = Ext->getModule()->getDataLayout();
Quentin Colombet6843ac42015-03-31 20:52:32 +00006874 std::advance(GTI, U.getOperandNo());
6875 Type *IdxTy = *GTI;
6876 // This extension will end up with a shift because of the scaling factor.
6877 // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
6878 // Get the shift amount based on the scaling factor:
6879 // log2(sizeof(IdxTy)) - log2(8).
6880 uint64_t ShiftAmt =
Mehdi Aminia749f2a2015-07-09 02:09:52 +00006881 countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3;
Quentin Colombet6843ac42015-03-31 20:52:32 +00006882 // Is the constant foldable in the shift of the addressing mode?
6883 // I.e., shift amount is between 1 and 4 inclusive.
6884 if (ShiftAmt == 0 || ShiftAmt > 4)
6885 return false;
6886 break;
6887 }
6888 case Instruction::Trunc:
6889 // Check if this is a noop.
6890 // trunc(sext ty1 to ty2) to ty1.
6891 if (Instr->getType() == Ext->getOperand(0)->getType())
6892 continue;
6893 // FALL THROUGH.
6894 default:
6895 return false;
6896 }
6897
6898 // At this point we can use the bfm family, so this extension is free
6899 // for that use.
6900 }
6901 return true;
6902}
6903
Tim Northover3b0846e2014-05-24 12:50:23 +00006904bool AArch64TargetLowering::hasPairedLoad(Type *LoadedType,
6905 unsigned &RequiredAligment) const {
6906 if (!LoadedType->isIntegerTy() && !LoadedType->isFloatTy())
6907 return false;
6908 // Cyclone supports unaligned accesses.
6909 RequiredAligment = 0;
6910 unsigned NumBits = LoadedType->getPrimitiveSizeInBits();
6911 return NumBits == 32 || NumBits == 64;
6912}
6913
6914bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
6915 unsigned &RequiredAligment) const {
6916 if (!LoadedType.isSimple() ||
6917 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
6918 return false;
6919 // Cyclone supports unaligned accesses.
6920 RequiredAligment = 0;
6921 unsigned NumBits = LoadedType.getSizeInBits();
6922 return NumBits == 32 || NumBits == 64;
6923}
6924
Hao Liu7ec8ee32015-06-26 02:32:07 +00006925/// \brief Lower an interleaved load into a ldN intrinsic.
6926///
6927/// E.g. Lower an interleaved load (Factor = 2):
6928/// %wide.vec = load <8 x i32>, <8 x i32>* %ptr
6929/// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
6930/// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
6931///
6932/// Into:
6933/// %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
6934/// %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
6935/// %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
6936bool AArch64TargetLowering::lowerInterleavedLoad(
6937 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
6938 ArrayRef<unsigned> Indices, unsigned Factor) const {
6939 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
6940 "Invalid interleave factor");
6941 assert(!Shuffles.empty() && "Empty shufflevector input");
6942 assert(Shuffles.size() == Indices.size() &&
6943 "Unmatched number of shufflevectors and indices");
6944
Mehdi Aminia749f2a2015-07-09 02:09:52 +00006945 const DataLayout &DL = LI->getModule()->getDataLayout();
Hao Liu7ec8ee32015-06-26 02:32:07 +00006946
6947 VectorType *VecTy = Shuffles[0]->getType();
Mehdi Aminia749f2a2015-07-09 02:09:52 +00006948 unsigned VecSize = DL.getTypeAllocSizeInBits(VecTy);
Hao Liu7ec8ee32015-06-26 02:32:07 +00006949
6950 // Skip illegal vector types.
6951 if (VecSize != 64 && VecSize != 128)
6952 return false;
6953
6954 // A pointer vector can not be the return type of the ldN intrinsics. Need to
6955 // load integer vectors first and then convert to pointer vectors.
6956 Type *EltTy = VecTy->getVectorElementType();
6957 if (EltTy->isPointerTy())
Mehdi Aminia749f2a2015-07-09 02:09:52 +00006958 VecTy =
6959 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
Hao Liu7ec8ee32015-06-26 02:32:07 +00006960
6961 Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
6962 Type *Tys[2] = {VecTy, PtrTy};
6963 static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
6964 Intrinsic::aarch64_neon_ld3,
6965 Intrinsic::aarch64_neon_ld4};
6966 Function *LdNFunc =
6967 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
6968
6969 IRBuilder<> Builder(LI);
6970 Value *Ptr = Builder.CreateBitCast(LI->getPointerOperand(), PtrTy);
6971
6972 CallInst *LdN = Builder.CreateCall(LdNFunc, Ptr, "ldN");
6973
6974 // Replace uses of each shufflevector with the corresponding vector loaded
6975 // by ldN.
6976 for (unsigned i = 0; i < Shuffles.size(); i++) {
6977 ShuffleVectorInst *SVI = Shuffles[i];
6978 unsigned Index = Indices[i];
6979
6980 Value *SubVec = Builder.CreateExtractValue(LdN, Index);
6981
6982 // Convert the integer vector to pointer vector if the element is pointer.
6983 if (EltTy->isPointerTy())
6984 SubVec = Builder.CreateIntToPtr(SubVec, SVI->getType());
6985
6986 SVI->replaceAllUsesWith(SubVec);
6987 }
6988
6989 return true;
6990}
6991
6992/// \brief Get a mask consisting of sequential integers starting from \p Start.
6993///
6994/// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
6995static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
6996 unsigned NumElts) {
6997 SmallVector<Constant *, 16> Mask;
6998 for (unsigned i = 0; i < NumElts; i++)
6999 Mask.push_back(Builder.getInt32(Start + i));
7000
7001 return ConstantVector::get(Mask);
7002}
7003
7004/// \brief Lower an interleaved store into a stN intrinsic.
7005///
7006/// E.g. Lower an interleaved store (Factor = 3):
7007/// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
7008/// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
7009/// store <12 x i32> %i.vec, <12 x i32>* %ptr
7010///
7011/// Into:
7012/// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
7013/// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
7014/// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
7015/// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
7016///
7017/// Note that the new shufflevectors will be removed and we'll only generate one
7018/// st3 instruction in CodeGen.
7019bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
7020 ShuffleVectorInst *SVI,
7021 unsigned Factor) const {
7022 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7023 "Invalid interleave factor");
7024
7025 VectorType *VecTy = SVI->getType();
7026 assert(VecTy->getVectorNumElements() % Factor == 0 &&
7027 "Invalid interleaved store");
7028
7029 unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
7030 Type *EltTy = VecTy->getVectorElementType();
7031 VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
7032
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007033 const DataLayout &DL = SI->getModule()->getDataLayout();
7034 unsigned SubVecSize = DL.getTypeAllocSizeInBits(SubVecTy);
Hao Liu7ec8ee32015-06-26 02:32:07 +00007035
7036 // Skip illegal vector types.
7037 if (SubVecSize != 64 && SubVecSize != 128)
7038 return false;
7039
7040 Value *Op0 = SVI->getOperand(0);
7041 Value *Op1 = SVI->getOperand(1);
7042 IRBuilder<> Builder(SI);
7043
7044 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
7045 // vectors to integer vectors.
7046 if (EltTy->isPointerTy()) {
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007047 Type *IntTy = DL.getIntPtrType(EltTy);
Hao Liu7ec8ee32015-06-26 02:32:07 +00007048 unsigned NumOpElts =
7049 dyn_cast<VectorType>(Op0->getType())->getVectorNumElements();
7050
7051 // Convert to the corresponding integer vector.
7052 Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
7053 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
7054 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
7055
7056 SubVecTy = VectorType::get(IntTy, NumSubElts);
7057 }
7058
7059 Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
7060 Type *Tys[2] = {SubVecTy, PtrTy};
7061 static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
7062 Intrinsic::aarch64_neon_st3,
7063 Intrinsic::aarch64_neon_st4};
7064 Function *StNFunc =
7065 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
7066
7067 SmallVector<Value *, 5> Ops;
7068
7069 // Split the shufflevector operands into sub vectors for the new stN call.
7070 for (unsigned i = 0; i < Factor; i++)
7071 Ops.push_back(Builder.CreateShuffleVector(
7072 Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
7073
7074 Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), PtrTy));
7075 Builder.CreateCall(StNFunc, Ops);
7076 return true;
7077}
7078
Tim Northover3b0846e2014-05-24 12:50:23 +00007079static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
7080 unsigned AlignCheck) {
7081 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
7082 (DstAlign == 0 || DstAlign % AlignCheck == 0));
7083}
7084
7085EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
7086 unsigned SrcAlign, bool IsMemset,
7087 bool ZeroMemset,
7088 bool MemcpyStrSrc,
7089 MachineFunction &MF) const {
7090 // Don't use AdvSIMD to implement 16-byte memset. It would have taken one
7091 // instruction to materialize the v2i64 zero and one store (with restrictive
7092 // addressing mode). Just do two i64 store of zero-registers.
7093 bool Fast;
7094 const Function *F = MF.getFunction();
7095 if (Subtarget->hasFPARMv8() && !IsMemset && Size >= 16 &&
Duncan P. N. Exon Smith003bb7d2015-02-14 02:09:06 +00007096 !F->hasFnAttribute(Attribute::NoImplicitFloat) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00007097 (memOpAlign(SrcAlign, DstAlign, 16) ||
Matt Arsenault6f2a5262014-07-27 17:46:40 +00007098 (allowsMisalignedMemoryAccesses(MVT::f128, 0, 1, &Fast) && Fast)))
Tim Northover3b0846e2014-05-24 12:50:23 +00007099 return MVT::f128;
7100
Lang Hames90333852015-04-09 03:40:33 +00007101 if (Size >= 8 &&
7102 (memOpAlign(SrcAlign, DstAlign, 8) ||
7103 (allowsMisalignedMemoryAccesses(MVT::i64, 0, 1, &Fast) && Fast)))
7104 return MVT::i64;
7105
7106 if (Size >= 4 &&
7107 (memOpAlign(SrcAlign, DstAlign, 4) ||
7108 (allowsMisalignedMemoryAccesses(MVT::i32, 0, 1, &Fast) && Fast)))
Lang Hames522bf132015-04-09 05:34:57 +00007109 return MVT::i32;
Lang Hames90333852015-04-09 03:40:33 +00007110
7111 return MVT::Other;
Tim Northover3b0846e2014-05-24 12:50:23 +00007112}
7113
7114// 12-bit optionally shifted immediates are legal for adds.
7115bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
7116 if ((Immed >> 12) == 0 || ((Immed & 0xfff) == 0 && Immed >> 24 == 0))
7117 return true;
7118 return false;
7119}
7120
7121// Integer comparisons are implemented with ADDS/SUBS, so the range of valid
7122// immediates is the same as for an add or a sub.
7123bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
7124 if (Immed < 0)
7125 Immed *= -1;
7126 return isLegalAddImmediate(Immed);
7127}
7128
7129/// isLegalAddressingMode - Return true if the addressing mode represented
7130/// by AM is legal for this target, for a load/store of the specified type.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00007131bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
7132 const AddrMode &AM, Type *Ty,
Matt Arsenaultbd7d80a2015-06-01 05:31:59 +00007133 unsigned AS) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00007134 // AArch64 has five basic addressing modes:
7135 // reg
7136 // reg + 9-bit signed offset
7137 // reg + SIZE_IN_BYTES * 12-bit unsigned offset
7138 // reg1 + reg2
7139 // reg + SIZE_IN_BYTES * reg
7140
7141 // No global is ever allowed as a base.
7142 if (AM.BaseGV)
7143 return false;
7144
7145 // No reg+reg+imm addressing.
7146 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
7147 return false;
7148
7149 // check reg + imm case:
7150 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
7151 uint64_t NumBytes = 0;
7152 if (Ty->isSized()) {
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00007153 uint64_t NumBits = DL.getTypeSizeInBits(Ty);
Tim Northover3b0846e2014-05-24 12:50:23 +00007154 NumBytes = NumBits / 8;
7155 if (!isPowerOf2_64(NumBits))
7156 NumBytes = 0;
7157 }
7158
7159 if (!AM.Scale) {
7160 int64_t Offset = AM.BaseOffs;
7161
7162 // 9-bit signed offset
7163 if (Offset >= -(1LL << 9) && Offset <= (1LL << 9) - 1)
7164 return true;
7165
7166 // 12-bit unsigned offset
7167 unsigned shift = Log2_64(NumBytes);
7168 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
7169 // Must be a multiple of NumBytes (NumBytes is a power of 2)
7170 (Offset >> shift) << shift == Offset)
7171 return true;
7172 return false;
7173 }
7174
7175 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
7176
7177 if (!AM.Scale || AM.Scale == 1 ||
7178 (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes))
7179 return true;
7180 return false;
7181}
7182
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00007183int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
7184 const AddrMode &AM, Type *Ty,
Matt Arsenaultbd7d80a2015-06-01 05:31:59 +00007185 unsigned AS) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00007186 // Scaling factors are not free at all.
7187 // Operands | Rt Latency
7188 // -------------------------------------------
7189 // Rt, [Xn, Xm] | 4
7190 // -------------------------------------------
7191 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5
7192 // Rt, [Xn, Wm, <extend> #imm] |
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00007193 if (isLegalAddressingMode(DL, AM, Ty, AS))
Tim Northover3b0846e2014-05-24 12:50:23 +00007194 // Scale represents reg2 * scale, thus account for 1 if
7195 // it is not equal to 0 or 1.
7196 return AM.Scale != 0 && AM.Scale != 1;
7197 return -1;
7198}
7199
7200bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
7201 VT = VT.getScalarType();
7202
7203 if (!VT.isSimple())
7204 return false;
7205
7206 switch (VT.getSimpleVT().SimpleTy) {
7207 case MVT::f32:
7208 case MVT::f64:
7209 return true;
7210 default:
7211 break;
7212 }
7213
7214 return false;
7215}
7216
7217const MCPhysReg *
7218AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
7219 // LR is a callee-save register, but we must treat it as clobbered by any call
7220 // site. Hence we include LR in the scratch registers, which are in turn added
7221 // as implicit-defs for stackmaps and patchpoints.
7222 static const MCPhysReg ScratchRegs[] = {
7223 AArch64::X16, AArch64::X17, AArch64::LR, 0
7224 };
7225 return ScratchRegs;
7226}
7227
7228bool
7229AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N) const {
7230 EVT VT = N->getValueType(0);
7231 // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
7232 // it with shift to let it be lowered to UBFX.
7233 if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
7234 isa<ConstantSDNode>(N->getOperand(1))) {
7235 uint64_t TruncMask = N->getConstantOperandVal(1);
7236 if (isMask_64(TruncMask) &&
7237 N->getOperand(0).getOpcode() == ISD::SRL &&
7238 isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
7239 return false;
7240 }
7241 return true;
7242}
7243
7244bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
7245 Type *Ty) const {
7246 assert(Ty->isIntegerTy());
7247
7248 unsigned BitSize = Ty->getPrimitiveSizeInBits();
7249 if (BitSize == 0)
7250 return false;
7251
7252 int64_t Val = Imm.getSExtValue();
7253 if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
7254 return true;
7255
7256 if ((int64_t)Val < 0)
7257 Val = ~Val;
7258 if (BitSize == 32)
7259 Val &= (1LL << 32) - 1;
7260
7261 unsigned LZ = countLeadingZeros((uint64_t)Val);
7262 unsigned Shift = (63 - LZ) / 16;
7263 // MOVZ is free so return true for one or fewer MOVK.
David Blaikie186d2cb2015-03-24 16:24:01 +00007264 return Shift < 3;
Tim Northover3b0846e2014-05-24 12:50:23 +00007265}
7266
7267// Generate SUBS and CSEL for integer abs.
7268static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
7269 EVT VT = N->getValueType(0);
7270
7271 SDValue N0 = N->getOperand(0);
7272 SDValue N1 = N->getOperand(1);
7273 SDLoc DL(N);
7274
7275 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
7276 // and change it to SUB and CSEL.
7277 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
7278 N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
7279 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
7280 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
7281 if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007282 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
Tim Northover3b0846e2014-05-24 12:50:23 +00007283 N0.getOperand(0));
7284 // Generate SUBS & CSEL.
7285 SDValue Cmp =
7286 DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007287 N0.getOperand(0), DAG.getConstant(0, DL, VT));
Tim Northover3b0846e2014-05-24 12:50:23 +00007288 return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007289 DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00007290 SDValue(Cmp.getNode(), 1));
7291 }
7292 return SDValue();
7293}
7294
7295// performXorCombine - Attempts to handle integer ABS.
7296static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
7297 TargetLowering::DAGCombinerInfo &DCI,
7298 const AArch64Subtarget *Subtarget) {
7299 if (DCI.isBeforeLegalizeOps())
7300 return SDValue();
7301
7302 return performIntegerAbsCombine(N, DAG);
7303}
7304
Chad Rosier17020f92014-07-23 14:57:52 +00007305SDValue
7306AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
7307 SelectionDAG &DAG,
7308 std::vector<SDNode *> *Created) const {
7309 // fold (sdiv X, pow2)
7310 EVT VT = N->getValueType(0);
7311 if ((VT != MVT::i32 && VT != MVT::i64) ||
7312 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
7313 return SDValue();
7314
7315 SDLoc DL(N);
7316 SDValue N0 = N->getOperand(0);
7317 unsigned Lg2 = Divisor.countTrailingZeros();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007318 SDValue Zero = DAG.getConstant(0, DL, VT);
7319 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
Chad Rosier17020f92014-07-23 14:57:52 +00007320
7321 // Add (N0 < 0) ? Pow2 - 1 : 0;
7322 SDValue CCVal;
7323 SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
7324 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
7325 SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
7326
7327 if (Created) {
7328 Created->push_back(Cmp.getNode());
7329 Created->push_back(Add.getNode());
7330 Created->push_back(CSel.getNode());
7331 }
7332
7333 // Divide by pow2.
7334 SDValue SRA =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007335 DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
Chad Rosier17020f92014-07-23 14:57:52 +00007336
7337 // If we're dividing by a positive value, we're done. Otherwise, we must
7338 // negate the result.
7339 if (Divisor.isNonNegative())
7340 return SRA;
7341
7342 if (Created)
7343 Created->push_back(SRA.getNode());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007344 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
Chad Rosier17020f92014-07-23 14:57:52 +00007345}
7346
Tim Northover3b0846e2014-05-24 12:50:23 +00007347static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
7348 TargetLowering::DAGCombinerInfo &DCI,
7349 const AArch64Subtarget *Subtarget) {
7350 if (DCI.isBeforeLegalizeOps())
7351 return SDValue();
7352
7353 // Multiplication of a power of two plus/minus one can be done more
7354 // cheaply as as shift+add/sub. For now, this is true unilaterally. If
7355 // future CPUs have a cheaper MADD instruction, this may need to be
7356 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
7357 // 64-bit is 5 cycles, so this is always a win.
7358 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
7359 APInt Value = C->getAPIntValue();
7360 EVT VT = N->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007361 SDLoc DL(N);
Chad Rosiere6b87612014-06-30 14:51:14 +00007362 if (Value.isNonNegative()) {
7363 // (mul x, 2^N + 1) => (add (shl x, N), x)
7364 APInt VM1 = Value - 1;
7365 if (VM1.isPowerOf2()) {
7366 SDValue ShiftedVal =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007367 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7368 DAG.getConstant(VM1.logBase2(), DL, MVT::i64));
7369 return DAG.getNode(ISD::ADD, DL, VT, ShiftedVal,
Chad Rosiere6b87612014-06-30 14:51:14 +00007370 N->getOperand(0));
7371 }
7372 // (mul x, 2^N - 1) => (sub (shl x, N), x)
7373 APInt VP1 = Value + 1;
7374 if (VP1.isPowerOf2()) {
7375 SDValue ShiftedVal =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007376 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7377 DAG.getConstant(VP1.logBase2(), DL, MVT::i64));
7378 return DAG.getNode(ISD::SUB, DL, VT, ShiftedVal,
Chad Rosiere6b87612014-06-30 14:51:14 +00007379 N->getOperand(0));
7380 }
7381 } else {
Chad Rosier8e38f302015-03-03 17:31:01 +00007382 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7383 APInt VNP1 = -Value + 1;
7384 if (VNP1.isPowerOf2()) {
7385 SDValue ShiftedVal =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007386 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7387 DAG.getConstant(VNP1.logBase2(), DL, MVT::i64));
7388 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0),
Chad Rosier8e38f302015-03-03 17:31:01 +00007389 ShiftedVal);
7390 }
Chad Rosiere6b87612014-06-30 14:51:14 +00007391 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7392 APInt VNM1 = -Value - 1;
7393 if (VNM1.isPowerOf2()) {
7394 SDValue ShiftedVal =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007395 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7396 DAG.getConstant(VNM1.logBase2(), DL, MVT::i64));
Chad Rosiere6b87612014-06-30 14:51:14 +00007397 SDValue Add =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007398 DAG.getNode(ISD::ADD, DL, VT, ShiftedVal, N->getOperand(0));
7399 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Add);
Chad Rosiere6b87612014-06-30 14:51:14 +00007400 }
Chad Rosierd96e9f12014-06-09 01:25:51 +00007401 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007402 }
7403 return SDValue();
7404}
7405
Jim Grosbachf7502c42014-07-18 00:40:52 +00007406static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
7407 SelectionDAG &DAG) {
7408 // Take advantage of vector comparisons producing 0 or -1 in each lane to
7409 // optimize away operation when it's from a constant.
7410 //
7411 // The general transformation is:
7412 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
7413 // AND(VECTOR_CMP(x,y), constant2)
7414 // constant2 = UNARYOP(constant)
7415
Jim Grosbach8f6f0852014-07-23 20:41:38 +00007416 // Early exit if this isn't a vector operation, the operand of the
7417 // unary operation isn't a bitwise AND, or if the sizes of the operations
7418 // aren't the same.
Jim Grosbachf7502c42014-07-18 00:40:52 +00007419 EVT VT = N->getValueType(0);
7420 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
Jim Grosbach8f6f0852014-07-23 20:41:38 +00007421 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
7422 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
Jim Grosbachf7502c42014-07-18 00:40:52 +00007423 return SDValue();
7424
Jim Grosbach724e4382014-07-23 20:41:43 +00007425 // Now check that the other operand of the AND is a constant. We could
Jim Grosbachf7502c42014-07-18 00:40:52 +00007426 // make the transformation for non-constant splats as well, but it's unclear
7427 // that would be a benefit as it would not eliminate any operations, just
7428 // perform one more step in scalar code before moving to the vector unit.
7429 if (BuildVectorSDNode *BV =
7430 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
Jim Grosbach724e4382014-07-23 20:41:43 +00007431 // Bail out if the vector isn't a constant.
7432 if (!BV->isConstant())
Jim Grosbachf7502c42014-07-18 00:40:52 +00007433 return SDValue();
7434
7435 // Everything checks out. Build up the new and improved node.
7436 SDLoc DL(N);
7437 EVT IntVT = BV->getValueType(0);
7438 // Create a new constant of the appropriate type for the transformed
7439 // DAG.
7440 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
7441 // The AND node needs bitcasts to/from an integer vector type around it.
7442 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
7443 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
7444 N->getOperand(0)->getOperand(0), MaskConst);
7445 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
7446 return Res;
7447 }
7448
7449 return SDValue();
7450}
7451
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00007452static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
7453 const AArch64Subtarget *Subtarget) {
Jim Grosbachf7502c42014-07-18 00:40:52 +00007454 // First try to optimize away the conversion when it's conditionally from
7455 // a constant. Vectors only.
7456 SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
7457 if (Res != SDValue())
7458 return Res;
7459
Tim Northover3b0846e2014-05-24 12:50:23 +00007460 EVT VT = N->getValueType(0);
7461 if (VT != MVT::f32 && VT != MVT::f64)
7462 return SDValue();
Jim Grosbachf7502c42014-07-18 00:40:52 +00007463
Tim Northover3b0846e2014-05-24 12:50:23 +00007464 // Only optimize when the source and destination types have the same width.
7465 if (VT.getSizeInBits() != N->getOperand(0).getValueType().getSizeInBits())
7466 return SDValue();
7467
7468 // If the result of an integer load is only used by an integer-to-float
7469 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
7470 // This eliminates an "integer-to-vector-move UOP and improve throughput.
7471 SDValue N0 = N->getOperand(0);
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00007472 if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Tim Northover3b0846e2014-05-24 12:50:23 +00007473 // Do not change the width of a volatile load.
7474 !cast<LoadSDNode>(N0)->isVolatile()) {
7475 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7476 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
7477 LN0->getPointerInfo(), LN0->isVolatile(),
7478 LN0->isNonTemporal(), LN0->isInvariant(),
7479 LN0->getAlignment());
7480
7481 // Make sure successors of the original load stay after it by updating them
7482 // to use the new Chain.
7483 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
7484
7485 unsigned Opcode =
7486 (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
7487 return DAG.getNode(Opcode, SDLoc(N), VT, Load);
7488 }
7489
7490 return SDValue();
7491}
7492
7493/// An EXTR instruction is made up of two shifts, ORed together. This helper
7494/// searches for and classifies those shifts.
7495static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
7496 bool &FromHi) {
7497 if (N.getOpcode() == ISD::SHL)
7498 FromHi = false;
7499 else if (N.getOpcode() == ISD::SRL)
7500 FromHi = true;
7501 else
7502 return false;
7503
7504 if (!isa<ConstantSDNode>(N.getOperand(1)))
7505 return false;
7506
7507 ShiftAmount = N->getConstantOperandVal(1);
7508 Src = N->getOperand(0);
7509 return true;
7510}
7511
7512/// EXTR instruction extracts a contiguous chunk of bits from two existing
7513/// registers viewed as a high/low pair. This function looks for the pattern:
7514/// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an
7515/// EXTR. Can't quite be done in TableGen because the two immediates aren't
7516/// independent.
7517static SDValue tryCombineToEXTR(SDNode *N,
7518 TargetLowering::DAGCombinerInfo &DCI) {
7519 SelectionDAG &DAG = DCI.DAG;
7520 SDLoc DL(N);
7521 EVT VT = N->getValueType(0);
7522
7523 assert(N->getOpcode() == ISD::OR && "Unexpected root");
7524
7525 if (VT != MVT::i32 && VT != MVT::i64)
7526 return SDValue();
7527
7528 SDValue LHS;
7529 uint32_t ShiftLHS = 0;
7530 bool LHSFromHi = 0;
7531 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
7532 return SDValue();
7533
7534 SDValue RHS;
7535 uint32_t ShiftRHS = 0;
7536 bool RHSFromHi = 0;
7537 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
7538 return SDValue();
7539
7540 // If they're both trying to come from the high part of the register, they're
7541 // not really an EXTR.
7542 if (LHSFromHi == RHSFromHi)
7543 return SDValue();
7544
7545 if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
7546 return SDValue();
7547
7548 if (LHSFromHi) {
7549 std::swap(LHS, RHS);
7550 std::swap(ShiftLHS, ShiftRHS);
7551 }
7552
7553 return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007554 DAG.getConstant(ShiftRHS, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00007555}
7556
7557static SDValue tryCombineToBSL(SDNode *N,
7558 TargetLowering::DAGCombinerInfo &DCI) {
7559 EVT VT = N->getValueType(0);
7560 SelectionDAG &DAG = DCI.DAG;
7561 SDLoc DL(N);
7562
7563 if (!VT.isVector())
7564 return SDValue();
7565
7566 SDValue N0 = N->getOperand(0);
7567 if (N0.getOpcode() != ISD::AND)
7568 return SDValue();
7569
7570 SDValue N1 = N->getOperand(1);
7571 if (N1.getOpcode() != ISD::AND)
7572 return SDValue();
7573
7574 // We only have to look for constant vectors here since the general, variable
7575 // case can be handled in TableGen.
7576 unsigned Bits = VT.getVectorElementType().getSizeInBits();
7577 uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
7578 for (int i = 1; i >= 0; --i)
7579 for (int j = 1; j >= 0; --j) {
7580 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
7581 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
7582 if (!BVN0 || !BVN1)
7583 continue;
7584
7585 bool FoundMatch = true;
7586 for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
7587 ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
7588 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
7589 if (!CN0 || !CN1 ||
7590 CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
7591 FoundMatch = false;
7592 break;
7593 }
7594 }
7595
7596 if (FoundMatch)
7597 return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
7598 N0->getOperand(1 - i), N1->getOperand(1 - j));
7599 }
7600
7601 return SDValue();
7602}
7603
7604static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
7605 const AArch64Subtarget *Subtarget) {
7606 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
7607 if (!EnableAArch64ExtrGeneration)
7608 return SDValue();
7609 SelectionDAG &DAG = DCI.DAG;
7610 EVT VT = N->getValueType(0);
7611
7612 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7613 return SDValue();
7614
7615 SDValue Res = tryCombineToEXTR(N, DCI);
7616 if (Res.getNode())
7617 return Res;
7618
7619 Res = tryCombineToBSL(N, DCI);
7620 if (Res.getNode())
7621 return Res;
7622
7623 return SDValue();
7624}
7625
7626static SDValue performBitcastCombine(SDNode *N,
7627 TargetLowering::DAGCombinerInfo &DCI,
7628 SelectionDAG &DAG) {
7629 // Wait 'til after everything is legalized to try this. That way we have
7630 // legal vector types and such.
7631 if (DCI.isBeforeLegalizeOps())
7632 return SDValue();
7633
7634 // Remove extraneous bitcasts around an extract_subvector.
7635 // For example,
7636 // (v4i16 (bitconvert
7637 // (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
7638 // becomes
7639 // (extract_subvector ((v8i16 ...), (i64 4)))
7640
7641 // Only interested in 64-bit vectors as the ultimate result.
7642 EVT VT = N->getValueType(0);
7643 if (!VT.isVector())
7644 return SDValue();
7645 if (VT.getSimpleVT().getSizeInBits() != 64)
7646 return SDValue();
7647 // Is the operand an extract_subvector starting at the beginning or halfway
7648 // point of the vector? A low half may also come through as an
7649 // EXTRACT_SUBREG, so look for that, too.
7650 SDValue Op0 = N->getOperand(0);
7651 if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
7652 !(Op0->isMachineOpcode() &&
7653 Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
7654 return SDValue();
7655 uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
7656 if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
7657 if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
7658 return SDValue();
7659 } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
7660 if (idx != AArch64::dsub)
7661 return SDValue();
7662 // The dsub reference is equivalent to a lane zero subvector reference.
7663 idx = 0;
7664 }
7665 // Look through the bitcast of the input to the extract.
7666 if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
7667 return SDValue();
7668 SDValue Source = Op0->getOperand(0)->getOperand(0);
7669 // If the source type has twice the number of elements as our destination
7670 // type, we know this is an extract of the high or low half of the vector.
7671 EVT SVT = Source->getValueType(0);
7672 if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
7673 return SDValue();
7674
7675 DEBUG(dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
7676
7677 // Create the simplified form to just extract the low or high half of the
7678 // vector directly rather than bothering with the bitcasts.
7679 SDLoc dl(N);
7680 unsigned NumElements = VT.getVectorNumElements();
7681 if (idx) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007682 SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00007683 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
7684 } else {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007685 SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00007686 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
7687 Source, SubReg),
7688 0);
7689 }
7690}
7691
7692static SDValue performConcatVectorsCombine(SDNode *N,
7693 TargetLowering::DAGCombinerInfo &DCI,
7694 SelectionDAG &DAG) {
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00007695 SDLoc dl(N);
7696 EVT VT = N->getValueType(0);
7697 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
7698
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00007699 // Optimize concat_vectors of truncated vectors, where the intermediate
7700 // type is illegal, to avoid said illegality, e.g.,
7701 // (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
7702 // (v2i16 (truncate (v2i64)))))
7703 // ->
Ahmed Bougachae6bb09a2015-03-21 01:08:39 +00007704 // (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
7705 // (v4i32 (bitcast (v2i64))),
7706 // <0, 2, 4, 6>)))
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00007707 // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
7708 // on both input and result type, so we might generate worse code.
7709 // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
7710 if (N->getNumOperands() == 2 &&
7711 N0->getOpcode() == ISD::TRUNCATE &&
7712 N1->getOpcode() == ISD::TRUNCATE) {
7713 SDValue N00 = N0->getOperand(0);
7714 SDValue N10 = N1->getOperand(0);
7715 EVT N00VT = N00.getValueType();
7716
7717 if (N00VT == N10.getValueType() &&
7718 (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
7719 N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
Ahmed Bougachae6bb09a2015-03-21 01:08:39 +00007720 MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
7721 SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
7722 for (size_t i = 0; i < Mask.size(); ++i)
7723 Mask[i] = i * 2;
7724 return DAG.getNode(ISD::TRUNCATE, dl, VT,
7725 DAG.getVectorShuffle(
7726 MidVT, dl,
7727 DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
7728 DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00007729 }
7730 }
7731
Tim Northover3b0846e2014-05-24 12:50:23 +00007732 // Wait 'til after everything is legalized to try this. That way we have
7733 // legal vector types and such.
7734 if (DCI.isBeforeLegalizeOps())
7735 return SDValue();
7736
Tim Northover3b0846e2014-05-24 12:50:23 +00007737 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
7738 // splat. The indexed instructions are going to be expecting a DUPLANE64, so
7739 // canonicalise to that.
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00007740 if (N0 == N1 && VT.getVectorNumElements() == 2) {
Tim Northover3b0846e2014-05-24 12:50:23 +00007741 assert(VT.getVectorElementType().getSizeInBits() == 64);
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00007742 return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007743 DAG.getConstant(0, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00007744 }
7745
7746 // Canonicalise concat_vectors so that the right-hand vector has as few
7747 // bit-casts as possible before its real operation. The primary matching
7748 // destination for these operations will be the narrowing "2" instructions,
7749 // which depend on the operation being performed on this right-hand vector.
7750 // For example,
7751 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS))))
7752 // becomes
7753 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
7754
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00007755 if (N1->getOpcode() != ISD::BITCAST)
Tim Northover3b0846e2014-05-24 12:50:23 +00007756 return SDValue();
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00007757 SDValue RHS = N1->getOperand(0);
Tim Northover3b0846e2014-05-24 12:50:23 +00007758 MVT RHSTy = RHS.getValueType().getSimpleVT();
7759 // If the RHS is not a vector, this is not the pattern we're looking for.
7760 if (!RHSTy.isVector())
7761 return SDValue();
7762
7763 DEBUG(dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
7764
7765 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
7766 RHSTy.getVectorNumElements() * 2);
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00007767 return DAG.getNode(ISD::BITCAST, dl, VT,
7768 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
7769 DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
7770 RHS));
Tim Northover3b0846e2014-05-24 12:50:23 +00007771}
7772
7773static SDValue tryCombineFixedPointConvert(SDNode *N,
7774 TargetLowering::DAGCombinerInfo &DCI,
7775 SelectionDAG &DAG) {
7776 // Wait 'til after everything is legalized to try this. That way we have
7777 // legal vector types and such.
7778 if (DCI.isBeforeLegalizeOps())
7779 return SDValue();
7780 // Transform a scalar conversion of a value from a lane extract into a
7781 // lane extract of a vector conversion. E.g., from foo1 to foo2:
7782 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
7783 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
7784 //
7785 // The second form interacts better with instruction selection and the
7786 // register allocator to avoid cross-class register copies that aren't
7787 // coalescable due to a lane reference.
7788
7789 // Check the operand and see if it originates from a lane extract.
7790 SDValue Op1 = N->getOperand(1);
7791 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7792 // Yep, no additional predication needed. Perform the transform.
7793 SDValue IID = N->getOperand(0);
7794 SDValue Shift = N->getOperand(2);
7795 SDValue Vec = Op1.getOperand(0);
7796 SDValue Lane = Op1.getOperand(1);
7797 EVT ResTy = N->getValueType(0);
7798 EVT VecResTy;
7799 SDLoc DL(N);
7800
7801 // The vector width should be 128 bits by the time we get here, even
7802 // if it started as 64 bits (the extract_vector handling will have
7803 // done so).
7804 assert(Vec.getValueType().getSizeInBits() == 128 &&
7805 "unexpected vector size on extract_vector_elt!");
7806 if (Vec.getValueType() == MVT::v4i32)
7807 VecResTy = MVT::v4f32;
7808 else if (Vec.getValueType() == MVT::v2i64)
7809 VecResTy = MVT::v2f64;
7810 else
Craig Topper2a30d782014-06-18 05:05:13 +00007811 llvm_unreachable("unexpected vector type!");
Tim Northover3b0846e2014-05-24 12:50:23 +00007812
7813 SDValue Convert =
7814 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
7815 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
7816 }
7817 return SDValue();
7818}
7819
7820// AArch64 high-vector "long" operations are formed by performing the non-high
7821// version on an extract_subvector of each operand which gets the high half:
7822//
7823// (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
7824//
7825// However, there are cases which don't have an extract_high explicitly, but
7826// have another operation that can be made compatible with one for free. For
7827// example:
7828//
7829// (dupv64 scalar) --> (extract_high (dup128 scalar))
7830//
7831// This routine does the actual conversion of such DUPs, once outer routines
7832// have determined that everything else is in order.
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00007833// It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
7834// similarly here.
Tim Northover3b0846e2014-05-24 12:50:23 +00007835static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00007836 switch (N.getOpcode()) {
7837 case AArch64ISD::DUP:
Tim Northover3b0846e2014-05-24 12:50:23 +00007838 case AArch64ISD::DUPLANE8:
7839 case AArch64ISD::DUPLANE16:
7840 case AArch64ISD::DUPLANE32:
7841 case AArch64ISD::DUPLANE64:
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00007842 case AArch64ISD::MOVI:
7843 case AArch64ISD::MOVIshift:
7844 case AArch64ISD::MOVIedit:
7845 case AArch64ISD::MOVImsl:
7846 case AArch64ISD::MVNIshift:
7847 case AArch64ISD::MVNImsl:
Tim Northover3b0846e2014-05-24 12:50:23 +00007848 break;
7849 default:
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00007850 // FMOV could be supported, but isn't very useful, as it would only occur
7851 // if you passed a bitcast' floating point immediate to an eligible long
7852 // integer op (addl, smull, ...).
Tim Northover3b0846e2014-05-24 12:50:23 +00007853 return SDValue();
7854 }
7855
7856 MVT NarrowTy = N.getSimpleValueType();
7857 if (!NarrowTy.is64BitVector())
7858 return SDValue();
7859
7860 MVT ElementTy = NarrowTy.getVectorElementType();
7861 unsigned NumElems = NarrowTy.getVectorNumElements();
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00007862 MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
Tim Northover3b0846e2014-05-24 12:50:23 +00007863
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007864 SDLoc dl(N);
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00007865 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
7866 DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007867 DAG.getConstant(NumElems, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00007868}
7869
7870static bool isEssentiallyExtractSubvector(SDValue N) {
7871 if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
7872 return true;
7873
7874 return N.getOpcode() == ISD::BITCAST &&
7875 N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
7876}
7877
7878/// \brief Helper structure to keep track of ISD::SET_CC operands.
7879struct GenericSetCCInfo {
7880 const SDValue *Opnd0;
7881 const SDValue *Opnd1;
7882 ISD::CondCode CC;
7883};
7884
7885/// \brief Helper structure to keep track of a SET_CC lowered into AArch64 code.
7886struct AArch64SetCCInfo {
7887 const SDValue *Cmp;
7888 AArch64CC::CondCode CC;
7889};
7890
7891/// \brief Helper structure to keep track of SetCC information.
7892union SetCCInfo {
7893 GenericSetCCInfo Generic;
7894 AArch64SetCCInfo AArch64;
7895};
7896
7897/// \brief Helper structure to be able to read SetCC information. If set to
7898/// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
7899/// GenericSetCCInfo.
7900struct SetCCInfoAndKind {
7901 SetCCInfo Info;
7902 bool IsAArch64;
7903};
7904
7905/// \brief Check whether or not \p Op is a SET_CC operation, either a generic or
7906/// an
7907/// AArch64 lowered one.
7908/// \p SetCCInfo is filled accordingly.
7909/// \post SetCCInfo is meanginfull only when this function returns true.
7910/// \return True when Op is a kind of SET_CC operation.
7911static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
7912 // If this is a setcc, this is straight forward.
7913 if (Op.getOpcode() == ISD::SETCC) {
7914 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
7915 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
7916 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
7917 SetCCInfo.IsAArch64 = false;
7918 return true;
7919 }
7920 // Otherwise, check if this is a matching csel instruction.
7921 // In other words:
7922 // - csel 1, 0, cc
7923 // - csel 0, 1, !cc
7924 if (Op.getOpcode() != AArch64ISD::CSEL)
7925 return false;
7926 // Set the information about the operands.
7927 // TODO: we want the operands of the Cmp not the csel
7928 SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
7929 SetCCInfo.IsAArch64 = true;
7930 SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
7931 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
7932
7933 // Check that the operands matches the constraints:
7934 // (1) Both operands must be constants.
7935 // (2) One must be 1 and the other must be 0.
7936 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
7937 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
7938
7939 // Check (1).
7940 if (!TValue || !FValue)
7941 return false;
7942
7943 // Check (2).
7944 if (!TValue->isOne()) {
7945 // Update the comparison when we are interested in !cc.
7946 std::swap(TValue, FValue);
7947 SetCCInfo.Info.AArch64.CC =
7948 AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
7949 }
7950 return TValue->isOne() && FValue->isNullValue();
7951}
7952
7953// Returns true if Op is setcc or zext of setcc.
7954static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
7955 if (isSetCC(Op, Info))
7956 return true;
7957 return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
7958 isSetCC(Op->getOperand(0), Info));
7959}
7960
7961// The folding we want to perform is:
7962// (add x, [zext] (setcc cc ...) )
7963// -->
7964// (csel x, (add x, 1), !cc ...)
7965//
7966// The latter will get matched to a CSINC instruction.
7967static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
7968 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
7969 SDValue LHS = Op->getOperand(0);
7970 SDValue RHS = Op->getOperand(1);
7971 SetCCInfoAndKind InfoAndKind;
7972
7973 // If neither operand is a SET_CC, give up.
7974 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
7975 std::swap(LHS, RHS);
7976 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
7977 return SDValue();
7978 }
7979
7980 // FIXME: This could be generatized to work for FP comparisons.
7981 EVT CmpVT = InfoAndKind.IsAArch64
7982 ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
7983 : InfoAndKind.Info.Generic.Opnd0->getValueType();
7984 if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
7985 return SDValue();
7986
7987 SDValue CCVal;
7988 SDValue Cmp;
7989 SDLoc dl(Op);
7990 if (InfoAndKind.IsAArch64) {
7991 CCVal = DAG.getConstant(
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007992 AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
7993 MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00007994 Cmp = *InfoAndKind.Info.AArch64.Cmp;
7995 } else
7996 Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
7997 *InfoAndKind.Info.Generic.Opnd1,
7998 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
7999 CCVal, DAG, dl);
8000
8001 EVT VT = Op->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008002 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
Tim Northover3b0846e2014-05-24 12:50:23 +00008003 return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
8004}
8005
8006// The basic add/sub long vector instructions have variants with "2" on the end
8007// which act on the high-half of their inputs. They are normally matched by
8008// patterns like:
8009//
8010// (add (zeroext (extract_high LHS)),
8011// (zeroext (extract_high RHS)))
8012// -> uaddl2 vD, vN, vM
8013//
8014// However, if one of the extracts is something like a duplicate, this
8015// instruction can still be used profitably. This function puts the DAG into a
8016// more appropriate form for those patterns to trigger.
8017static SDValue performAddSubLongCombine(SDNode *N,
8018 TargetLowering::DAGCombinerInfo &DCI,
8019 SelectionDAG &DAG) {
8020 if (DCI.isBeforeLegalizeOps())
8021 return SDValue();
8022
8023 MVT VT = N->getSimpleValueType(0);
8024 if (!VT.is128BitVector()) {
8025 if (N->getOpcode() == ISD::ADD)
8026 return performSetccAddFolding(N, DAG);
8027 return SDValue();
8028 }
8029
8030 // Make sure both branches are extended in the same way.
8031 SDValue LHS = N->getOperand(0);
8032 SDValue RHS = N->getOperand(1);
8033 if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
8034 LHS.getOpcode() != ISD::SIGN_EXTEND) ||
8035 LHS.getOpcode() != RHS.getOpcode())
8036 return SDValue();
8037
8038 unsigned ExtType = LHS.getOpcode();
8039
8040 // It's not worth doing if at least one of the inputs isn't already an
8041 // extract, but we don't know which it'll be so we have to try both.
8042 if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
8043 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
8044 if (!RHS.getNode())
8045 return SDValue();
8046
8047 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
8048 } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
8049 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
8050 if (!LHS.getNode())
8051 return SDValue();
8052
8053 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
8054 }
8055
8056 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
8057}
8058
8059// Massage DAGs which we can use the high-half "long" operations on into
8060// something isel will recognize better. E.g.
8061//
8062// (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
8063// (aarch64_neon_umull (extract_high (v2i64 vec)))
8064// (extract_high (v2i64 (dup128 scalar)))))
8065//
8066static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
8067 TargetLowering::DAGCombinerInfo &DCI,
8068 SelectionDAG &DAG) {
8069 if (DCI.isBeforeLegalizeOps())
8070 return SDValue();
8071
8072 SDValue LHS = N->getOperand(1);
8073 SDValue RHS = N->getOperand(2);
8074 assert(LHS.getValueType().is64BitVector() &&
8075 RHS.getValueType().is64BitVector() &&
8076 "unexpected shape for long operation");
8077
8078 // Either node could be a DUP, but it's not worth doing both of them (you'd
8079 // just as well use the non-high version) so look for a corresponding extract
8080 // operation on the other "wing".
8081 if (isEssentiallyExtractSubvector(LHS)) {
8082 RHS = tryExtendDUPToExtractHigh(RHS, DAG);
8083 if (!RHS.getNode())
8084 return SDValue();
8085 } else if (isEssentiallyExtractSubvector(RHS)) {
8086 LHS = tryExtendDUPToExtractHigh(LHS, DAG);
8087 if (!LHS.getNode())
8088 return SDValue();
8089 }
8090
8091 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
8092 N->getOperand(0), LHS, RHS);
8093}
8094
8095static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
8096 MVT ElemTy = N->getSimpleValueType(0).getScalarType();
8097 unsigned ElemBits = ElemTy.getSizeInBits();
8098
8099 int64_t ShiftAmount;
8100 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
8101 APInt SplatValue, SplatUndef;
8102 unsigned SplatBitSize;
8103 bool HasAnyUndefs;
8104 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
8105 HasAnyUndefs, ElemBits) ||
8106 SplatBitSize != ElemBits)
8107 return SDValue();
8108
8109 ShiftAmount = SplatValue.getSExtValue();
8110 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
8111 ShiftAmount = CVN->getSExtValue();
8112 } else
8113 return SDValue();
8114
8115 unsigned Opcode;
8116 bool IsRightShift;
8117 switch (IID) {
8118 default:
8119 llvm_unreachable("Unknown shift intrinsic");
8120 case Intrinsic::aarch64_neon_sqshl:
8121 Opcode = AArch64ISD::SQSHL_I;
8122 IsRightShift = false;
8123 break;
8124 case Intrinsic::aarch64_neon_uqshl:
8125 Opcode = AArch64ISD::UQSHL_I;
8126 IsRightShift = false;
8127 break;
8128 case Intrinsic::aarch64_neon_srshl:
8129 Opcode = AArch64ISD::SRSHR_I;
8130 IsRightShift = true;
8131 break;
8132 case Intrinsic::aarch64_neon_urshl:
8133 Opcode = AArch64ISD::URSHR_I;
8134 IsRightShift = true;
8135 break;
8136 case Intrinsic::aarch64_neon_sqshlu:
8137 Opcode = AArch64ISD::SQSHLU_I;
8138 IsRightShift = false;
8139 break;
8140 }
8141
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008142 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
8143 SDLoc dl(N);
8144 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8145 DAG.getConstant(-ShiftAmount, dl, MVT::i32));
8146 } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
8147 SDLoc dl(N);
8148 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8149 DAG.getConstant(ShiftAmount, dl, MVT::i32));
8150 }
Tim Northover3b0846e2014-05-24 12:50:23 +00008151
8152 return SDValue();
8153}
8154
8155// The CRC32[BH] instructions ignore the high bits of their data operand. Since
8156// the intrinsics must be legal and take an i32, this means there's almost
8157// certainly going to be a zext in the DAG which we can eliminate.
8158static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
8159 SDValue AndN = N->getOperand(2);
8160 if (AndN.getOpcode() != ISD::AND)
8161 return SDValue();
8162
8163 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
8164 if (!CMask || CMask->getZExtValue() != Mask)
8165 return SDValue();
8166
8167 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
8168 N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
8169}
8170
Ahmed Bougachafab58922015-03-10 20:45:38 +00008171static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
8172 SelectionDAG &DAG) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008173 SDLoc dl(N);
8174 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
8175 DAG.getNode(Opc, dl,
Ahmed Bougachafab58922015-03-10 20:45:38 +00008176 N->getOperand(1).getSimpleValueType(),
8177 N->getOperand(1)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008178 DAG.getConstant(0, dl, MVT::i64));
Ahmed Bougachafab58922015-03-10 20:45:38 +00008179}
8180
Tim Northover3b0846e2014-05-24 12:50:23 +00008181static SDValue performIntrinsicCombine(SDNode *N,
8182 TargetLowering::DAGCombinerInfo &DCI,
8183 const AArch64Subtarget *Subtarget) {
8184 SelectionDAG &DAG = DCI.DAG;
8185 unsigned IID = getIntrinsicID(N);
8186 switch (IID) {
8187 default:
8188 break;
8189 case Intrinsic::aarch64_neon_vcvtfxs2fp:
8190 case Intrinsic::aarch64_neon_vcvtfxu2fp:
8191 return tryCombineFixedPointConvert(N, DCI, DAG);
8192 break;
Ahmed Bougachafab58922015-03-10 20:45:38 +00008193 case Intrinsic::aarch64_neon_saddv:
8194 return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
8195 case Intrinsic::aarch64_neon_uaddv:
8196 return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
8197 case Intrinsic::aarch64_neon_sminv:
8198 return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
8199 case Intrinsic::aarch64_neon_uminv:
8200 return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
8201 case Intrinsic::aarch64_neon_smaxv:
8202 return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
8203 case Intrinsic::aarch64_neon_umaxv:
8204 return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00008205 case Intrinsic::aarch64_neon_fmax:
8206 return DAG.getNode(AArch64ISD::FMAX, SDLoc(N), N->getValueType(0),
8207 N->getOperand(1), N->getOperand(2));
8208 case Intrinsic::aarch64_neon_fmin:
8209 return DAG.getNode(AArch64ISD::FMIN, SDLoc(N), N->getValueType(0),
8210 N->getOperand(1), N->getOperand(2));
8211 case Intrinsic::aarch64_neon_smull:
8212 case Intrinsic::aarch64_neon_umull:
8213 case Intrinsic::aarch64_neon_pmull:
8214 case Intrinsic::aarch64_neon_sqdmull:
8215 return tryCombineLongOpWithDup(IID, N, DCI, DAG);
8216 case Intrinsic::aarch64_neon_sqshl:
8217 case Intrinsic::aarch64_neon_uqshl:
8218 case Intrinsic::aarch64_neon_sqshlu:
8219 case Intrinsic::aarch64_neon_srshl:
8220 case Intrinsic::aarch64_neon_urshl:
8221 return tryCombineShiftImm(IID, N, DAG);
8222 case Intrinsic::aarch64_crc32b:
8223 case Intrinsic::aarch64_crc32cb:
8224 return tryCombineCRC32(0xff, N, DAG);
8225 case Intrinsic::aarch64_crc32h:
8226 case Intrinsic::aarch64_crc32ch:
8227 return tryCombineCRC32(0xffff, N, DAG);
8228 }
8229 return SDValue();
8230}
8231
8232static SDValue performExtendCombine(SDNode *N,
8233 TargetLowering::DAGCombinerInfo &DCI,
8234 SelectionDAG &DAG) {
8235 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
8236 // we can convert that DUP into another extract_high (of a bigger DUP), which
8237 // helps the backend to decide that an sabdl2 would be useful, saving a real
8238 // extract_high operation.
8239 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
8240 N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
8241 SDNode *ABDNode = N->getOperand(0).getNode();
8242 unsigned IID = getIntrinsicID(ABDNode);
8243 if (IID == Intrinsic::aarch64_neon_sabd ||
8244 IID == Intrinsic::aarch64_neon_uabd) {
8245 SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
8246 if (!NewABD.getNode())
8247 return SDValue();
8248
8249 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
8250 NewABD);
8251 }
8252 }
8253
8254 // This is effectively a custom type legalization for AArch64.
8255 //
8256 // Type legalization will split an extend of a small, legal, type to a larger
8257 // illegal type by first splitting the destination type, often creating
8258 // illegal source types, which then get legalized in isel-confusing ways,
8259 // leading to really terrible codegen. E.g.,
8260 // %result = v8i32 sext v8i8 %value
8261 // becomes
8262 // %losrc = extract_subreg %value, ...
8263 // %hisrc = extract_subreg %value, ...
8264 // %lo = v4i32 sext v4i8 %losrc
8265 // %hi = v4i32 sext v4i8 %hisrc
8266 // Things go rapidly downhill from there.
8267 //
8268 // For AArch64, the [sz]ext vector instructions can only go up one element
8269 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
8270 // take two instructions.
8271 //
8272 // This implies that the most efficient way to do the extend from v8i8
8273 // to two v4i32 values is to first extend the v8i8 to v8i16, then do
8274 // the normal splitting to happen for the v8i16->v8i32.
8275
8276 // This is pre-legalization to catch some cases where the default
8277 // type legalization will create ill-tempered code.
8278 if (!DCI.isBeforeLegalizeOps())
8279 return SDValue();
8280
8281 // We're only interested in cleaning things up for non-legal vector types
8282 // here. If both the source and destination are legal, things will just
8283 // work naturally without any fiddling.
8284 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8285 EVT ResVT = N->getValueType(0);
8286 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
8287 return SDValue();
8288 // If the vector type isn't a simple VT, it's beyond the scope of what
8289 // we're worried about here. Let legalization do its thing and hope for
8290 // the best.
Jim Grosbachec2b0d02014-08-28 22:08:28 +00008291 SDValue Src = N->getOperand(0);
8292 EVT SrcVT = Src->getValueType(0);
8293 if (!ResVT.isSimple() || !SrcVT.isSimple())
Tim Northover3b0846e2014-05-24 12:50:23 +00008294 return SDValue();
8295
Tim Northover3b0846e2014-05-24 12:50:23 +00008296 // If the source VT is a 64-bit vector, we can play games and get the
8297 // better results we want.
8298 if (SrcVT.getSizeInBits() != 64)
8299 return SDValue();
8300
8301 unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits();
8302 unsigned ElementCount = SrcVT.getVectorNumElements();
8303 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
8304 SDLoc DL(N);
8305 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
8306
8307 // Now split the rest of the operation into two halves, each with a 64
8308 // bit source.
8309 EVT LoVT, HiVT;
8310 SDValue Lo, Hi;
8311 unsigned NumElements = ResVT.getVectorNumElements();
8312 assert(!(NumElements & 1) && "Splitting vector, but not in half!");
8313 LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
8314 ResVT.getVectorElementType(), NumElements / 2);
8315
8316 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
8317 LoVT.getVectorNumElements());
8318 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008319 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008320 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008321 DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008322 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
8323 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
8324
8325 // Now combine the parts back together so we still have a single result
8326 // like the combiner expects.
8327 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
8328}
8329
8330/// Replace a splat of a scalar to a vector store by scalar stores of the scalar
8331/// value. The load store optimizer pass will merge them to store pair stores.
8332/// This has better performance than a splat of the scalar followed by a split
8333/// vector store. Even if the stores are not merged it is four stores vs a dup,
8334/// followed by an ext.b and two stores.
8335static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode *St) {
8336 SDValue StVal = St->getValue();
8337 EVT VT = StVal.getValueType();
8338
8339 // Don't replace floating point stores, they possibly won't be transformed to
8340 // stp because of the store pair suppress pass.
8341 if (VT.isFloatingPoint())
8342 return SDValue();
8343
8344 // Check for insert vector elements.
8345 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
8346 return SDValue();
8347
8348 // We can express a splat as store pair(s) for 2 or 4 elements.
8349 unsigned NumVecElts = VT.getVectorNumElements();
8350 if (NumVecElts != 4 && NumVecElts != 2)
8351 return SDValue();
8352 SDValue SplatVal = StVal.getOperand(1);
8353 unsigned RemainInsertElts = NumVecElts - 1;
8354
8355 // Check that this is a splat.
8356 while (--RemainInsertElts) {
8357 SDValue NextInsertElt = StVal.getOperand(0);
8358 if (NextInsertElt.getOpcode() != ISD::INSERT_VECTOR_ELT)
8359 return SDValue();
8360 if (NextInsertElt.getOperand(1) != SplatVal)
8361 return SDValue();
8362 StVal = NextInsertElt;
8363 }
8364 unsigned OrigAlignment = St->getAlignment();
8365 unsigned EltOffset = NumVecElts == 4 ? 4 : 8;
8366 unsigned Alignment = std::min(OrigAlignment, EltOffset);
8367
8368 // Create scalar stores. This is at least as good as the code sequence for a
8369 // split unaligned store wich is a dup.s, ext.b, and two stores.
8370 // Most of the time the three stores should be replaced by store pair
8371 // instructions (stp).
8372 SDLoc DL(St);
8373 SDValue BasePtr = St->getBasePtr();
8374 SDValue NewST1 =
8375 DAG.getStore(St->getChain(), DL, SplatVal, BasePtr, St->getPointerInfo(),
8376 St->isVolatile(), St->isNonTemporal(), St->getAlignment());
8377
8378 unsigned Offset = EltOffset;
8379 while (--NumVecElts) {
8380 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008381 DAG.getConstant(Offset, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008382 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
8383 St->getPointerInfo(), St->isVolatile(),
8384 St->isNonTemporal(), Alignment);
8385 Offset += EltOffset;
8386 }
8387 return NewST1;
8388}
8389
8390static SDValue performSTORECombine(SDNode *N,
8391 TargetLowering::DAGCombinerInfo &DCI,
8392 SelectionDAG &DAG,
8393 const AArch64Subtarget *Subtarget) {
8394 if (!DCI.isBeforeLegalize())
8395 return SDValue();
8396
8397 StoreSDNode *S = cast<StoreSDNode>(N);
8398 if (S->isVolatile())
8399 return SDValue();
8400
8401 // Cyclone has bad performance on unaligned 16B stores when crossing line and
Sanjay Patel08efcd92015-01-28 22:37:32 +00008402 // page boundaries. We want to split such stores.
Tim Northover3b0846e2014-05-24 12:50:23 +00008403 if (!Subtarget->isCyclone())
8404 return SDValue();
8405
8406 // Don't split at Oz.
8407 MachineFunction &MF = DAG.getMachineFunction();
Duncan P. N. Exon Smith003bb7d2015-02-14 02:09:06 +00008408 bool IsMinSize = MF.getFunction()->hasFnAttribute(Attribute::MinSize);
Tim Northover3b0846e2014-05-24 12:50:23 +00008409 if (IsMinSize)
8410 return SDValue();
8411
8412 SDValue StVal = S->getValue();
8413 EVT VT = StVal.getValueType();
8414
8415 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
8416 // those up regresses performance on micro-benchmarks and olden/bh.
8417 if (!VT.isVector() || VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
8418 return SDValue();
8419
8420 // Split unaligned 16B stores. They are terrible for performance.
8421 // Don't split stores with alignment of 1 or 2. Code that uses clang vector
8422 // extensions can use this to mark that it does not want splitting to happen
8423 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
8424 // eliminating alignment hazards is only 1 in 8 for alignment of 2.
8425 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
8426 S->getAlignment() <= 2)
8427 return SDValue();
8428
8429 // If we get a splat of a scalar convert this vector store to a store of
8430 // scalars. They will be merged into store pairs thereby removing two
8431 // instructions.
8432 SDValue ReplacedSplat = replaceSplatVectorStore(DAG, S);
8433 if (ReplacedSplat != SDValue())
8434 return ReplacedSplat;
8435
8436 SDLoc DL(S);
8437 unsigned NumElts = VT.getVectorNumElements() / 2;
8438 // Split VT into two.
8439 EVT HalfVT =
8440 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
8441 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008442 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008443 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008444 DAG.getConstant(NumElts, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008445 SDValue BasePtr = S->getBasePtr();
8446 SDValue NewST1 =
8447 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
8448 S->isVolatile(), S->isNonTemporal(), S->getAlignment());
8449 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008450 DAG.getConstant(8, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008451 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
8452 S->getPointerInfo(), S->isVolatile(), S->isNonTemporal(),
8453 S->getAlignment());
8454}
8455
8456/// Target-specific DAG combine function for post-increment LD1 (lane) and
8457/// post-increment LD1R.
8458static SDValue performPostLD1Combine(SDNode *N,
8459 TargetLowering::DAGCombinerInfo &DCI,
8460 bool IsLaneOp) {
8461 if (DCI.isBeforeLegalizeOps())
8462 return SDValue();
8463
8464 SelectionDAG &DAG = DCI.DAG;
8465 EVT VT = N->getValueType(0);
8466
8467 unsigned LoadIdx = IsLaneOp ? 1 : 0;
8468 SDNode *LD = N->getOperand(LoadIdx).getNode();
8469 // If it is not LOAD, can not do such combine.
8470 if (LD->getOpcode() != ISD::LOAD)
8471 return SDValue();
8472
8473 LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
8474 EVT MemVT = LoadSDN->getMemoryVT();
8475 // Check if memory operand is the same type as the vector element.
8476 if (MemVT != VT.getVectorElementType())
8477 return SDValue();
8478
8479 // Check if there are other uses. If so, do not combine as it will introduce
8480 // an extra load.
8481 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
8482 ++UI) {
8483 if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
8484 continue;
8485 if (*UI != N)
8486 return SDValue();
8487 }
8488
8489 SDValue Addr = LD->getOperand(1);
8490 SDValue Vector = N->getOperand(0);
8491 // Search for a use of the address operand that is an increment.
8492 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
8493 Addr.getNode()->use_end(); UI != UE; ++UI) {
8494 SDNode *User = *UI;
8495 if (User->getOpcode() != ISD::ADD
8496 || UI.getUse().getResNo() != Addr.getResNo())
8497 continue;
8498
8499 // Check that the add is independent of the load. Otherwise, folding it
8500 // would create a cycle.
8501 if (User->isPredecessorOf(LD) || LD->isPredecessorOf(User))
8502 continue;
8503 // Also check that add is not used in the vector operand. This would also
8504 // create a cycle.
8505 if (User->isPredecessorOf(Vector.getNode()))
8506 continue;
8507
8508 // If the increment is a constant, it must match the memory ref size.
8509 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8510 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8511 uint32_t IncVal = CInc->getZExtValue();
8512 unsigned NumBytes = VT.getScalarSizeInBits() / 8;
8513 if (IncVal != NumBytes)
8514 continue;
8515 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
8516 }
8517
Ahmed Bougacha2448ef52015-04-17 21:02:30 +00008518 // Finally, check that the vector doesn't depend on the load.
8519 // Again, this would create a cycle.
8520 // The load depending on the vector is fine, as that's the case for the
8521 // LD1*post we'll eventually generate anyway.
8522 if (LoadSDN->isPredecessorOf(Vector.getNode()))
8523 continue;
8524
Tim Northover3b0846e2014-05-24 12:50:23 +00008525 SmallVector<SDValue, 8> Ops;
8526 Ops.push_back(LD->getOperand(0)); // Chain
8527 if (IsLaneOp) {
8528 Ops.push_back(Vector); // The vector to be inserted
8529 Ops.push_back(N->getOperand(2)); // The lane to be inserted in the vector
8530 }
8531 Ops.push_back(Addr);
8532 Ops.push_back(Inc);
8533
8534 EVT Tys[3] = { VT, MVT::i64, MVT::Other };
Craig Toppere1d12942014-08-27 05:25:25 +00008535 SDVTList SDTys = DAG.getVTList(Tys);
Tim Northover3b0846e2014-05-24 12:50:23 +00008536 unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
8537 SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
8538 MemVT,
8539 LoadSDN->getMemOperand());
8540
8541 // Update the uses.
Ahmed Bougacha4c2b0782015-02-19 23:13:10 +00008542 SmallVector<SDValue, 2> NewResults;
Tim Northover3b0846e2014-05-24 12:50:23 +00008543 NewResults.push_back(SDValue(LD, 0)); // The result of load
8544 NewResults.push_back(SDValue(UpdN.getNode(), 2)); // Chain
8545 DCI.CombineTo(LD, NewResults);
8546 DCI.CombineTo(N, SDValue(UpdN.getNode(), 0)); // Dup/Inserted Result
8547 DCI.CombineTo(User, SDValue(UpdN.getNode(), 1)); // Write back register
8548
8549 break;
8550 }
8551 return SDValue();
8552}
8553
8554/// Target-specific DAG combine function for NEON load/store intrinsics
8555/// to merge base address updates.
8556static SDValue performNEONPostLDSTCombine(SDNode *N,
8557 TargetLowering::DAGCombinerInfo &DCI,
8558 SelectionDAG &DAG) {
8559 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
8560 return SDValue();
8561
8562 unsigned AddrOpIdx = N->getNumOperands() - 1;
8563 SDValue Addr = N->getOperand(AddrOpIdx);
8564
8565 // Search for a use of the address operand that is an increment.
8566 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
8567 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
8568 SDNode *User = *UI;
8569 if (User->getOpcode() != ISD::ADD ||
8570 UI.getUse().getResNo() != Addr.getResNo())
8571 continue;
8572
8573 // Check that the add is independent of the load/store. Otherwise, folding
8574 // it would create a cycle.
8575 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
8576 continue;
8577
8578 // Find the new opcode for the updating load/store.
8579 bool IsStore = false;
8580 bool IsLaneOp = false;
8581 bool IsDupOp = false;
8582 unsigned NewOpc = 0;
8583 unsigned NumVecs = 0;
8584 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
8585 switch (IntNo) {
8586 default: llvm_unreachable("unexpected intrinsic for Neon base update");
8587 case Intrinsic::aarch64_neon_ld2: NewOpc = AArch64ISD::LD2post;
8588 NumVecs = 2; break;
8589 case Intrinsic::aarch64_neon_ld3: NewOpc = AArch64ISD::LD3post;
8590 NumVecs = 3; break;
8591 case Intrinsic::aarch64_neon_ld4: NewOpc = AArch64ISD::LD4post;
8592 NumVecs = 4; break;
8593 case Intrinsic::aarch64_neon_st2: NewOpc = AArch64ISD::ST2post;
8594 NumVecs = 2; IsStore = true; break;
8595 case Intrinsic::aarch64_neon_st3: NewOpc = AArch64ISD::ST3post;
8596 NumVecs = 3; IsStore = true; break;
8597 case Intrinsic::aarch64_neon_st4: NewOpc = AArch64ISD::ST4post;
8598 NumVecs = 4; IsStore = true; break;
8599 case Intrinsic::aarch64_neon_ld1x2: NewOpc = AArch64ISD::LD1x2post;
8600 NumVecs = 2; break;
8601 case Intrinsic::aarch64_neon_ld1x3: NewOpc = AArch64ISD::LD1x3post;
8602 NumVecs = 3; break;
8603 case Intrinsic::aarch64_neon_ld1x4: NewOpc = AArch64ISD::LD1x4post;
8604 NumVecs = 4; break;
8605 case Intrinsic::aarch64_neon_st1x2: NewOpc = AArch64ISD::ST1x2post;
8606 NumVecs = 2; IsStore = true; break;
8607 case Intrinsic::aarch64_neon_st1x3: NewOpc = AArch64ISD::ST1x3post;
8608 NumVecs = 3; IsStore = true; break;
8609 case Intrinsic::aarch64_neon_st1x4: NewOpc = AArch64ISD::ST1x4post;
8610 NumVecs = 4; IsStore = true; break;
8611 case Intrinsic::aarch64_neon_ld2r: NewOpc = AArch64ISD::LD2DUPpost;
8612 NumVecs = 2; IsDupOp = true; break;
8613 case Intrinsic::aarch64_neon_ld3r: NewOpc = AArch64ISD::LD3DUPpost;
8614 NumVecs = 3; IsDupOp = true; break;
8615 case Intrinsic::aarch64_neon_ld4r: NewOpc = AArch64ISD::LD4DUPpost;
8616 NumVecs = 4; IsDupOp = true; break;
8617 case Intrinsic::aarch64_neon_ld2lane: NewOpc = AArch64ISD::LD2LANEpost;
8618 NumVecs = 2; IsLaneOp = true; break;
8619 case Intrinsic::aarch64_neon_ld3lane: NewOpc = AArch64ISD::LD3LANEpost;
8620 NumVecs = 3; IsLaneOp = true; break;
8621 case Intrinsic::aarch64_neon_ld4lane: NewOpc = AArch64ISD::LD4LANEpost;
8622 NumVecs = 4; IsLaneOp = true; break;
8623 case Intrinsic::aarch64_neon_st2lane: NewOpc = AArch64ISD::ST2LANEpost;
8624 NumVecs = 2; IsStore = true; IsLaneOp = true; break;
8625 case Intrinsic::aarch64_neon_st3lane: NewOpc = AArch64ISD::ST3LANEpost;
8626 NumVecs = 3; IsStore = true; IsLaneOp = true; break;
8627 case Intrinsic::aarch64_neon_st4lane: NewOpc = AArch64ISD::ST4LANEpost;
8628 NumVecs = 4; IsStore = true; IsLaneOp = true; break;
8629 }
8630
8631 EVT VecTy;
8632 if (IsStore)
8633 VecTy = N->getOperand(2).getValueType();
8634 else
8635 VecTy = N->getValueType(0);
8636
8637 // If the increment is a constant, it must match the memory ref size.
8638 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8639 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8640 uint32_t IncVal = CInc->getZExtValue();
8641 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
8642 if (IsLaneOp || IsDupOp)
8643 NumBytes /= VecTy.getVectorNumElements();
8644 if (IncVal != NumBytes)
8645 continue;
8646 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
8647 }
8648 SmallVector<SDValue, 8> Ops;
8649 Ops.push_back(N->getOperand(0)); // Incoming chain
8650 // Load lane and store have vector list as input.
8651 if (IsLaneOp || IsStore)
8652 for (unsigned i = 2; i < AddrOpIdx; ++i)
8653 Ops.push_back(N->getOperand(i));
8654 Ops.push_back(Addr); // Base register
8655 Ops.push_back(Inc);
8656
8657 // Return Types.
8658 EVT Tys[6];
8659 unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
8660 unsigned n;
8661 for (n = 0; n < NumResultVecs; ++n)
8662 Tys[n] = VecTy;
8663 Tys[n++] = MVT::i64; // Type of write back register
8664 Tys[n] = MVT::Other; // Type of the chain
Craig Toppere1d12942014-08-27 05:25:25 +00008665 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
Tim Northover3b0846e2014-05-24 12:50:23 +00008666
8667 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
8668 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
8669 MemInt->getMemoryVT(),
8670 MemInt->getMemOperand());
8671
8672 // Update the uses.
8673 std::vector<SDValue> NewResults;
8674 for (unsigned i = 0; i < NumResultVecs; ++i) {
8675 NewResults.push_back(SDValue(UpdN.getNode(), i));
8676 }
8677 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
8678 DCI.CombineTo(N, NewResults);
8679 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
8680
8681 break;
8682 }
8683 return SDValue();
8684}
8685
Louis Gerbarg03c627e2014-08-29 21:00:22 +00008686// Checks to see if the value is the prescribed width and returns information
8687// about its extension mode.
8688static
8689bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
8690 ExtType = ISD::NON_EXTLOAD;
8691 switch(V.getNode()->getOpcode()) {
8692 default:
8693 return false;
8694 case ISD::LOAD: {
8695 LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
8696 if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
8697 || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
8698 ExtType = LoadNode->getExtensionType();
8699 return true;
8700 }
8701 return false;
8702 }
8703 case ISD::AssertSext: {
8704 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
8705 if ((TypeNode->getVT() == MVT::i8 && width == 8)
8706 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
8707 ExtType = ISD::SEXTLOAD;
8708 return true;
8709 }
8710 return false;
8711 }
8712 case ISD::AssertZext: {
8713 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
8714 if ((TypeNode->getVT() == MVT::i8 && width == 8)
8715 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
8716 ExtType = ISD::ZEXTLOAD;
8717 return true;
8718 }
8719 return false;
8720 }
8721 case ISD::Constant:
8722 case ISD::TargetConstant: {
Reid Kleckner39ad7c92014-08-29 22:14:26 +00008723 if (std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
Aaron Ballman8ca53882014-09-02 12:19:02 +00008724 1LL << (width - 1))
Louis Gerbarg03c627e2014-08-29 21:00:22 +00008725 return true;
8726 return false;
8727 }
8728 }
8729
8730 return true;
8731}
8732
8733// This function does a whole lot of voodoo to determine if the tests are
8734// equivalent without and with a mask. Essentially what happens is that given a
8735// DAG resembling:
8736//
8737// +-------------+ +-------------+ +-------------+ +-------------+
8738// | Input | | AddConstant | | CompConstant| | CC |
8739// +-------------+ +-------------+ +-------------+ +-------------+
8740// | | | |
8741// V V | +----------+
8742// +-------------+ +----+ | |
8743// | ADD | |0xff| | |
8744// +-------------+ +----+ | |
8745// | | | |
8746// V V | |
8747// +-------------+ | |
8748// | AND | | |
8749// +-------------+ | |
8750// | | |
8751// +-----+ | |
8752// | | |
8753// V V V
8754// +-------------+
8755// | CMP |
8756// +-------------+
8757//
8758// The AND node may be safely removed for some combinations of inputs. In
8759// particular we need to take into account the extension type of the Input,
8760// the exact values of AddConstant, CompConstant, and CC, along with the nominal
8761// width of the input (this can work for any width inputs, the above graph is
8762// specific to 8 bits.
8763//
8764// The specific equations were worked out by generating output tables for each
8765// AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
8766// problem was simplified by working with 4 bit inputs, which means we only
8767// needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
8768// extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
8769// patterns present in both extensions (0,7). For every distinct set of
8770// AddConstant and CompConstants bit patterns we can consider the masked and
8771// unmasked versions to be equivalent if the result of this function is true for
8772// all 16 distinct bit patterns of for the current extension type of Input (w0).
8773//
8774// sub w8, w0, w1
8775// and w10, w8, #0x0f
8776// cmp w8, w2
8777// cset w9, AArch64CC
8778// cmp w10, w2
8779// cset w11, AArch64CC
8780// cmp w9, w11
8781// cset w0, eq
8782// ret
8783//
8784// Since the above function shows when the outputs are equivalent it defines
8785// when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
8786// would be expensive to run during compiles. The equations below were written
8787// in a test harness that confirmed they gave equivalent outputs to the above
8788// for all inputs function, so they can be used determine if the removal is
8789// legal instead.
8790//
8791// isEquivalentMaskless() is the code for testing if the AND can be removed
8792// factored out of the DAG recognition as the DAG can take several forms.
8793
8794static
8795bool isEquivalentMaskless(unsigned CC, unsigned width,
8796 ISD::LoadExtType ExtType, signed AddConstant,
8797 signed CompConstant) {
8798 // By being careful about our equations and only writing the in term
8799 // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
8800 // make them generally applicable to all bit widths.
8801 signed MaxUInt = (1 << width);
8802
8803 // For the purposes of these comparisons sign extending the type is
8804 // equivalent to zero extending the add and displacing it by half the integer
8805 // width. Provided we are careful and make sure our equations are valid over
8806 // the whole range we can just adjust the input and avoid writing equations
8807 // for sign extended inputs.
8808 if (ExtType == ISD::SEXTLOAD)
8809 AddConstant -= (1 << (width-1));
8810
8811 switch(CC) {
8812 case AArch64CC::LE:
8813 case AArch64CC::GT: {
8814 if ((AddConstant == 0) ||
8815 (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
8816 (AddConstant >= 0 && CompConstant < 0) ||
8817 (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
8818 return true;
8819 } break;
8820 case AArch64CC::LT:
8821 case AArch64CC::GE: {
8822 if ((AddConstant == 0) ||
8823 (AddConstant >= 0 && CompConstant <= 0) ||
8824 (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
8825 return true;
8826 } break;
8827 case AArch64CC::HI:
8828 case AArch64CC::LS: {
8829 if ((AddConstant >= 0 && CompConstant < 0) ||
8830 (AddConstant <= 0 && CompConstant >= -1 &&
8831 CompConstant < AddConstant + MaxUInt))
8832 return true;
8833 } break;
8834 case AArch64CC::PL:
8835 case AArch64CC::MI: {
8836 if ((AddConstant == 0) ||
8837 (AddConstant > 0 && CompConstant <= 0) ||
8838 (AddConstant < 0 && CompConstant <= AddConstant))
8839 return true;
8840 } break;
8841 case AArch64CC::LO:
8842 case AArch64CC::HS: {
8843 if ((AddConstant >= 0 && CompConstant <= 0) ||
8844 (AddConstant <= 0 && CompConstant >= 0 &&
8845 CompConstant <= AddConstant + MaxUInt))
8846 return true;
8847 } break;
8848 case AArch64CC::EQ:
8849 case AArch64CC::NE: {
8850 if ((AddConstant > 0 && CompConstant < 0) ||
8851 (AddConstant < 0 && CompConstant >= 0 &&
8852 CompConstant < AddConstant + MaxUInt) ||
8853 (AddConstant >= 0 && CompConstant >= 0 &&
8854 CompConstant >= AddConstant) ||
8855 (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
8856
8857 return true;
8858 } break;
8859 case AArch64CC::VS:
8860 case AArch64CC::VC:
8861 case AArch64CC::AL:
8862 case AArch64CC::NV:
8863 return true;
8864 case AArch64CC::Invalid:
8865 break;
8866 }
8867
8868 return false;
8869}
8870
8871static
8872SDValue performCONDCombine(SDNode *N,
8873 TargetLowering::DAGCombinerInfo &DCI,
8874 SelectionDAG &DAG, unsigned CCIndex,
8875 unsigned CmpIndex) {
8876 unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
8877 SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
8878 unsigned CondOpcode = SubsNode->getOpcode();
8879
8880 if (CondOpcode != AArch64ISD::SUBS)
8881 return SDValue();
8882
8883 // There is a SUBS feeding this condition. Is it fed by a mask we can
8884 // use?
8885
8886 SDNode *AndNode = SubsNode->getOperand(0).getNode();
8887 unsigned MaskBits = 0;
8888
8889 if (AndNode->getOpcode() != ISD::AND)
8890 return SDValue();
8891
8892 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
8893 uint32_t CNV = CN->getZExtValue();
8894 if (CNV == 255)
8895 MaskBits = 8;
8896 else if (CNV == 65535)
8897 MaskBits = 16;
8898 }
8899
8900 if (!MaskBits)
8901 return SDValue();
8902
8903 SDValue AddValue = AndNode->getOperand(0);
8904
8905 if (AddValue.getOpcode() != ISD::ADD)
8906 return SDValue();
8907
8908 // The basic dag structure is correct, grab the inputs and validate them.
8909
8910 SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
8911 SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
8912 SDValue SubsInputValue = SubsNode->getOperand(1);
8913
8914 // The mask is present and the provenance of all the values is a smaller type,
8915 // lets see if the mask is superfluous.
8916
8917 if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
8918 !isa<ConstantSDNode>(SubsInputValue.getNode()))
8919 return SDValue();
8920
8921 ISD::LoadExtType ExtType;
8922
8923 if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
8924 !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
8925 !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
8926 return SDValue();
8927
8928 if(!isEquivalentMaskless(CC, MaskBits, ExtType,
8929 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
8930 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
8931 return SDValue();
8932
8933 // The AND is not necessary, remove it.
8934
8935 SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
8936 SubsNode->getValueType(1));
8937 SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
8938
8939 SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
8940 DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
8941
8942 return SDValue(N, 0);
8943}
8944
Tim Northover3b0846e2014-05-24 12:50:23 +00008945// Optimize compare with zero and branch.
8946static SDValue performBRCONDCombine(SDNode *N,
8947 TargetLowering::DAGCombinerInfo &DCI,
8948 SelectionDAG &DAG) {
Louis Gerbarg03c627e2014-08-29 21:00:22 +00008949 SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3);
8950 if (NV.getNode())
8951 N = NV.getNode();
Tim Northover3b0846e2014-05-24 12:50:23 +00008952 SDValue Chain = N->getOperand(0);
8953 SDValue Dest = N->getOperand(1);
8954 SDValue CCVal = N->getOperand(2);
8955 SDValue Cmp = N->getOperand(3);
8956
8957 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
8958 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
8959 if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
8960 return SDValue();
8961
8962 unsigned CmpOpc = Cmp.getOpcode();
8963 if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
8964 return SDValue();
8965
8966 // Only attempt folding if there is only one use of the flag and no use of the
8967 // value.
8968 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
8969 return SDValue();
8970
8971 SDValue LHS = Cmp.getOperand(0);
8972 SDValue RHS = Cmp.getOperand(1);
8973
8974 assert(LHS.getValueType() == RHS.getValueType() &&
8975 "Expected the value type to be the same for both operands!");
8976 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
8977 return SDValue();
8978
8979 if (isa<ConstantSDNode>(LHS) && cast<ConstantSDNode>(LHS)->isNullValue())
8980 std::swap(LHS, RHS);
8981
8982 if (!isa<ConstantSDNode>(RHS) || !cast<ConstantSDNode>(RHS)->isNullValue())
8983 return SDValue();
8984
8985 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
8986 LHS.getOpcode() == ISD::SRL)
8987 return SDValue();
8988
8989 // Fold the compare into the branch instruction.
8990 SDValue BR;
8991 if (CC == AArch64CC::EQ)
8992 BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
8993 else
8994 BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
8995
8996 // Do not add new nodes to DAG combiner worklist.
8997 DCI.CombineTo(N, BR, false);
8998
8999 return SDValue();
9000}
9001
9002// vselect (v1i1 setcc) ->
9003// vselect (v1iXX setcc) (XX is the size of the compared operand type)
9004// FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
9005// condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
9006// such VSELECT.
9007static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
9008 SDValue N0 = N->getOperand(0);
9009 EVT CCVT = N0.getValueType();
9010
9011 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
9012 CCVT.getVectorElementType() != MVT::i1)
9013 return SDValue();
9014
9015 EVT ResVT = N->getValueType(0);
9016 EVT CmpVT = N0.getOperand(0).getValueType();
9017 // Only combine when the result type is of the same size as the compared
9018 // operands.
9019 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
9020 return SDValue();
9021
9022 SDValue IfTrue = N->getOperand(1);
9023 SDValue IfFalse = N->getOperand(2);
9024 SDValue SetCC =
9025 DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
9026 N0.getOperand(0), N0.getOperand(1),
9027 cast<CondCodeSDNode>(N0.getOperand(2))->get());
9028 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
9029 IfTrue, IfFalse);
9030}
9031
9032/// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
9033/// the compare-mask instructions rather than going via NZCV, even if LHS and
9034/// RHS are really scalar. This replaces any scalar setcc in the above pattern
9035/// with a vector one followed by a DUP shuffle on the result.
Ahmed Bougachac004c602015-04-27 21:43:12 +00009036static SDValue performSelectCombine(SDNode *N,
9037 TargetLowering::DAGCombinerInfo &DCI) {
9038 SelectionDAG &DAG = DCI.DAG;
Tim Northover3b0846e2014-05-24 12:50:23 +00009039 SDValue N0 = N->getOperand(0);
9040 EVT ResVT = N->getValueType(0);
Tim Northover3c0915e2014-08-29 15:34:58 +00009041
Ahmed Bougachac004c602015-04-27 21:43:12 +00009042 if (N0.getOpcode() != ISD::SETCC)
Tim Northover3c0915e2014-08-29 15:34:58 +00009043 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00009044
Ahmed Bougachac004c602015-04-27 21:43:12 +00009045 // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
9046 // scalar SetCCResultType. We also don't expect vectors, because we assume
9047 // that selects fed by vector SETCCs are canonicalized to VSELECT.
9048 assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
9049 "Scalar-SETCC feeding SELECT has unexpected result type!");
9050
Tim Northoverc1c05ae2014-08-29 13:05:18 +00009051 // If NumMaskElts == 0, the comparison is larger than select result. The
9052 // largest real NEON comparison is 64-bits per lane, which means the result is
9053 // at most 32-bits and an illegal vector. Just bail out for now.
Tim Northover3c0915e2014-08-29 15:34:58 +00009054 EVT SrcVT = N0.getOperand(0).getValueType();
Ahmed Bougachad0ce0582014-12-01 20:59:00 +00009055
9056 // Don't try to do this optimization when the setcc itself has i1 operands.
9057 // There are no legal vectors of i1, so this would be pointless.
9058 if (SrcVT == MVT::i1)
9059 return SDValue();
9060
Tim Northover3c0915e2014-08-29 15:34:58 +00009061 int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
Tim Northoverc1c05ae2014-08-29 13:05:18 +00009062 if (!ResVT.isVector() || NumMaskElts == 0)
Tim Northover3b0846e2014-05-24 12:50:23 +00009063 return SDValue();
9064
Tim Northoverc1c05ae2014-08-29 13:05:18 +00009065 SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
Tim Northover3b0846e2014-05-24 12:50:23 +00009066 EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
9067
Ahmed Bougacha89bba612015-04-27 21:01:20 +00009068 // Also bail out if the vector CCVT isn't the same size as ResVT.
9069 // This can happen if the SETCC operand size doesn't divide the ResVT size
9070 // (e.g., f64 vs v3f32).
9071 if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
9072 return SDValue();
9073
Ahmed Bougachac004c602015-04-27 21:43:12 +00009074 // Make sure we didn't create illegal types, if we're not supposed to.
9075 assert(DCI.isBeforeLegalize() ||
9076 DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
9077
Tim Northover3b0846e2014-05-24 12:50:23 +00009078 // First perform a vector comparison, where lane 0 is the one we're interested
9079 // in.
Tim Northoverc1c05ae2014-08-29 13:05:18 +00009080 SDLoc DL(N0);
Tim Northover3b0846e2014-05-24 12:50:23 +00009081 SDValue LHS =
9082 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
9083 SDValue RHS =
9084 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
9085 SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
9086
9087 // Now duplicate the comparison mask we want across all other lanes.
9088 SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
9089 SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask.data());
Tim Northoverc1c05ae2014-08-29 13:05:18 +00009090 Mask = DAG.getNode(ISD::BITCAST, DL,
9091 ResVT.changeVectorElementTypeToInteger(), Mask);
Tim Northover3b0846e2014-05-24 12:50:23 +00009092
9093 return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
9094}
9095
Artyom Skrobova70dfe12015-05-14 12:59:46 +00009096/// performSelectCCCombine - Target-specific DAG combining for ISD::SELECT_CC
9097/// to match FMIN/FMAX patterns.
9098static SDValue performSelectCCCombine(SDNode *N, SelectionDAG &DAG) {
9099 // Try to use FMIN/FMAX instructions for FP selects like "x < y ? x : y".
9100 // Unless the NoNaNsFPMath option is set, be careful about NaNs:
9101 // vmax/vmin return NaN if either operand is a NaN;
9102 // only do the transformation when it matches that behavior.
9103
9104 SDValue CondLHS = N->getOperand(0);
9105 SDValue CondRHS = N->getOperand(1);
9106 SDValue LHS = N->getOperand(2);
9107 SDValue RHS = N->getOperand(3);
9108 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
9109
9110 unsigned Opcode;
9111 bool IsReversed;
9112 if (selectCCOpsAreFMaxCompatible(CondLHS, LHS) &&
9113 selectCCOpsAreFMaxCompatible(CondRHS, RHS)) {
9114 IsReversed = false; // x CC y ? x : y
9115 } else if (selectCCOpsAreFMaxCompatible(CondRHS, LHS) &&
9116 selectCCOpsAreFMaxCompatible(CondLHS, RHS)) {
9117 IsReversed = true ; // x CC y ? y : x
9118 } else {
9119 return SDValue();
9120 }
9121
9122 bool IsUnordered = false, IsOrEqual;
9123 switch (CC) {
9124 default:
9125 return SDValue();
9126 case ISD::SETULT:
9127 case ISD::SETULE:
9128 IsUnordered = true;
9129 case ISD::SETOLT:
9130 case ISD::SETOLE:
9131 case ISD::SETLT:
9132 case ISD::SETLE:
9133 IsOrEqual = (CC == ISD::SETLE || CC == ISD::SETOLE || CC == ISD::SETULE);
9134 Opcode = IsReversed ? AArch64ISD::FMAX : AArch64ISD::FMIN;
9135 break;
9136
9137 case ISD::SETUGT:
9138 case ISD::SETUGE:
9139 IsUnordered = true;
9140 case ISD::SETOGT:
9141 case ISD::SETOGE:
9142 case ISD::SETGT:
9143 case ISD::SETGE:
9144 IsOrEqual = (CC == ISD::SETGE || CC == ISD::SETOGE || CC == ISD::SETUGE);
9145 Opcode = IsReversed ? AArch64ISD::FMIN : AArch64ISD::FMAX;
9146 break;
9147 }
9148
9149 // If LHS is NaN, an ordered comparison will be false and the result will be
9150 // the RHS, but FMIN(NaN, RHS) = FMAX(NaN, RHS) = NaN. Avoid this by checking
9151 // that LHS != NaN. Likewise, for unordered comparisons, check for RHS != NaN.
9152 if (!DAG.isKnownNeverNaN(IsUnordered ? RHS : LHS))
9153 return SDValue();
9154
9155 // For xxx-or-equal comparisons, "+0 <= -0" and "-0 >= +0" will both be true,
9156 // but FMIN will return -0, and FMAX will return +0. So FMIN/FMAX can only be
9157 // used for unsafe math or if one of the operands is known to be nonzero.
9158 if (IsOrEqual && !DAG.getTarget().Options.UnsafeFPMath &&
9159 !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
9160 return SDValue();
9161
9162 return DAG.getNode(Opcode, SDLoc(N), N->getValueType(0), LHS, RHS);
9163}
9164
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009165/// Get rid of unnecessary NVCASTs (that don't change the type).
9166static SDValue performNVCASTCombine(SDNode *N) {
9167 if (N->getValueType(0) == N->getOperand(0).getValueType())
9168 return N->getOperand(0);
9169
9170 return SDValue();
9171}
9172
Tim Northover3b0846e2014-05-24 12:50:23 +00009173SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
9174 DAGCombinerInfo &DCI) const {
9175 SelectionDAG &DAG = DCI.DAG;
9176 switch (N->getOpcode()) {
9177 default:
9178 break;
9179 case ISD::ADD:
9180 case ISD::SUB:
9181 return performAddSubLongCombine(N, DCI, DAG);
9182 case ISD::XOR:
9183 return performXorCombine(N, DAG, DCI, Subtarget);
9184 case ISD::MUL:
9185 return performMulCombine(N, DAG, DCI, Subtarget);
9186 case ISD::SINT_TO_FP:
9187 case ISD::UINT_TO_FP:
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00009188 return performIntToFpCombine(N, DAG, Subtarget);
Tim Northover3b0846e2014-05-24 12:50:23 +00009189 case ISD::OR:
9190 return performORCombine(N, DCI, Subtarget);
9191 case ISD::INTRINSIC_WO_CHAIN:
9192 return performIntrinsicCombine(N, DCI, Subtarget);
9193 case ISD::ANY_EXTEND:
9194 case ISD::ZERO_EXTEND:
9195 case ISD::SIGN_EXTEND:
9196 return performExtendCombine(N, DCI, DAG);
9197 case ISD::BITCAST:
9198 return performBitcastCombine(N, DCI, DAG);
9199 case ISD::CONCAT_VECTORS:
9200 return performConcatVectorsCombine(N, DCI, DAG);
9201 case ISD::SELECT:
Ahmed Bougachac004c602015-04-27 21:43:12 +00009202 return performSelectCombine(N, DCI);
Tim Northover3b0846e2014-05-24 12:50:23 +00009203 case ISD::VSELECT:
9204 return performVSelectCombine(N, DCI.DAG);
Artyom Skrobova70dfe12015-05-14 12:59:46 +00009205 case ISD::SELECT_CC:
9206 return performSelectCCCombine(N, DCI.DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00009207 case ISD::STORE:
9208 return performSTORECombine(N, DCI, DAG, Subtarget);
9209 case AArch64ISD::BRCOND:
9210 return performBRCONDCombine(N, DCI, DAG);
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009211 case AArch64ISD::CSEL:
9212 return performCONDCombine(N, DCI, DAG, 2, 3);
Tim Northover3b0846e2014-05-24 12:50:23 +00009213 case AArch64ISD::DUP:
9214 return performPostLD1Combine(N, DCI, false);
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009215 case AArch64ISD::NVCAST:
9216 return performNVCASTCombine(N);
Tim Northover3b0846e2014-05-24 12:50:23 +00009217 case ISD::INSERT_VECTOR_ELT:
9218 return performPostLD1Combine(N, DCI, true);
9219 case ISD::INTRINSIC_VOID:
9220 case ISD::INTRINSIC_W_CHAIN:
9221 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9222 case Intrinsic::aarch64_neon_ld2:
9223 case Intrinsic::aarch64_neon_ld3:
9224 case Intrinsic::aarch64_neon_ld4:
9225 case Intrinsic::aarch64_neon_ld1x2:
9226 case Intrinsic::aarch64_neon_ld1x3:
9227 case Intrinsic::aarch64_neon_ld1x4:
9228 case Intrinsic::aarch64_neon_ld2lane:
9229 case Intrinsic::aarch64_neon_ld3lane:
9230 case Intrinsic::aarch64_neon_ld4lane:
9231 case Intrinsic::aarch64_neon_ld2r:
9232 case Intrinsic::aarch64_neon_ld3r:
9233 case Intrinsic::aarch64_neon_ld4r:
9234 case Intrinsic::aarch64_neon_st2:
9235 case Intrinsic::aarch64_neon_st3:
9236 case Intrinsic::aarch64_neon_st4:
9237 case Intrinsic::aarch64_neon_st1x2:
9238 case Intrinsic::aarch64_neon_st1x3:
9239 case Intrinsic::aarch64_neon_st1x4:
9240 case Intrinsic::aarch64_neon_st2lane:
9241 case Intrinsic::aarch64_neon_st3lane:
9242 case Intrinsic::aarch64_neon_st4lane:
9243 return performNEONPostLDSTCombine(N, DCI, DAG);
9244 default:
9245 break;
9246 }
9247 }
9248 return SDValue();
9249}
9250
9251// Check if the return value is used as only a return value, as otherwise
9252// we can't perform a tail-call. In particular, we need to check for
9253// target ISD nodes that are returns and any other "odd" constructs
9254// that the generic analysis code won't necessarily catch.
9255bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
9256 SDValue &Chain) const {
9257 if (N->getNumValues() != 1)
9258 return false;
9259 if (!N->hasNUsesOfValue(1, 0))
9260 return false;
9261
9262 SDValue TCChain = Chain;
9263 SDNode *Copy = *N->use_begin();
9264 if (Copy->getOpcode() == ISD::CopyToReg) {
9265 // If the copy has a glue operand, we conservatively assume it isn't safe to
9266 // perform a tail call.
9267 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
9268 MVT::Glue)
9269 return false;
9270 TCChain = Copy->getOperand(0);
9271 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
9272 return false;
9273
9274 bool HasRet = false;
9275 for (SDNode *Node : Copy->uses()) {
9276 if (Node->getOpcode() != AArch64ISD::RET_FLAG)
9277 return false;
9278 HasRet = true;
9279 }
9280
9281 if (!HasRet)
9282 return false;
9283
9284 Chain = TCChain;
9285 return true;
9286}
9287
9288// Return whether the an instruction can potentially be optimized to a tail
9289// call. This will cause the optimizers to attempt to move, or duplicate,
9290// return instructions to help enable tail call optimizations for this
9291// instruction.
9292bool AArch64TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
9293 if (!CI->isTailCall())
9294 return false;
9295
9296 return true;
9297}
9298
9299bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
9300 SDValue &Offset,
9301 ISD::MemIndexedMode &AM,
9302 bool &IsInc,
9303 SelectionDAG &DAG) const {
9304 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
9305 return false;
9306
9307 Base = Op->getOperand(0);
9308 // All of the indexed addressing mode instructions take a signed
9309 // 9 bit immediate offset.
9310 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
9311 int64_t RHSC = (int64_t)RHS->getZExtValue();
9312 if (RHSC >= 256 || RHSC <= -256)
9313 return false;
9314 IsInc = (Op->getOpcode() == ISD::ADD);
9315 Offset = Op->getOperand(1);
9316 return true;
9317 }
9318 return false;
9319}
9320
9321bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
9322 SDValue &Offset,
9323 ISD::MemIndexedMode &AM,
9324 SelectionDAG &DAG) const {
9325 EVT VT;
9326 SDValue Ptr;
9327 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9328 VT = LD->getMemoryVT();
9329 Ptr = LD->getBasePtr();
9330 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9331 VT = ST->getMemoryVT();
9332 Ptr = ST->getBasePtr();
9333 } else
9334 return false;
9335
9336 bool IsInc;
9337 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
9338 return false;
9339 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
9340 return true;
9341}
9342
9343bool AArch64TargetLowering::getPostIndexedAddressParts(
9344 SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
9345 ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
9346 EVT VT;
9347 SDValue Ptr;
9348 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9349 VT = LD->getMemoryVT();
9350 Ptr = LD->getBasePtr();
9351 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9352 VT = ST->getMemoryVT();
9353 Ptr = ST->getBasePtr();
9354 } else
9355 return false;
9356
9357 bool IsInc;
9358 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
9359 return false;
9360 // Post-indexing updates the base, so it's not a valid transform
9361 // if that's not the same as the load's pointer.
9362 if (Ptr != Base)
9363 return false;
9364 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
9365 return true;
9366}
9367
Tim Northoverf8bfe212014-07-18 13:07:05 +00009368static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
9369 SelectionDAG &DAG) {
Tim Northoverf8bfe212014-07-18 13:07:05 +00009370 SDLoc DL(N);
9371 SDValue Op = N->getOperand(0);
Ahmed Bougacha87946322014-12-01 20:52:32 +00009372
9373 if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
9374 return;
9375
Tim Northoverf8bfe212014-07-18 13:07:05 +00009376 Op = SDValue(
9377 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
9378 DAG.getUNDEF(MVT::i32), Op,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009379 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
Tim Northoverf8bfe212014-07-18 13:07:05 +00009380 0);
9381 Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
9382 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
9383}
9384
Tim Northover3b0846e2014-05-24 12:50:23 +00009385void AArch64TargetLowering::ReplaceNodeResults(
9386 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
9387 switch (N->getOpcode()) {
9388 default:
9389 llvm_unreachable("Don't know how to custom expand this");
Tim Northoverf8bfe212014-07-18 13:07:05 +00009390 case ISD::BITCAST:
9391 ReplaceBITCASTResults(N, Results, DAG);
9392 return;
Tim Northover3b0846e2014-05-24 12:50:23 +00009393 case ISD::FP_TO_UINT:
9394 case ISD::FP_TO_SINT:
9395 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
9396 // Let normal code take care of it by not adding anything to Results.
9397 return;
9398 }
9399}
9400
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +00009401bool AArch64TargetLowering::useLoadStackGuardNode() const {
9402 return true;
9403}
9404
Hao Liu44e5d7a2014-11-21 06:39:58 +00009405bool AArch64TargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
9406 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
9407 // reciprocal if there are three or more FDIVs.
9408 return NumUsers > 2;
9409}
9410
Chandler Carruth9d010ff2014-07-03 00:23:43 +00009411TargetLoweringBase::LegalizeTypeAction
9412AArch64TargetLowering::getPreferredVectorAction(EVT VT) const {
9413 MVT SVT = VT.getSimpleVT();
9414 // During type legalization, we prefer to widen v1i8, v1i16, v1i32 to v8i8,
9415 // v4i16, v2i32 instead of to promote.
9416 if (SVT == MVT::v1i8 || SVT == MVT::v1i16 || SVT == MVT::v1i32
9417 || SVT == MVT::v1f32)
9418 return TypeWidenVector;
9419
9420 return TargetLoweringBase::getPreferredVectorAction(VT);
9421}
9422
Robin Morisseted3d48f2014-09-03 21:29:59 +00009423// Loads and stores less than 128-bits are already atomic; ones above that
9424// are doomed anyway, so defer to the default libcall and blame the OS when
9425// things go wrong.
9426bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
9427 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
9428 return Size == 128;
9429}
9430
9431// Loads and stores less than 128-bits are already atomic; ones above that
9432// are doomed anyway, so defer to the default libcall and blame the OS when
9433// things go wrong.
9434bool AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
9435 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
9436 return Size == 128;
9437}
9438
9439// For the real atomic operations, we have ldxr/stxr up to 128 bits,
JF Bastienf14889e2015-03-04 15:47:57 +00009440TargetLoweringBase::AtomicRMWExpansionKind
9441AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
Robin Morisseted3d48f2014-09-03 21:29:59 +00009442 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
JF Bastienf14889e2015-03-04 15:47:57 +00009443 return Size <= 128 ? AtomicRMWExpansionKind::LLSC
9444 : AtomicRMWExpansionKind::None;
Robin Morisseted3d48f2014-09-03 21:29:59 +00009445}
9446
Robin Morisset25c8e312014-09-17 00:06:58 +00009447bool AArch64TargetLowering::hasLoadLinkedStoreConditional() const {
9448 return true;
9449}
9450
Tim Northover3b0846e2014-05-24 12:50:23 +00009451Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
9452 AtomicOrdering Ord) const {
9453 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
9454 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
Robin Morissetb155f522014-08-18 16:48:58 +00009455 bool IsAcquire = isAtLeastAcquire(Ord);
Tim Northover3b0846e2014-05-24 12:50:23 +00009456
9457 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
9458 // intrinsic must return {i64, i64} and we have to recombine them into a
9459 // single i128 here.
9460 if (ValTy->getPrimitiveSizeInBits() == 128) {
9461 Intrinsic::ID Int =
9462 IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
9463 Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int);
9464
9465 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
9466 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
9467
9468 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
9469 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
9470 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
9471 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
9472 return Builder.CreateOr(
9473 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
9474 }
9475
9476 Type *Tys[] = { Addr->getType() };
9477 Intrinsic::ID Int =
9478 IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
9479 Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int, Tys);
9480
9481 return Builder.CreateTruncOrBitCast(
9482 Builder.CreateCall(Ldxr, Addr),
9483 cast<PointerType>(Addr->getType())->getElementType());
9484}
9485
9486Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
9487 Value *Val, Value *Addr,
9488 AtomicOrdering Ord) const {
9489 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
Robin Morissetb155f522014-08-18 16:48:58 +00009490 bool IsRelease = isAtLeastRelease(Ord);
Tim Northover3b0846e2014-05-24 12:50:23 +00009491
9492 // Since the intrinsics must have legal type, the i128 intrinsics take two
9493 // parameters: "i64, i64". We must marshal Val into the appropriate form
9494 // before the call.
9495 if (Val->getType()->getPrimitiveSizeInBits() == 128) {
9496 Intrinsic::ID Int =
9497 IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
9498 Function *Stxr = Intrinsic::getDeclaration(M, Int);
9499 Type *Int64Ty = Type::getInt64Ty(M->getContext());
9500
9501 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
9502 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
9503 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
David Blaikieff6409d2015-05-18 22:13:54 +00009504 return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
Tim Northover3b0846e2014-05-24 12:50:23 +00009505 }
9506
9507 Intrinsic::ID Int =
9508 IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
9509 Type *Tys[] = { Addr->getType() };
9510 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
9511
David Blaikieff6409d2015-05-18 22:13:54 +00009512 return Builder.CreateCall(Stxr,
9513 {Builder.CreateZExtOrBitCast(
9514 Val, Stxr->getFunctionType()->getParamType(0)),
9515 Addr});
Tim Northover3b0846e2014-05-24 12:50:23 +00009516}
Tim Northover3c55cca2014-11-27 21:02:42 +00009517
9518bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
9519 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
9520 return Ty->isArrayTy();
9521}
Matthias Braunaf7d7702015-07-16 20:02:37 +00009522
9523bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
9524 EVT) const {
9525 return false;
9526}