blob: f9af05e84d24a43ca9b4a513c0339b313d9fb0a9 [file] [log] [blame]
Tim Northover3b0846e2014-05-24 12:50:23 +00001//===-- AArch64ISelLowering.cpp - AArch64 DAG Lowering Implementation ----===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the AArch64TargetLowering class.
11//
12//===----------------------------------------------------------------------===//
13
14#include "AArch64ISelLowering.h"
Tim Northover3c55cca2014-11-27 21:02:42 +000015#include "AArch64CallingConvention.h"
Benjamin Kramer1f8930e2014-07-25 11:42:14 +000016#include "AArch64MachineFunctionInfo.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000017#include "AArch64PerfectShuffle.h"
18#include "AArch64Subtarget.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000019#include "AArch64TargetMachine.h"
20#include "AArch64TargetObjectFile.h"
21#include "MCTargetDesc/AArch64AddressingModes.h"
22#include "llvm/ADT/Statistic.h"
23#include "llvm/CodeGen/CallingConvLower.h"
24#include "llvm/CodeGen/MachineFrameInfo.h"
25#include "llvm/CodeGen/MachineInstrBuilder.h"
26#include "llvm/CodeGen/MachineRegisterInfo.h"
27#include "llvm/IR/Function.h"
David Blaikie457343d2015-05-21 21:12:43 +000028#include "llvm/IR/GetElementPtrTypeIterator.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000029#include "llvm/IR/Intrinsics.h"
30#include "llvm/IR/Type.h"
31#include "llvm/Support/CommandLine.h"
32#include "llvm/Support/Debug.h"
33#include "llvm/Support/ErrorHandling.h"
34#include "llvm/Support/raw_ostream.h"
35#include "llvm/Target/TargetOptions.h"
36using namespace llvm;
37
38#define DEBUG_TYPE "aarch64-lower"
39
40STATISTIC(NumTailCalls, "Number of tail calls");
41STATISTIC(NumShiftInserts, "Number of vector shift inserts");
42
Tim Northover3b0846e2014-05-24 12:50:23 +000043// Place holder until extr generation is tested fully.
44static cl::opt<bool>
45EnableAArch64ExtrGeneration("aarch64-extr-generation", cl::Hidden,
46 cl::desc("Allow AArch64 (or (shift)(shift))->extract"),
47 cl::init(true));
48
49static cl::opt<bool>
50EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden,
Kristof Beylsaea84612015-03-04 09:12:08 +000051 cl::desc("Allow AArch64 SLI/SRI formation"),
52 cl::init(false));
53
54// FIXME: The necessary dtprel relocations don't seem to be supported
55// well in the GNU bfd and gold linkers at the moment. Therefore, by
56// default, for now, fall back to GeneralDynamic code generation.
57cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration(
58 "aarch64-elf-ldtls-generation", cl::Hidden,
59 cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
60 cl::init(false));
Tim Northover3b0846e2014-05-24 12:50:23 +000061
Matthias Braunaf7d7702015-07-16 20:02:37 +000062/// Value type used for condition codes.
63static const MVT MVT_CC = MVT::i32;
64
Eric Christopher905f12d2015-01-29 00:19:42 +000065AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
66 const AArch64Subtarget &STI)
67 : TargetLowering(TM), Subtarget(&STI) {
Tim Northover3b0846e2014-05-24 12:50:23 +000068
69 // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
70 // we have to make something up. Arbitrarily, choose ZeroOrOne.
71 setBooleanContents(ZeroOrOneBooleanContent);
72 // When comparing vectors the result sets the different elements in the
73 // vector to all-one or all-zero.
74 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
75
76 // Set up the register classes.
77 addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
78 addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
79
80 if (Subtarget->hasFPARMv8()) {
81 addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
82 addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
83 addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
84 addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
85 }
86
87 if (Subtarget->hasNEON()) {
88 addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
89 addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
90 // Someone set us up the NEON.
91 addDRTypeForNEON(MVT::v2f32);
92 addDRTypeForNEON(MVT::v8i8);
93 addDRTypeForNEON(MVT::v4i16);
94 addDRTypeForNEON(MVT::v2i32);
95 addDRTypeForNEON(MVT::v1i64);
96 addDRTypeForNEON(MVT::v1f64);
Oliver Stannard89d15422014-08-27 16:16:04 +000097 addDRTypeForNEON(MVT::v4f16);
Tim Northover3b0846e2014-05-24 12:50:23 +000098
99 addQRTypeForNEON(MVT::v4f32);
100 addQRTypeForNEON(MVT::v2f64);
101 addQRTypeForNEON(MVT::v16i8);
102 addQRTypeForNEON(MVT::v8i16);
103 addQRTypeForNEON(MVT::v4i32);
104 addQRTypeForNEON(MVT::v2i64);
Oliver Stannard89d15422014-08-27 16:16:04 +0000105 addQRTypeForNEON(MVT::v8f16);
Tim Northover3b0846e2014-05-24 12:50:23 +0000106 }
107
108 // Compute derived properties from the register classes
Eric Christopher23a3a7c2015-02-26 00:00:24 +0000109 computeRegisterProperties(Subtarget->getRegisterInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +0000110
111 // Provide all sorts of operation actions
112 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
113 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
114 setOperationAction(ISD::SETCC, MVT::i32, Custom);
115 setOperationAction(ISD::SETCC, MVT::i64, Custom);
116 setOperationAction(ISD::SETCC, MVT::f32, Custom);
117 setOperationAction(ISD::SETCC, MVT::f64, Custom);
118 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
119 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
120 setOperationAction(ISD::BR_CC, MVT::i64, Custom);
121 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
122 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
123 setOperationAction(ISD::SELECT, MVT::i32, Custom);
124 setOperationAction(ISD::SELECT, MVT::i64, Custom);
125 setOperationAction(ISD::SELECT, MVT::f32, Custom);
126 setOperationAction(ISD::SELECT, MVT::f64, Custom);
127 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
128 setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
129 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
130 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
131 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
132 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
133
134 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
135 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
136 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
137
138 setOperationAction(ISD::FREM, MVT::f32, Expand);
139 setOperationAction(ISD::FREM, MVT::f64, Expand);
140 setOperationAction(ISD::FREM, MVT::f80, Expand);
141
142 // Custom lowering hooks are needed for XOR
143 // to fold it into CSINC/CSINV.
144 setOperationAction(ISD::XOR, MVT::i32, Custom);
145 setOperationAction(ISD::XOR, MVT::i64, Custom);
146
147 // Virtually no operation on f128 is legal, but LLVM can't expand them when
148 // there's a valid register class, so we need custom operations in most cases.
149 setOperationAction(ISD::FABS, MVT::f128, Expand);
150 setOperationAction(ISD::FADD, MVT::f128, Custom);
151 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
152 setOperationAction(ISD::FCOS, MVT::f128, Expand);
153 setOperationAction(ISD::FDIV, MVT::f128, Custom);
154 setOperationAction(ISD::FMA, MVT::f128, Expand);
155 setOperationAction(ISD::FMUL, MVT::f128, Custom);
156 setOperationAction(ISD::FNEG, MVT::f128, Expand);
157 setOperationAction(ISD::FPOW, MVT::f128, Expand);
158 setOperationAction(ISD::FREM, MVT::f128, Expand);
159 setOperationAction(ISD::FRINT, MVT::f128, Expand);
160 setOperationAction(ISD::FSIN, MVT::f128, Expand);
161 setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
162 setOperationAction(ISD::FSQRT, MVT::f128, Expand);
163 setOperationAction(ISD::FSUB, MVT::f128, Custom);
164 setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
165 setOperationAction(ISD::SETCC, MVT::f128, Custom);
166 setOperationAction(ISD::BR_CC, MVT::f128, Custom);
167 setOperationAction(ISD::SELECT, MVT::f128, Custom);
168 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
169 setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
170
171 // Lowering for many of the conversions is actually specified by the non-f128
172 // type. The LowerXXX function will be trivial when f128 isn't involved.
173 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
174 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
175 setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
176 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
177 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
178 setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
179 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
180 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
181 setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
182 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
183 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
184 setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
185 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
186 setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
187
188 // Variable arguments.
189 setOperationAction(ISD::VASTART, MVT::Other, Custom);
190 setOperationAction(ISD::VAARG, MVT::Other, Custom);
191 setOperationAction(ISD::VACOPY, MVT::Other, Custom);
192 setOperationAction(ISD::VAEND, MVT::Other, Expand);
193
194 // Variable-sized objects.
195 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
196 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
197 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
198
Tim Northover3b0846e2014-05-24 12:50:23 +0000199 // Constant pool entries
200 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
201
202 // BlockAddress
203 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
204
205 // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
206 setOperationAction(ISD::ADDC, MVT::i32, Custom);
207 setOperationAction(ISD::ADDE, MVT::i32, Custom);
208 setOperationAction(ISD::SUBC, MVT::i32, Custom);
209 setOperationAction(ISD::SUBE, MVT::i32, Custom);
210 setOperationAction(ISD::ADDC, MVT::i64, Custom);
211 setOperationAction(ISD::ADDE, MVT::i64, Custom);
212 setOperationAction(ISD::SUBC, MVT::i64, Custom);
213 setOperationAction(ISD::SUBE, MVT::i64, Custom);
214
215 // AArch64 lacks both left-rotate and popcount instructions.
216 setOperationAction(ISD::ROTL, MVT::i32, Expand);
217 setOperationAction(ISD::ROTL, MVT::i64, Expand);
Charlie Turner458e79b2015-10-27 10:25:20 +0000218 for (MVT VT : MVT::vector_valuetypes()) {
219 setOperationAction(ISD::ROTL, VT, Expand);
220 setOperationAction(ISD::ROTR, VT, Expand);
221 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000222
223 // AArch64 doesn't have {U|S}MUL_LOHI.
224 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
225 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
226
227
228 // Expand the undefined-at-zero variants to cttz/ctlz to their defined-at-zero
229 // counterparts, which AArch64 supports directly.
230 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
231 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
232 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
233 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
234
235 setOperationAction(ISD::CTPOP, MVT::i32, Custom);
236 setOperationAction(ISD::CTPOP, MVT::i64, Custom);
237
238 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
239 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
Chad Rosierf3491492015-12-04 21:38:44 +0000240 for (MVT VT : MVT::vector_valuetypes()) {
241 setOperationAction(ISD::SDIVREM, VT, Expand);
242 setOperationAction(ISD::UDIVREM, VT, Expand);
243 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000244 setOperationAction(ISD::SREM, MVT::i32, Expand);
245 setOperationAction(ISD::SREM, MVT::i64, Expand);
246 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
247 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
248 setOperationAction(ISD::UREM, MVT::i32, Expand);
249 setOperationAction(ISD::UREM, MVT::i64, Expand);
250
251 // Custom lower Add/Sub/Mul with overflow.
252 setOperationAction(ISD::SADDO, MVT::i32, Custom);
253 setOperationAction(ISD::SADDO, MVT::i64, Custom);
254 setOperationAction(ISD::UADDO, MVT::i32, Custom);
255 setOperationAction(ISD::UADDO, MVT::i64, Custom);
256 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
257 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
258 setOperationAction(ISD::USUBO, MVT::i32, Custom);
259 setOperationAction(ISD::USUBO, MVT::i64, Custom);
260 setOperationAction(ISD::SMULO, MVT::i32, Custom);
261 setOperationAction(ISD::SMULO, MVT::i64, Custom);
262 setOperationAction(ISD::UMULO, MVT::i32, Custom);
263 setOperationAction(ISD::UMULO, MVT::i64, Custom);
264
265 setOperationAction(ISD::FSIN, MVT::f32, Expand);
266 setOperationAction(ISD::FSIN, MVT::f64, Expand);
267 setOperationAction(ISD::FCOS, MVT::f32, Expand);
268 setOperationAction(ISD::FCOS, MVT::f64, Expand);
269 setOperationAction(ISD::FPOW, MVT::f32, Expand);
270 setOperationAction(ISD::FPOW, MVT::f64, Expand);
271 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
272 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
273
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +0000274 // f16 is a storage-only type, always promote it to f32.
275 setOperationAction(ISD::SETCC, MVT::f16, Promote);
276 setOperationAction(ISD::BR_CC, MVT::f16, Promote);
277 setOperationAction(ISD::SELECT_CC, MVT::f16, Promote);
278 setOperationAction(ISD::SELECT, MVT::f16, Promote);
279 setOperationAction(ISD::FADD, MVT::f16, Promote);
280 setOperationAction(ISD::FSUB, MVT::f16, Promote);
281 setOperationAction(ISD::FMUL, MVT::f16, Promote);
282 setOperationAction(ISD::FDIV, MVT::f16, Promote);
283 setOperationAction(ISD::FREM, MVT::f16, Promote);
284 setOperationAction(ISD::FMA, MVT::f16, Promote);
285 setOperationAction(ISD::FNEG, MVT::f16, Promote);
286 setOperationAction(ISD::FABS, MVT::f16, Promote);
287 setOperationAction(ISD::FCEIL, MVT::f16, Promote);
288 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote);
289 setOperationAction(ISD::FCOS, MVT::f16, Promote);
290 setOperationAction(ISD::FFLOOR, MVT::f16, Promote);
291 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote);
292 setOperationAction(ISD::FPOW, MVT::f16, Promote);
293 setOperationAction(ISD::FPOWI, MVT::f16, Promote);
294 setOperationAction(ISD::FRINT, MVT::f16, Promote);
295 setOperationAction(ISD::FSIN, MVT::f16, Promote);
296 setOperationAction(ISD::FSINCOS, MVT::f16, Promote);
297 setOperationAction(ISD::FSQRT, MVT::f16, Promote);
298 setOperationAction(ISD::FEXP, MVT::f16, Promote);
299 setOperationAction(ISD::FEXP2, MVT::f16, Promote);
300 setOperationAction(ISD::FLOG, MVT::f16, Promote);
301 setOperationAction(ISD::FLOG2, MVT::f16, Promote);
302 setOperationAction(ISD::FLOG10, MVT::f16, Promote);
303 setOperationAction(ISD::FROUND, MVT::f16, Promote);
304 setOperationAction(ISD::FTRUNC, MVT::f16, Promote);
305 setOperationAction(ISD::FMINNUM, MVT::f16, Promote);
306 setOperationAction(ISD::FMAXNUM, MVT::f16, Promote);
James Molloy63be1982015-08-14 09:08:50 +0000307 setOperationAction(ISD::FMINNAN, MVT::f16, Promote);
308 setOperationAction(ISD::FMAXNAN, MVT::f16, Promote);
Oliver Stannardf5469be2014-08-18 14:22:39 +0000309
Oliver Stannard89d15422014-08-27 16:16:04 +0000310 // v4f16 is also a storage-only type, so promote it to v4f32 when that is
311 // known to be safe.
312 setOperationAction(ISD::FADD, MVT::v4f16, Promote);
313 setOperationAction(ISD::FSUB, MVT::v4f16, Promote);
314 setOperationAction(ISD::FMUL, MVT::v4f16, Promote);
315 setOperationAction(ISD::FDIV, MVT::v4f16, Promote);
316 setOperationAction(ISD::FP_EXTEND, MVT::v4f16, Promote);
317 setOperationAction(ISD::FP_ROUND, MVT::v4f16, Promote);
318 AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32);
319 AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32);
320 AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32);
321 AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32);
322 AddPromotedToType(ISD::FP_EXTEND, MVT::v4f16, MVT::v4f32);
323 AddPromotedToType(ISD::FP_ROUND, MVT::v4f16, MVT::v4f32);
324
325 // Expand all other v4f16 operations.
326 // FIXME: We could generate better code by promoting some operations to
327 // a pair of v4f32s
328 setOperationAction(ISD::FABS, MVT::v4f16, Expand);
329 setOperationAction(ISD::FCEIL, MVT::v4f16, Expand);
330 setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand);
331 setOperationAction(ISD::FCOS, MVT::v4f16, Expand);
332 setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand);
333 setOperationAction(ISD::FMA, MVT::v4f16, Expand);
334 setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand);
335 setOperationAction(ISD::FNEG, MVT::v4f16, Expand);
336 setOperationAction(ISD::FPOW, MVT::v4f16, Expand);
337 setOperationAction(ISD::FPOWI, MVT::v4f16, Expand);
338 setOperationAction(ISD::FREM, MVT::v4f16, Expand);
339 setOperationAction(ISD::FROUND, MVT::v4f16, Expand);
340 setOperationAction(ISD::FRINT, MVT::v4f16, Expand);
341 setOperationAction(ISD::FSIN, MVT::v4f16, Expand);
342 setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand);
343 setOperationAction(ISD::FSQRT, MVT::v4f16, Expand);
344 setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand);
345 setOperationAction(ISD::SETCC, MVT::v4f16, Expand);
346 setOperationAction(ISD::BR_CC, MVT::v4f16, Expand);
347 setOperationAction(ISD::SELECT, MVT::v4f16, Expand);
348 setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand);
349 setOperationAction(ISD::FEXP, MVT::v4f16, Expand);
350 setOperationAction(ISD::FEXP2, MVT::v4f16, Expand);
351 setOperationAction(ISD::FLOG, MVT::v4f16, Expand);
352 setOperationAction(ISD::FLOG2, MVT::v4f16, Expand);
353 setOperationAction(ISD::FLOG10, MVT::v4f16, Expand);
354
355
356 // v8f16 is also a storage-only type, so expand it.
357 setOperationAction(ISD::FABS, MVT::v8f16, Expand);
358 setOperationAction(ISD::FADD, MVT::v8f16, Expand);
359 setOperationAction(ISD::FCEIL, MVT::v8f16, Expand);
360 setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand);
361 setOperationAction(ISD::FCOS, MVT::v8f16, Expand);
362 setOperationAction(ISD::FDIV, MVT::v8f16, Expand);
363 setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand);
364 setOperationAction(ISD::FMA, MVT::v8f16, Expand);
365 setOperationAction(ISD::FMUL, MVT::v8f16, Expand);
366 setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand);
367 setOperationAction(ISD::FNEG, MVT::v8f16, Expand);
368 setOperationAction(ISD::FPOW, MVT::v8f16, Expand);
369 setOperationAction(ISD::FPOWI, MVT::v8f16, Expand);
370 setOperationAction(ISD::FREM, MVT::v8f16, Expand);
371 setOperationAction(ISD::FROUND, MVT::v8f16, Expand);
372 setOperationAction(ISD::FRINT, MVT::v8f16, Expand);
373 setOperationAction(ISD::FSIN, MVT::v8f16, Expand);
374 setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
375 setOperationAction(ISD::FSQRT, MVT::v8f16, Expand);
376 setOperationAction(ISD::FSUB, MVT::v8f16, Expand);
377 setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand);
378 setOperationAction(ISD::SETCC, MVT::v8f16, Expand);
379 setOperationAction(ISD::BR_CC, MVT::v8f16, Expand);
380 setOperationAction(ISD::SELECT, MVT::v8f16, Expand);
381 setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand);
382 setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand);
383 setOperationAction(ISD::FEXP, MVT::v8f16, Expand);
384 setOperationAction(ISD::FEXP2, MVT::v8f16, Expand);
385 setOperationAction(ISD::FLOG, MVT::v8f16, Expand);
386 setOperationAction(ISD::FLOG2, MVT::v8f16, Expand);
387 setOperationAction(ISD::FLOG10, MVT::v8f16, Expand);
388
Tim Northover3b0846e2014-05-24 12:50:23 +0000389 // AArch64 has implementations of a lot of rounding-like FP operations.
Benjamin Kramer57a3d082015-03-08 16:07:39 +0000390 for (MVT Ty : {MVT::f32, MVT::f64}) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000391 setOperationAction(ISD::FFLOOR, Ty, Legal);
392 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
393 setOperationAction(ISD::FCEIL, Ty, Legal);
394 setOperationAction(ISD::FRINT, Ty, Legal);
395 setOperationAction(ISD::FTRUNC, Ty, Legal);
396 setOperationAction(ISD::FROUND, Ty, Legal);
James Molloyb7b2a1e2015-08-11 12:06:37 +0000397 setOperationAction(ISD::FMINNUM, Ty, Legal);
398 setOperationAction(ISD::FMAXNUM, Ty, Legal);
James Molloy88edc822015-08-17 07:13:20 +0000399 setOperationAction(ISD::FMINNAN, Ty, Legal);
400 setOperationAction(ISD::FMAXNAN, Ty, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000401 }
402
403 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
404
Ahmed Bougachab0ff6432015-09-01 16:23:45 +0000405 // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
406 // This requires the Performance Monitors extension.
407 if (Subtarget->hasPerfMon())
408 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
409
Tim Northover3b0846e2014-05-24 12:50:23 +0000410 if (Subtarget->isTargetMachO()) {
411 // For iOS, we don't want to the normal expansion of a libcall to
412 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
413 // traffic.
414 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
415 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
416 } else {
417 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
418 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
419 }
420
Juergen Ributzka23266502014-12-10 19:43:32 +0000421 // Make floating-point constants legal for the large code model, so they don't
422 // become loads from the constant pool.
423 if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
424 setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
425 setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
426 }
427
Tim Northover3b0846e2014-05-24 12:50:23 +0000428 // AArch64 does not have floating-point extending loads, i1 sign-extending
429 // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000430 for (MVT VT : MVT::fp_valuetypes()) {
431 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
432 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
433 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
434 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
435 }
436 for (MVT VT : MVT::integer_valuetypes())
437 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
438
Tim Northover3b0846e2014-05-24 12:50:23 +0000439 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
440 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
441 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
442 setTruncStoreAction(MVT::f128, MVT::f80, Expand);
443 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
444 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
445 setTruncStoreAction(MVT::f128, MVT::f16, Expand);
Tim Northoverf8bfe212014-07-18 13:07:05 +0000446
447 setOperationAction(ISD::BITCAST, MVT::i16, Custom);
448 setOperationAction(ISD::BITCAST, MVT::f16, Custom);
449
Tim Northover3b0846e2014-05-24 12:50:23 +0000450 // Indexed loads and stores are supported.
451 for (unsigned im = (unsigned)ISD::PRE_INC;
452 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
453 setIndexedLoadAction(im, MVT::i8, Legal);
454 setIndexedLoadAction(im, MVT::i16, Legal);
455 setIndexedLoadAction(im, MVT::i32, Legal);
456 setIndexedLoadAction(im, MVT::i64, Legal);
457 setIndexedLoadAction(im, MVT::f64, Legal);
458 setIndexedLoadAction(im, MVT::f32, Legal);
Ahmed Bougachae0e12db2015-08-04 01:29:38 +0000459 setIndexedLoadAction(im, MVT::f16, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000460 setIndexedStoreAction(im, MVT::i8, Legal);
461 setIndexedStoreAction(im, MVT::i16, Legal);
462 setIndexedStoreAction(im, MVT::i32, Legal);
463 setIndexedStoreAction(im, MVT::i64, Legal);
464 setIndexedStoreAction(im, MVT::f64, Legal);
465 setIndexedStoreAction(im, MVT::f32, Legal);
Ahmed Bougachae0e12db2015-08-04 01:29:38 +0000466 setIndexedStoreAction(im, MVT::f16, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000467 }
468
469 // Trap.
470 setOperationAction(ISD::TRAP, MVT::Other, Legal);
471
472 // We combine OR nodes for bitfield operations.
473 setTargetDAGCombine(ISD::OR);
474
475 // Vector add and sub nodes may conceal a high-half opportunity.
476 // Also, try to fold ADD into CSINC/CSINV..
477 setTargetDAGCombine(ISD::ADD);
478 setTargetDAGCombine(ISD::SUB);
479
480 setTargetDAGCombine(ISD::XOR);
481 setTargetDAGCombine(ISD::SINT_TO_FP);
482 setTargetDAGCombine(ISD::UINT_TO_FP);
483
Chad Rosierfa30c9b2015-10-07 17:39:18 +0000484 setTargetDAGCombine(ISD::FP_TO_SINT);
485 setTargetDAGCombine(ISD::FP_TO_UINT);
Chad Rosier7c6ac2b2015-10-07 17:51:37 +0000486 setTargetDAGCombine(ISD::FDIV);
Chad Rosierfa30c9b2015-10-07 17:39:18 +0000487
Tim Northover3b0846e2014-05-24 12:50:23 +0000488 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
489
490 setTargetDAGCombine(ISD::ANY_EXTEND);
491 setTargetDAGCombine(ISD::ZERO_EXTEND);
492 setTargetDAGCombine(ISD::SIGN_EXTEND);
493 setTargetDAGCombine(ISD::BITCAST);
494 setTargetDAGCombine(ISD::CONCAT_VECTORS);
495 setTargetDAGCombine(ISD::STORE);
Tim Northover339c83e2015-11-10 00:44:23 +0000496 if (Subtarget->supportsAddressTopByteIgnored())
497 setTargetDAGCombine(ISD::LOAD);
Tim Northover3b0846e2014-05-24 12:50:23 +0000498
499 setTargetDAGCombine(ISD::MUL);
500
501 setTargetDAGCombine(ISD::SELECT);
502 setTargetDAGCombine(ISD::VSELECT);
503
504 setTargetDAGCombine(ISD::INTRINSIC_VOID);
505 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
506 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
Chad Rosier6c36eff2015-09-03 18:13:57 +0000507 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
Tim Northover3b0846e2014-05-24 12:50:23 +0000508
509 MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 8;
510 MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 4;
511 MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = 4;
512
513 setStackPointerRegisterToSaveRestore(AArch64::SP);
514
515 setSchedulingPreference(Sched::Hybrid);
516
517 // Enable TBZ/TBNZ
518 MaskAndBranchFoldingIsLegal = true;
Quentin Colombet6843ac42015-03-31 20:52:32 +0000519 EnableExtLdPromotion = true;
Tim Northover3b0846e2014-05-24 12:50:23 +0000520
521 setMinFunctionAlignment(2);
522
Tim Northover3b0846e2014-05-24 12:50:23 +0000523 setHasExtractBitsInsn(true);
524
Adhemerval Zanella7bc33192015-07-28 13:03:31 +0000525 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
526
Tim Northover3b0846e2014-05-24 12:50:23 +0000527 if (Subtarget->hasNEON()) {
528 // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
529 // silliness like this:
530 setOperationAction(ISD::FABS, MVT::v1f64, Expand);
531 setOperationAction(ISD::FADD, MVT::v1f64, Expand);
532 setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
533 setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
534 setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
535 setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
536 setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
537 setOperationAction(ISD::FMA, MVT::v1f64, Expand);
538 setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
539 setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
540 setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
541 setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
542 setOperationAction(ISD::FREM, MVT::v1f64, Expand);
543 setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
544 setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
545 setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
546 setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
547 setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
548 setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
549 setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
550 setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
551 setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
552 setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
553 setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
554 setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
555
556 setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
557 setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
558 setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
559 setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
560 setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
561
562 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
563
564 // AArch64 doesn't have a direct vector ->f32 conversion instructions for
565 // elements smaller than i32, so promote the input to i32 first.
566 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Promote);
567 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Promote);
568 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Promote);
569 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Promote);
Pirama Arumuga Nainarb1881532015-04-23 17:16:27 +0000570 // i8 and i16 vector elements also need promotion to i32 for v8i8 or v8i16
571 // -> v8f16 conversions.
572 setOperationAction(ISD::SINT_TO_FP, MVT::v8i8, Promote);
573 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Promote);
574 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
575 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Promote);
Tim Northover3b0846e2014-05-24 12:50:23 +0000576 // Similarly, there is no direct i32 -> f64 vector conversion instruction.
577 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
578 setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
579 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
580 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
Pirama Arumuga Nainarb1881532015-04-23 17:16:27 +0000581 // Or, direct i32 -> f16 vector conversion. Set it so custom, so the
582 // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
583 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
584 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000585
586 // AArch64 doesn't have MUL.2d:
587 setOperationAction(ISD::MUL, MVT::v2i64, Expand);
Chad Rosierd9d0f862014-10-08 02:31:24 +0000588 // Custom handling for some quad-vector types to detect MULL.
589 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
590 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
591 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
592
Tim Northover3b0846e2014-05-24 12:50:23 +0000593 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
594 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
595 // Likewise, narrowing and extending vector loads/stores aren't handled
596 // directly.
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000597 for (MVT VT : MVT::vector_valuetypes()) {
598 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000599
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000600 setOperationAction(ISD::MULHS, VT, Expand);
601 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
602 setOperationAction(ISD::MULHU, VT, Expand);
603 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000604
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000605 setOperationAction(ISD::BSWAP, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000606
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000607 for (MVT InnerVT : MVT::vector_valuetypes()) {
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000608 setTruncStoreAction(VT, InnerVT, Expand);
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000609 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
610 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
611 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
612 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000613 }
614
615 // AArch64 has implementations of a lot of rounding-like FP operations.
Benjamin Kramer57a3d082015-03-08 16:07:39 +0000616 for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000617 setOperationAction(ISD::FFLOOR, Ty, Legal);
618 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
619 setOperationAction(ISD::FCEIL, Ty, Legal);
620 setOperationAction(ISD::FRINT, Ty, Legal);
621 setOperationAction(ISD::FTRUNC, Ty, Legal);
622 setOperationAction(ISD::FROUND, Ty, Legal);
623 }
624 }
James Molloyf089ab72014-08-06 10:42:18 +0000625
626 // Prefer likely predicted branches to selects on out-of-order cores.
627 if (Subtarget->isCortexA57())
628 PredictableSelectIsExpensive = true;
Tim Northover3b0846e2014-05-24 12:50:23 +0000629}
630
631void AArch64TargetLowering::addTypeForNEON(EVT VT, EVT PromotedBitwiseVT) {
Jiangning Liu08f4cda2014-08-29 01:31:42 +0000632 if (VT == MVT::v2f32 || VT == MVT::v4f16) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000633 setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
634 AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i32);
635
636 setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
637 AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i32);
Jiangning Liu08f4cda2014-08-29 01:31:42 +0000638 } else if (VT == MVT::v2f64 || VT == MVT::v4f32 || VT == MVT::v8f16) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000639 setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
640 AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i64);
641
642 setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
643 AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i64);
644 }
645
646 // Mark vector float intrinsics as expand.
647 if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
648 setOperationAction(ISD::FSIN, VT.getSimpleVT(), Expand);
649 setOperationAction(ISD::FCOS, VT.getSimpleVT(), Expand);
650 setOperationAction(ISD::FPOWI, VT.getSimpleVT(), Expand);
651 setOperationAction(ISD::FPOW, VT.getSimpleVT(), Expand);
652 setOperationAction(ISD::FLOG, VT.getSimpleVT(), Expand);
653 setOperationAction(ISD::FLOG2, VT.getSimpleVT(), Expand);
654 setOperationAction(ISD::FLOG10, VT.getSimpleVT(), Expand);
655 setOperationAction(ISD::FEXP, VT.getSimpleVT(), Expand);
656 setOperationAction(ISD::FEXP2, VT.getSimpleVT(), Expand);
Ahmed Bougachab0ae36f2015-08-04 00:42:34 +0000657
658 // But we do support custom-lowering for FCOPYSIGN.
659 setOperationAction(ISD::FCOPYSIGN, VT.getSimpleVT(), Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000660 }
661
662 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT.getSimpleVT(), Custom);
663 setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getSimpleVT(), Custom);
664 setOperationAction(ISD::BUILD_VECTOR, VT.getSimpleVT(), Custom);
665 setOperationAction(ISD::VECTOR_SHUFFLE, VT.getSimpleVT(), Custom);
666 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT.getSimpleVT(), Custom);
667 setOperationAction(ISD::SRA, VT.getSimpleVT(), Custom);
668 setOperationAction(ISD::SRL, VT.getSimpleVT(), Custom);
669 setOperationAction(ISD::SHL, VT.getSimpleVT(), Custom);
670 setOperationAction(ISD::AND, VT.getSimpleVT(), Custom);
671 setOperationAction(ISD::OR, VT.getSimpleVT(), Custom);
672 setOperationAction(ISD::SETCC, VT.getSimpleVT(), Custom);
673 setOperationAction(ISD::CONCAT_VECTORS, VT.getSimpleVT(), Legal);
674
675 setOperationAction(ISD::SELECT, VT.getSimpleVT(), Expand);
676 setOperationAction(ISD::SELECT_CC, VT.getSimpleVT(), Expand);
677 setOperationAction(ISD::VSELECT, VT.getSimpleVT(), Expand);
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000678 for (MVT InnerVT : MVT::all_valuetypes())
679 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT.getSimpleVT(), Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000680
681 // CNT supports only B element sizes.
682 if (VT != MVT::v8i8 && VT != MVT::v16i8)
683 setOperationAction(ISD::CTPOP, VT.getSimpleVT(), Expand);
684
685 setOperationAction(ISD::UDIV, VT.getSimpleVT(), Expand);
686 setOperationAction(ISD::SDIV, VT.getSimpleVT(), Expand);
687 setOperationAction(ISD::UREM, VT.getSimpleVT(), Expand);
688 setOperationAction(ISD::SREM, VT.getSimpleVT(), Expand);
689 setOperationAction(ISD::FREM, VT.getSimpleVT(), Expand);
690
691 setOperationAction(ISD::FP_TO_SINT, VT.getSimpleVT(), Custom);
692 setOperationAction(ISD::FP_TO_UINT, VT.getSimpleVT(), Custom);
693
Hal Finkelcd8664c2015-12-11 23:11:52 +0000694 // [SU][MIN|MAX] are available for all NEON types apart from i64.
James Molloycfb04432015-05-15 16:15:57 +0000695 if (!VT.isFloatingPoint() &&
696 VT.getSimpleVT() != MVT::v2i64 && VT.getSimpleVT() != MVT::v1i64)
Hal Finkelcd8664c2015-12-11 23:11:52 +0000697 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
James Molloycfb04432015-05-15 16:15:57 +0000698 setOperationAction(Opcode, VT.getSimpleVT(), Legal);
699
James Molloy63be1982015-08-14 09:08:50 +0000700 // F[MIN|MAX][NUM|NAN] are available for all FP NEON types (not f16 though!).
701 if (VT.isFloatingPoint() && VT.getVectorElementType() != MVT::f16)
James Molloyb7b2a1e2015-08-11 12:06:37 +0000702 for (unsigned Opcode : {ISD::FMINNAN, ISD::FMAXNAN,
703 ISD::FMINNUM, ISD::FMAXNUM})
James Molloyedf38f02015-08-11 12:06:33 +0000704 setOperationAction(Opcode, VT.getSimpleVT(), Legal);
705
Tim Northover3b0846e2014-05-24 12:50:23 +0000706 if (Subtarget->isLittleEndian()) {
707 for (unsigned im = (unsigned)ISD::PRE_INC;
708 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
709 setIndexedLoadAction(im, VT.getSimpleVT(), Legal);
710 setIndexedStoreAction(im, VT.getSimpleVT(), Legal);
711 }
712 }
713}
714
715void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
716 addRegisterClass(VT, &AArch64::FPR64RegClass);
717 addTypeForNEON(VT, MVT::v2i32);
718}
719
720void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
721 addRegisterClass(VT, &AArch64::FPR128RegClass);
722 addTypeForNEON(VT, MVT::v4i32);
723}
724
Mehdi Amini44ede332015-07-09 02:09:04 +0000725EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
726 EVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +0000727 if (!VT.isVector())
728 return MVT::i32;
729 return VT.changeVectorElementTypeToInteger();
730}
731
732/// computeKnownBitsForTargetNode - Determine which of the bits specified in
733/// Mask are known to be either zero or one and return them in the
734/// KnownZero/KnownOne bitsets.
735void AArch64TargetLowering::computeKnownBitsForTargetNode(
736 const SDValue Op, APInt &KnownZero, APInt &KnownOne,
737 const SelectionDAG &DAG, unsigned Depth) const {
738 switch (Op.getOpcode()) {
739 default:
740 break;
741 case AArch64ISD::CSEL: {
742 APInt KnownZero2, KnownOne2;
743 DAG.computeKnownBits(Op->getOperand(0), KnownZero, KnownOne, Depth + 1);
744 DAG.computeKnownBits(Op->getOperand(1), KnownZero2, KnownOne2, Depth + 1);
745 KnownZero &= KnownZero2;
746 KnownOne &= KnownOne2;
747 break;
748 }
749 case ISD::INTRINSIC_W_CHAIN: {
Jun Bum Lim4d3c5982015-09-08 16:11:22 +0000750 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +0000751 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
752 switch (IntID) {
753 default: return;
754 case Intrinsic::aarch64_ldaxr:
755 case Intrinsic::aarch64_ldxr: {
756 unsigned BitWidth = KnownOne.getBitWidth();
757 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
758 unsigned MemBits = VT.getScalarType().getSizeInBits();
759 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
760 return;
761 }
762 }
763 break;
764 }
765 case ISD::INTRINSIC_WO_CHAIN:
766 case ISD::INTRINSIC_VOID: {
767 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
768 switch (IntNo) {
769 default:
770 break;
771 case Intrinsic::aarch64_neon_umaxv:
772 case Intrinsic::aarch64_neon_uminv: {
773 // Figure out the datatype of the vector operand. The UMINV instruction
774 // will zero extend the result, so we can mark as known zero all the
775 // bits larger than the element datatype. 32-bit or larget doesn't need
776 // this as those are legal types and will be handled by isel directly.
777 MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
778 unsigned BitWidth = KnownZero.getBitWidth();
779 if (VT == MVT::v8i8 || VT == MVT::v16i8) {
780 assert(BitWidth >= 8 && "Unexpected width!");
781 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
782 KnownZero |= Mask;
783 } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
784 assert(BitWidth >= 16 && "Unexpected width!");
785 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
786 KnownZero |= Mask;
787 }
788 break;
789 } break;
790 }
791 }
792 }
793}
794
Mehdi Aminieaabc512015-07-09 15:12:23 +0000795MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
796 EVT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +0000797 return MVT::i64;
798}
799
Akira Hatanakaf53b0402015-07-29 14:17:26 +0000800bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
801 unsigned AddrSpace,
802 unsigned Align,
803 bool *Fast) const {
804 if (Subtarget->requiresStrictAlign())
805 return false;
Sanjay Patelbbbf9a12015-09-25 21:49:48 +0000806
807 // FIXME: This is mostly true for Cyclone, but not necessarily others.
808 if (Fast) {
809 // FIXME: Define an attribute for slow unaligned accesses instead of
810 // relying on the CPU type as a proxy.
811 // On Cyclone, unaligned 128-bit stores are slow.
812 *Fast = !Subtarget->isCyclone() || VT.getStoreSize() != 16 ||
813 // See comments in performSTORECombine() for more details about
814 // these conditions.
815
816 // Code that uses clang vector extensions can mark that it
817 // wants unaligned accesses to be treated as fast by
818 // underspecifying alignment to be 1 or 2.
819 Align <= 2 ||
820
821 // Disregard v2i64. Memcpy lowering produces those and splitting
822 // them regresses performance on micro-benchmarks and olden/bh.
823 VT == MVT::v2i64;
824 }
Akira Hatanakaf53b0402015-07-29 14:17:26 +0000825 return true;
826}
827
Tim Northover3b0846e2014-05-24 12:50:23 +0000828FastISel *
829AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
830 const TargetLibraryInfo *libInfo) const {
831 return AArch64::createFastISel(funcInfo, libInfo);
832}
833
834const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
Matthias Braund04893f2015-05-07 21:33:59 +0000835 switch ((AArch64ISD::NodeType)Opcode) {
836 case AArch64ISD::FIRST_NUMBER: break;
Tim Northover3b0846e2014-05-24 12:50:23 +0000837 case AArch64ISD::CALL: return "AArch64ISD::CALL";
838 case AArch64ISD::ADRP: return "AArch64ISD::ADRP";
839 case AArch64ISD::ADDlow: return "AArch64ISD::ADDlow";
840 case AArch64ISD::LOADgot: return "AArch64ISD::LOADgot";
841 case AArch64ISD::RET_FLAG: return "AArch64ISD::RET_FLAG";
842 case AArch64ISD::BRCOND: return "AArch64ISD::BRCOND";
843 case AArch64ISD::CSEL: return "AArch64ISD::CSEL";
844 case AArch64ISD::FCSEL: return "AArch64ISD::FCSEL";
845 case AArch64ISD::CSINV: return "AArch64ISD::CSINV";
846 case AArch64ISD::CSNEG: return "AArch64ISD::CSNEG";
847 case AArch64ISD::CSINC: return "AArch64ISD::CSINC";
848 case AArch64ISD::THREAD_POINTER: return "AArch64ISD::THREAD_POINTER";
Kristof Beylsaea84612015-03-04 09:12:08 +0000849 case AArch64ISD::TLSDESC_CALLSEQ: return "AArch64ISD::TLSDESC_CALLSEQ";
Tim Northover3b0846e2014-05-24 12:50:23 +0000850 case AArch64ISD::ADC: return "AArch64ISD::ADC";
851 case AArch64ISD::SBC: return "AArch64ISD::SBC";
852 case AArch64ISD::ADDS: return "AArch64ISD::ADDS";
853 case AArch64ISD::SUBS: return "AArch64ISD::SUBS";
854 case AArch64ISD::ADCS: return "AArch64ISD::ADCS";
855 case AArch64ISD::SBCS: return "AArch64ISD::SBCS";
856 case AArch64ISD::ANDS: return "AArch64ISD::ANDS";
Matthias Braunaf7d7702015-07-16 20:02:37 +0000857 case AArch64ISD::CCMP: return "AArch64ISD::CCMP";
858 case AArch64ISD::CCMN: return "AArch64ISD::CCMN";
859 case AArch64ISD::FCCMP: return "AArch64ISD::FCCMP";
Tim Northover3b0846e2014-05-24 12:50:23 +0000860 case AArch64ISD::FCMP: return "AArch64ISD::FCMP";
Tim Northover3b0846e2014-05-24 12:50:23 +0000861 case AArch64ISD::DUP: return "AArch64ISD::DUP";
862 case AArch64ISD::DUPLANE8: return "AArch64ISD::DUPLANE8";
863 case AArch64ISD::DUPLANE16: return "AArch64ISD::DUPLANE16";
864 case AArch64ISD::DUPLANE32: return "AArch64ISD::DUPLANE32";
865 case AArch64ISD::DUPLANE64: return "AArch64ISD::DUPLANE64";
866 case AArch64ISD::MOVI: return "AArch64ISD::MOVI";
867 case AArch64ISD::MOVIshift: return "AArch64ISD::MOVIshift";
868 case AArch64ISD::MOVIedit: return "AArch64ISD::MOVIedit";
869 case AArch64ISD::MOVImsl: return "AArch64ISD::MOVImsl";
870 case AArch64ISD::FMOV: return "AArch64ISD::FMOV";
871 case AArch64ISD::MVNIshift: return "AArch64ISD::MVNIshift";
872 case AArch64ISD::MVNImsl: return "AArch64ISD::MVNImsl";
873 case AArch64ISD::BICi: return "AArch64ISD::BICi";
874 case AArch64ISD::ORRi: return "AArch64ISD::ORRi";
875 case AArch64ISD::BSL: return "AArch64ISD::BSL";
876 case AArch64ISD::NEG: return "AArch64ISD::NEG";
877 case AArch64ISD::EXTR: return "AArch64ISD::EXTR";
878 case AArch64ISD::ZIP1: return "AArch64ISD::ZIP1";
879 case AArch64ISD::ZIP2: return "AArch64ISD::ZIP2";
880 case AArch64ISD::UZP1: return "AArch64ISD::UZP1";
881 case AArch64ISD::UZP2: return "AArch64ISD::UZP2";
882 case AArch64ISD::TRN1: return "AArch64ISD::TRN1";
883 case AArch64ISD::TRN2: return "AArch64ISD::TRN2";
884 case AArch64ISD::REV16: return "AArch64ISD::REV16";
885 case AArch64ISD::REV32: return "AArch64ISD::REV32";
886 case AArch64ISD::REV64: return "AArch64ISD::REV64";
887 case AArch64ISD::EXT: return "AArch64ISD::EXT";
888 case AArch64ISD::VSHL: return "AArch64ISD::VSHL";
889 case AArch64ISD::VLSHR: return "AArch64ISD::VLSHR";
890 case AArch64ISD::VASHR: return "AArch64ISD::VASHR";
891 case AArch64ISD::CMEQ: return "AArch64ISD::CMEQ";
892 case AArch64ISD::CMGE: return "AArch64ISD::CMGE";
893 case AArch64ISD::CMGT: return "AArch64ISD::CMGT";
894 case AArch64ISD::CMHI: return "AArch64ISD::CMHI";
895 case AArch64ISD::CMHS: return "AArch64ISD::CMHS";
896 case AArch64ISD::FCMEQ: return "AArch64ISD::FCMEQ";
897 case AArch64ISD::FCMGE: return "AArch64ISD::FCMGE";
898 case AArch64ISD::FCMGT: return "AArch64ISD::FCMGT";
899 case AArch64ISD::CMEQz: return "AArch64ISD::CMEQz";
900 case AArch64ISD::CMGEz: return "AArch64ISD::CMGEz";
901 case AArch64ISD::CMGTz: return "AArch64ISD::CMGTz";
902 case AArch64ISD::CMLEz: return "AArch64ISD::CMLEz";
903 case AArch64ISD::CMLTz: return "AArch64ISD::CMLTz";
904 case AArch64ISD::FCMEQz: return "AArch64ISD::FCMEQz";
905 case AArch64ISD::FCMGEz: return "AArch64ISD::FCMGEz";
906 case AArch64ISD::FCMGTz: return "AArch64ISD::FCMGTz";
907 case AArch64ISD::FCMLEz: return "AArch64ISD::FCMLEz";
908 case AArch64ISD::FCMLTz: return "AArch64ISD::FCMLTz";
Ahmed Bougachafab58922015-03-10 20:45:38 +0000909 case AArch64ISD::SADDV: return "AArch64ISD::SADDV";
910 case AArch64ISD::UADDV: return "AArch64ISD::UADDV";
911 case AArch64ISD::SMINV: return "AArch64ISD::SMINV";
912 case AArch64ISD::UMINV: return "AArch64ISD::UMINV";
913 case AArch64ISD::SMAXV: return "AArch64ISD::SMAXV";
914 case AArch64ISD::UMAXV: return "AArch64ISD::UMAXV";
Tim Northover3b0846e2014-05-24 12:50:23 +0000915 case AArch64ISD::NOT: return "AArch64ISD::NOT";
916 case AArch64ISD::BIT: return "AArch64ISD::BIT";
917 case AArch64ISD::CBZ: return "AArch64ISD::CBZ";
918 case AArch64ISD::CBNZ: return "AArch64ISD::CBNZ";
919 case AArch64ISD::TBZ: return "AArch64ISD::TBZ";
920 case AArch64ISD::TBNZ: return "AArch64ISD::TBNZ";
921 case AArch64ISD::TC_RETURN: return "AArch64ISD::TC_RETURN";
Matthias Braund04893f2015-05-07 21:33:59 +0000922 case AArch64ISD::PREFETCH: return "AArch64ISD::PREFETCH";
Tim Northover3b0846e2014-05-24 12:50:23 +0000923 case AArch64ISD::SITOF: return "AArch64ISD::SITOF";
924 case AArch64ISD::UITOF: return "AArch64ISD::UITOF";
Asiri Rathnayake530b3ed2014-10-01 09:59:45 +0000925 case AArch64ISD::NVCAST: return "AArch64ISD::NVCAST";
Tim Northover3b0846e2014-05-24 12:50:23 +0000926 case AArch64ISD::SQSHL_I: return "AArch64ISD::SQSHL_I";
927 case AArch64ISD::UQSHL_I: return "AArch64ISD::UQSHL_I";
928 case AArch64ISD::SRSHR_I: return "AArch64ISD::SRSHR_I";
929 case AArch64ISD::URSHR_I: return "AArch64ISD::URSHR_I";
930 case AArch64ISD::SQSHLU_I: return "AArch64ISD::SQSHLU_I";
931 case AArch64ISD::WrapperLarge: return "AArch64ISD::WrapperLarge";
932 case AArch64ISD::LD2post: return "AArch64ISD::LD2post";
933 case AArch64ISD::LD3post: return "AArch64ISD::LD3post";
934 case AArch64ISD::LD4post: return "AArch64ISD::LD4post";
935 case AArch64ISD::ST2post: return "AArch64ISD::ST2post";
936 case AArch64ISD::ST3post: return "AArch64ISD::ST3post";
937 case AArch64ISD::ST4post: return "AArch64ISD::ST4post";
938 case AArch64ISD::LD1x2post: return "AArch64ISD::LD1x2post";
939 case AArch64ISD::LD1x3post: return "AArch64ISD::LD1x3post";
940 case AArch64ISD::LD1x4post: return "AArch64ISD::LD1x4post";
941 case AArch64ISD::ST1x2post: return "AArch64ISD::ST1x2post";
942 case AArch64ISD::ST1x3post: return "AArch64ISD::ST1x3post";
943 case AArch64ISD::ST1x4post: return "AArch64ISD::ST1x4post";
944 case AArch64ISD::LD1DUPpost: return "AArch64ISD::LD1DUPpost";
945 case AArch64ISD::LD2DUPpost: return "AArch64ISD::LD2DUPpost";
946 case AArch64ISD::LD3DUPpost: return "AArch64ISD::LD3DUPpost";
947 case AArch64ISD::LD4DUPpost: return "AArch64ISD::LD4DUPpost";
948 case AArch64ISD::LD1LANEpost: return "AArch64ISD::LD1LANEpost";
949 case AArch64ISD::LD2LANEpost: return "AArch64ISD::LD2LANEpost";
950 case AArch64ISD::LD3LANEpost: return "AArch64ISD::LD3LANEpost";
951 case AArch64ISD::LD4LANEpost: return "AArch64ISD::LD4LANEpost";
952 case AArch64ISD::ST2LANEpost: return "AArch64ISD::ST2LANEpost";
953 case AArch64ISD::ST3LANEpost: return "AArch64ISD::ST3LANEpost";
954 case AArch64ISD::ST4LANEpost: return "AArch64ISD::ST4LANEpost";
Chad Rosierd9d0f862014-10-08 02:31:24 +0000955 case AArch64ISD::SMULL: return "AArch64ISD::SMULL";
956 case AArch64ISD::UMULL: return "AArch64ISD::UMULL";
Tim Northover3b0846e2014-05-24 12:50:23 +0000957 }
Matthias Braund04893f2015-05-07 21:33:59 +0000958 return nullptr;
Tim Northover3b0846e2014-05-24 12:50:23 +0000959}
960
961MachineBasicBlock *
962AArch64TargetLowering::EmitF128CSEL(MachineInstr *MI,
963 MachineBasicBlock *MBB) const {
964 // We materialise the F128CSEL pseudo-instruction as some control flow and a
965 // phi node:
966
967 // OrigBB:
968 // [... previous instrs leading to comparison ...]
969 // b.ne TrueBB
970 // b EndBB
971 // TrueBB:
972 // ; Fallthrough
973 // EndBB:
974 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
975
Tim Northover3b0846e2014-05-24 12:50:23 +0000976 MachineFunction *MF = MBB->getParent();
Eric Christopher905f12d2015-01-29 00:19:42 +0000977 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +0000978 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
979 DebugLoc DL = MI->getDebugLoc();
Duncan P. N. Exon Smithd3b9df02015-10-13 20:02:15 +0000980 MachineFunction::iterator It = ++MBB->getIterator();
Tim Northover3b0846e2014-05-24 12:50:23 +0000981
982 unsigned DestReg = MI->getOperand(0).getReg();
983 unsigned IfTrueReg = MI->getOperand(1).getReg();
984 unsigned IfFalseReg = MI->getOperand(2).getReg();
985 unsigned CondCode = MI->getOperand(3).getImm();
986 bool NZCVKilled = MI->getOperand(4).isKill();
987
988 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
989 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
990 MF->insert(It, TrueBB);
991 MF->insert(It, EndBB);
992
993 // Transfer rest of current basic-block to EndBB
994 EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
995 MBB->end());
996 EndBB->transferSuccessorsAndUpdatePHIs(MBB);
997
998 BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
999 BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
1000 MBB->addSuccessor(TrueBB);
1001 MBB->addSuccessor(EndBB);
1002
1003 // TrueBB falls through to the end.
1004 TrueBB->addSuccessor(EndBB);
1005
1006 if (!NZCVKilled) {
1007 TrueBB->addLiveIn(AArch64::NZCV);
1008 EndBB->addLiveIn(AArch64::NZCV);
1009 }
1010
1011 BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
1012 .addReg(IfTrueReg)
1013 .addMBB(TrueBB)
1014 .addReg(IfFalseReg)
1015 .addMBB(MBB);
1016
1017 MI->eraseFromParent();
1018 return EndBB;
1019}
1020
1021MachineBasicBlock *
1022AArch64TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1023 MachineBasicBlock *BB) const {
1024 switch (MI->getOpcode()) {
1025 default:
1026#ifndef NDEBUG
1027 MI->dump();
1028#endif
Craig Topper35b2f752014-06-19 06:10:58 +00001029 llvm_unreachable("Unexpected instruction for custom inserter!");
Tim Northover3b0846e2014-05-24 12:50:23 +00001030
1031 case AArch64::F128CSEL:
1032 return EmitF128CSEL(MI, BB);
1033
1034 case TargetOpcode::STACKMAP:
1035 case TargetOpcode::PATCHPOINT:
1036 return emitPatchPoint(MI, BB);
1037 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001038}
1039
1040//===----------------------------------------------------------------------===//
1041// AArch64 Lowering private implementation.
1042//===----------------------------------------------------------------------===//
1043
1044//===----------------------------------------------------------------------===//
1045// Lowering Code
1046//===----------------------------------------------------------------------===//
1047
1048/// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1049/// CC
1050static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1051 switch (CC) {
1052 default:
1053 llvm_unreachable("Unknown condition code!");
1054 case ISD::SETNE:
1055 return AArch64CC::NE;
1056 case ISD::SETEQ:
1057 return AArch64CC::EQ;
1058 case ISD::SETGT:
1059 return AArch64CC::GT;
1060 case ISD::SETGE:
1061 return AArch64CC::GE;
1062 case ISD::SETLT:
1063 return AArch64CC::LT;
1064 case ISD::SETLE:
1065 return AArch64CC::LE;
1066 case ISD::SETUGT:
1067 return AArch64CC::HI;
1068 case ISD::SETUGE:
1069 return AArch64CC::HS;
1070 case ISD::SETULT:
1071 return AArch64CC::LO;
1072 case ISD::SETULE:
1073 return AArch64CC::LS;
1074 }
1075}
1076
1077/// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1078static void changeFPCCToAArch64CC(ISD::CondCode CC,
1079 AArch64CC::CondCode &CondCode,
1080 AArch64CC::CondCode &CondCode2) {
1081 CondCode2 = AArch64CC::AL;
1082 switch (CC) {
1083 default:
1084 llvm_unreachable("Unknown FP condition!");
1085 case ISD::SETEQ:
1086 case ISD::SETOEQ:
1087 CondCode = AArch64CC::EQ;
1088 break;
1089 case ISD::SETGT:
1090 case ISD::SETOGT:
1091 CondCode = AArch64CC::GT;
1092 break;
1093 case ISD::SETGE:
1094 case ISD::SETOGE:
1095 CondCode = AArch64CC::GE;
1096 break;
1097 case ISD::SETOLT:
1098 CondCode = AArch64CC::MI;
1099 break;
1100 case ISD::SETOLE:
1101 CondCode = AArch64CC::LS;
1102 break;
1103 case ISD::SETONE:
1104 CondCode = AArch64CC::MI;
1105 CondCode2 = AArch64CC::GT;
1106 break;
1107 case ISD::SETO:
1108 CondCode = AArch64CC::VC;
1109 break;
1110 case ISD::SETUO:
1111 CondCode = AArch64CC::VS;
1112 break;
1113 case ISD::SETUEQ:
1114 CondCode = AArch64CC::EQ;
1115 CondCode2 = AArch64CC::VS;
1116 break;
1117 case ISD::SETUGT:
1118 CondCode = AArch64CC::HI;
1119 break;
1120 case ISD::SETUGE:
1121 CondCode = AArch64CC::PL;
1122 break;
1123 case ISD::SETLT:
1124 case ISD::SETULT:
1125 CondCode = AArch64CC::LT;
1126 break;
1127 case ISD::SETLE:
1128 case ISD::SETULE:
1129 CondCode = AArch64CC::LE;
1130 break;
1131 case ISD::SETNE:
1132 case ISD::SETUNE:
1133 CondCode = AArch64CC::NE;
1134 break;
1135 }
1136}
1137
1138/// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1139/// CC usable with the vector instructions. Fewer operations are available
1140/// without a real NZCV register, so we have to use less efficient combinations
1141/// to get the same effect.
1142static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1143 AArch64CC::CondCode &CondCode,
1144 AArch64CC::CondCode &CondCode2,
1145 bool &Invert) {
1146 Invert = false;
1147 switch (CC) {
1148 default:
1149 // Mostly the scalar mappings work fine.
1150 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1151 break;
1152 case ISD::SETUO:
1153 Invert = true; // Fallthrough
1154 case ISD::SETO:
1155 CondCode = AArch64CC::MI;
1156 CondCode2 = AArch64CC::GE;
1157 break;
1158 case ISD::SETUEQ:
1159 case ISD::SETULT:
1160 case ISD::SETULE:
1161 case ISD::SETUGT:
1162 case ISD::SETUGE:
1163 // All of the compare-mask comparisons are ordered, but we can switch
1164 // between the two by a double inversion. E.g. ULE == !OGT.
1165 Invert = true;
1166 changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1167 break;
1168 }
1169}
1170
1171static bool isLegalArithImmed(uint64_t C) {
1172 // Matches AArch64DAGToDAGISel::SelectArithImmed().
1173 return (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1174}
1175
1176static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1177 SDLoc dl, SelectionDAG &DAG) {
1178 EVT VT = LHS.getValueType();
1179
1180 if (VT.isFloatingPoint())
1181 return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
1182
1183 // The CMP instruction is just an alias for SUBS, and representing it as
1184 // SUBS means that it's possible to get CSE with subtract operations.
1185 // A later phase can perform the optimization of setting the destination
1186 // register to WZR/XZR if it ends up being unused.
1187 unsigned Opcode = AArch64ISD::SUBS;
1188
Artyom Skrobov314ee042015-11-25 19:41:11 +00001189 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001190 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1191 // We'd like to combine a (CMP op1, (sub 0, op2) into a CMN instruction on
1192 // the grounds that "op1 - (-op2) == op1 + op2". However, the C and V flags
1193 // can be set differently by this operation. It comes down to whether
1194 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1195 // everything is fine. If not then the optimization is wrong. Thus general
1196 // comparisons are only valid if op2 != 0.
1197
1198 // So, finally, the only LLVM-native comparisons that don't mention C and V
1199 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1200 // the absence of information about op2.
1201 Opcode = AArch64ISD::ADDS;
1202 RHS = RHS.getOperand(1);
Artyom Skrobov314ee042015-11-25 19:41:11 +00001203 } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001204 !isUnsignedIntSetCC(CC)) {
1205 // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1206 // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1207 // of the signed comparisons.
1208 Opcode = AArch64ISD::ANDS;
1209 RHS = LHS.getOperand(1);
1210 LHS = LHS.getOperand(0);
1211 }
1212
Matthias Braunaf7d7702015-07-16 20:02:37 +00001213 return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
Tim Northover3b0846e2014-05-24 12:50:23 +00001214 .getValue(1);
1215}
1216
Matthias Braunaf7d7702015-07-16 20:02:37 +00001217/// \defgroup AArch64CCMP CMP;CCMP matching
1218///
1219/// These functions deal with the formation of CMP;CCMP;... sequences.
1220/// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1221/// a comparison. They set the NZCV flags to a predefined value if their
1222/// predicate is false. This allows to express arbitrary conjunctions, for
1223/// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B))))"
1224/// expressed as:
1225/// cmp A
1226/// ccmp B, inv(CB), CA
1227/// check for CB flags
1228///
1229/// In general we can create code for arbitrary "... (and (and A B) C)"
1230/// sequences. We can also implement some "or" expressions, because "(or A B)"
1231/// is equivalent to "not (and (not A) (not B))" and we can implement some
1232/// negation operations:
1233/// We can negate the results of a single comparison by inverting the flags
1234/// used when the predicate fails and inverting the flags tested in the next
1235/// instruction; We can also negate the results of the whole previous
1236/// conditional compare sequence by inverting the flags tested in the next
1237/// instruction. However there is no way to negate the result of a partial
1238/// sequence.
1239///
1240/// Therefore on encountering an "or" expression we can negate the subtree on
1241/// one side and have to be able to push the negate to the leafs of the subtree
1242/// on the other side (see also the comments in code). As complete example:
1243/// "or (or (setCA (cmp A)) (setCB (cmp B)))
1244/// (and (setCC (cmp C)) (setCD (cmp D)))"
1245/// is transformed to
1246/// "not (and (not (and (setCC (cmp C)) (setCC (cmp D))))
1247/// (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1248/// and implemented as:
1249/// cmp C
1250/// ccmp D, inv(CD), CC
1251/// ccmp A, CA, inv(CD)
1252/// ccmp B, CB, inv(CA)
1253/// check for CB flags
1254/// A counterexample is "or (and A B) (and C D)" which cannot be implemented
1255/// by conditional compare sequences.
1256/// @{
1257
Geoff Berrye41c2df2015-07-20 22:03:52 +00001258/// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001259static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1260 ISD::CondCode CC, SDValue CCOp,
1261 SDValue Condition, unsigned NZCV,
1262 SDLoc DL, SelectionDAG &DAG) {
1263 unsigned Opcode = 0;
1264 if (LHS.getValueType().isFloatingPoint())
1265 Opcode = AArch64ISD::FCCMP;
1266 else if (RHS.getOpcode() == ISD::SUB) {
1267 SDValue SubOp0 = RHS.getOperand(0);
Artyom Skrobov314ee042015-11-25 19:41:11 +00001268 if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001269 // See emitComparison() on why we can only do this for SETEQ and SETNE.
1270 Opcode = AArch64ISD::CCMN;
1271 RHS = RHS.getOperand(1);
1272 }
1273 }
1274 if (Opcode == 0)
1275 Opcode = AArch64ISD::CCMP;
1276
1277 SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1278 return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1279}
1280
1281/// Returns true if @p Val is a tree of AND/OR/SETCC operations.
1282/// CanPushNegate is set to true if we can push a negate operation through
1283/// the tree in a was that we are left with AND operations and negate operations
1284/// at the leafs only. i.e. "not (or (or x y) z)" can be changed to
1285/// "and (and (not x) (not y)) (not z)"; "not (or (and x y) z)" cannot be
1286/// brought into such a form.
1287static bool isConjunctionDisjunctionTree(const SDValue Val, bool &CanPushNegate,
1288 unsigned Depth = 0) {
1289 if (!Val.hasOneUse())
1290 return false;
1291 unsigned Opcode = Val->getOpcode();
1292 if (Opcode == ISD::SETCC) {
1293 CanPushNegate = true;
1294 return true;
1295 }
1296 // Protect against stack overflow.
1297 if (Depth > 15)
1298 return false;
1299 if (Opcode == ISD::AND || Opcode == ISD::OR) {
1300 SDValue O0 = Val->getOperand(0);
1301 SDValue O1 = Val->getOperand(1);
1302 bool CanPushNegateL;
1303 if (!isConjunctionDisjunctionTree(O0, CanPushNegateL, Depth+1))
1304 return false;
1305 bool CanPushNegateR;
1306 if (!isConjunctionDisjunctionTree(O1, CanPushNegateR, Depth+1))
1307 return false;
1308 // We cannot push a negate through an AND operation (it would become an OR),
1309 // we can however change a (not (or x y)) to (and (not x) (not y)) if we can
1310 // push the negate through the x/y subtrees.
1311 CanPushNegate = (Opcode == ISD::OR) && CanPushNegateL && CanPushNegateR;
1312 return true;
1313 }
1314 return false;
1315}
1316
1317/// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1318/// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1319/// Tries to transform the given i1 producing node @p Val to a series compare
1320/// and conditional compare operations. @returns an NZCV flags producing node
1321/// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1322/// transformation was not possible.
1323/// On recursive invocations @p PushNegate may be set to true to have negation
1324/// effects pushed to the tree leafs; @p Predicate is an NZCV flag predicate
1325/// for the comparisons in the current subtree; @p Depth limits the search
1326/// depth to avoid stack overflow.
1327static SDValue emitConjunctionDisjunctionTree(SelectionDAG &DAG, SDValue Val,
1328 AArch64CC::CondCode &OutCC, bool PushNegate = false,
1329 SDValue CCOp = SDValue(), AArch64CC::CondCode Predicate = AArch64CC::AL,
1330 unsigned Depth = 0) {
1331 // We're at a tree leaf, produce a conditional comparison operation.
1332 unsigned Opcode = Val->getOpcode();
1333 if (Opcode == ISD::SETCC) {
1334 SDValue LHS = Val->getOperand(0);
1335 SDValue RHS = Val->getOperand(1);
1336 ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1337 bool isInteger = LHS.getValueType().isInteger();
1338 if (PushNegate)
1339 CC = getSetCCInverse(CC, isInteger);
1340 SDLoc DL(Val);
1341 // Determine OutCC and handle FP special case.
1342 if (isInteger) {
1343 OutCC = changeIntCCToAArch64CC(CC);
1344 } else {
1345 assert(LHS.getValueType().isFloatingPoint());
1346 AArch64CC::CondCode ExtraCC;
1347 changeFPCCToAArch64CC(CC, OutCC, ExtraCC);
1348 // Surpisingly some floating point conditions can't be tested with a
1349 // single condition code. Construct an additional comparison in this case.
1350 // See comment below on how we deal with OR conditions.
1351 if (ExtraCC != AArch64CC::AL) {
1352 SDValue ExtraCmp;
1353 if (!CCOp.getNode())
1354 ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
1355 else {
1356 SDValue ConditionOp = DAG.getConstant(Predicate, DL, MVT_CC);
1357 // Note that we want the inverse of ExtraCC, so NZCV is not inversed.
1358 unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(ExtraCC);
1359 ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, ConditionOp,
1360 NZCV, DL, DAG);
1361 }
1362 CCOp = ExtraCmp;
1363 Predicate = AArch64CC::getInvertedCondCode(ExtraCC);
1364 OutCC = AArch64CC::getInvertedCondCode(OutCC);
1365 }
1366 }
1367
1368 // Produce a normal comparison if we are first in the chain
1369 if (!CCOp.getNode())
1370 return emitComparison(LHS, RHS, CC, DL, DAG);
1371 // Otherwise produce a ccmp.
1372 SDValue ConditionOp = DAG.getConstant(Predicate, DL, MVT_CC);
1373 AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1374 unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
1375 return emitConditionalComparison(LHS, RHS, CC, CCOp, ConditionOp, NZCV, DL,
1376 DAG);
Matthias Braun266204b2015-08-20 23:33:31 +00001377 } else if ((Opcode != ISD::AND && Opcode != ISD::OR) || !Val->hasOneUse())
Matthias Braunaf7d7702015-07-16 20:02:37 +00001378 return SDValue();
1379
1380 assert((Opcode == ISD::OR || !PushNegate)
1381 && "Can only push negate through OR operation");
1382
1383 // Check if both sides can be transformed.
1384 SDValue LHS = Val->getOperand(0);
1385 SDValue RHS = Val->getOperand(1);
1386 bool CanPushNegateL;
1387 if (!isConjunctionDisjunctionTree(LHS, CanPushNegateL, Depth+1))
1388 return SDValue();
1389 bool CanPushNegateR;
1390 if (!isConjunctionDisjunctionTree(RHS, CanPushNegateR, Depth+1))
1391 return SDValue();
1392
1393 // Do we need to negate our operands?
1394 bool NegateOperands = Opcode == ISD::OR;
1395 // We can negate the results of all previous operations by inverting the
1396 // predicate flags giving us a free negation for one side. For the other side
1397 // we need to be able to push the negation to the leafs of the tree.
1398 if (NegateOperands) {
1399 if (!CanPushNegateL && !CanPushNegateR)
1400 return SDValue();
1401 // Order the side where we can push the negate through to LHS.
Matthias Braun46e56392015-08-20 23:33:34 +00001402 if (!CanPushNegateL && CanPushNegateR)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001403 std::swap(LHS, RHS);
Matthias Braun46e56392015-08-20 23:33:34 +00001404 } else {
1405 bool NeedsNegOutL = LHS->getOpcode() == ISD::OR;
1406 bool NeedsNegOutR = RHS->getOpcode() == ISD::OR;
1407 if (NeedsNegOutL && NeedsNegOutR)
1408 return SDValue();
1409 // Order the side where we need to negate the output flags to RHS so it
1410 // gets emitted first.
1411 if (NeedsNegOutL)
1412 std::swap(LHS, RHS);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001413 }
1414
1415 // Emit RHS. If we want to negate the tree we only need to push a negate
1416 // through if we are already in a PushNegate case, otherwise we can negate
1417 // the "flags to test" afterwards.
1418 AArch64CC::CondCode RHSCC;
1419 SDValue CmpR = emitConjunctionDisjunctionTree(DAG, RHS, RHSCC, PushNegate,
1420 CCOp, Predicate, Depth+1);
1421 if (NegateOperands && !PushNegate)
1422 RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
1423 // Emit LHS. We must push the negate through if we need to negate it.
1424 SDValue CmpL = emitConjunctionDisjunctionTree(DAG, LHS, OutCC, NegateOperands,
1425 CmpR, RHSCC, Depth+1);
1426 // If we transformed an OR to and AND then we have to negate the result
1427 // (or absorb a PushNegate resulting in a double negation).
1428 if (Opcode == ISD::OR && !PushNegate)
1429 OutCC = AArch64CC::getInvertedCondCode(OutCC);
1430 return CmpL;
1431}
1432
1433/// @}
1434
Tim Northover3b0846e2014-05-24 12:50:23 +00001435static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1436 SDValue &AArch64cc, SelectionDAG &DAG, SDLoc dl) {
1437 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1438 EVT VT = RHS.getValueType();
1439 uint64_t C = RHSC->getZExtValue();
1440 if (!isLegalArithImmed(C)) {
1441 // Constant does not fit, try adjusting it by one?
1442 switch (CC) {
1443 default:
1444 break;
1445 case ISD::SETLT:
1446 case ISD::SETGE:
1447 if ((VT == MVT::i32 && C != 0x80000000 &&
1448 isLegalArithImmed((uint32_t)(C - 1))) ||
1449 (VT == MVT::i64 && C != 0x80000000ULL &&
1450 isLegalArithImmed(C - 1ULL))) {
1451 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1452 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001453 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001454 }
1455 break;
1456 case ISD::SETULT:
1457 case ISD::SETUGE:
1458 if ((VT == MVT::i32 && C != 0 &&
1459 isLegalArithImmed((uint32_t)(C - 1))) ||
1460 (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1461 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1462 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001463 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001464 }
1465 break;
1466 case ISD::SETLE:
1467 case ISD::SETGT:
Oliver Stannard269a275c2014-11-03 15:28:40 +00001468 if ((VT == MVT::i32 && C != INT32_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001469 isLegalArithImmed((uint32_t)(C + 1))) ||
Oliver Stannard269a275c2014-11-03 15:28:40 +00001470 (VT == MVT::i64 && C != INT64_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001471 isLegalArithImmed(C + 1ULL))) {
1472 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1473 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001474 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001475 }
1476 break;
1477 case ISD::SETULE:
1478 case ISD::SETUGT:
Oliver Stannard269a275c2014-11-03 15:28:40 +00001479 if ((VT == MVT::i32 && C != UINT32_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001480 isLegalArithImmed((uint32_t)(C + 1))) ||
Oliver Stannard269a275c2014-11-03 15:28:40 +00001481 (VT == MVT::i64 && C != UINT64_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001482 isLegalArithImmed(C + 1ULL))) {
1483 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1484 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001485 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001486 }
1487 break;
1488 }
1489 }
1490 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001491 SDValue Cmp;
1492 AArch64CC::CondCode AArch64CC;
David Xuee978202014-08-28 04:59:53 +00001493 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001494 const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
1495
1496 // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
1497 // For the i8 operand, the largest immediate is 255, so this can be easily
1498 // encoded in the compare instruction. For the i16 operand, however, the
1499 // largest immediate cannot be encoded in the compare.
1500 // Therefore, use a sign extending load and cmn to avoid materializing the
1501 // -1 constant. For example,
1502 // movz w1, #65535
1503 // ldrh w0, [x0, #0]
1504 // cmp w0, w1
1505 // >
1506 // ldrsh w0, [x0, #0]
1507 // cmn w0, #1
1508 // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
1509 // if and only if (sext LHS) == (sext RHS). The checks are in place to
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001510 // ensure both the LHS and RHS are truly zero extended and to make sure the
Matthias Braunaf7d7702015-07-16 20:02:37 +00001511 // transformation is profitable.
1512 if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
1513 cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
1514 cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
1515 LHS.getNode()->hasNUsesOfValue(1, 0)) {
1516 int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
1517 if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
1518 SDValue SExt =
1519 DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
1520 DAG.getValueType(MVT::i16));
1521 Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
1522 RHS.getValueType()),
1523 CC, dl, DAG);
1524 AArch64CC = changeIntCCToAArch64CC(CC);
1525 }
1526 }
1527
1528 if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
1529 if ((Cmp = emitConjunctionDisjunctionTree(DAG, LHS, AArch64CC))) {
1530 if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
1531 AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
David Xuee978202014-08-28 04:59:53 +00001532 }
1533 }
1534 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001535
1536 if (!Cmp) {
1537 Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
1538 AArch64CC = changeIntCCToAArch64CC(CC);
1539 }
1540 AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
Tim Northover3b0846e2014-05-24 12:50:23 +00001541 return Cmp;
1542}
1543
1544static std::pair<SDValue, SDValue>
1545getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
1546 assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
1547 "Unsupported value type");
1548 SDValue Value, Overflow;
1549 SDLoc DL(Op);
1550 SDValue LHS = Op.getOperand(0);
1551 SDValue RHS = Op.getOperand(1);
1552 unsigned Opc = 0;
1553 switch (Op.getOpcode()) {
1554 default:
1555 llvm_unreachable("Unknown overflow instruction!");
1556 case ISD::SADDO:
1557 Opc = AArch64ISD::ADDS;
1558 CC = AArch64CC::VS;
1559 break;
1560 case ISD::UADDO:
1561 Opc = AArch64ISD::ADDS;
1562 CC = AArch64CC::HS;
1563 break;
1564 case ISD::SSUBO:
1565 Opc = AArch64ISD::SUBS;
1566 CC = AArch64CC::VS;
1567 break;
1568 case ISD::USUBO:
1569 Opc = AArch64ISD::SUBS;
1570 CC = AArch64CC::LO;
1571 break;
1572 // Multiply needs a little bit extra work.
1573 case ISD::SMULO:
1574 case ISD::UMULO: {
1575 CC = AArch64CC::NE;
David Blaikie186d2cb2015-03-24 16:24:01 +00001576 bool IsSigned = Op.getOpcode() == ISD::SMULO;
Tim Northover3b0846e2014-05-24 12:50:23 +00001577 if (Op.getValueType() == MVT::i32) {
1578 unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1579 // For a 32 bit multiply with overflow check we want the instruction
1580 // selector to generate a widening multiply (SMADDL/UMADDL). For that we
1581 // need to generate the following pattern:
1582 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
1583 LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
1584 RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
1585 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1586 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001587 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001588 // On AArch64 the upper 32 bits are always zero extended for a 32 bit
1589 // operation. We need to clear out the upper 32 bits, because we used a
1590 // widening multiply that wrote all 64 bits. In the end this should be a
1591 // noop.
1592 Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
1593 if (IsSigned) {
1594 // The signed overflow check requires more than just a simple check for
1595 // any bit set in the upper 32 bits of the result. These bits could be
1596 // just the sign bits of a negative number. To perform the overflow
1597 // check we have to arithmetic shift right the 32nd bit of the result by
1598 // 31 bits. Then we compare the result to the upper 32 bits.
1599 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001600 DAG.getConstant(32, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001601 UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
1602 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001603 DAG.getConstant(31, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001604 // It is important that LowerBits is last, otherwise the arithmetic
1605 // shift will not be folded into the compare (SUBS).
1606 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
1607 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1608 .getValue(1);
1609 } else {
1610 // The overflow check for unsigned multiply is easy. We only need to
1611 // check if any of the upper 32 bits are set. This can be done with a
1612 // CMP (shifted register). For that we need to generate the following
1613 // pattern:
1614 // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
1615 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001616 DAG.getConstant(32, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001617 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1618 Overflow =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001619 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1620 DAG.getConstant(0, DL, MVT::i64),
Tim Northover3b0846e2014-05-24 12:50:23 +00001621 UpperBits).getValue(1);
1622 }
1623 break;
1624 }
1625 assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
1626 // For the 64 bit multiply
1627 Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1628 if (IsSigned) {
1629 SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
1630 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001631 DAG.getConstant(63, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001632 // It is important that LowerBits is last, otherwise the arithmetic
1633 // shift will not be folded into the compare (SUBS).
1634 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1635 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1636 .getValue(1);
1637 } else {
1638 SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
1639 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1640 Overflow =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001641 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1642 DAG.getConstant(0, DL, MVT::i64),
Tim Northover3b0846e2014-05-24 12:50:23 +00001643 UpperBits).getValue(1);
1644 }
1645 break;
1646 }
1647 } // switch (...)
1648
1649 if (Opc) {
1650 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
1651
1652 // Emit the AArch64 operation with overflow check.
1653 Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
1654 Overflow = Value.getValue(1);
1655 }
1656 return std::make_pair(Value, Overflow);
1657}
1658
1659SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
1660 RTLIB::Libcall Call) const {
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00001661 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
Craig Topper8fe40e02015-10-22 17:05:00 +00001662 return makeLibCall(DAG, Call, MVT::f128, Ops, false, SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00001663}
1664
1665static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
1666 SDValue Sel = Op.getOperand(0);
1667 SDValue Other = Op.getOperand(1);
1668
1669 // If neither operand is a SELECT_CC, give up.
1670 if (Sel.getOpcode() != ISD::SELECT_CC)
1671 std::swap(Sel, Other);
1672 if (Sel.getOpcode() != ISD::SELECT_CC)
1673 return Op;
1674
1675 // The folding we want to perform is:
1676 // (xor x, (select_cc a, b, cc, 0, -1) )
1677 // -->
1678 // (csel x, (xor x, -1), cc ...)
1679 //
1680 // The latter will get matched to a CSINV instruction.
1681
1682 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
1683 SDValue LHS = Sel.getOperand(0);
1684 SDValue RHS = Sel.getOperand(1);
1685 SDValue TVal = Sel.getOperand(2);
1686 SDValue FVal = Sel.getOperand(3);
1687 SDLoc dl(Sel);
1688
1689 // FIXME: This could be generalized to non-integer comparisons.
1690 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
1691 return Op;
1692
1693 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
1694 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
1695
Eric Christopher572e03a2015-06-19 01:53:21 +00001696 // The values aren't constants, this isn't the pattern we're looking for.
Tim Northover3b0846e2014-05-24 12:50:23 +00001697 if (!CFVal || !CTVal)
1698 return Op;
1699
1700 // We can commute the SELECT_CC by inverting the condition. This
1701 // might be needed to make this fit into a CSINV pattern.
1702 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
1703 std::swap(TVal, FVal);
1704 std::swap(CTVal, CFVal);
1705 CC = ISD::getSetCCInverse(CC, true);
1706 }
1707
1708 // If the constants line up, perform the transform!
1709 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
1710 SDValue CCVal;
1711 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
1712
1713 FVal = Other;
1714 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001715 DAG.getConstant(-1ULL, dl, Other.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00001716
1717 return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
1718 CCVal, Cmp);
1719 }
1720
1721 return Op;
1722}
1723
1724static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
1725 EVT VT = Op.getValueType();
1726
1727 // Let legalize expand this if it isn't a legal type yet.
1728 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
1729 return SDValue();
1730
1731 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
1732
1733 unsigned Opc;
1734 bool ExtraOp = false;
1735 switch (Op.getOpcode()) {
1736 default:
Craig Topper2a30d782014-06-18 05:05:13 +00001737 llvm_unreachable("Invalid code");
Tim Northover3b0846e2014-05-24 12:50:23 +00001738 case ISD::ADDC:
1739 Opc = AArch64ISD::ADDS;
1740 break;
1741 case ISD::SUBC:
1742 Opc = AArch64ISD::SUBS;
1743 break;
1744 case ISD::ADDE:
1745 Opc = AArch64ISD::ADCS;
1746 ExtraOp = true;
1747 break;
1748 case ISD::SUBE:
1749 Opc = AArch64ISD::SBCS;
1750 ExtraOp = true;
1751 break;
1752 }
1753
1754 if (!ExtraOp)
1755 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
1756 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
1757 Op.getOperand(2));
1758}
1759
1760static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
1761 // Let legalize expand this if it isn't a legal type yet.
1762 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
1763 return SDValue();
1764
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001765 SDLoc dl(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00001766 AArch64CC::CondCode CC;
1767 // The actual operation that sets the overflow or carry flag.
1768 SDValue Value, Overflow;
1769 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
1770
1771 // We use 0 and 1 as false and true values.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001772 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
1773 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00001774
1775 // We use an inverted condition, because the conditional select is inverted
1776 // too. This will allow it to be selected to a single instruction:
1777 // CSINC Wd, WZR, WZR, invert(cond).
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001778 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
1779 Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
Tim Northover3b0846e2014-05-24 12:50:23 +00001780 CCVal, Overflow);
1781
1782 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001783 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
Tim Northover3b0846e2014-05-24 12:50:23 +00001784}
1785
1786// Prefetch operands are:
1787// 1: Address to prefetch
1788// 2: bool isWrite
1789// 3: int locality (0 = no locality ... 3 = extreme locality)
1790// 4: bool isDataCache
1791static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
1792 SDLoc DL(Op);
1793 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
1794 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
Yi Konge56de692014-08-05 12:46:47 +00001795 unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00001796
1797 bool IsStream = !Locality;
1798 // When the locality number is set
1799 if (Locality) {
1800 // The front-end should have filtered out the out-of-range values
1801 assert(Locality <= 3 && "Prefetch locality out-of-range");
1802 // The locality degree is the opposite of the cache speed.
1803 // Put the number the other way around.
1804 // The encoding starts at 0 for level 1
1805 Locality = 3 - Locality;
1806 }
1807
1808 // built the mask value encoding the expected behavior.
1809 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit
Yi Konge56de692014-08-05 12:46:47 +00001810 (!IsData << 3) | // IsDataCache bit
Tim Northover3b0846e2014-05-24 12:50:23 +00001811 (Locality << 1) | // Cache level bits
1812 (unsigned)IsStream; // Stream bit
1813 return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001814 DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00001815}
1816
1817SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
1818 SelectionDAG &DAG) const {
1819 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
1820
1821 RTLIB::Libcall LC;
1822 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
1823
1824 return LowerF128Call(Op, DAG, LC);
1825}
1826
1827SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
1828 SelectionDAG &DAG) const {
1829 if (Op.getOperand(0).getValueType() != MVT::f128) {
1830 // It's legal except when f128 is involved
1831 return Op;
1832 }
1833
1834 RTLIB::Libcall LC;
1835 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
1836
1837 // FP_ROUND node has a second operand indicating whether it is known to be
1838 // precise. That doesn't take part in the LibCall so we can't directly use
1839 // LowerF128Call.
1840 SDValue SrcVal = Op.getOperand(0);
Craig Topper8fe40e02015-10-22 17:05:00 +00001841 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
1842 SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00001843}
1844
1845static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
1846 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1847 // Any additional optimization in this function should be recorded
1848 // in the cost tables.
1849 EVT InVT = Op.getOperand(0).getValueType();
1850 EVT VT = Op.getValueType();
Pirama Arumuga Nainar1317d5f2015-12-10 17:16:49 +00001851 unsigned NumElts = InVT.getVectorNumElements();
1852
1853 // f16 vectors are promoted to f32 before a conversion.
1854 if (InVT.getVectorElementType() == MVT::f16) {
1855 MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
1856 SDLoc dl(Op);
1857 return DAG.getNode(
1858 Op.getOpcode(), dl, Op.getValueType(),
1859 DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
1860 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001861
Tim Northoverdbecc3b2014-06-15 09:27:15 +00001862 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001863 SDLoc dl(Op);
1864 SDValue Cv =
1865 DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
1866 Op.getOperand(0));
1867 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
Tim Northoverdbecc3b2014-06-15 09:27:15 +00001868 }
1869
1870 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001871 SDLoc dl(Op);
Oliver Stannard89d15422014-08-27 16:16:04 +00001872 MVT ExtVT =
1873 MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
1874 VT.getVectorNumElements());
1875 SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
Tim Northover3b0846e2014-05-24 12:50:23 +00001876 return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
1877 }
1878
1879 // Type changing conversions are illegal.
Tim Northoverdbecc3b2014-06-15 09:27:15 +00001880 return Op;
Tim Northover3b0846e2014-05-24 12:50:23 +00001881}
1882
1883SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
1884 SelectionDAG &DAG) const {
1885 if (Op.getOperand(0).getValueType().isVector())
1886 return LowerVectorFP_TO_INT(Op, DAG);
1887
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00001888 // f16 conversions are promoted to f32.
1889 if (Op.getOperand(0).getValueType() == MVT::f16) {
1890 SDLoc dl(Op);
1891 return DAG.getNode(
1892 Op.getOpcode(), dl, Op.getValueType(),
1893 DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
1894 }
1895
Tim Northover3b0846e2014-05-24 12:50:23 +00001896 if (Op.getOperand(0).getValueType() != MVT::f128) {
1897 // It's legal except when f128 is involved
1898 return Op;
1899 }
1900
1901 RTLIB::Libcall LC;
1902 if (Op.getOpcode() == ISD::FP_TO_SINT)
1903 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
1904 else
1905 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
1906
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00001907 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
Craig Topper8fe40e02015-10-22 17:05:00 +00001908 return makeLibCall(DAG, LC, Op.getValueType(), Ops, false, SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00001909}
1910
1911static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
1912 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1913 // Any additional optimization in this function should be recorded
1914 // in the cost tables.
1915 EVT VT = Op.getValueType();
1916 SDLoc dl(Op);
1917 SDValue In = Op.getOperand(0);
1918 EVT InVT = In.getValueType();
1919
Tim Northoveref0d7602014-06-15 09:27:06 +00001920 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
1921 MVT CastVT =
1922 MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
1923 InVT.getVectorNumElements());
1924 In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001925 return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
Tim Northover3b0846e2014-05-24 12:50:23 +00001926 }
1927
Tim Northoveref0d7602014-06-15 09:27:06 +00001928 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
1929 unsigned CastOpc =
1930 Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1931 EVT CastVT = VT.changeVectorElementTypeToInteger();
1932 In = DAG.getNode(CastOpc, dl, CastVT, In);
1933 return DAG.getNode(Op.getOpcode(), dl, VT, In);
Tim Northover3b0846e2014-05-24 12:50:23 +00001934 }
1935
Tim Northoveref0d7602014-06-15 09:27:06 +00001936 return Op;
Tim Northover3b0846e2014-05-24 12:50:23 +00001937}
1938
1939SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
1940 SelectionDAG &DAG) const {
1941 if (Op.getValueType().isVector())
1942 return LowerVectorINT_TO_FP(Op, DAG);
1943
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00001944 // f16 conversions are promoted to f32.
1945 if (Op.getValueType() == MVT::f16) {
1946 SDLoc dl(Op);
1947 return DAG.getNode(
1948 ISD::FP_ROUND, dl, MVT::f16,
1949 DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001950 DAG.getIntPtrConstant(0, dl));
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00001951 }
1952
Tim Northover3b0846e2014-05-24 12:50:23 +00001953 // i128 conversions are libcalls.
1954 if (Op.getOperand(0).getValueType() == MVT::i128)
1955 return SDValue();
1956
1957 // Other conversions are legal, unless it's to the completely software-based
1958 // fp128.
1959 if (Op.getValueType() != MVT::f128)
1960 return Op;
1961
1962 RTLIB::Libcall LC;
1963 if (Op.getOpcode() == ISD::SINT_TO_FP)
1964 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
1965 else
1966 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
1967
1968 return LowerF128Call(Op, DAG, LC);
1969}
1970
1971SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
1972 SelectionDAG &DAG) const {
1973 // For iOS, we want to call an alternative entry point: __sincos_stret,
1974 // which returns the values in two S / D registers.
1975 SDLoc dl(Op);
1976 SDValue Arg = Op.getOperand(0);
1977 EVT ArgVT = Arg.getValueType();
1978 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
1979
1980 ArgListTy Args;
1981 ArgListEntry Entry;
1982
1983 Entry.Node = Arg;
1984 Entry.Ty = ArgTy;
1985 Entry.isSExt = false;
1986 Entry.isZExt = false;
1987 Args.push_back(Entry);
1988
1989 const char *LibcallName =
1990 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
Mehdi Amini44ede332015-07-09 02:09:04 +00001991 SDValue Callee =
1992 DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00001993
Reid Kleckner343c3952014-11-20 23:51:47 +00001994 StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
Tim Northover3b0846e2014-05-24 12:50:23 +00001995 TargetLowering::CallLoweringInfo CLI(DAG);
1996 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
Juergen Ributzka3bd03c72014-07-01 22:01:54 +00001997 .setCallee(CallingConv::Fast, RetTy, Callee, std::move(Args), 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00001998
1999 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2000 return CallResult.first;
2001}
2002
Tim Northoverf8bfe212014-07-18 13:07:05 +00002003static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
2004 if (Op.getValueType() != MVT::f16)
2005 return SDValue();
2006
2007 assert(Op.getOperand(0).getValueType() == MVT::i16);
2008 SDLoc DL(Op);
2009
2010 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
2011 Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
2012 return SDValue(
2013 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002014 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
Tim Northoverf8bfe212014-07-18 13:07:05 +00002015 0);
2016}
2017
Chad Rosierd9d0f862014-10-08 02:31:24 +00002018static EVT getExtensionTo64Bits(const EVT &OrigVT) {
2019 if (OrigVT.getSizeInBits() >= 64)
2020 return OrigVT;
2021
2022 assert(OrigVT.isSimple() && "Expecting a simple value type");
2023
2024 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
2025 switch (OrigSimpleTy) {
2026 default: llvm_unreachable("Unexpected Vector Type");
2027 case MVT::v2i8:
2028 case MVT::v2i16:
2029 return MVT::v2i32;
2030 case MVT::v4i8:
2031 return MVT::v4i16;
2032 }
2033}
2034
2035static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2036 const EVT &OrigTy,
2037 const EVT &ExtTy,
2038 unsigned ExtOpcode) {
2039 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2040 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2041 // 64-bits we need to insert a new extension so that it will be 64-bits.
2042 assert(ExtTy.is128BitVector() && "Unexpected extension size");
2043 if (OrigTy.getSizeInBits() >= 64)
2044 return N;
2045
2046 // Must extend size to at least 64 bits to be used as an operand for VMULL.
2047 EVT NewVT = getExtensionTo64Bits(OrigTy);
2048
2049 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2050}
2051
2052static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2053 bool isSigned) {
2054 EVT VT = N->getValueType(0);
2055
2056 if (N->getOpcode() != ISD::BUILD_VECTOR)
2057 return false;
2058
Pete Cooper3af9a252015-06-26 18:17:36 +00002059 for (const SDValue &Elt : N->op_values()) {
Chad Rosierd9d0f862014-10-08 02:31:24 +00002060 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
2061 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
2062 unsigned HalfSize = EltSize / 2;
2063 if (isSigned) {
2064 if (!isIntN(HalfSize, C->getSExtValue()))
2065 return false;
2066 } else {
2067 if (!isUIntN(HalfSize, C->getZExtValue()))
2068 return false;
2069 }
2070 continue;
2071 }
2072 return false;
2073 }
2074
2075 return true;
2076}
2077
2078static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2079 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2080 return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2081 N->getOperand(0)->getValueType(0),
2082 N->getValueType(0),
2083 N->getOpcode());
2084
2085 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2086 EVT VT = N->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002087 SDLoc dl(N);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002088 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
2089 unsigned NumElts = VT.getVectorNumElements();
2090 MVT TruncVT = MVT::getIntegerVT(EltSize);
2091 SmallVector<SDValue, 8> Ops;
2092 for (unsigned i = 0; i != NumElts; ++i) {
2093 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2094 const APInt &CInt = C->getAPIntValue();
2095 // Element types smaller than 32 bits are not legal, so use i32 elements.
2096 // The values are implicitly truncated so sext vs. zext doesn't matter.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002097 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
Chad Rosierd9d0f862014-10-08 02:31:24 +00002098 }
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002099 return DAG.getNode(ISD::BUILD_VECTOR, dl,
Chad Rosierd9d0f862014-10-08 02:31:24 +00002100 MVT::getVectorVT(TruncVT, NumElts), Ops);
2101}
2102
2103static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
2104 if (N->getOpcode() == ISD::SIGN_EXTEND)
2105 return true;
2106 if (isExtendedBUILD_VECTOR(N, DAG, true))
2107 return true;
2108 return false;
2109}
2110
2111static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
2112 if (N->getOpcode() == ISD::ZERO_EXTEND)
2113 return true;
2114 if (isExtendedBUILD_VECTOR(N, DAG, false))
2115 return true;
2116 return false;
2117}
2118
2119static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2120 unsigned Opcode = N->getOpcode();
2121 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2122 SDNode *N0 = N->getOperand(0).getNode();
2123 SDNode *N1 = N->getOperand(1).getNode();
2124 return N0->hasOneUse() && N1->hasOneUse() &&
2125 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2126 }
2127 return false;
2128}
2129
2130static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2131 unsigned Opcode = N->getOpcode();
2132 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2133 SDNode *N0 = N->getOperand(0).getNode();
2134 SDNode *N1 = N->getOperand(1).getNode();
2135 return N0->hasOneUse() && N1->hasOneUse() &&
2136 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2137 }
2138 return false;
2139}
2140
2141static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2142 // Multiplications are only custom-lowered for 128-bit vectors so that
2143 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
2144 EVT VT = Op.getValueType();
2145 assert(VT.is128BitVector() && VT.isInteger() &&
2146 "unexpected type for custom-lowering ISD::MUL");
2147 SDNode *N0 = Op.getOperand(0).getNode();
2148 SDNode *N1 = Op.getOperand(1).getNode();
2149 unsigned NewOpc = 0;
2150 bool isMLA = false;
2151 bool isN0SExt = isSignExtended(N0, DAG);
2152 bool isN1SExt = isSignExtended(N1, DAG);
2153 if (isN0SExt && isN1SExt)
2154 NewOpc = AArch64ISD::SMULL;
2155 else {
2156 bool isN0ZExt = isZeroExtended(N0, DAG);
2157 bool isN1ZExt = isZeroExtended(N1, DAG);
2158 if (isN0ZExt && isN1ZExt)
2159 NewOpc = AArch64ISD::UMULL;
2160 else if (isN1SExt || isN1ZExt) {
2161 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2162 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2163 if (isN1SExt && isAddSubSExt(N0, DAG)) {
2164 NewOpc = AArch64ISD::SMULL;
2165 isMLA = true;
2166 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2167 NewOpc = AArch64ISD::UMULL;
2168 isMLA = true;
2169 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2170 std::swap(N0, N1);
2171 NewOpc = AArch64ISD::UMULL;
2172 isMLA = true;
2173 }
2174 }
2175
2176 if (!NewOpc) {
2177 if (VT == MVT::v2i64)
2178 // Fall through to expand this. It is not legal.
2179 return SDValue();
2180 else
2181 // Other vector multiplications are legal.
2182 return Op;
2183 }
2184 }
2185
2186 // Legalize to a S/UMULL instruction
2187 SDLoc DL(Op);
2188 SDValue Op0;
2189 SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2190 if (!isMLA) {
2191 Op0 = skipExtensionForVectorMULL(N0, DAG);
2192 assert(Op0.getValueType().is64BitVector() &&
2193 Op1.getValueType().is64BitVector() &&
2194 "unexpected types for extended operands to VMULL");
2195 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2196 }
2197 // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2198 // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2199 // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2200 SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2201 SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2202 EVT Op1VT = Op1.getValueType();
2203 return DAG.getNode(N0->getOpcode(), DL, VT,
2204 DAG.getNode(NewOpc, DL, VT,
2205 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2206 DAG.getNode(NewOpc, DL, VT,
2207 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2208}
Tim Northoverf8bfe212014-07-18 13:07:05 +00002209
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002210SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2211 SelectionDAG &DAG) const {
2212 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2213 SDLoc dl(Op);
2214 switch (IntNo) {
2215 default: return SDValue(); // Don't custom lower most intrinsics.
2216 case Intrinsic::aarch64_thread_pointer: {
2217 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2218 return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
2219 }
Silviu Barangadb1ddb32015-08-26 11:11:14 +00002220 case Intrinsic::aarch64_neon_smax:
2221 return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
2222 Op.getOperand(1), Op.getOperand(2));
2223 case Intrinsic::aarch64_neon_umax:
2224 return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
2225 Op.getOperand(1), Op.getOperand(2));
2226 case Intrinsic::aarch64_neon_smin:
2227 return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
2228 Op.getOperand(1), Op.getOperand(2));
2229 case Intrinsic::aarch64_neon_umin:
2230 return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
2231 Op.getOperand(1), Op.getOperand(2));
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002232 }
2233}
2234
Tim Northover3b0846e2014-05-24 12:50:23 +00002235SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
2236 SelectionDAG &DAG) const {
2237 switch (Op.getOpcode()) {
2238 default:
2239 llvm_unreachable("unimplemented operand");
2240 return SDValue();
Tim Northoverf8bfe212014-07-18 13:07:05 +00002241 case ISD::BITCAST:
2242 return LowerBITCAST(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002243 case ISD::GlobalAddress:
2244 return LowerGlobalAddress(Op, DAG);
2245 case ISD::GlobalTLSAddress:
2246 return LowerGlobalTLSAddress(Op, DAG);
2247 case ISD::SETCC:
2248 return LowerSETCC(Op, DAG);
2249 case ISD::BR_CC:
2250 return LowerBR_CC(Op, DAG);
2251 case ISD::SELECT:
2252 return LowerSELECT(Op, DAG);
2253 case ISD::SELECT_CC:
2254 return LowerSELECT_CC(Op, DAG);
2255 case ISD::JumpTable:
2256 return LowerJumpTable(Op, DAG);
2257 case ISD::ConstantPool:
2258 return LowerConstantPool(Op, DAG);
2259 case ISD::BlockAddress:
2260 return LowerBlockAddress(Op, DAG);
2261 case ISD::VASTART:
2262 return LowerVASTART(Op, DAG);
2263 case ISD::VACOPY:
2264 return LowerVACOPY(Op, DAG);
2265 case ISD::VAARG:
2266 return LowerVAARG(Op, DAG);
2267 case ISD::ADDC:
2268 case ISD::ADDE:
2269 case ISD::SUBC:
2270 case ISD::SUBE:
2271 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
2272 case ISD::SADDO:
2273 case ISD::UADDO:
2274 case ISD::SSUBO:
2275 case ISD::USUBO:
2276 case ISD::SMULO:
2277 case ISD::UMULO:
2278 return LowerXALUO(Op, DAG);
2279 case ISD::FADD:
2280 return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
2281 case ISD::FSUB:
2282 return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
2283 case ISD::FMUL:
2284 return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
2285 case ISD::FDIV:
2286 return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
2287 case ISD::FP_ROUND:
2288 return LowerFP_ROUND(Op, DAG);
2289 case ISD::FP_EXTEND:
2290 return LowerFP_EXTEND(Op, DAG);
2291 case ISD::FRAMEADDR:
2292 return LowerFRAMEADDR(Op, DAG);
2293 case ISD::RETURNADDR:
2294 return LowerRETURNADDR(Op, DAG);
2295 case ISD::INSERT_VECTOR_ELT:
2296 return LowerINSERT_VECTOR_ELT(Op, DAG);
2297 case ISD::EXTRACT_VECTOR_ELT:
2298 return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2299 case ISD::BUILD_VECTOR:
2300 return LowerBUILD_VECTOR(Op, DAG);
2301 case ISD::VECTOR_SHUFFLE:
2302 return LowerVECTOR_SHUFFLE(Op, DAG);
2303 case ISD::EXTRACT_SUBVECTOR:
2304 return LowerEXTRACT_SUBVECTOR(Op, DAG);
2305 case ISD::SRA:
2306 case ISD::SRL:
2307 case ISD::SHL:
2308 return LowerVectorSRA_SRL_SHL(Op, DAG);
2309 case ISD::SHL_PARTS:
2310 return LowerShiftLeftParts(Op, DAG);
2311 case ISD::SRL_PARTS:
2312 case ISD::SRA_PARTS:
2313 return LowerShiftRightParts(Op, DAG);
2314 case ISD::CTPOP:
2315 return LowerCTPOP(Op, DAG);
2316 case ISD::FCOPYSIGN:
2317 return LowerFCOPYSIGN(Op, DAG);
2318 case ISD::AND:
2319 return LowerVectorAND(Op, DAG);
2320 case ISD::OR:
2321 return LowerVectorOR(Op, DAG);
2322 case ISD::XOR:
2323 return LowerXOR(Op, DAG);
2324 case ISD::PREFETCH:
2325 return LowerPREFETCH(Op, DAG);
2326 case ISD::SINT_TO_FP:
2327 case ISD::UINT_TO_FP:
2328 return LowerINT_TO_FP(Op, DAG);
2329 case ISD::FP_TO_SINT:
2330 case ISD::FP_TO_UINT:
2331 return LowerFP_TO_INT(Op, DAG);
2332 case ISD::FSINCOS:
2333 return LowerFSINCOS(Op, DAG);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002334 case ISD::MUL:
2335 return LowerMUL(Op, DAG);
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002336 case ISD::INTRINSIC_WO_CHAIN:
2337 return LowerINTRINSIC_WO_CHAIN(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002338 }
2339}
2340
2341/// getFunctionAlignment - Return the Log2 alignment of this function.
2342unsigned AArch64TargetLowering::getFunctionAlignment(const Function *F) const {
2343 return 2;
2344}
2345
2346//===----------------------------------------------------------------------===//
2347// Calling Convention Implementation
2348//===----------------------------------------------------------------------===//
2349
2350#include "AArch64GenCallingConv.inc"
2351
Robin Morisset039781e2014-08-29 21:53:01 +00002352/// Selects the correct CCAssignFn for a given CallingConvention value.
Tim Northover3b0846e2014-05-24 12:50:23 +00002353CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2354 bool IsVarArg) const {
2355 switch (CC) {
2356 default:
2357 llvm_unreachable("Unsupported calling convention.");
2358 case CallingConv::WebKit_JS:
2359 return CC_AArch64_WebKit_JS;
Greg Fitzgeraldfa78d082015-01-19 17:40:05 +00002360 case CallingConv::GHC:
2361 return CC_AArch64_GHC;
Tim Northover3b0846e2014-05-24 12:50:23 +00002362 case CallingConv::C:
2363 case CallingConv::Fast:
2364 if (!Subtarget->isTargetDarwin())
2365 return CC_AArch64_AAPCS;
2366 return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
2367 }
2368}
2369
2370SDValue AArch64TargetLowering::LowerFormalArguments(
2371 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2372 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2373 SmallVectorImpl<SDValue> &InVals) const {
2374 MachineFunction &MF = DAG.getMachineFunction();
2375 MachineFrameInfo *MFI = MF.getFrameInfo();
2376
2377 // Assign locations to all of the incoming arguments.
2378 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002379 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2380 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002381
2382 // At this point, Ins[].VT may already be promoted to i32. To correctly
2383 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2384 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2385 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
2386 // we use a special version of AnalyzeFormalArguments to pass in ValVT and
2387 // LocVT.
2388 unsigned NumArgs = Ins.size();
2389 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2390 unsigned CurArgIdx = 0;
2391 for (unsigned i = 0; i != NumArgs; ++i) {
2392 MVT ValVT = Ins[i].VT;
Andrew Trick05938a52015-02-16 18:10:47 +00002393 if (Ins[i].isOrigArg()) {
2394 std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
2395 CurArgIdx = Ins[i].getOrigArgIndex();
Tim Northover3b0846e2014-05-24 12:50:23 +00002396
Andrew Trick05938a52015-02-16 18:10:47 +00002397 // Get type of the original argument.
Mehdi Amini44ede332015-07-09 02:09:04 +00002398 EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
2399 /*AllowUnknown*/ true);
Andrew Trick05938a52015-02-16 18:10:47 +00002400 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
2401 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2402 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2403 ValVT = MVT::i8;
2404 else if (ActualMVT == MVT::i16)
2405 ValVT = MVT::i16;
2406 }
Tim Northover3b0846e2014-05-24 12:50:23 +00002407 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2408 bool Res =
Tim Northover47e003c2014-05-26 17:21:53 +00002409 AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00002410 assert(!Res && "Call operand has unhandled type");
2411 (void)Res;
2412 }
2413 assert(ArgLocs.size() == Ins.size());
2414 SmallVector<SDValue, 16> ArgValues;
2415 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2416 CCValAssign &VA = ArgLocs[i];
2417
2418 if (Ins[i].Flags.isByVal()) {
2419 // Byval is used for HFAs in the PCS, but the system should work in a
2420 // non-compliant manner for larger structs.
Mehdi Amini44ede332015-07-09 02:09:04 +00002421 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00002422 int Size = Ins[i].Flags.getByValSize();
2423 unsigned NumRegs = (Size + 7) / 8;
2424
2425 // FIXME: This works on big-endian for composite byvals, which are the common
2426 // case. It should also work for fundamental types too.
2427 unsigned FrameIdx =
2428 MFI->CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
Mehdi Amini44ede332015-07-09 02:09:04 +00002429 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00002430 InVals.push_back(FrameIdxN);
2431
2432 continue;
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002433 }
2434
2435 if (VA.isRegLoc()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00002436 // Arguments stored in registers.
2437 EVT RegVT = VA.getLocVT();
2438
2439 SDValue ArgValue;
2440 const TargetRegisterClass *RC;
2441
2442 if (RegVT == MVT::i32)
2443 RC = &AArch64::GPR32RegClass;
2444 else if (RegVT == MVT::i64)
2445 RC = &AArch64::GPR64RegClass;
Oliver Stannard6eda6ff2014-07-11 13:33:46 +00002446 else if (RegVT == MVT::f16)
2447 RC = &AArch64::FPR16RegClass;
Tim Northover3b0846e2014-05-24 12:50:23 +00002448 else if (RegVT == MVT::f32)
2449 RC = &AArch64::FPR32RegClass;
2450 else if (RegVT == MVT::f64 || RegVT.is64BitVector())
2451 RC = &AArch64::FPR64RegClass;
2452 else if (RegVT == MVT::f128 || RegVT.is128BitVector())
2453 RC = &AArch64::FPR128RegClass;
2454 else
2455 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2456
2457 // Transform the arguments in physical registers into virtual ones.
2458 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2459 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2460
2461 // If this is an 8, 16 or 32-bit value, it is really passed promoted
2462 // to 64 bits. Insert an assert[sz]ext to capture this, then
2463 // truncate to the right size.
2464 switch (VA.getLocInfo()) {
2465 default:
2466 llvm_unreachable("Unknown loc info!");
2467 case CCValAssign::Full:
2468 break;
2469 case CCValAssign::BCvt:
2470 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
2471 break;
Tim Northover47e003c2014-05-26 17:21:53 +00002472 case CCValAssign::AExt:
Tim Northover3b0846e2014-05-24 12:50:23 +00002473 case CCValAssign::SExt:
Tim Northover3b0846e2014-05-24 12:50:23 +00002474 case CCValAssign::ZExt:
Tim Northover47e003c2014-05-26 17:21:53 +00002475 // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
2476 // nodes after our lowering.
2477 assert(RegVT == Ins[i].VT && "incorrect register location selected");
Tim Northover3b0846e2014-05-24 12:50:23 +00002478 break;
2479 }
2480
2481 InVals.push_back(ArgValue);
2482
2483 } else { // VA.isRegLoc()
2484 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
2485 unsigned ArgOffset = VA.getLocMemOffset();
Amara Emerson82da7d02014-08-15 14:29:57 +00002486 unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
Tim Northover3b0846e2014-05-24 12:50:23 +00002487
2488 uint32_t BEAlign = 0;
Tim Northover293d4142014-12-03 17:49:26 +00002489 if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
2490 !Ins[i].Flags.isInConsecutiveRegs())
Tim Northover3b0846e2014-05-24 12:50:23 +00002491 BEAlign = 8 - ArgSize;
2492
2493 int FI = MFI->CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
2494
2495 // Create load nodes to retrieve arguments from the stack.
Mehdi Amini44ede332015-07-09 02:09:04 +00002496 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00002497 SDValue ArgValue;
2498
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002499 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
Tim Northover47e003c2014-05-26 17:21:53 +00002500 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002501 MVT MemVT = VA.getValVT();
2502
Tim Northover47e003c2014-05-26 17:21:53 +00002503 switch (VA.getLocInfo()) {
2504 default:
2505 break;
Tim Northover6890add2014-06-03 13:54:53 +00002506 case CCValAssign::BCvt:
2507 MemVT = VA.getLocVT();
2508 break;
Tim Northover47e003c2014-05-26 17:21:53 +00002509 case CCValAssign::SExt:
2510 ExtType = ISD::SEXTLOAD;
2511 break;
2512 case CCValAssign::ZExt:
2513 ExtType = ISD::ZEXTLOAD;
2514 break;
2515 case CCValAssign::AExt:
2516 ExtType = ISD::EXTLOAD;
2517 break;
Tim Northover3b0846e2014-05-24 12:50:23 +00002518 }
2519
Alex Lorenze40c8a22015-08-11 23:09:45 +00002520 ArgValue = DAG.getExtLoad(
2521 ExtType, DL, VA.getLocVT(), Chain, FIN,
2522 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
2523 MemVT, false, false, false, 0);
Tim Northover47e003c2014-05-26 17:21:53 +00002524
Tim Northover3b0846e2014-05-24 12:50:23 +00002525 InVals.push_back(ArgValue);
2526 }
2527 }
2528
2529 // varargs
2530 if (isVarArg) {
2531 if (!Subtarget->isTargetDarwin()) {
2532 // The AAPCS variadic function ABI is identical to the non-variadic
2533 // one. As a result there may be more arguments in registers and we should
2534 // save them for future reference.
2535 saveVarArgRegisters(CCInfo, DAG, DL, Chain);
2536 }
2537
2538 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
2539 // This will point to the next argument passed via stack.
2540 unsigned StackOffset = CCInfo.getNextStackOffset();
2541 // We currently pass all varargs at 8-byte alignment.
2542 StackOffset = ((StackOffset + 7) & ~7);
2543 AFI->setVarArgsStackIndex(MFI->CreateFixedObject(4, StackOffset, true));
2544 }
2545
2546 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2547 unsigned StackArgSize = CCInfo.getNextStackOffset();
2548 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2549 if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
2550 // This is a non-standard ABI so by fiat I say we're allowed to make full
2551 // use of the stack area to be popped, which must be aligned to 16 bytes in
2552 // any case:
2553 StackArgSize = RoundUpToAlignment(StackArgSize, 16);
2554
2555 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
2556 // a multiple of 16.
2557 FuncInfo->setArgumentStackToRestore(StackArgSize);
2558
2559 // This realignment carries over to the available bytes below. Our own
2560 // callers will guarantee the space is free by giving an aligned value to
2561 // CALLSEQ_START.
2562 }
2563 // Even if we're not expected to free up the space, it's useful to know how
2564 // much is there while considering tail calls (because we can reuse it).
2565 FuncInfo->setBytesInStackArgArea(StackArgSize);
2566
2567 return Chain;
2568}
2569
2570void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
2571 SelectionDAG &DAG, SDLoc DL,
2572 SDValue &Chain) const {
2573 MachineFunction &MF = DAG.getMachineFunction();
2574 MachineFrameInfo *MFI = MF.getFrameInfo();
2575 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Mehdi Amini44ede332015-07-09 02:09:04 +00002576 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00002577
2578 SmallVector<SDValue, 8> MemOps;
2579
2580 static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
2581 AArch64::X3, AArch64::X4, AArch64::X5,
2582 AArch64::X6, AArch64::X7 };
2583 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
Tim Northover3b6b7ca2015-02-21 02:11:17 +00002584 unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
Tim Northover3b0846e2014-05-24 12:50:23 +00002585
2586 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
2587 int GPRIdx = 0;
2588 if (GPRSaveSize != 0) {
2589 GPRIdx = MFI->CreateStackObject(GPRSaveSize, 8, false);
2590
Mehdi Amini44ede332015-07-09 02:09:04 +00002591 SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00002592
2593 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
2594 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
2595 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
Alex Lorenze40c8a22015-08-11 23:09:45 +00002596 SDValue Store = DAG.getStore(
2597 Val.getValue(1), DL, Val, FIN,
2598 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8), false,
2599 false, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00002600 MemOps.push_back(Store);
Mehdi Amini44ede332015-07-09 02:09:04 +00002601 FIN =
2602 DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00002603 }
2604 }
2605 FuncInfo->setVarArgsGPRIndex(GPRIdx);
2606 FuncInfo->setVarArgsGPRSize(GPRSaveSize);
2607
2608 if (Subtarget->hasFPARMv8()) {
2609 static const MCPhysReg FPRArgRegs[] = {
2610 AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
2611 AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
2612 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
Tim Northover3b6b7ca2015-02-21 02:11:17 +00002613 unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
Tim Northover3b0846e2014-05-24 12:50:23 +00002614
2615 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
2616 int FPRIdx = 0;
2617 if (FPRSaveSize != 0) {
2618 FPRIdx = MFI->CreateStackObject(FPRSaveSize, 16, false);
2619
Mehdi Amini44ede332015-07-09 02:09:04 +00002620 SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00002621
2622 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
2623 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
2624 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
2625
Alex Lorenze40c8a22015-08-11 23:09:45 +00002626 SDValue Store = DAG.getStore(
2627 Val.getValue(1), DL, Val, FIN,
2628 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16),
2629 false, false, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00002630 MemOps.push_back(Store);
Mehdi Amini44ede332015-07-09 02:09:04 +00002631 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
2632 DAG.getConstant(16, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00002633 }
2634 }
2635 FuncInfo->setVarArgsFPRIndex(FPRIdx);
2636 FuncInfo->setVarArgsFPRSize(FPRSaveSize);
2637 }
2638
2639 if (!MemOps.empty()) {
2640 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
2641 }
2642}
2643
2644/// LowerCallResult - Lower the result values of a call into the
2645/// appropriate copies out of appropriate physical registers.
2646SDValue AArch64TargetLowering::LowerCallResult(
2647 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
2648 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2649 SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
2650 SDValue ThisVal) const {
2651 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
2652 ? RetCC_AArch64_WebKit_JS
2653 : RetCC_AArch64_AAPCS;
2654 // Assign locations to each value returned by this call.
2655 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002656 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2657 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002658 CCInfo.AnalyzeCallResult(Ins, RetCC);
2659
2660 // Copy all of the result registers out of their specified physreg.
2661 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2662 CCValAssign VA = RVLocs[i];
2663
2664 // Pass 'this' value directly from the argument to return value, to avoid
2665 // reg unit interference
2666 if (i == 0 && isThisReturn) {
2667 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
2668 "unexpected return calling convention register assignment");
2669 InVals.push_back(ThisVal);
2670 continue;
2671 }
2672
2673 SDValue Val =
2674 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2675 Chain = Val.getValue(1);
2676 InFlag = Val.getValue(2);
2677
2678 switch (VA.getLocInfo()) {
2679 default:
2680 llvm_unreachable("Unknown loc info!");
2681 case CCValAssign::Full:
2682 break;
2683 case CCValAssign::BCvt:
2684 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2685 break;
2686 }
2687
2688 InVals.push_back(Val);
2689 }
2690
2691 return Chain;
2692}
2693
2694bool AArch64TargetLowering::isEligibleForTailCallOptimization(
2695 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
2696 bool isCalleeStructRet, bool isCallerStructRet,
2697 const SmallVectorImpl<ISD::OutputArg> &Outs,
2698 const SmallVectorImpl<SDValue> &OutVals,
2699 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2700 // For CallingConv::C this function knows whether the ABI needs
2701 // changing. That's not true for other conventions so they will have to opt in
2702 // manually.
2703 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
2704 return false;
2705
2706 const MachineFunction &MF = DAG.getMachineFunction();
2707 const Function *CallerF = MF.getFunction();
2708 CallingConv::ID CallerCC = CallerF->getCallingConv();
2709 bool CCMatch = CallerCC == CalleeCC;
2710
2711 // Byval parameters hand the function a pointer directly into the stack area
2712 // we want to reuse during a tail call. Working around this *is* possible (see
2713 // X86) but less efficient and uglier in LowerCall.
2714 for (Function::const_arg_iterator i = CallerF->arg_begin(),
2715 e = CallerF->arg_end();
2716 i != e; ++i)
2717 if (i->hasByValAttr())
2718 return false;
2719
2720 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
2721 if (IsTailCallConvention(CalleeCC) && CCMatch)
2722 return true;
2723 return false;
2724 }
2725
Oliver Stannard12993dd2014-08-18 12:42:15 +00002726 // Externally-defined functions with weak linkage should not be
2727 // tail-called on AArch64 when the OS does not support dynamic
2728 // pre-emption of symbols, as the AAELF spec requires normal calls
2729 // to undefined weak functions to be replaced with a NOP or jump to the
2730 // next instruction. The behaviour of branch instructions in this
2731 // situation (as used for tail calls) is implementation-defined, so we
2732 // cannot rely on the linker replacing the tail call with a return.
2733 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2734 const GlobalValue *GV = G->getGlobal();
Daniel Sandersc81f4502015-06-16 15:44:21 +00002735 const Triple &TT = getTargetMachine().getTargetTriple();
Saleem Abdulrasool67f72992015-01-03 21:35:00 +00002736 if (GV->hasExternalWeakLinkage() &&
2737 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
Oliver Stannard12993dd2014-08-18 12:42:15 +00002738 return false;
2739 }
2740
Tim Northover3b0846e2014-05-24 12:50:23 +00002741 // Now we search for cases where we can use a tail call without changing the
2742 // ABI. Sibcall is used in some places (particularly gcc) to refer to this
2743 // concept.
2744
2745 // I want anyone implementing a new calling convention to think long and hard
2746 // about this assert.
2747 assert((!isVarArg || CalleeCC == CallingConv::C) &&
2748 "Unexpected variadic calling convention");
2749
2750 if (isVarArg && !Outs.empty()) {
2751 // At least two cases here: if caller is fastcc then we can't have any
2752 // memory arguments (we'd be expected to clean up the stack afterwards). If
2753 // caller is C then we could potentially use its argument area.
2754
2755 // FIXME: for now we take the most conservative of these in both cases:
2756 // disallow all variadic memory operands.
2757 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002758 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2759 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002760
2761 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
Pete Cooper7be8f8f2015-08-03 19:04:32 +00002762 for (const CCValAssign &ArgLoc : ArgLocs)
2763 if (!ArgLoc.isRegLoc())
Tim Northover3b0846e2014-05-24 12:50:23 +00002764 return false;
2765 }
2766
2767 // If the calling conventions do not match, then we'd better make sure the
2768 // results are returned in the same way as what the caller expects.
2769 if (!CCMatch) {
2770 SmallVector<CCValAssign, 16> RVLocs1;
Eric Christopherb5217502014-08-06 18:45:26 +00002771 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2772 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002773 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForCall(CalleeCC, isVarArg));
2774
2775 SmallVector<CCValAssign, 16> RVLocs2;
Eric Christopherb5217502014-08-06 18:45:26 +00002776 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2777 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002778 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForCall(CallerCC, isVarArg));
2779
2780 if (RVLocs1.size() != RVLocs2.size())
2781 return false;
2782 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2783 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2784 return false;
2785 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2786 return false;
2787 if (RVLocs1[i].isRegLoc()) {
2788 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2789 return false;
2790 } else {
2791 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2792 return false;
2793 }
2794 }
2795 }
2796
2797 // Nothing more to check if the callee is taking no arguments
2798 if (Outs.empty())
2799 return true;
2800
2801 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002802 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2803 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002804
2805 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2806
2807 const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2808
2809 // If the stack arguments for this call would fit into our own save area then
2810 // the call can be made tail.
2811 return CCInfo.getNextStackOffset() <= FuncInfo->getBytesInStackArgArea();
2812}
2813
2814SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
2815 SelectionDAG &DAG,
2816 MachineFrameInfo *MFI,
2817 int ClobberedFI) const {
2818 SmallVector<SDValue, 8> ArgChains;
2819 int64_t FirstByte = MFI->getObjectOffset(ClobberedFI);
2820 int64_t LastByte = FirstByte + MFI->getObjectSize(ClobberedFI) - 1;
2821
2822 // Include the original chain at the beginning of the list. When this is
2823 // used by target LowerCall hooks, this helps legalize find the
2824 // CALLSEQ_BEGIN node.
2825 ArgChains.push_back(Chain);
2826
2827 // Add a chain value for each stack argument corresponding
2828 for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
2829 UE = DAG.getEntryNode().getNode()->use_end();
2830 U != UE; ++U)
2831 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
2832 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
2833 if (FI->getIndex() < 0) {
2834 int64_t InFirstByte = MFI->getObjectOffset(FI->getIndex());
2835 int64_t InLastByte = InFirstByte;
2836 InLastByte += MFI->getObjectSize(FI->getIndex()) - 1;
2837
2838 if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
2839 (FirstByte <= InFirstByte && InFirstByte <= LastByte))
2840 ArgChains.push_back(SDValue(L, 1));
2841 }
2842
2843 // Build a tokenfactor for all the chains.
2844 return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
2845}
2846
2847bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
2848 bool TailCallOpt) const {
2849 return CallCC == CallingConv::Fast && TailCallOpt;
2850}
2851
2852bool AArch64TargetLowering::IsTailCallConvention(CallingConv::ID CallCC) const {
2853 return CallCC == CallingConv::Fast;
2854}
2855
2856/// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
2857/// and add input and output parameter nodes.
2858SDValue
2859AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
2860 SmallVectorImpl<SDValue> &InVals) const {
2861 SelectionDAG &DAG = CLI.DAG;
2862 SDLoc &DL = CLI.DL;
2863 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2864 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2865 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2866 SDValue Chain = CLI.Chain;
2867 SDValue Callee = CLI.Callee;
2868 bool &IsTailCall = CLI.IsTailCall;
2869 CallingConv::ID CallConv = CLI.CallConv;
2870 bool IsVarArg = CLI.IsVarArg;
2871
2872 MachineFunction &MF = DAG.getMachineFunction();
2873 bool IsStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
2874 bool IsThisReturn = false;
2875
2876 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2877 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2878 bool IsSibCall = false;
2879
2880 if (IsTailCall) {
2881 // Check if it's really possible to do a tail call.
2882 IsTailCall = isEligibleForTailCallOptimization(
2883 Callee, CallConv, IsVarArg, IsStructRet,
2884 MF.getFunction()->hasStructRetAttr(), Outs, OutVals, Ins, DAG);
2885 if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
2886 report_fatal_error("failed to perform tail call elimination on a call "
2887 "site marked musttail");
2888
2889 // A sibling call is one where we're under the usual C ABI and not planning
2890 // to change that but can still do a tail call:
2891 if (!TailCallOpt && IsTailCall)
2892 IsSibCall = true;
2893
2894 if (IsTailCall)
2895 ++NumTailCalls;
2896 }
2897
2898 // Analyze operands of the call, assigning locations to each operand.
2899 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002900 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
2901 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002902
2903 if (IsVarArg) {
2904 // Handle fixed and variable vector arguments differently.
2905 // Variable vector arguments always go into memory.
2906 unsigned NumArgs = Outs.size();
2907
2908 for (unsigned i = 0; i != NumArgs; ++i) {
2909 MVT ArgVT = Outs[i].VT;
2910 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2911 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
2912 /*IsVarArg=*/ !Outs[i].IsFixed);
2913 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
2914 assert(!Res && "Call operand has unhandled type");
2915 (void)Res;
2916 }
2917 } else {
2918 // At this point, Outs[].VT may already be promoted to i32. To correctly
2919 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2920 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2921 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
2922 // we use a special version of AnalyzeCallOperands to pass in ValVT and
2923 // LocVT.
2924 unsigned NumArgs = Outs.size();
2925 for (unsigned i = 0; i != NumArgs; ++i) {
2926 MVT ValVT = Outs[i].VT;
2927 // Get type of the original argument.
Mehdi Amini44ede332015-07-09 02:09:04 +00002928 EVT ActualVT = getValueType(DAG.getDataLayout(),
2929 CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
Tim Northover3b0846e2014-05-24 12:50:23 +00002930 /*AllowUnknown*/ true);
2931 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
2932 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2933 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
Tim Northover3b0846e2014-05-24 12:50:23 +00002934 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
Tim Northover47e003c2014-05-26 17:21:53 +00002935 ValVT = MVT::i8;
Tim Northover3b0846e2014-05-24 12:50:23 +00002936 else if (ActualMVT == MVT::i16)
Tim Northover47e003c2014-05-26 17:21:53 +00002937 ValVT = MVT::i16;
Tim Northover3b0846e2014-05-24 12:50:23 +00002938
2939 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
Tim Northover47e003c2014-05-26 17:21:53 +00002940 bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00002941 assert(!Res && "Call operand has unhandled type");
2942 (void)Res;
2943 }
2944 }
2945
2946 // Get a count of how many bytes are to be pushed on the stack.
2947 unsigned NumBytes = CCInfo.getNextStackOffset();
2948
2949 if (IsSibCall) {
2950 // Since we're not changing the ABI to make this a tail call, the memory
2951 // operands are already available in the caller's incoming argument space.
2952 NumBytes = 0;
2953 }
2954
2955 // FPDiff is the byte offset of the call's argument area from the callee's.
2956 // Stores to callee stack arguments will be placed in FixedStackSlots offset
2957 // by this amount for a tail call. In a sibling call it must be 0 because the
2958 // caller will deallocate the entire stack and the callee still expects its
2959 // arguments to begin at SP+0. Completely unused for non-tail calls.
2960 int FPDiff = 0;
2961
2962 if (IsTailCall && !IsSibCall) {
2963 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
2964
2965 // Since callee will pop argument stack as a tail call, we must keep the
2966 // popped size 16-byte aligned.
2967 NumBytes = RoundUpToAlignment(NumBytes, 16);
2968
2969 // FPDiff will be negative if this tail call requires more space than we
2970 // would automatically have in our incoming argument space. Positive if we
2971 // can actually shrink the stack.
2972 FPDiff = NumReusableBytes - NumBytes;
2973
2974 // The stack pointer must be 16-byte aligned at all times it's used for a
2975 // memory operation, which in practice means at *all* times and in
2976 // particular across call boundaries. Therefore our own arguments started at
2977 // a 16-byte aligned SP and the delta applied for the tail call should
2978 // satisfy the same constraint.
2979 assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
2980 }
2981
2982 // Adjust the stack pointer for the new arguments...
2983 // These operations are automatically eliminated by the prolog/epilog pass
2984 if (!IsSibCall)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002985 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, DL,
2986 true),
2987 DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00002988
Mehdi Amini44ede332015-07-09 02:09:04 +00002989 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
2990 getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00002991
2992 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2993 SmallVector<SDValue, 8> MemOpChains;
Mehdi Amini44ede332015-07-09 02:09:04 +00002994 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00002995
2996 // Walk the register/memloc assignments, inserting copies/loads.
2997 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
2998 ++i, ++realArgIdx) {
2999 CCValAssign &VA = ArgLocs[i];
3000 SDValue Arg = OutVals[realArgIdx];
3001 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
3002
3003 // Promote the value if needed.
3004 switch (VA.getLocInfo()) {
3005 default:
3006 llvm_unreachable("Unknown loc info!");
3007 case CCValAssign::Full:
3008 break;
3009 case CCValAssign::SExt:
3010 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3011 break;
3012 case CCValAssign::ZExt:
3013 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3014 break;
3015 case CCValAssign::AExt:
Tim Northover68ae5032014-05-26 17:22:07 +00003016 if (Outs[realArgIdx].ArgVT == MVT::i1) {
3017 // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
3018 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3019 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
3020 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003021 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3022 break;
3023 case CCValAssign::BCvt:
3024 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3025 break;
3026 case CCValAssign::FPExt:
3027 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3028 break;
3029 }
3030
3031 if (VA.isRegLoc()) {
3032 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i64) {
3033 assert(VA.getLocVT() == MVT::i64 &&
3034 "unexpected calling convention register assignment");
3035 assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
3036 "unexpected use of 'returned'");
3037 IsThisReturn = true;
3038 }
3039 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3040 } else {
3041 assert(VA.isMemLoc());
3042
3043 SDValue DstAddr;
3044 MachinePointerInfo DstInfo;
3045
3046 // FIXME: This works on big-endian for composite byvals, which are the
3047 // common case. It should also work for fundamental types too.
3048 uint32_t BEAlign = 0;
3049 unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
Amara Emerson82da7d02014-08-15 14:29:57 +00003050 : VA.getValVT().getSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00003051 OpSize = (OpSize + 7) / 8;
Tim Northover293d4142014-12-03 17:49:26 +00003052 if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
3053 !Flags.isInConsecutiveRegs()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003054 if (OpSize < 8)
3055 BEAlign = 8 - OpSize;
3056 }
3057 unsigned LocMemOffset = VA.getLocMemOffset();
3058 int32_t Offset = LocMemOffset + BEAlign;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003059 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
Mehdi Amini44ede332015-07-09 02:09:04 +00003060 PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
Tim Northover3b0846e2014-05-24 12:50:23 +00003061
3062 if (IsTailCall) {
3063 Offset = Offset + FPDiff;
3064 int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3065
Mehdi Amini44ede332015-07-09 02:09:04 +00003066 DstAddr = DAG.getFrameIndex(FI, PtrVT);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003067 DstInfo =
3068 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
Tim Northover3b0846e2014-05-24 12:50:23 +00003069
3070 // Make sure any stack arguments overlapping with where we're storing
3071 // are loaded before this eventual operation. Otherwise they'll be
3072 // clobbered.
3073 Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
3074 } else {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003075 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003076
Mehdi Amini44ede332015-07-09 02:09:04 +00003077 DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003078 DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
3079 LocMemOffset);
Tim Northover3b0846e2014-05-24 12:50:23 +00003080 }
3081
3082 if (Outs[i].Flags.isByVal()) {
3083 SDValue SizeNode =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003084 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00003085 SDValue Cpy = DAG.getMemcpy(
3086 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
Krzysztof Parzyszeka46c36b2015-04-13 17:16:45 +00003087 /*isVol = */ false, /*AlwaysInline = */ false,
3088 /*isTailCall = */ false,
3089 DstInfo, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00003090
3091 MemOpChains.push_back(Cpy);
3092 } else {
3093 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
3094 // promoted to a legal register type i32, we should truncate Arg back to
3095 // i1/i8/i16.
Tim Northover6890add2014-06-03 13:54:53 +00003096 if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
3097 VA.getValVT() == MVT::i16)
3098 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
Tim Northover3b0846e2014-05-24 12:50:23 +00003099
3100 SDValue Store =
3101 DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, false, false, 0);
3102 MemOpChains.push_back(Store);
3103 }
3104 }
3105 }
3106
3107 if (!MemOpChains.empty())
3108 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3109
3110 // Build a sequence of copy-to-reg nodes chained together with token chain
3111 // and flag operands which copy the outgoing args into the appropriate regs.
3112 SDValue InFlag;
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003113 for (auto &RegToPass : RegsToPass) {
3114 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3115 RegToPass.second, InFlag);
Tim Northover3b0846e2014-05-24 12:50:23 +00003116 InFlag = Chain.getValue(1);
3117 }
3118
3119 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3120 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3121 // node so that legalize doesn't hack it.
3122 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3123 Subtarget->isTargetMachO()) {
3124 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3125 const GlobalValue *GV = G->getGlobal();
3126 bool InternalLinkage = GV->hasInternalLinkage();
3127 if (InternalLinkage)
Mehdi Amini44ede332015-07-09 02:09:04 +00003128 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00003129 else {
Mehdi Amini44ede332015-07-09 02:09:04 +00003130 Callee =
3131 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT);
3132 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
Tim Northover3b0846e2014-05-24 12:50:23 +00003133 }
3134 } else if (ExternalSymbolSDNode *S =
3135 dyn_cast<ExternalSymbolSDNode>(Callee)) {
3136 const char *Sym = S->getSymbol();
Mehdi Amini44ede332015-07-09 02:09:04 +00003137 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
3138 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
Tim Northover3b0846e2014-05-24 12:50:23 +00003139 }
3140 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3141 const GlobalValue *GV = G->getGlobal();
Mehdi Amini44ede332015-07-09 02:09:04 +00003142 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00003143 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3144 const char *Sym = S->getSymbol();
Mehdi Amini44ede332015-07-09 02:09:04 +00003145 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00003146 }
3147
3148 // We don't usually want to end the call-sequence here because we would tidy
3149 // the frame up *after* the call, however in the ABI-changing tail-call case
3150 // we've carefully laid out the parameters so that when sp is reset they'll be
3151 // in the correct location.
3152 if (IsTailCall && !IsSibCall) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003153 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3154 DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003155 InFlag = Chain.getValue(1);
3156 }
3157
3158 std::vector<SDValue> Ops;
3159 Ops.push_back(Chain);
3160 Ops.push_back(Callee);
3161
3162 if (IsTailCall) {
3163 // Each tail call may have to adjust the stack by a different amount, so
3164 // this information must travel along with the operation for eventual
3165 // consumption by emitEpilogue.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003166 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00003167 }
3168
3169 // Add argument registers to the end of the list so that they are known live
3170 // into the call.
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003171 for (auto &RegToPass : RegsToPass)
3172 Ops.push_back(DAG.getRegister(RegToPass.first,
3173 RegToPass.second.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00003174
3175 // Add a register mask operand representing the call-preserved registers.
3176 const uint32_t *Mask;
Eric Christopher905f12d2015-01-29 00:19:42 +00003177 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00003178 if (IsThisReturn) {
3179 // For 'this' returns, use the X0-preserving mask if applicable
Eric Christopher9deb75d2015-03-11 22:42:13 +00003180 Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003181 if (!Mask) {
3182 IsThisReturn = false;
Eric Christopher9deb75d2015-03-11 22:42:13 +00003183 Mask = TRI->getCallPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003184 }
3185 } else
Eric Christopher9deb75d2015-03-11 22:42:13 +00003186 Mask = TRI->getCallPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003187
3188 assert(Mask && "Missing call preserved mask for calling convention");
3189 Ops.push_back(DAG.getRegisterMask(Mask));
3190
3191 if (InFlag.getNode())
3192 Ops.push_back(InFlag);
3193
3194 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3195
3196 // If we're doing a tall call, use a TC_RETURN here rather than an
3197 // actual call instruction.
Arnold Schwaighoferf54b73d2015-05-08 23:52:00 +00003198 if (IsTailCall) {
3199 MF.getFrameInfo()->setHasTailCall();
Tim Northover3b0846e2014-05-24 12:50:23 +00003200 return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
Arnold Schwaighoferf54b73d2015-05-08 23:52:00 +00003201 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003202
3203 // Returns a chain and a flag for retval copy to use.
3204 Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
3205 InFlag = Chain.getValue(1);
3206
3207 uint64_t CalleePopBytes = DoesCalleeRestoreStack(CallConv, TailCallOpt)
3208 ? RoundUpToAlignment(NumBytes, 16)
3209 : 0;
3210
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003211 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3212 DAG.getIntPtrConstant(CalleePopBytes, DL, true),
Tim Northover3b0846e2014-05-24 12:50:23 +00003213 InFlag, DL);
3214 if (!Ins.empty())
3215 InFlag = Chain.getValue(1);
3216
3217 // Handle result values, copying them out of physregs into vregs that we
3218 // return.
3219 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3220 InVals, IsThisReturn,
3221 IsThisReturn ? OutVals[0] : SDValue());
3222}
3223
3224bool AArch64TargetLowering::CanLowerReturn(
3225 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
3226 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
3227 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3228 ? RetCC_AArch64_WebKit_JS
3229 : RetCC_AArch64_AAPCS;
3230 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003231 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
Tim Northover3b0846e2014-05-24 12:50:23 +00003232 return CCInfo.CheckReturn(Outs, RetCC);
3233}
3234
3235SDValue
3236AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3237 bool isVarArg,
3238 const SmallVectorImpl<ISD::OutputArg> &Outs,
3239 const SmallVectorImpl<SDValue> &OutVals,
3240 SDLoc DL, SelectionDAG &DAG) const {
3241 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3242 ? RetCC_AArch64_WebKit_JS
3243 : RetCC_AArch64_AAPCS;
3244 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003245 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3246 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00003247 CCInfo.AnalyzeReturn(Outs, RetCC);
3248
3249 // Copy the result values into the output registers.
3250 SDValue Flag;
3251 SmallVector<SDValue, 4> RetOps(1, Chain);
3252 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
3253 ++i, ++realRVLocIdx) {
3254 CCValAssign &VA = RVLocs[i];
3255 assert(VA.isRegLoc() && "Can only return in registers!");
3256 SDValue Arg = OutVals[realRVLocIdx];
3257
3258 switch (VA.getLocInfo()) {
3259 default:
3260 llvm_unreachable("Unknown loc info!");
3261 case CCValAssign::Full:
Tim Northover68ae5032014-05-26 17:22:07 +00003262 if (Outs[i].ArgVT == MVT::i1) {
3263 // AAPCS requires i1 to be zero-extended to i8 by the producer of the
3264 // value. This is strictly redundant on Darwin (which uses "zeroext
3265 // i1"), but will be optimised out before ISel.
3266 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3267 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3268 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003269 break;
3270 case CCValAssign::BCvt:
3271 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3272 break;
3273 }
3274
3275 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
3276 Flag = Chain.getValue(1);
3277 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3278 }
3279
3280 RetOps[0] = Chain; // Update chain.
3281
3282 // Add the flag if we have it.
3283 if (Flag.getNode())
3284 RetOps.push_back(Flag);
3285
3286 return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
3287}
3288
3289//===----------------------------------------------------------------------===//
3290// Other Lowering Code
3291//===----------------------------------------------------------------------===//
3292
3293SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
3294 SelectionDAG &DAG) const {
Mehdi Amini44ede332015-07-09 02:09:04 +00003295 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003296 SDLoc DL(Op);
Asiri Rathnayake369c0302014-09-10 13:54:38 +00003297 const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
3298 const GlobalValue *GV = GN->getGlobal();
Tim Northover3b0846e2014-05-24 12:50:23 +00003299 unsigned char OpFlags =
3300 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
3301
3302 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
3303 "unexpected offset in global node");
3304
3305 // This also catched the large code model case for Darwin.
3306 if ((OpFlags & AArch64II::MO_GOT) != 0) {
3307 SDValue GotAddr = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
3308 // FIXME: Once remat is capable of dealing with instructions with register
3309 // operands, expand this into two nodes instead of using a wrapper node.
3310 return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
3311 }
3312
Asiri Rathnayake369c0302014-09-10 13:54:38 +00003313 if ((OpFlags & AArch64II::MO_CONSTPOOL) != 0) {
3314 assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
3315 "use of MO_CONSTPOOL only supported on small model");
3316 SDValue Hi = DAG.getTargetConstantPool(GV, PtrVT, 0, 0, AArch64II::MO_PAGE);
3317 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3318 unsigned char LoFlags = AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
3319 SDValue Lo = DAG.getTargetConstantPool(GV, PtrVT, 0, 0, LoFlags);
3320 SDValue PoolAddr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003321 SDValue GlobalAddr = DAG.getLoad(
3322 PtrVT, DL, DAG.getEntryNode(), PoolAddr,
3323 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
3324 /*isVolatile=*/false,
3325 /*isNonTemporal=*/true,
3326 /*isInvariant=*/true, 8);
Asiri Rathnayake369c0302014-09-10 13:54:38 +00003327 if (GN->getOffset() != 0)
3328 return DAG.getNode(ISD::ADD, DL, PtrVT, GlobalAddr,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003329 DAG.getConstant(GN->getOffset(), DL, PtrVT));
Asiri Rathnayake369c0302014-09-10 13:54:38 +00003330 return GlobalAddr;
3331 }
3332
Tim Northover3b0846e2014-05-24 12:50:23 +00003333 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
3334 const unsigned char MO_NC = AArch64II::MO_NC;
3335 return DAG.getNode(
3336 AArch64ISD::WrapperLarge, DL, PtrVT,
3337 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G3),
3338 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
3339 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
3340 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
3341 } else {
3342 // Use ADRP/ADD or ADRP/LDR for everything else: the small model on ELF and
3343 // the only correct model on Darwin.
3344 SDValue Hi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
3345 OpFlags | AArch64II::MO_PAGE);
3346 unsigned char LoFlags = OpFlags | AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
3347 SDValue Lo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, LoFlags);
3348
3349 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3350 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3351 }
3352}
3353
3354/// \brief Convert a TLS address reference into the correct sequence of loads
3355/// and calls to compute the variable's address (for Darwin, currently) and
3356/// return an SDValue containing the final node.
3357
3358/// Darwin only has one TLS scheme which must be capable of dealing with the
3359/// fully general situation, in the worst case. This means:
3360/// + "extern __thread" declaration.
3361/// + Defined in a possibly unknown dynamic library.
3362///
3363/// The general system is that each __thread variable has a [3 x i64] descriptor
3364/// which contains information used by the runtime to calculate the address. The
3365/// only part of this the compiler needs to know about is the first xword, which
3366/// contains a function pointer that must be called with the address of the
3367/// entire descriptor in "x0".
3368///
3369/// Since this descriptor may be in a different unit, in general even the
3370/// descriptor must be accessed via an indirect load. The "ideal" code sequence
3371/// is:
3372/// adrp x0, _var@TLVPPAGE
3373/// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor
3374/// ldr x1, [x0] ; x1 contains 1st entry of descriptor,
3375/// ; the function pointer
3376/// blr x1 ; Uses descriptor address in x0
3377/// ; Address of _var is now in x0.
3378///
3379/// If the address of _var's descriptor *is* known to the linker, then it can
3380/// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
3381/// a slight efficiency gain.
3382SDValue
3383AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
3384 SelectionDAG &DAG) const {
3385 assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
3386
3387 SDLoc DL(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00003388 MVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003389 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3390
3391 SDValue TLVPAddr =
3392 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3393 SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
3394
3395 // The first entry in the descriptor is a function pointer that we must call
3396 // to obtain the address of the variable.
3397 SDValue Chain = DAG.getEntryNode();
3398 SDValue FuncTLVGet =
Alex Lorenze40c8a22015-08-11 23:09:45 +00003399 DAG.getLoad(MVT::i64, DL, Chain, DescAddr,
3400 MachinePointerInfo::getGOT(DAG.getMachineFunction()), false,
3401 true, true, 8);
Tim Northover3b0846e2014-05-24 12:50:23 +00003402 Chain = FuncTLVGet.getValue(1);
3403
3404 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3405 MFI->setAdjustsStack(true);
3406
3407 // TLS calls preserve all registers except those that absolutely must be
3408 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
3409 // silly).
Eric Christopher6c901622015-01-28 03:51:33 +00003410 const uint32_t *Mask =
Eric Christopher905f12d2015-01-29 00:19:42 +00003411 Subtarget->getRegisterInfo()->getTLSCallPreservedMask();
Tim Northover3b0846e2014-05-24 12:50:23 +00003412
3413 // Finally, we can make the call. This is just a degenerate version of a
3414 // normal AArch64 call node: x0 takes the address of the descriptor, and
3415 // returns the address of the variable in this thread.
3416 Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
3417 Chain =
3418 DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3419 Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
3420 DAG.getRegisterMask(Mask), Chain.getValue(1));
3421 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
3422}
3423
3424/// When accessing thread-local variables under either the general-dynamic or
3425/// local-dynamic system, we make a "TLS-descriptor" call. The variable will
3426/// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
Kristof Beylsaea84612015-03-04 09:12:08 +00003427/// is a function pointer to carry out the resolution.
Tim Northover3b0846e2014-05-24 12:50:23 +00003428///
Kristof Beylsaea84612015-03-04 09:12:08 +00003429/// The sequence is:
3430/// adrp x0, :tlsdesc:var
3431/// ldr x1, [x0, #:tlsdesc_lo12:var]
3432/// add x0, x0, #:tlsdesc_lo12:var
3433/// .tlsdesccall var
3434/// blr x1
3435/// (TPIDR_EL0 offset now in x0)
Tim Northover3b0846e2014-05-24 12:50:23 +00003436///
Kristof Beylsaea84612015-03-04 09:12:08 +00003437/// The above sequence must be produced unscheduled, to enable the linker to
3438/// optimize/relax this sequence.
3439/// Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
3440/// above sequence, and expanded really late in the compilation flow, to ensure
3441/// the sequence is produced as per above.
3442SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr, SDLoc DL,
3443 SelectionDAG &DAG) const {
Mehdi Amini44ede332015-07-09 02:09:04 +00003444 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003445
Kristof Beylsaea84612015-03-04 09:12:08 +00003446 SDValue Chain = DAG.getEntryNode();
Tim Northover3b0846e2014-05-24 12:50:23 +00003447 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
Kristof Beylsaea84612015-03-04 09:12:08 +00003448
3449 SmallVector<SDValue, 2> Ops;
3450 Ops.push_back(Chain);
3451 Ops.push_back(SymAddr);
3452
3453 Chain = DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, Ops);
3454 SDValue Glue = Chain.getValue(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00003455
3456 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
3457}
3458
3459SDValue
3460AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
3461 SelectionDAG &DAG) const {
3462 assert(Subtarget->isTargetELF() && "This function expects an ELF target");
3463 assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
3464 "ELF TLS only supported in small memory model");
Kristof Beylsaea84612015-03-04 09:12:08 +00003465 // Different choices can be made for the maximum size of the TLS area for a
3466 // module. For the small address model, the default TLS size is 16MiB and the
3467 // maximum TLS size is 4GiB.
3468 // FIXME: add -mtls-size command line option and make it control the 16MiB
3469 // vs. 4GiB code sequence generation.
Tim Northover3b0846e2014-05-24 12:50:23 +00003470 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3471
3472 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
Chih-Hung Hsieh1e859582015-07-28 16:24:05 +00003473
3474 if (DAG.getTarget().Options.EmulatedTLS)
3475 return LowerToTLSEmulatedModel(GA, DAG);
3476
Kristof Beylsaea84612015-03-04 09:12:08 +00003477 if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
3478 if (Model == TLSModel::LocalDynamic)
3479 Model = TLSModel::GeneralDynamic;
3480 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003481
3482 SDValue TPOff;
Mehdi Amini44ede332015-07-09 02:09:04 +00003483 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003484 SDLoc DL(Op);
3485 const GlobalValue *GV = GA->getGlobal();
3486
3487 SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
3488
3489 if (Model == TLSModel::LocalExec) {
3490 SDValue HiVar = DAG.getTargetGlobalAddress(
Kristof Beylsaea84612015-03-04 09:12:08 +00003491 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
Tim Northover3b0846e2014-05-24 12:50:23 +00003492 SDValue LoVar = DAG.getTargetGlobalAddress(
3493 GV, DL, PtrVT, 0,
Kristof Beylsaea84612015-03-04 09:12:08 +00003494 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
Tim Northover3b0846e2014-05-24 12:50:23 +00003495
Kristof Beylsaea84612015-03-04 09:12:08 +00003496 SDValue TPWithOff_lo =
3497 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003498 HiVar,
3499 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003500 0);
3501 SDValue TPWithOff =
3502 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003503 LoVar,
3504 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003505 0);
3506 return TPWithOff;
Tim Northover3b0846e2014-05-24 12:50:23 +00003507 } else if (Model == TLSModel::InitialExec) {
3508 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3509 TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
3510 } else if (Model == TLSModel::LocalDynamic) {
3511 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
3512 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
3513 // the beginning of the module's TLS region, followed by a DTPREL offset
3514 // calculation.
3515
3516 // These accesses will need deduplicating if there's more than one.
3517 AArch64FunctionInfo *MFI =
3518 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
3519 MFI->incNumLocalDynamicTLSAccesses();
3520
Tim Northover3b0846e2014-05-24 12:50:23 +00003521 // The call needs a relocation too for linker relaxation. It doesn't make
3522 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3523 // the address.
3524 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
3525 AArch64II::MO_TLS);
3526
3527 // Now we can calculate the offset from TPIDR_EL0 to this module's
3528 // thread-local area.
Kristof Beylsaea84612015-03-04 09:12:08 +00003529 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00003530
3531 // Now use :dtprel_whatever: operations to calculate this variable's offset
3532 // in its thread-storage area.
3533 SDValue HiVar = DAG.getTargetGlobalAddress(
Kristof Beylsaea84612015-03-04 09:12:08 +00003534 GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
Tim Northover3b0846e2014-05-24 12:50:23 +00003535 SDValue LoVar = DAG.getTargetGlobalAddress(
3536 GV, DL, MVT::i64, 0,
Tim Northover3b0846e2014-05-24 12:50:23 +00003537 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3538
Kristof Beylsaea84612015-03-04 09:12:08 +00003539 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003540 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003541 0);
3542 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003543 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003544 0);
3545 } else if (Model == TLSModel::GeneralDynamic) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003546 // The call needs a relocation too for linker relaxation. It doesn't make
3547 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3548 // the address.
3549 SDValue SymAddr =
3550 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3551
3552 // Finally we can make a call to calculate the offset from tpidr_el0.
Kristof Beylsaea84612015-03-04 09:12:08 +00003553 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00003554 } else
3555 llvm_unreachable("Unsupported ELF TLS access model");
3556
3557 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
3558}
3559
3560SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
3561 SelectionDAG &DAG) const {
3562 if (Subtarget->isTargetDarwin())
3563 return LowerDarwinGlobalTLSAddress(Op, DAG);
3564 else if (Subtarget->isTargetELF())
3565 return LowerELFGlobalTLSAddress(Op, DAG);
3566
3567 llvm_unreachable("Unexpected platform trying to use TLS");
3568}
3569SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3570 SDValue Chain = Op.getOperand(0);
3571 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3572 SDValue LHS = Op.getOperand(2);
3573 SDValue RHS = Op.getOperand(3);
3574 SDValue Dest = Op.getOperand(4);
3575 SDLoc dl(Op);
3576
3577 // Handle f128 first, since lowering it will result in comparing the return
3578 // value of a libcall against zero, which is just what the rest of LowerBR_CC
3579 // is expecting to deal with.
3580 if (LHS.getValueType() == MVT::f128) {
3581 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3582
3583 // If softenSetCCOperands returned a scalar, we need to compare the result
3584 // against zero to select between true and false values.
3585 if (!RHS.getNode()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003586 RHS = DAG.getConstant(0, dl, LHS.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00003587 CC = ISD::SETNE;
3588 }
3589 }
3590
3591 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
3592 // instruction.
3593 unsigned Opc = LHS.getOpcode();
Artyom Skrobov314ee042015-11-25 19:41:11 +00003594 if (LHS.getResNo() == 1 && isOneConstant(RHS) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00003595 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3596 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
3597 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
3598 "Unexpected condition code.");
3599 // Only lower legal XALUO ops.
3600 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
3601 return SDValue();
3602
3603 // The actual operation with overflow check.
3604 AArch64CC::CondCode OFCC;
3605 SDValue Value, Overflow;
3606 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
3607
3608 if (CC == ISD::SETNE)
3609 OFCC = getInvertedCondCode(OFCC);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003610 SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003611
Ahmed Bougachadf956a22015-02-06 23:15:39 +00003612 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3613 Overflow);
Tim Northover3b0846e2014-05-24 12:50:23 +00003614 }
3615
3616 if (LHS.getValueType().isInteger()) {
3617 assert((LHS.getValueType() == RHS.getValueType()) &&
3618 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3619
3620 // If the RHS of the comparison is zero, we can potentially fold this
3621 // to a specialized branch.
3622 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
3623 if (RHSC && RHSC->getZExtValue() == 0) {
3624 if (CC == ISD::SETEQ) {
3625 // See if we can use a TBZ to fold in an AND as well.
3626 // TBZ has a smaller branch displacement than CBZ. If the offset is
3627 // out of bounds, a late MI-layer pass rewrites branches.
3628 // 403.gcc is an example that hits this case.
3629 if (LHS.getOpcode() == ISD::AND &&
3630 isa<ConstantSDNode>(LHS.getOperand(1)) &&
3631 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3632 SDValue Test = LHS.getOperand(0);
3633 uint64_t Mask = LHS.getConstantOperandVal(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00003634 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003635 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3636 Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00003637 }
3638
3639 return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
3640 } else if (CC == ISD::SETNE) {
3641 // See if we can use a TBZ to fold in an AND as well.
3642 // TBZ has a smaller branch displacement than CBZ. If the offset is
3643 // out of bounds, a late MI-layer pass rewrites branches.
3644 // 403.gcc is an example that hits this case.
3645 if (LHS.getOpcode() == ISD::AND &&
3646 isa<ConstantSDNode>(LHS.getOperand(1)) &&
3647 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3648 SDValue Test = LHS.getOperand(0);
3649 uint64_t Mask = LHS.getConstantOperandVal(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00003650 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003651 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3652 Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00003653 }
3654
3655 return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
Chad Rosier579c02c2014-08-01 14:48:56 +00003656 } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
3657 // Don't combine AND since emitComparison converts the AND to an ANDS
3658 // (a.k.a. TST) and the test in the test bit and branch instruction
3659 // becomes redundant. This would also increase register pressure.
3660 uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
3661 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003662 DAG.getConstant(Mask, dl, MVT::i64), Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00003663 }
3664 }
Chad Rosier579c02c2014-08-01 14:48:56 +00003665 if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
3666 LHS.getOpcode() != ISD::AND) {
3667 // Don't combine AND since emitComparison converts the AND to an ANDS
3668 // (a.k.a. TST) and the test in the test bit and branch instruction
3669 // becomes redundant. This would also increase register pressure.
3670 uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
3671 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003672 DAG.getConstant(Mask, dl, MVT::i64), Dest);
Chad Rosier579c02c2014-08-01 14:48:56 +00003673 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003674
3675 SDValue CCVal;
3676 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3677 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3678 Cmp);
3679 }
3680
3681 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3682
3683 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
3684 // clean. Some of them require two branches to implement.
3685 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3686 AArch64CC::CondCode CC1, CC2;
3687 changeFPCCToAArch64CC(CC, CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003688 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003689 SDValue BR1 =
3690 DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
3691 if (CC2 != AArch64CC::AL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003692 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003693 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
3694 Cmp);
3695 }
3696
3697 return BR1;
3698}
3699
3700SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
3701 SelectionDAG &DAG) const {
3702 EVT VT = Op.getValueType();
3703 SDLoc DL(Op);
3704
3705 SDValue In1 = Op.getOperand(0);
3706 SDValue In2 = Op.getOperand(1);
3707 EVT SrcVT = In2.getValueType();
Ahmed Bougacha2a97b1b2015-08-13 01:13:56 +00003708
3709 if (SrcVT.bitsLT(VT))
3710 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
3711 else if (SrcVT.bitsGT(VT))
3712 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
Tim Northover3b0846e2014-05-24 12:50:23 +00003713
3714 EVT VecVT;
3715 EVT EltVT;
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00003716 uint64_t EltMask;
3717 SDValue VecVal1, VecVal2;
Tim Northover3b0846e2014-05-24 12:50:23 +00003718 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
3719 EltVT = MVT::i32;
Ahmed Bougachab0ae36f2015-08-04 00:42:34 +00003720 VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00003721 EltMask = 0x80000000ULL;
Tim Northover3b0846e2014-05-24 12:50:23 +00003722
3723 if (!VT.isVector()) {
3724 VecVal1 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3725 DAG.getUNDEF(VecVT), In1);
3726 VecVal2 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3727 DAG.getUNDEF(VecVT), In2);
3728 } else {
3729 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3730 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3731 }
3732 } else if (VT == MVT::f64 || VT == MVT::v2f64) {
3733 EltVT = MVT::i64;
3734 VecVT = MVT::v2i64;
3735
Eric Christopher572e03a2015-06-19 01:53:21 +00003736 // We want to materialize a mask with the high bit set, but the AdvSIMD
Tim Northover3b0846e2014-05-24 12:50:23 +00003737 // immediate moves cannot materialize that in a single instruction for
3738 // 64-bit elements. Instead, materialize zero and then negate it.
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00003739 EltMask = 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00003740
3741 if (!VT.isVector()) {
3742 VecVal1 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3743 DAG.getUNDEF(VecVT), In1);
3744 VecVal2 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3745 DAG.getUNDEF(VecVT), In2);
3746 } else {
3747 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3748 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3749 }
3750 } else {
3751 llvm_unreachable("Invalid type for copysign!");
3752 }
3753
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003754 SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00003755
3756 // If we couldn't materialize the mask above, then the mask vector will be
3757 // the zero vector, and we need to negate it here.
3758 if (VT == MVT::f64 || VT == MVT::v2f64) {
3759 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
3760 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
3761 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
3762 }
3763
3764 SDValue Sel =
3765 DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
3766
3767 if (VT == MVT::f32)
3768 return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
3769 else if (VT == MVT::f64)
3770 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
3771 else
3772 return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
3773}
3774
3775SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
Duncan P. N. Exon Smith003bb7d2015-02-14 02:09:06 +00003776 if (DAG.getMachineFunction().getFunction()->hasFnAttribute(
3777 Attribute::NoImplicitFloat))
Tim Northover3b0846e2014-05-24 12:50:23 +00003778 return SDValue();
3779
Weiming Zhao7a2d1562014-11-19 00:29:14 +00003780 if (!Subtarget->hasNEON())
3781 return SDValue();
3782
Tim Northover3b0846e2014-05-24 12:50:23 +00003783 // While there is no integer popcount instruction, it can
3784 // be more efficiently lowered to the following sequence that uses
3785 // AdvSIMD registers/instructions as long as the copies to/from
3786 // the AdvSIMD registers are cheap.
3787 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd
3788 // CNT V0.8B, V0.8B // 8xbyte pop-counts
3789 // ADDV B0, V0.8B // sum 8xbyte pop-counts
3790 // UMOV X0, V0.B[0] // copy byte result back to integer reg
3791 SDValue Val = Op.getOperand(0);
3792 SDLoc DL(Op);
3793 EVT VT = Op.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00003794
Hao Liue0335d72015-01-30 02:13:53 +00003795 if (VT == MVT::i32)
3796 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
3797 Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
Tim Northover3b0846e2014-05-24 12:50:23 +00003798
Hao Liue0335d72015-01-30 02:13:53 +00003799 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
Tim Northover3b0846e2014-05-24 12:50:23 +00003800 SDValue UaddLV = DAG.getNode(
3801 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003802 DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
Tim Northover3b0846e2014-05-24 12:50:23 +00003803
3804 if (VT == MVT::i64)
3805 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
3806 return UaddLV;
3807}
3808
3809SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3810
3811 if (Op.getValueType().isVector())
3812 return LowerVSETCC(Op, DAG);
3813
3814 SDValue LHS = Op.getOperand(0);
3815 SDValue RHS = Op.getOperand(1);
3816 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3817 SDLoc dl(Op);
3818
3819 // We chose ZeroOrOneBooleanContents, so use zero and one.
3820 EVT VT = Op.getValueType();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003821 SDValue TVal = DAG.getConstant(1, dl, VT);
3822 SDValue FVal = DAG.getConstant(0, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00003823
3824 // Handle f128 first, since one possible outcome is a normal integer
3825 // comparison which gets picked up by the next if statement.
3826 if (LHS.getValueType() == MVT::f128) {
3827 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3828
3829 // If softenSetCCOperands returned a scalar, use it.
3830 if (!RHS.getNode()) {
3831 assert(LHS.getValueType() == Op.getValueType() &&
3832 "Unexpected setcc expansion!");
3833 return LHS;
3834 }
3835 }
3836
3837 if (LHS.getValueType().isInteger()) {
3838 SDValue CCVal;
3839 SDValue Cmp =
3840 getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
3841
3842 // Note that we inverted the condition above, so we reverse the order of
3843 // the true and false operands here. This will allow the setcc to be
3844 // matched to a single CSINC instruction.
3845 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
3846 }
3847
3848 // Now we know we're dealing with FP values.
3849 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3850
3851 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
3852 // and do the comparison.
3853 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3854
3855 AArch64CC::CondCode CC1, CC2;
3856 changeFPCCToAArch64CC(CC, CC1, CC2);
3857 if (CC2 == AArch64CC::AL) {
3858 changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003859 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003860
3861 // Note that we inverted the condition above, so we reverse the order of
3862 // the true and false operands here. This will allow the setcc to be
3863 // matched to a single CSINC instruction.
3864 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
3865 } else {
3866 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
3867 // totally clean. Some of them require two CSELs to implement. As is in
3868 // this case, we emit the first CSEL and then emit a second using the output
3869 // of the first as the RHS. We're effectively OR'ing the two CC's together.
3870
3871 // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003872 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003873 SDValue CS1 =
3874 DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3875
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003876 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003877 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3878 }
3879}
3880
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00003881SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
3882 SDValue RHS, SDValue TVal,
3883 SDValue FVal, SDLoc dl,
Tim Northover3b0846e2014-05-24 12:50:23 +00003884 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00003885 // Handle f128 first, because it will result in a comparison of some RTLIB
3886 // call result against zero.
3887 if (LHS.getValueType() == MVT::f128) {
3888 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3889
3890 // If softenSetCCOperands returned a scalar, we need to compare the result
3891 // against zero to select between true and false values.
3892 if (!RHS.getNode()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003893 RHS = DAG.getConstant(0, dl, LHS.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00003894 CC = ISD::SETNE;
3895 }
3896 }
3897
Ahmed Bougacha88ddeae2015-11-17 16:45:40 +00003898 // Also handle f16, for which we need to do a f32 comparison.
3899 if (LHS.getValueType() == MVT::f16) {
3900 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
3901 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
3902 }
3903
3904 // Next, handle integers.
Tim Northover3b0846e2014-05-24 12:50:23 +00003905 if (LHS.getValueType().isInteger()) {
3906 assert((LHS.getValueType() == RHS.getValueType()) &&
3907 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3908
3909 unsigned Opcode = AArch64ISD::CSEL;
3910
3911 // If both the TVal and the FVal are constants, see if we can swap them in
3912 // order to for a CSINV or CSINC out of them.
3913 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
3914 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
3915
3916 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
3917 std::swap(TVal, FVal);
3918 std::swap(CTVal, CFVal);
3919 CC = ISD::getSetCCInverse(CC, true);
3920 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
3921 std::swap(TVal, FVal);
3922 std::swap(CTVal, CFVal);
3923 CC = ISD::getSetCCInverse(CC, true);
3924 } else if (TVal.getOpcode() == ISD::XOR) {
3925 // If TVal is a NOT we want to swap TVal and FVal so that we can match
3926 // with a CSINV rather than a CSEL.
Artyom Skrobov314ee042015-11-25 19:41:11 +00003927 if (isAllOnesConstant(TVal.getOperand(1))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003928 std::swap(TVal, FVal);
3929 std::swap(CTVal, CFVal);
3930 CC = ISD::getSetCCInverse(CC, true);
3931 }
3932 } else if (TVal.getOpcode() == ISD::SUB) {
3933 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
3934 // that we can match with a CSNEG rather than a CSEL.
Artyom Skrobov314ee042015-11-25 19:41:11 +00003935 if (isNullConstant(TVal.getOperand(0))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003936 std::swap(TVal, FVal);
3937 std::swap(CTVal, CFVal);
3938 CC = ISD::getSetCCInverse(CC, true);
3939 }
3940 } else if (CTVal && CFVal) {
3941 const int64_t TrueVal = CTVal->getSExtValue();
3942 const int64_t FalseVal = CFVal->getSExtValue();
3943 bool Swap = false;
3944
3945 // If both TVal and FVal are constants, see if FVal is the
3946 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
3947 // instead of a CSEL in that case.
3948 if (TrueVal == ~FalseVal) {
3949 Opcode = AArch64ISD::CSINV;
3950 } else if (TrueVal == -FalseVal) {
3951 Opcode = AArch64ISD::CSNEG;
3952 } else if (TVal.getValueType() == MVT::i32) {
3953 // If our operands are only 32-bit wide, make sure we use 32-bit
3954 // arithmetic for the check whether we can use CSINC. This ensures that
3955 // the addition in the check will wrap around properly in case there is
3956 // an overflow (which would not be the case if we do the check with
3957 // 64-bit arithmetic).
3958 const uint32_t TrueVal32 = CTVal->getZExtValue();
3959 const uint32_t FalseVal32 = CFVal->getZExtValue();
3960
3961 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
3962 Opcode = AArch64ISD::CSINC;
3963
3964 if (TrueVal32 > FalseVal32) {
3965 Swap = true;
3966 }
3967 }
3968 // 64-bit check whether we can use CSINC.
3969 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
3970 Opcode = AArch64ISD::CSINC;
3971
3972 if (TrueVal > FalseVal) {
3973 Swap = true;
3974 }
3975 }
3976
3977 // Swap TVal and FVal if necessary.
3978 if (Swap) {
3979 std::swap(TVal, FVal);
3980 std::swap(CTVal, CFVal);
3981 CC = ISD::getSetCCInverse(CC, true);
3982 }
3983
3984 if (Opcode != AArch64ISD::CSEL) {
3985 // Drop FVal since we can get its value by simply inverting/negating
3986 // TVal.
3987 FVal = TVal;
3988 }
3989 }
3990
3991 SDValue CCVal;
3992 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3993
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00003994 EVT VT = TVal.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00003995 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
3996 }
3997
3998 // Now we know we're dealing with FP values.
3999 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
4000 assert(LHS.getValueType() == RHS.getValueType());
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004001 EVT VT = TVal.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00004002 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
4003
4004 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4005 // clean. Some of them require two CSELs to implement.
4006 AArch64CC::CondCode CC1, CC2;
4007 changeFPCCToAArch64CC(CC, CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004008 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004009 SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4010
4011 // If we need a second CSEL, emit it, using the output of the first as the
4012 // RHS. We're effectively OR'ing the two CC's together.
4013 if (CC2 != AArch64CC::AL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004014 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004015 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4016 }
4017
4018 // Otherwise, return the output of the first CSEL.
4019 return CS1;
4020}
4021
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004022SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
4023 SelectionDAG &DAG) const {
4024 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4025 SDValue LHS = Op.getOperand(0);
4026 SDValue RHS = Op.getOperand(1);
4027 SDValue TVal = Op.getOperand(2);
4028 SDValue FVal = Op.getOperand(3);
4029 SDLoc DL(Op);
4030 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4031}
4032
4033SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
4034 SelectionDAG &DAG) const {
4035 SDValue CCVal = Op->getOperand(0);
4036 SDValue TVal = Op->getOperand(1);
4037 SDValue FVal = Op->getOperand(2);
4038 SDLoc DL(Op);
4039
4040 unsigned Opc = CCVal.getOpcode();
4041 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
4042 // instruction.
4043 if (CCVal.getResNo() == 1 &&
4044 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4045 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
4046 // Only lower legal XALUO ops.
4047 if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
4048 return SDValue();
4049
4050 AArch64CC::CondCode OFCC;
4051 SDValue Value, Overflow;
4052 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004053 SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004054
4055 return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
4056 CCVal, Overflow);
4057 }
4058
4059 // Lower it the same way as we would lower a SELECT_CC node.
4060 ISD::CondCode CC;
4061 SDValue LHS, RHS;
4062 if (CCVal.getOpcode() == ISD::SETCC) {
4063 LHS = CCVal.getOperand(0);
4064 RHS = CCVal.getOperand(1);
4065 CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
4066 } else {
4067 LHS = CCVal;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004068 RHS = DAG.getConstant(0, DL, CCVal.getValueType());
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004069 CC = ISD::SETNE;
4070 }
4071 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4072}
4073
Tim Northover3b0846e2014-05-24 12:50:23 +00004074SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
4075 SelectionDAG &DAG) const {
4076 // Jump table entries as PC relative offsets. No additional tweaking
4077 // is necessary here. Just get the address of the jump table.
4078 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00004079 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004080 SDLoc DL(Op);
4081
4082 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4083 !Subtarget->isTargetMachO()) {
4084 const unsigned char MO_NC = AArch64II::MO_NC;
4085 return DAG.getNode(
4086 AArch64ISD::WrapperLarge, DL, PtrVT,
4087 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G3),
4088 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G2 | MO_NC),
4089 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G1 | MO_NC),
4090 DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4091 AArch64II::MO_G0 | MO_NC));
4092 }
4093
4094 SDValue Hi =
4095 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_PAGE);
4096 SDValue Lo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4097 AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4098 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4099 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4100}
4101
4102SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
4103 SelectionDAG &DAG) const {
4104 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00004105 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004106 SDLoc DL(Op);
4107
4108 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4109 // Use the GOT for the large code model on iOS.
4110 if (Subtarget->isTargetMachO()) {
4111 SDValue GotAddr = DAG.getTargetConstantPool(
4112 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4113 AArch64II::MO_GOT);
4114 return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
4115 }
4116
4117 const unsigned char MO_NC = AArch64II::MO_NC;
4118 return DAG.getNode(
4119 AArch64ISD::WrapperLarge, DL, PtrVT,
4120 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4121 CP->getOffset(), AArch64II::MO_G3),
4122 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4123 CP->getOffset(), AArch64II::MO_G2 | MO_NC),
4124 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4125 CP->getOffset(), AArch64II::MO_G1 | MO_NC),
4126 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4127 CP->getOffset(), AArch64II::MO_G0 | MO_NC));
4128 } else {
4129 // Use ADRP/ADD or ADRP/LDR for everything else: the small memory model on
4130 // ELF, the only valid one on Darwin.
4131 SDValue Hi =
4132 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4133 CP->getOffset(), AArch64II::MO_PAGE);
4134 SDValue Lo = DAG.getTargetConstantPool(
4135 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4136 AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4137
4138 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4139 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4140 }
4141}
4142
4143SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
4144 SelectionDAG &DAG) const {
4145 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
Mehdi Amini44ede332015-07-09 02:09:04 +00004146 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004147 SDLoc DL(Op);
4148 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4149 !Subtarget->isTargetMachO()) {
4150 const unsigned char MO_NC = AArch64II::MO_NC;
4151 return DAG.getNode(
4152 AArch64ISD::WrapperLarge, DL, PtrVT,
4153 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G3),
4154 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
4155 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
4156 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
4157 } else {
4158 SDValue Hi = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGE);
4159 SDValue Lo = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGEOFF |
4160 AArch64II::MO_NC);
4161 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4162 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4163 }
4164}
4165
4166SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
4167 SelectionDAG &DAG) const {
4168 AArch64FunctionInfo *FuncInfo =
4169 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4170
4171 SDLoc DL(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00004172 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
4173 getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00004174 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4175 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
4176 MachinePointerInfo(SV), false, false, 0);
4177}
4178
4179SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
4180 SelectionDAG &DAG) const {
4181 // The layout of the va_list struct is specified in the AArch64 Procedure Call
4182 // Standard, section B.3.
4183 MachineFunction &MF = DAG.getMachineFunction();
4184 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Mehdi Amini44ede332015-07-09 02:09:04 +00004185 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004186 SDLoc DL(Op);
4187
4188 SDValue Chain = Op.getOperand(0);
4189 SDValue VAList = Op.getOperand(1);
4190 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4191 SmallVector<SDValue, 4> MemOps;
4192
4193 // void *__stack at offset 0
Mehdi Amini44ede332015-07-09 02:09:04 +00004194 SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004195 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
4196 MachinePointerInfo(SV), false, false, 8));
4197
4198 // void *__gr_top at offset 8
4199 int GPRSize = FuncInfo->getVarArgsGPRSize();
4200 if (GPRSize > 0) {
4201 SDValue GRTop, GRTopAddr;
4202
Mehdi Amini44ede332015-07-09 02:09:04 +00004203 GRTopAddr =
4204 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004205
Mehdi Amini44ede332015-07-09 02:09:04 +00004206 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
4207 GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
4208 DAG.getConstant(GPRSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004209
4210 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
4211 MachinePointerInfo(SV, 8), false, false, 8));
4212 }
4213
4214 // void *__vr_top at offset 16
4215 int FPRSize = FuncInfo->getVarArgsFPRSize();
4216 if (FPRSize > 0) {
4217 SDValue VRTop, VRTopAddr;
Mehdi Amini44ede332015-07-09 02:09:04 +00004218 VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4219 DAG.getConstant(16, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004220
Mehdi Amini44ede332015-07-09 02:09:04 +00004221 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
4222 VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
4223 DAG.getConstant(FPRSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004224
4225 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
4226 MachinePointerInfo(SV, 16), false, false, 8));
4227 }
4228
4229 // int __gr_offs at offset 24
Mehdi Amini44ede332015-07-09 02:09:04 +00004230 SDValue GROffsAddr =
4231 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004232 MemOps.push_back(DAG.getStore(Chain, DL,
4233 DAG.getConstant(-GPRSize, DL, MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00004234 GROffsAddr, MachinePointerInfo(SV, 24), false,
4235 false, 4));
4236
4237 // int __vr_offs at offset 28
Mehdi Amini44ede332015-07-09 02:09:04 +00004238 SDValue VROffsAddr =
4239 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004240 MemOps.push_back(DAG.getStore(Chain, DL,
4241 DAG.getConstant(-FPRSize, DL, MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00004242 VROffsAddr, MachinePointerInfo(SV, 28), false,
4243 false, 4));
4244
4245 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
4246}
4247
4248SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
4249 SelectionDAG &DAG) const {
4250 return Subtarget->isTargetDarwin() ? LowerDarwin_VASTART(Op, DAG)
4251 : LowerAAPCS_VASTART(Op, DAG);
4252}
4253
4254SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
4255 SelectionDAG &DAG) const {
4256 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
4257 // pointer.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004258 SDLoc DL(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00004259 unsigned VaListSize = Subtarget->isTargetDarwin() ? 8 : 32;
4260 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4261 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4262
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004263 return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1),
4264 Op.getOperand(2),
4265 DAG.getConstant(VaListSize, DL, MVT::i32),
Krzysztof Parzyszeka46c36b2015-04-13 17:16:45 +00004266 8, false, false, false, MachinePointerInfo(DestSV),
Tim Northover3b0846e2014-05-24 12:50:23 +00004267 MachinePointerInfo(SrcSV));
4268}
4269
4270SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
4271 assert(Subtarget->isTargetDarwin() &&
4272 "automatic va_arg instruction only works on Darwin");
4273
4274 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4275 EVT VT = Op.getValueType();
4276 SDLoc DL(Op);
4277 SDValue Chain = Op.getOperand(0);
4278 SDValue Addr = Op.getOperand(1);
4279 unsigned Align = Op.getConstantOperandVal(3);
Mehdi Amini44ede332015-07-09 02:09:04 +00004280 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004281
Mehdi Amini44ede332015-07-09 02:09:04 +00004282 SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V),
4283 false, false, false, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00004284 Chain = VAList.getValue(1);
4285
4286 if (Align > 8) {
4287 assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
Mehdi Amini44ede332015-07-09 02:09:04 +00004288 VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4289 DAG.getConstant(Align - 1, DL, PtrVT));
4290 VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
4291 DAG.getConstant(-(int64_t)Align, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004292 }
4293
4294 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
Mehdi Amini44ede332015-07-09 02:09:04 +00004295 uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
Tim Northover3b0846e2014-05-24 12:50:23 +00004296
4297 // Scalar integer and FP values smaller than 64 bits are implicitly extended
4298 // up to 64 bits. At the very least, we have to increase the striding of the
4299 // vaargs list to match this, and for FP values we need to introduce
4300 // FP_ROUND nodes as well.
4301 if (VT.isInteger() && !VT.isVector())
4302 ArgSize = 8;
4303 bool NeedFPTrunc = false;
4304 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
4305 ArgSize = 8;
4306 NeedFPTrunc = true;
4307 }
4308
4309 // Increment the pointer, VAList, to the next vaarg
Mehdi Amini44ede332015-07-09 02:09:04 +00004310 SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4311 DAG.getConstant(ArgSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004312 // Store the incremented VAList to the legalized pointer
4313 SDValue APStore = DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V),
4314 false, false, 0);
4315
4316 // Load the actual argument out of the pointer VAList
4317 if (NeedFPTrunc) {
4318 // Load the value as an f64.
4319 SDValue WideFP = DAG.getLoad(MVT::f64, DL, APStore, VAList,
4320 MachinePointerInfo(), false, false, false, 0);
4321 // Round the value down to an f32.
4322 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004323 DAG.getIntPtrConstant(1, DL));
Tim Northover3b0846e2014-05-24 12:50:23 +00004324 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
4325 // Merge the rounded value with the chain output of the load.
4326 return DAG.getMergeValues(Ops, DL);
4327 }
4328
4329 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo(), false,
4330 false, false, 0);
4331}
4332
4333SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
4334 SelectionDAG &DAG) const {
4335 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4336 MFI->setFrameAddressIsTaken(true);
4337
4338 EVT VT = Op.getValueType();
4339 SDLoc DL(Op);
4340 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4341 SDValue FrameAddr =
4342 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
4343 while (Depth--)
4344 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
4345 MachinePointerInfo(), false, false, false, 0);
4346 return FrameAddr;
4347}
4348
4349// FIXME? Maybe this could be a TableGen attribute on some registers and
4350// this table could be generated automatically from RegInfo.
Pat Gavlina717f252015-07-09 17:40:29 +00004351unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT,
4352 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004353 unsigned Reg = StringSwitch<unsigned>(RegName)
4354 .Case("sp", AArch64::SP)
4355 .Default(0);
4356 if (Reg)
4357 return Reg;
Luke Cheeseman85fd06d2015-06-01 12:02:47 +00004358 report_fatal_error(Twine("Invalid register name \""
4359 + StringRef(RegName) + "\"."));
Tim Northover3b0846e2014-05-24 12:50:23 +00004360}
4361
4362SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
4363 SelectionDAG &DAG) const {
4364 MachineFunction &MF = DAG.getMachineFunction();
4365 MachineFrameInfo *MFI = MF.getFrameInfo();
4366 MFI->setReturnAddressIsTaken(true);
4367
4368 EVT VT = Op.getValueType();
4369 SDLoc DL(Op);
4370 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4371 if (Depth) {
4372 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
Mehdi Amini44ede332015-07-09 02:09:04 +00004373 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00004374 return DAG.getLoad(VT, DL, DAG.getEntryNode(),
4375 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
4376 MachinePointerInfo(), false, false, false, 0);
4377 }
4378
4379 // Return LR, which contains the return address. Mark it an implicit live-in.
4380 unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
4381 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4382}
4383
4384/// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4385/// i64 values and take a 2 x i64 value to shift plus a shift amount.
4386SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
4387 SelectionDAG &DAG) const {
4388 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4389 EVT VT = Op.getValueType();
4390 unsigned VTBits = VT.getSizeInBits();
4391 SDLoc dl(Op);
4392 SDValue ShOpLo = Op.getOperand(0);
4393 SDValue ShOpHi = Op.getOperand(1);
4394 SDValue ShAmt = Op.getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00004395 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4396
4397 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4398
4399 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004400 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
Tim Northoverf3be9d52015-12-02 00:33:54 +00004401 SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4402
4403 // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
4404 // is "undef". We wanted 0, so CSEL it directly.
4405 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
4406 ISD::SETEQ, dl, DAG);
4407 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
4408 HiBitsForLo =
4409 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
4410 HiBitsForLo, CCVal, Cmp);
4411
Tim Northover3b0846e2014-05-24 12:50:23 +00004412 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004413 DAG.getConstant(VTBits, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00004414
Tim Northoverf3be9d52015-12-02 00:33:54 +00004415 SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4416 SDValue LoForNormalShift =
4417 DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
Tim Northover3b0846e2014-05-24 12:50:23 +00004418
Tim Northoverf3be9d52015-12-02 00:33:54 +00004419 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
4420 dl, DAG);
4421 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4422 SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4423 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
4424 LoForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00004425
4426 // AArch64 shifts larger than the register width are wrapped rather than
4427 // clamped, so we can't just emit "hi >> x".
Tim Northoverf3be9d52015-12-02 00:33:54 +00004428 SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4429 SDValue HiForBigShift =
4430 Opc == ISD::SRA
4431 ? DAG.getNode(Opc, dl, VT, ShOpHi,
4432 DAG.getConstant(VTBits - 1, dl, MVT::i64))
4433 : DAG.getConstant(0, dl, VT);
4434 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
4435 HiForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00004436
4437 SDValue Ops[2] = { Lo, Hi };
4438 return DAG.getMergeValues(Ops, dl);
4439}
4440
Tim Northoverf3be9d52015-12-02 00:33:54 +00004441
Tim Northover3b0846e2014-05-24 12:50:23 +00004442/// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4443/// i64 values and take a 2 x i64 value to shift plus a shift amount.
4444SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
Tim Northoverf3be9d52015-12-02 00:33:54 +00004445 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004446 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4447 EVT VT = Op.getValueType();
4448 unsigned VTBits = VT.getSizeInBits();
4449 SDLoc dl(Op);
4450 SDValue ShOpLo = Op.getOperand(0);
4451 SDValue ShOpHi = Op.getOperand(1);
4452 SDValue ShAmt = Op.getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00004453
4454 assert(Op.getOpcode() == ISD::SHL_PARTS);
4455 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004456 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
Tim Northoverf3be9d52015-12-02 00:33:54 +00004457 SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4458
4459 // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
4460 // is "undef". We wanted 0, so CSEL it directly.
4461 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
4462 ISD::SETEQ, dl, DAG);
4463 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
4464 LoBitsForHi =
4465 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
4466 LoBitsForHi, CCVal, Cmp);
4467
Tim Northover3b0846e2014-05-24 12:50:23 +00004468 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004469 DAG.getConstant(VTBits, dl, MVT::i64));
Tim Northoverf3be9d52015-12-02 00:33:54 +00004470 SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4471 SDValue HiForNormalShift =
4472 DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
Tim Northover3b0846e2014-05-24 12:50:23 +00004473
Tim Northoverf3be9d52015-12-02 00:33:54 +00004474 SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
Tim Northover3b0846e2014-05-24 12:50:23 +00004475
Tim Northoverf3be9d52015-12-02 00:33:54 +00004476 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
4477 dl, DAG);
4478 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4479 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
4480 HiForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00004481
4482 // AArch64 shifts of larger than register sizes are wrapped rather than
4483 // clamped, so we can't just emit "lo << a" if a is too big.
Tim Northoverf3be9d52015-12-02 00:33:54 +00004484 SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
4485 SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4486 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
4487 LoForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00004488
4489 SDValue Ops[2] = { Lo, Hi };
4490 return DAG.getMergeValues(Ops, dl);
4491}
4492
4493bool AArch64TargetLowering::isOffsetFoldingLegal(
4494 const GlobalAddressSDNode *GA) const {
4495 // The AArch64 target doesn't support folding offsets into global addresses.
4496 return false;
4497}
4498
4499bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4500 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
4501 // FIXME: We should be able to handle f128 as well with a clever lowering.
4502 if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32))
4503 return true;
4504
4505 if (VT == MVT::f64)
4506 return AArch64_AM::getFP64Imm(Imm) != -1;
4507 else if (VT == MVT::f32)
4508 return AArch64_AM::getFP32Imm(Imm) != -1;
4509 return false;
4510}
4511
4512//===----------------------------------------------------------------------===//
4513// AArch64 Optimization Hooks
4514//===----------------------------------------------------------------------===//
4515
4516//===----------------------------------------------------------------------===//
4517// AArch64 Inline Assembly Support
4518//===----------------------------------------------------------------------===//
4519
4520// Table of Constraints
4521// TODO: This is the current set of constraints supported by ARM for the
4522// compiler, not all of them may make sense, e.g. S may be difficult to support.
4523//
4524// r - A general register
4525// w - An FP/SIMD register of some size in the range v0-v31
4526// x - An FP/SIMD register of some size in the range v0-v15
4527// I - Constant that can be used with an ADD instruction
4528// J - Constant that can be used with a SUB instruction
4529// K - Constant that can be used with a 32-bit logical instruction
4530// L - Constant that can be used with a 64-bit logical instruction
4531// M - Constant that can be used as a 32-bit MOV immediate
4532// N - Constant that can be used as a 64-bit MOV immediate
4533// Q - A memory reference with base register and no offset
4534// S - A symbolic address
4535// Y - Floating point constant zero
4536// Z - Integer constant zero
4537//
4538// Note that general register operands will be output using their 64-bit x
4539// register name, whatever the size of the variable, unless the asm operand
4540// is prefixed by the %w modifier. Floating-point and SIMD register operands
4541// will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
4542// %q modifier.
4543
4544/// getConstraintType - Given a constraint letter, return the type of
4545/// constraint it is for this target.
4546AArch64TargetLowering::ConstraintType
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00004547AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004548 if (Constraint.size() == 1) {
4549 switch (Constraint[0]) {
4550 default:
4551 break;
4552 case 'z':
4553 return C_Other;
4554 case 'x':
4555 case 'w':
4556 return C_RegisterClass;
4557 // An address with a single base register. Due to the way we
4558 // currently handle addresses it is the same as 'r'.
4559 case 'Q':
4560 return C_Memory;
4561 }
4562 }
4563 return TargetLowering::getConstraintType(Constraint);
4564}
4565
4566/// Examine constraint type and operand type and determine a weight value.
4567/// This object must already have been set up with the operand type
4568/// and the current alternative constraint selected.
4569TargetLowering::ConstraintWeight
4570AArch64TargetLowering::getSingleConstraintMatchWeight(
4571 AsmOperandInfo &info, const char *constraint) const {
4572 ConstraintWeight weight = CW_Invalid;
4573 Value *CallOperandVal = info.CallOperandVal;
4574 // If we don't have a value, we can't do a match,
4575 // but allow it at the lowest weight.
4576 if (!CallOperandVal)
4577 return CW_Default;
4578 Type *type = CallOperandVal->getType();
4579 // Look at the constraint type.
4580 switch (*constraint) {
4581 default:
4582 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
4583 break;
4584 case 'x':
4585 case 'w':
4586 if (type->isFloatingPointTy() || type->isVectorTy())
4587 weight = CW_Register;
4588 break;
4589 case 'z':
4590 weight = CW_Constant;
4591 break;
4592 }
4593 return weight;
4594}
4595
4596std::pair<unsigned, const TargetRegisterClass *>
4597AArch64TargetLowering::getRegForInlineAsmConstraint(
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00004598 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004599 if (Constraint.size() == 1) {
4600 switch (Constraint[0]) {
4601 case 'r':
4602 if (VT.getSizeInBits() == 64)
4603 return std::make_pair(0U, &AArch64::GPR64commonRegClass);
4604 return std::make_pair(0U, &AArch64::GPR32commonRegClass);
4605 case 'w':
4606 if (VT == MVT::f32)
4607 return std::make_pair(0U, &AArch64::FPR32RegClass);
4608 if (VT.getSizeInBits() == 64)
4609 return std::make_pair(0U, &AArch64::FPR64RegClass);
4610 if (VT.getSizeInBits() == 128)
4611 return std::make_pair(0U, &AArch64::FPR128RegClass);
4612 break;
4613 // The instructions that this constraint is designed for can
4614 // only take 128-bit registers so just use that regclass.
4615 case 'x':
4616 if (VT.getSizeInBits() == 128)
4617 return std::make_pair(0U, &AArch64::FPR128_loRegClass);
4618 break;
4619 }
4620 }
4621 if (StringRef("{cc}").equals_lower(Constraint))
4622 return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
4623
4624 // Use the default implementation in TargetLowering to convert the register
4625 // constraint into a member of a register class.
4626 std::pair<unsigned, const TargetRegisterClass *> Res;
Eric Christopher11e4df72015-02-26 22:38:43 +00004627 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004628
4629 // Not found as a standard register?
4630 if (!Res.second) {
4631 unsigned Size = Constraint.size();
4632 if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
4633 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00004634 int RegNo;
4635 bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
4636 if (!Failed && RegNo >= 0 && RegNo <= 31) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004637 // v0 - v31 are aliases of q0 - q31.
4638 // By default we'll emit v0-v31 for this unless there's a modifier where
4639 // we'll emit the correct register as well.
4640 Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
4641 Res.second = &AArch64::FPR128RegClass;
4642 }
4643 }
4644 }
4645
4646 return Res;
4647}
4648
4649/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
4650/// vector. If it is invalid, don't add anything to Ops.
4651void AArch64TargetLowering::LowerAsmOperandForConstraint(
4652 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
4653 SelectionDAG &DAG) const {
4654 SDValue Result;
4655
4656 // Currently only support length 1 constraints.
4657 if (Constraint.length() != 1)
4658 return;
4659
4660 char ConstraintLetter = Constraint[0];
4661 switch (ConstraintLetter) {
4662 default:
4663 break;
4664
4665 // This set of constraints deal with valid constants for various instructions.
4666 // Validate and return a target constant for them if we can.
4667 case 'z': {
4668 // 'z' maps to xzr or wzr so it needs an input of 0.
Artyom Skrobov314ee042015-11-25 19:41:11 +00004669 if (!isNullConstant(Op))
Tim Northover3b0846e2014-05-24 12:50:23 +00004670 return;
4671
4672 if (Op.getValueType() == MVT::i64)
4673 Result = DAG.getRegister(AArch64::XZR, MVT::i64);
4674 else
4675 Result = DAG.getRegister(AArch64::WZR, MVT::i32);
4676 break;
4677 }
4678
4679 case 'I':
4680 case 'J':
4681 case 'K':
4682 case 'L':
4683 case 'M':
4684 case 'N':
4685 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4686 if (!C)
4687 return;
4688
4689 // Grab the value and do some validation.
4690 uint64_t CVal = C->getZExtValue();
4691 switch (ConstraintLetter) {
4692 // The I constraint applies only to simple ADD or SUB immediate operands:
4693 // i.e. 0 to 4095 with optional shift by 12
4694 // The J constraint applies only to ADD or SUB immediates that would be
4695 // valid when negated, i.e. if [an add pattern] were to be output as a SUB
4696 // instruction [or vice versa], in other words -1 to -4095 with optional
4697 // left shift by 12.
4698 case 'I':
4699 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
4700 break;
4701 return;
4702 case 'J': {
4703 uint64_t NVal = -C->getSExtValue();
Tim Northover2c46beb2014-07-27 07:10:29 +00004704 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
4705 CVal = C->getSExtValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00004706 break;
Tim Northover2c46beb2014-07-27 07:10:29 +00004707 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004708 return;
4709 }
4710 // The K and L constraints apply *only* to logical immediates, including
4711 // what used to be the MOVI alias for ORR (though the MOVI alias has now
4712 // been removed and MOV should be used). So these constraints have to
4713 // distinguish between bit patterns that are valid 32-bit or 64-bit
4714 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
4715 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
4716 // versa.
4717 case 'K':
4718 if (AArch64_AM::isLogicalImmediate(CVal, 32))
4719 break;
4720 return;
4721 case 'L':
4722 if (AArch64_AM::isLogicalImmediate(CVal, 64))
4723 break;
4724 return;
4725 // The M and N constraints are a superset of K and L respectively, for use
4726 // with the MOV (immediate) alias. As well as the logical immediates they
4727 // also match 32 or 64-bit immediates that can be loaded either using a
4728 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
4729 // (M) or 64-bit 0x1234000000000000 (N) etc.
4730 // As a note some of this code is liberally stolen from the asm parser.
4731 case 'M': {
4732 if (!isUInt<32>(CVal))
4733 return;
4734 if (AArch64_AM::isLogicalImmediate(CVal, 32))
4735 break;
4736 if ((CVal & 0xFFFF) == CVal)
4737 break;
4738 if ((CVal & 0xFFFF0000ULL) == CVal)
4739 break;
4740 uint64_t NCVal = ~(uint32_t)CVal;
4741 if ((NCVal & 0xFFFFULL) == NCVal)
4742 break;
4743 if ((NCVal & 0xFFFF0000ULL) == NCVal)
4744 break;
4745 return;
4746 }
4747 case 'N': {
4748 if (AArch64_AM::isLogicalImmediate(CVal, 64))
4749 break;
4750 if ((CVal & 0xFFFFULL) == CVal)
4751 break;
4752 if ((CVal & 0xFFFF0000ULL) == CVal)
4753 break;
4754 if ((CVal & 0xFFFF00000000ULL) == CVal)
4755 break;
4756 if ((CVal & 0xFFFF000000000000ULL) == CVal)
4757 break;
4758 uint64_t NCVal = ~CVal;
4759 if ((NCVal & 0xFFFFULL) == NCVal)
4760 break;
4761 if ((NCVal & 0xFFFF0000ULL) == NCVal)
4762 break;
4763 if ((NCVal & 0xFFFF00000000ULL) == NCVal)
4764 break;
4765 if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
4766 break;
4767 return;
4768 }
4769 default:
4770 return;
4771 }
4772
4773 // All assembler immediates are 64-bit integers.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004774 Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00004775 break;
4776 }
4777
4778 if (Result.getNode()) {
4779 Ops.push_back(Result);
4780 return;
4781 }
4782
4783 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
4784}
4785
4786//===----------------------------------------------------------------------===//
4787// AArch64 Advanced SIMD Support
4788//===----------------------------------------------------------------------===//
4789
4790/// WidenVector - Given a value in the V64 register class, produce the
4791/// equivalent value in the V128 register class.
4792static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
4793 EVT VT = V64Reg.getValueType();
4794 unsigned NarrowSize = VT.getVectorNumElements();
4795 MVT EltTy = VT.getVectorElementType().getSimpleVT();
4796 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
4797 SDLoc DL(V64Reg);
4798
4799 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004800 V64Reg, DAG.getConstant(0, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00004801}
4802
4803/// getExtFactor - Determine the adjustment factor for the position when
4804/// generating an "extract from vector registers" instruction.
4805static unsigned getExtFactor(SDValue &V) {
4806 EVT EltType = V.getValueType().getVectorElementType();
4807 return EltType.getSizeInBits() / 8;
4808}
4809
4810/// NarrowVector - Given a value in the V128 register class, produce the
4811/// equivalent value in the V64 register class.
4812static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
4813 EVT VT = V128Reg.getValueType();
4814 unsigned WideSize = VT.getVectorNumElements();
4815 MVT EltTy = VT.getVectorElementType().getSimpleVT();
4816 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
4817 SDLoc DL(V128Reg);
4818
4819 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
4820}
4821
4822// Gather data to see if the operation can be modelled as a
4823// shuffle in combination with VEXTs.
4824SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
4825 SelectionDAG &DAG) const {
Kevin Qinf0ec9af2014-06-18 05:54:42 +00004826 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
Tim Northover3b0846e2014-05-24 12:50:23 +00004827 SDLoc dl(Op);
4828 EVT VT = Op.getValueType();
4829 unsigned NumElts = VT.getVectorNumElements();
4830
Tim Northover7324e842014-07-24 15:39:55 +00004831 struct ShuffleSourceInfo {
4832 SDValue Vec;
4833 unsigned MinElt;
4834 unsigned MaxElt;
Tim Northover3b0846e2014-05-24 12:50:23 +00004835
Tim Northover7324e842014-07-24 15:39:55 +00004836 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
4837 // be compatible with the shuffle we intend to construct. As a result
4838 // ShuffleVec will be some sliding window into the original Vec.
4839 SDValue ShuffleVec;
4840
4841 // Code should guarantee that element i in Vec starts at element "WindowBase
4842 // + i * WindowScale in ShuffleVec".
4843 int WindowBase;
4844 int WindowScale;
4845
4846 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
4847 ShuffleSourceInfo(SDValue Vec)
4848 : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
4849 WindowScale(1) {}
4850 };
4851
4852 // First gather all vectors used as an immediate source for this BUILD_VECTOR
4853 // node.
4854 SmallVector<ShuffleSourceInfo, 2> Sources;
Tim Northover3b0846e2014-05-24 12:50:23 +00004855 for (unsigned i = 0; i < NumElts; ++i) {
4856 SDValue V = Op.getOperand(i);
4857 if (V.getOpcode() == ISD::UNDEF)
4858 continue;
4859 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
4860 // A shuffle can only come from building a vector from various
4861 // elements of other vectors.
4862 return SDValue();
4863 }
4864
Tim Northover7324e842014-07-24 15:39:55 +00004865 // Add this element source to the list if it's not already there.
Tim Northover3b0846e2014-05-24 12:50:23 +00004866 SDValue SourceVec = V.getOperand(0);
Tim Northover7324e842014-07-24 15:39:55 +00004867 auto Source = std::find(Sources.begin(), Sources.end(), SourceVec);
4868 if (Source == Sources.end())
James Molloyf497d552014-10-17 17:06:31 +00004869 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
Tim Northover3b0846e2014-05-24 12:50:23 +00004870
Tim Northover7324e842014-07-24 15:39:55 +00004871 // Update the minimum and maximum lane number seen.
4872 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4873 Source->MinElt = std::min(Source->MinElt, EltNo);
4874 Source->MaxElt = std::max(Source->MaxElt, EltNo);
Tim Northover3b0846e2014-05-24 12:50:23 +00004875 }
4876
4877 // Currently only do something sane when at most two source vectors
Tim Northover7324e842014-07-24 15:39:55 +00004878 // are involved.
4879 if (Sources.size() > 2)
Tim Northover3b0846e2014-05-24 12:50:23 +00004880 return SDValue();
4881
Kevin Qin9a2a2c52014-07-24 02:05:42 +00004882 // Find out the smallest element size among result and two sources, and use
4883 // it as element size to build the shuffle_vector.
4884 EVT SmallestEltTy = VT.getVectorElementType();
Tim Northover7324e842014-07-24 15:39:55 +00004885 for (auto &Source : Sources) {
4886 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00004887 if (SrcEltTy.bitsLT(SmallestEltTy)) {
4888 SmallestEltTy = SrcEltTy;
4889 }
4890 }
4891 unsigned ResMultiplier =
4892 VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00004893 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
4894 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
Tim Northover3b0846e2014-05-24 12:50:23 +00004895
Tim Northover7324e842014-07-24 15:39:55 +00004896 // If the source vector is too wide or too narrow, we may nevertheless be able
4897 // to construct a compatible shuffle either by concatenating it with UNDEF or
4898 // extracting a suitable range of elements.
4899 for (auto &Src : Sources) {
4900 EVT SrcVT = Src.ShuffleVec.getValueType();
Kevin Qinf0ec9af2014-06-18 05:54:42 +00004901
Tim Northover7324e842014-07-24 15:39:55 +00004902 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
Tim Northover3b0846e2014-05-24 12:50:23 +00004903 continue;
Tim Northover7324e842014-07-24 15:39:55 +00004904
4905 // This stage of the search produces a source with the same element type as
4906 // the original, but with a total width matching the BUILD_VECTOR output.
4907 EVT EltVT = SrcVT.getVectorElementType();
James Molloyf497d552014-10-17 17:06:31 +00004908 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
4909 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
Tim Northover7324e842014-07-24 15:39:55 +00004910
4911 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
4912 assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00004913 // We can pad out the smaller vector for free, so if it's part of a
4914 // shuffle...
Tim Northover7324e842014-07-24 15:39:55 +00004915 Src.ShuffleVec =
4916 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
4917 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00004918 continue;
4919 }
4920
Tim Northover7324e842014-07-24 15:39:55 +00004921 assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00004922
James Molloyf497d552014-10-17 17:06:31 +00004923 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004924 // Span too large for a VEXT to cope
4925 return SDValue();
4926 }
4927
James Molloyf497d552014-10-17 17:06:31 +00004928 if (Src.MinElt >= NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004929 // The extraction can just take the second half
Tim Northover7324e842014-07-24 15:39:55 +00004930 Src.ShuffleVec =
4931 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004932 DAG.getConstant(NumSrcElts, dl, MVT::i64));
James Molloyf497d552014-10-17 17:06:31 +00004933 Src.WindowBase = -NumSrcElts;
4934 } else if (Src.MaxElt < NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004935 // The extraction can just take the first half
Tim Northover5e84fe32014-12-06 00:33:37 +00004936 Src.ShuffleVec =
4937 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004938 DAG.getConstant(0, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00004939 } else {
4940 // An actual VEXT is needed
Tim Northover5e84fe32014-12-06 00:33:37 +00004941 SDValue VEXTSrc1 =
4942 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004943 DAG.getConstant(0, dl, MVT::i64));
Tim Northover7324e842014-07-24 15:39:55 +00004944 SDValue VEXTSrc2 =
4945 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004946 DAG.getConstant(NumSrcElts, dl, MVT::i64));
Tim Northover7324e842014-07-24 15:39:55 +00004947 unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
4948
4949 Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004950 VEXTSrc2,
4951 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover7324e842014-07-24 15:39:55 +00004952 Src.WindowBase = -Src.MinElt;
Tim Northover3b0846e2014-05-24 12:50:23 +00004953 }
4954 }
4955
Tim Northover7324e842014-07-24 15:39:55 +00004956 // Another possible incompatibility occurs from the vector element types. We
4957 // can fix this by bitcasting the source vectors to the same type we intend
4958 // for the shuffle.
4959 for (auto &Src : Sources) {
4960 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
4961 if (SrcEltTy == SmallestEltTy)
4962 continue;
4963 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
4964 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
4965 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
4966 Src.WindowBase *= Src.WindowScale;
4967 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004968
Tim Northover7324e842014-07-24 15:39:55 +00004969 // Final sanity check before we try to actually produce a shuffle.
4970 DEBUG(
4971 for (auto Src : Sources)
4972 assert(Src.ShuffleVec.getValueType() == ShuffleVT);
4973 );
4974
4975 // The stars all align, our next step is to produce the mask for the shuffle.
4976 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
4977 int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00004978 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004979 SDValue Entry = Op.getOperand(i);
Tim Northover7324e842014-07-24 15:39:55 +00004980 if (Entry.getOpcode() == ISD::UNDEF)
4981 continue;
Tim Northover3b0846e2014-05-24 12:50:23 +00004982
Tim Northover7324e842014-07-24 15:39:55 +00004983 auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0));
4984 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
4985
4986 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
4987 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
4988 // segment.
4989 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
4990 int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
4991 VT.getVectorElementType().getSizeInBits());
4992 int LanesDefined = BitsDefined / BitsPerShuffleLane;
4993
4994 // This source is expected to fill ResMultiplier lanes of the final shuffle,
4995 // starting at the appropriate offset.
4996 int *LaneMask = &Mask[i * ResMultiplier];
4997
4998 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
4999 ExtractBase += NumElts * (Src - Sources.begin());
5000 for (int j = 0; j < LanesDefined; ++j)
5001 LaneMask[j] = ExtractBase + j;
Tim Northover3b0846e2014-05-24 12:50:23 +00005002 }
5003
5004 // Final check before we try to produce nonsense...
Tim Northover7324e842014-07-24 15:39:55 +00005005 if (!isShuffleMaskLegal(Mask, ShuffleVT))
5006 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00005007
Tim Northover7324e842014-07-24 15:39:55 +00005008 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
5009 for (unsigned i = 0; i < Sources.size(); ++i)
5010 ShuffleOps[i] = Sources[i].ShuffleVec;
5011
5012 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
5013 ShuffleOps[1], &Mask[0]);
5014 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
Tim Northover3b0846e2014-05-24 12:50:23 +00005015}
5016
5017// check if an EXT instruction can handle the shuffle mask when the
5018// vector sources of the shuffle are the same.
5019static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
5020 unsigned NumElts = VT.getVectorNumElements();
5021
5022 // Assume that the first shuffle index is not UNDEF. Fail if it is.
5023 if (M[0] < 0)
5024 return false;
5025
5026 Imm = M[0];
5027
5028 // If this is a VEXT shuffle, the immediate value is the index of the first
5029 // element. The other shuffle indices must be the successive elements after
5030 // the first one.
5031 unsigned ExpectedElt = Imm;
5032 for (unsigned i = 1; i < NumElts; ++i) {
5033 // Increment the expected index. If it wraps around, just follow it
5034 // back to index zero and keep going.
5035 ++ExpectedElt;
5036 if (ExpectedElt == NumElts)
5037 ExpectedElt = 0;
5038
5039 if (M[i] < 0)
5040 continue; // ignore UNDEF indices
5041 if (ExpectedElt != static_cast<unsigned>(M[i]))
5042 return false;
5043 }
5044
5045 return true;
5046}
5047
5048// check if an EXT instruction can handle the shuffle mask when the
5049// vector sources of the shuffle are different.
5050static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
5051 unsigned &Imm) {
5052 // Look for the first non-undef element.
5053 const int *FirstRealElt = std::find_if(M.begin(), M.end(),
5054 [](int Elt) {return Elt >= 0;});
5055
5056 // Benefit form APInt to handle overflow when calculating expected element.
5057 unsigned NumElts = VT.getVectorNumElements();
5058 unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
5059 APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
5060 // The following shuffle indices must be the successive elements after the
5061 // first real element.
5062 const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
5063 [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
5064 if (FirstWrongElt != M.end())
5065 return false;
5066
5067 // The index of an EXT is the first element if it is not UNDEF.
5068 // Watch out for the beginning UNDEFs. The EXT index should be the expected
5069 // value of the first element. E.g.
5070 // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
5071 // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
5072 // ExpectedElt is the last mask index plus 1.
5073 Imm = ExpectedElt.getZExtValue();
5074
5075 // There are two difference cases requiring to reverse input vectors.
5076 // For example, for vector <4 x i32> we have the following cases,
5077 // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
5078 // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
5079 // For both cases, we finally use mask <5, 6, 7, 0>, which requires
5080 // to reverse two input vectors.
5081 if (Imm < NumElts)
5082 ReverseEXT = true;
5083 else
5084 Imm -= NumElts;
5085
5086 return true;
5087}
5088
5089/// isREVMask - Check if a vector shuffle corresponds to a REV
5090/// instruction with the specified blocksize. (The order of the elements
5091/// within each block of the vector is reversed.)
5092static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5093 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
5094 "Only possible block sizes for REV are: 16, 32, 64");
5095
5096 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5097 if (EltSz == 64)
5098 return false;
5099
5100 unsigned NumElts = VT.getVectorNumElements();
5101 unsigned BlockElts = M[0] + 1;
5102 // If the first shuffle index is UNDEF, be optimistic.
5103 if (M[0] < 0)
5104 BlockElts = BlockSize / EltSz;
5105
5106 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5107 return false;
5108
5109 for (unsigned i = 0; i < NumElts; ++i) {
5110 if (M[i] < 0)
5111 continue; // ignore UNDEF indices
5112 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
5113 return false;
5114 }
5115
5116 return true;
5117}
5118
5119static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5120 unsigned NumElts = VT.getVectorNumElements();
5121 WhichResult = (M[0] == 0 ? 0 : 1);
5122 unsigned Idx = WhichResult * NumElts / 2;
5123 for (unsigned i = 0; i != NumElts; i += 2) {
5124 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5125 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
5126 return false;
5127 Idx += 1;
5128 }
5129
5130 return true;
5131}
5132
5133static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5134 unsigned NumElts = VT.getVectorNumElements();
5135 WhichResult = (M[0] == 0 ? 0 : 1);
5136 for (unsigned i = 0; i != NumElts; ++i) {
5137 if (M[i] < 0)
5138 continue; // ignore UNDEF indices
5139 if ((unsigned)M[i] != 2 * i + WhichResult)
5140 return false;
5141 }
5142
5143 return true;
5144}
5145
5146static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5147 unsigned NumElts = VT.getVectorNumElements();
5148 WhichResult = (M[0] == 0 ? 0 : 1);
5149 for (unsigned i = 0; i < NumElts; i += 2) {
5150 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5151 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
5152 return false;
5153 }
5154 return true;
5155}
5156
5157/// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
5158/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5159/// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5160static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5161 unsigned NumElts = VT.getVectorNumElements();
5162 WhichResult = (M[0] == 0 ? 0 : 1);
5163 unsigned Idx = WhichResult * NumElts / 2;
5164 for (unsigned i = 0; i != NumElts; i += 2) {
5165 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5166 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
5167 return false;
5168 Idx += 1;
5169 }
5170
5171 return true;
5172}
5173
5174/// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
5175/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5176/// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5177static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5178 unsigned Half = VT.getVectorNumElements() / 2;
5179 WhichResult = (M[0] == 0 ? 0 : 1);
5180 for (unsigned j = 0; j != 2; ++j) {
5181 unsigned Idx = WhichResult;
5182 for (unsigned i = 0; i != Half; ++i) {
5183 int MIdx = M[i + j * Half];
5184 if (MIdx >= 0 && (unsigned)MIdx != Idx)
5185 return false;
5186 Idx += 2;
5187 }
5188 }
5189
5190 return true;
5191}
5192
5193/// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
5194/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5195/// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5196static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5197 unsigned NumElts = VT.getVectorNumElements();
5198 WhichResult = (M[0] == 0 ? 0 : 1);
5199 for (unsigned i = 0; i < NumElts; i += 2) {
5200 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5201 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
5202 return false;
5203 }
5204 return true;
5205}
5206
5207static bool isINSMask(ArrayRef<int> M, int NumInputElements,
5208 bool &DstIsLeft, int &Anomaly) {
5209 if (M.size() != static_cast<size_t>(NumInputElements))
5210 return false;
5211
5212 int NumLHSMatch = 0, NumRHSMatch = 0;
5213 int LastLHSMismatch = -1, LastRHSMismatch = -1;
5214
5215 for (int i = 0; i < NumInputElements; ++i) {
5216 if (M[i] == -1) {
5217 ++NumLHSMatch;
5218 ++NumRHSMatch;
5219 continue;
5220 }
5221
5222 if (M[i] == i)
5223 ++NumLHSMatch;
5224 else
5225 LastLHSMismatch = i;
5226
5227 if (M[i] == i + NumInputElements)
5228 ++NumRHSMatch;
5229 else
5230 LastRHSMismatch = i;
5231 }
5232
5233 if (NumLHSMatch == NumInputElements - 1) {
5234 DstIsLeft = true;
5235 Anomaly = LastLHSMismatch;
5236 return true;
5237 } else if (NumRHSMatch == NumInputElements - 1) {
5238 DstIsLeft = false;
5239 Anomaly = LastRHSMismatch;
5240 return true;
5241 }
5242
5243 return false;
5244}
5245
5246static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
5247 if (VT.getSizeInBits() != 128)
5248 return false;
5249
5250 unsigned NumElts = VT.getVectorNumElements();
5251
5252 for (int I = 0, E = NumElts / 2; I != E; I++) {
5253 if (Mask[I] != I)
5254 return false;
5255 }
5256
5257 int Offset = NumElts / 2;
5258 for (int I = NumElts / 2, E = NumElts; I != E; I++) {
5259 if (Mask[I] != I + SplitLHS * Offset)
5260 return false;
5261 }
5262
5263 return true;
5264}
5265
5266static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
5267 SDLoc DL(Op);
5268 EVT VT = Op.getValueType();
5269 SDValue V0 = Op.getOperand(0);
5270 SDValue V1 = Op.getOperand(1);
5271 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
5272
5273 if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
5274 VT.getVectorElementType() != V1.getValueType().getVectorElementType())
5275 return SDValue();
5276
5277 bool SplitV0 = V0.getValueType().getSizeInBits() == 128;
5278
5279 if (!isConcatMask(Mask, VT, SplitV0))
5280 return SDValue();
5281
5282 EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
5283 VT.getVectorNumElements() / 2);
5284 if (SplitV0) {
5285 V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005286 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005287 }
5288 if (V1.getValueType().getSizeInBits() == 128) {
5289 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005290 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005291 }
5292 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
5293}
5294
5295/// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5296/// the specified operations to build the shuffle.
5297static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5298 SDValue RHS, SelectionDAG &DAG,
5299 SDLoc dl) {
5300 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5301 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
5302 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
5303
5304 enum {
5305 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5306 OP_VREV,
5307 OP_VDUP0,
5308 OP_VDUP1,
5309 OP_VDUP2,
5310 OP_VDUP3,
5311 OP_VEXT1,
5312 OP_VEXT2,
5313 OP_VEXT3,
5314 OP_VUZPL, // VUZP, left result
5315 OP_VUZPR, // VUZP, right result
5316 OP_VZIPL, // VZIP, left result
5317 OP_VZIPR, // VZIP, right result
5318 OP_VTRNL, // VTRN, left result
5319 OP_VTRNR // VTRN, right result
5320 };
5321
5322 if (OpNum == OP_COPY) {
5323 if (LHSID == (1 * 9 + 2) * 9 + 3)
5324 return LHS;
5325 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
5326 return RHS;
5327 }
5328
5329 SDValue OpLHS, OpRHS;
5330 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5331 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5332 EVT VT = OpLHS.getValueType();
5333
5334 switch (OpNum) {
5335 default:
5336 llvm_unreachable("Unknown shuffle opcode!");
5337 case OP_VREV:
5338 // VREV divides the vector in half and swaps within the half.
5339 if (VT.getVectorElementType() == MVT::i32 ||
5340 VT.getVectorElementType() == MVT::f32)
5341 return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
5342 // vrev <4 x i16> -> REV32
Oliver Stannard89d15422014-08-27 16:16:04 +00005343 if (VT.getVectorElementType() == MVT::i16 ||
5344 VT.getVectorElementType() == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00005345 return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
5346 // vrev <4 x i8> -> REV16
5347 assert(VT.getVectorElementType() == MVT::i8);
5348 return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
5349 case OP_VDUP0:
5350 case OP_VDUP1:
5351 case OP_VDUP2:
5352 case OP_VDUP3: {
5353 EVT EltTy = VT.getVectorElementType();
5354 unsigned Opcode;
5355 if (EltTy == MVT::i8)
5356 Opcode = AArch64ISD::DUPLANE8;
Ahmed Bougacha941420d2015-04-16 23:57:07 +00005357 else if (EltTy == MVT::i16 || EltTy == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00005358 Opcode = AArch64ISD::DUPLANE16;
5359 else if (EltTy == MVT::i32 || EltTy == MVT::f32)
5360 Opcode = AArch64ISD::DUPLANE32;
5361 else if (EltTy == MVT::i64 || EltTy == MVT::f64)
5362 Opcode = AArch64ISD::DUPLANE64;
5363 else
5364 llvm_unreachable("Invalid vector element type?");
5365
5366 if (VT.getSizeInBits() == 64)
5367 OpLHS = WidenVector(OpLHS, DAG);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005368 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00005369 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
5370 }
5371 case OP_VEXT1:
5372 case OP_VEXT2:
5373 case OP_VEXT3: {
5374 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
5375 return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005376 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005377 }
5378 case OP_VUZPL:
5379 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
5380 OpRHS);
5381 case OP_VUZPR:
5382 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
5383 OpRHS);
5384 case OP_VZIPL:
5385 return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
5386 OpRHS);
5387 case OP_VZIPR:
5388 return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
5389 OpRHS);
5390 case OP_VTRNL:
5391 return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
5392 OpRHS);
5393 case OP_VTRNR:
5394 return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
5395 OpRHS);
5396 }
5397}
5398
5399static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
5400 SelectionDAG &DAG) {
5401 // Check to see if we can use the TBL instruction.
5402 SDValue V1 = Op.getOperand(0);
5403 SDValue V2 = Op.getOperand(1);
5404 SDLoc DL(Op);
5405
5406 EVT EltVT = Op.getValueType().getVectorElementType();
5407 unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
5408
5409 SmallVector<SDValue, 8> TBLMask;
5410 for (int Val : ShuffleMask) {
5411 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
5412 unsigned Offset = Byte + Val * BytesPerElt;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005413 TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005414 }
5415 }
5416
5417 MVT IndexVT = MVT::v8i8;
5418 unsigned IndexLen = 8;
5419 if (Op.getValueType().getSizeInBits() == 128) {
5420 IndexVT = MVT::v16i8;
5421 IndexLen = 16;
5422 }
5423
5424 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
5425 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
5426
5427 SDValue Shuffle;
5428 if (V2.getNode()->getOpcode() == ISD::UNDEF) {
5429 if (IndexLen == 8)
5430 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
5431 Shuffle = DAG.getNode(
5432 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005433 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
Tim Northover3b0846e2014-05-24 12:50:23 +00005434 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5435 makeArrayRef(TBLMask.data(), IndexLen)));
5436 } else {
5437 if (IndexLen == 8) {
5438 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
5439 Shuffle = DAG.getNode(
5440 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005441 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
Tim Northover3b0846e2014-05-24 12:50:23 +00005442 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5443 makeArrayRef(TBLMask.data(), IndexLen)));
5444 } else {
5445 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
5446 // cannot currently represent the register constraints on the input
5447 // table registers.
5448 // Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
5449 // DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5450 // &TBLMask[0], IndexLen));
5451 Shuffle = DAG.getNode(
5452 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005453 DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32),
5454 V1Cst, V2Cst,
Tim Northover3b0846e2014-05-24 12:50:23 +00005455 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5456 makeArrayRef(TBLMask.data(), IndexLen)));
5457 }
5458 }
5459 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
5460}
5461
5462static unsigned getDUPLANEOp(EVT EltType) {
5463 if (EltType == MVT::i8)
5464 return AArch64ISD::DUPLANE8;
Oliver Stannard89d15422014-08-27 16:16:04 +00005465 if (EltType == MVT::i16 || EltType == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00005466 return AArch64ISD::DUPLANE16;
5467 if (EltType == MVT::i32 || EltType == MVT::f32)
5468 return AArch64ISD::DUPLANE32;
5469 if (EltType == MVT::i64 || EltType == MVT::f64)
5470 return AArch64ISD::DUPLANE64;
5471
5472 llvm_unreachable("Invalid vector element type?");
5473}
5474
5475SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5476 SelectionDAG &DAG) const {
5477 SDLoc dl(Op);
5478 EVT VT = Op.getValueType();
5479
5480 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5481
5482 // Convert shuffles that are directly supported on NEON to target-specific
5483 // DAG nodes, instead of keeping them as shuffles and matching them again
5484 // during code selection. This is more efficient and avoids the possibility
5485 // of inconsistencies between legalization and selection.
5486 ArrayRef<int> ShuffleMask = SVN->getMask();
5487
5488 SDValue V1 = Op.getOperand(0);
5489 SDValue V2 = Op.getOperand(1);
5490
5491 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0],
5492 V1.getValueType().getSimpleVT())) {
5493 int Lane = SVN->getSplatIndex();
5494 // If this is undef splat, generate it via "just" vdup, if possible.
5495 if (Lane == -1)
5496 Lane = 0;
5497
5498 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
5499 return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
5500 V1.getOperand(0));
5501 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
5502 // constant. If so, we can just reference the lane's definition directly.
5503 if (V1.getOpcode() == ISD::BUILD_VECTOR &&
5504 !isa<ConstantSDNode>(V1.getOperand(Lane)))
5505 return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
5506
5507 // Otherwise, duplicate from the lane of the input vector.
5508 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
5509
5510 // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
5511 // to make a vector of the same size as this SHUFFLE. We can ignore the
5512 // extract entirely, and canonicalise the concat using WidenVector.
5513 if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
5514 Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
5515 V1 = V1.getOperand(0);
5516 } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
5517 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
5518 Lane -= Idx * VT.getVectorNumElements() / 2;
5519 V1 = WidenVector(V1.getOperand(Idx), DAG);
5520 } else if (VT.getSizeInBits() == 64)
5521 V1 = WidenVector(V1, DAG);
5522
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005523 return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005524 }
5525
5526 if (isREVMask(ShuffleMask, VT, 64))
5527 return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
5528 if (isREVMask(ShuffleMask, VT, 32))
5529 return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
5530 if (isREVMask(ShuffleMask, VT, 16))
5531 return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
5532
5533 bool ReverseEXT = false;
5534 unsigned Imm;
5535 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
5536 if (ReverseEXT)
5537 std::swap(V1, V2);
5538 Imm *= getExtFactor(V1);
5539 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005540 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005541 } else if (V2->getOpcode() == ISD::UNDEF &&
5542 isSingletonEXTMask(ShuffleMask, VT, Imm)) {
5543 Imm *= getExtFactor(V1);
5544 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005545 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005546 }
5547
5548 unsigned WhichResult;
5549 if (isZIPMask(ShuffleMask, VT, WhichResult)) {
5550 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5551 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5552 }
5553 if (isUZPMask(ShuffleMask, VT, WhichResult)) {
5554 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5555 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5556 }
5557 if (isTRNMask(ShuffleMask, VT, WhichResult)) {
5558 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5559 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5560 }
5561
5562 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5563 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5564 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5565 }
5566 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5567 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5568 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5569 }
5570 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5571 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5572 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5573 }
5574
5575 SDValue Concat = tryFormConcatFromShuffle(Op, DAG);
5576 if (Concat.getNode())
5577 return Concat;
5578
5579 bool DstIsLeft;
5580 int Anomaly;
5581 int NumInputElements = V1.getValueType().getVectorNumElements();
5582 if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
5583 SDValue DstVec = DstIsLeft ? V1 : V2;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005584 SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00005585
5586 SDValue SrcVec = V1;
5587 int SrcLane = ShuffleMask[Anomaly];
5588 if (SrcLane >= NumInputElements) {
5589 SrcVec = V2;
5590 SrcLane -= VT.getVectorNumElements();
5591 }
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005592 SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00005593
5594 EVT ScalarVT = VT.getVectorElementType();
Oliver Stannard89d15422014-08-27 16:16:04 +00005595
5596 if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00005597 ScalarVT = MVT::i32;
5598
5599 return DAG.getNode(
5600 ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5601 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
5602 DstLaneV);
5603 }
5604
5605 // If the shuffle is not directly supported and it has 4 elements, use
5606 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5607 unsigned NumElts = VT.getVectorNumElements();
5608 if (NumElts == 4) {
5609 unsigned PFIndexes[4];
5610 for (unsigned i = 0; i != 4; ++i) {
5611 if (ShuffleMask[i] < 0)
5612 PFIndexes[i] = 8;
5613 else
5614 PFIndexes[i] = ShuffleMask[i];
5615 }
5616
5617 // Compute the index in the perfect shuffle table.
5618 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
5619 PFIndexes[2] * 9 + PFIndexes[3];
5620 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5621 unsigned Cost = (PFEntry >> 30);
5622
5623 if (Cost <= 4)
5624 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5625 }
5626
5627 return GenerateTBL(Op, ShuffleMask, DAG);
5628}
5629
5630static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
5631 APInt &UndefBits) {
5632 EVT VT = BVN->getValueType(0);
5633 APInt SplatBits, SplatUndef;
5634 unsigned SplatBitSize;
5635 bool HasAnyUndefs;
5636 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5637 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
5638
5639 for (unsigned i = 0; i < NumSplats; ++i) {
5640 CnstBits <<= SplatBitSize;
5641 UndefBits <<= SplatBitSize;
5642 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
5643 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
5644 }
5645
5646 return true;
5647 }
5648
5649 return false;
5650}
5651
5652SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op,
5653 SelectionDAG &DAG) const {
5654 BuildVectorSDNode *BVN =
5655 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5656 SDValue LHS = Op.getOperand(0);
5657 SDLoc dl(Op);
5658 EVT VT = Op.getValueType();
5659
5660 if (!BVN)
5661 return Op;
5662
5663 APInt CnstBits(VT.getSizeInBits(), 0);
5664 APInt UndefBits(VT.getSizeInBits(), 0);
5665 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5666 // We only have BIC vector immediate instruction, which is and-not.
5667 CnstBits = ~CnstBits;
5668
5669 // We make use of a little bit of goto ickiness in order to avoid having to
5670 // duplicate the immediate matching logic for the undef toggled case.
5671 bool SecondTry = false;
5672 AttemptModImm:
5673
5674 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5675 CnstBits = CnstBits.zextOrTrunc(64);
5676 uint64_t CnstVal = CnstBits.getZExtValue();
5677
5678 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5679 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5680 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5681 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005682 DAG.getConstant(CnstVal, dl, MVT::i32),
5683 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005684 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005685 }
5686
5687 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5688 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5689 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5690 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005691 DAG.getConstant(CnstVal, dl, MVT::i32),
5692 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005693 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005694 }
5695
5696 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5697 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5698 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5699 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005700 DAG.getConstant(CnstVal, dl, MVT::i32),
5701 DAG.getConstant(16, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005702 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005703 }
5704
5705 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5706 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5707 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5708 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005709 DAG.getConstant(CnstVal, dl, MVT::i32),
5710 DAG.getConstant(24, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005711 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005712 }
5713
5714 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5715 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5716 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5717 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005718 DAG.getConstant(CnstVal, dl, MVT::i32),
5719 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005720 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005721 }
5722
5723 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5724 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5725 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5726 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005727 DAG.getConstant(CnstVal, dl, MVT::i32),
5728 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005729 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005730 }
5731 }
5732
5733 if (SecondTry)
5734 goto FailedModImm;
5735 SecondTry = true;
5736 CnstBits = ~UndefBits;
5737 goto AttemptModImm;
5738 }
5739
5740// We can always fall back to a non-immediate AND.
5741FailedModImm:
5742 return Op;
5743}
5744
5745// Specialized code to quickly find if PotentialBVec is a BuildVector that
5746// consists of only the same constant int value, returned in reference arg
5747// ConstVal
5748static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
5749 uint64_t &ConstVal) {
5750 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
5751 if (!Bvec)
5752 return false;
5753 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
5754 if (!FirstElt)
5755 return false;
5756 EVT VT = Bvec->getValueType(0);
5757 unsigned NumElts = VT.getVectorNumElements();
5758 for (unsigned i = 1; i < NumElts; ++i)
5759 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
5760 return false;
5761 ConstVal = FirstElt->getZExtValue();
5762 return true;
5763}
5764
5765static unsigned getIntrinsicID(const SDNode *N) {
5766 unsigned Opcode = N->getOpcode();
5767 switch (Opcode) {
5768 default:
5769 return Intrinsic::not_intrinsic;
5770 case ISD::INTRINSIC_WO_CHAIN: {
5771 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
5772 if (IID < Intrinsic::num_intrinsics)
5773 return IID;
5774 return Intrinsic::not_intrinsic;
5775 }
5776 }
5777}
5778
5779// Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
5780// to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
5781// BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
5782// Also, logical shift right -> sri, with the same structure.
5783static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
5784 EVT VT = N->getValueType(0);
5785
5786 if (!VT.isVector())
5787 return SDValue();
5788
5789 SDLoc DL(N);
5790
5791 // Is the first op an AND?
5792 const SDValue And = N->getOperand(0);
5793 if (And.getOpcode() != ISD::AND)
5794 return SDValue();
5795
5796 // Is the second op an shl or lshr?
5797 SDValue Shift = N->getOperand(1);
5798 // This will have been turned into: AArch64ISD::VSHL vector, #shift
5799 // or AArch64ISD::VLSHR vector, #shift
5800 unsigned ShiftOpc = Shift.getOpcode();
5801 if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
5802 return SDValue();
5803 bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
5804
5805 // Is the shift amount constant?
5806 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
5807 if (!C2node)
5808 return SDValue();
5809
5810 // Is the and mask vector all constant?
5811 uint64_t C1;
5812 if (!isAllConstantBuildVector(And.getOperand(1), C1))
5813 return SDValue();
5814
5815 // Is C1 == ~C2, taking into account how much one can shift elements of a
5816 // particular size?
5817 uint64_t C2 = C2node->getZExtValue();
5818 unsigned ElemSizeInBits = VT.getVectorElementType().getSizeInBits();
5819 if (C2 > ElemSizeInBits)
5820 return SDValue();
5821 unsigned ElemMask = (1 << ElemSizeInBits) - 1;
5822 if ((C1 & ElemMask) != (~C2 & ElemMask))
5823 return SDValue();
5824
5825 SDValue X = And.getOperand(0);
5826 SDValue Y = Shift.getOperand(0);
5827
5828 unsigned Intrin =
5829 IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
5830 SDValue ResultSLI =
5831 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005832 DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
5833 Shift.getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00005834
5835 DEBUG(dbgs() << "aarch64-lower: transformed: \n");
5836 DEBUG(N->dump(&DAG));
5837 DEBUG(dbgs() << "into: \n");
5838 DEBUG(ResultSLI->dump(&DAG));
5839
5840 ++NumShiftInserts;
5841 return ResultSLI;
5842}
5843
5844SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
5845 SelectionDAG &DAG) const {
5846 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
5847 if (EnableAArch64SlrGeneration) {
5848 SDValue Res = tryLowerToSLI(Op.getNode(), DAG);
5849 if (Res.getNode())
5850 return Res;
5851 }
5852
5853 BuildVectorSDNode *BVN =
5854 dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
5855 SDValue LHS = Op.getOperand(1);
5856 SDLoc dl(Op);
5857 EVT VT = Op.getValueType();
5858
5859 // OR commutes, so try swapping the operands.
5860 if (!BVN) {
5861 LHS = Op.getOperand(0);
5862 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5863 }
5864 if (!BVN)
5865 return Op;
5866
5867 APInt CnstBits(VT.getSizeInBits(), 0);
5868 APInt UndefBits(VT.getSizeInBits(), 0);
5869 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5870 // We make use of a little bit of goto ickiness in order to avoid having to
5871 // duplicate the immediate matching logic for the undef toggled case.
5872 bool SecondTry = false;
5873 AttemptModImm:
5874
5875 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5876 CnstBits = CnstBits.zextOrTrunc(64);
5877 uint64_t CnstVal = CnstBits.getZExtValue();
5878
5879 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5880 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5881 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5882 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005883 DAG.getConstant(CnstVal, dl, MVT::i32),
5884 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005885 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005886 }
5887
5888 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5889 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5890 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5891 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005892 DAG.getConstant(CnstVal, dl, MVT::i32),
5893 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005894 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005895 }
5896
5897 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5898 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5899 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5900 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005901 DAG.getConstant(CnstVal, dl, MVT::i32),
5902 DAG.getConstant(16, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005903 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005904 }
5905
5906 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5907 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5908 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5909 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005910 DAG.getConstant(CnstVal, dl, MVT::i32),
5911 DAG.getConstant(24, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005912 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005913 }
5914
5915 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5916 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5917 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5918 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005919 DAG.getConstant(CnstVal, dl, MVT::i32),
5920 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005921 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005922 }
5923
5924 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5925 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5926 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5927 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005928 DAG.getConstant(CnstVal, dl, MVT::i32),
5929 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005930 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005931 }
5932 }
5933
5934 if (SecondTry)
5935 goto FailedModImm;
5936 SecondTry = true;
5937 CnstBits = UndefBits;
5938 goto AttemptModImm;
5939 }
5940
5941// We can always fall back to a non-immediate OR.
5942FailedModImm:
5943 return Op;
5944}
5945
Kevin Qin4473c192014-07-07 02:45:40 +00005946// Normalize the operands of BUILD_VECTOR. The value of constant operands will
5947// be truncated to fit element width.
5948static SDValue NormalizeBuildVector(SDValue Op,
5949 SelectionDAG &DAG) {
5950 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
Tim Northover3b0846e2014-05-24 12:50:23 +00005951 SDLoc dl(Op);
5952 EVT VT = Op.getValueType();
Kevin Qin4473c192014-07-07 02:45:40 +00005953 EVT EltTy= VT.getVectorElementType();
5954
5955 if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
5956 return Op;
5957
5958 SmallVector<SDValue, 16> Ops;
Pete Cooper7be8f8f2015-08-03 19:04:32 +00005959 for (SDValue Lane : Op->ops()) {
5960 if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
Kevin Qin4473c192014-07-07 02:45:40 +00005961 APInt LowBits(EltTy.getSizeInBits(),
Pete Cooper7be8f8f2015-08-03 19:04:32 +00005962 CstLane->getZExtValue());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005963 Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
Kevin Qin4473c192014-07-07 02:45:40 +00005964 }
5965 Ops.push_back(Lane);
5966 }
5967 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5968}
5969
5970SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
5971 SelectionDAG &DAG) const {
5972 SDLoc dl(Op);
5973 EVT VT = Op.getValueType();
5974 Op = NormalizeBuildVector(Op, DAG);
5975 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
Tim Northover3b0846e2014-05-24 12:50:23 +00005976
5977 APInt CnstBits(VT.getSizeInBits(), 0);
5978 APInt UndefBits(VT.getSizeInBits(), 0);
5979 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5980 // We make use of a little bit of goto ickiness in order to avoid having to
5981 // duplicate the immediate matching logic for the undef toggled case.
5982 bool SecondTry = false;
5983 AttemptModImm:
5984
5985 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5986 CnstBits = CnstBits.zextOrTrunc(64);
5987 uint64_t CnstVal = CnstBits.getZExtValue();
5988
5989 // Certain magic vector constants (used to express things like NOT
5990 // and NEG) are passed through unmodified. This allows codegen patterns
5991 // for these operations to match. Special-purpose patterns will lower
5992 // these immediates to MOVIs if it proves necessary.
5993 if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL))
5994 return Op;
5995
5996 // The many faces of MOVI...
5997 if (AArch64_AM::isAdvSIMDModImmType10(CnstVal)) {
5998 CnstVal = AArch64_AM::encodeAdvSIMDModImmType10(CnstVal);
5999 if (VT.getSizeInBits() == 128) {
6000 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::v2i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006001 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006002 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006003 }
6004
6005 // Support the V64 version via subregister insertion.
6006 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::f64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006007 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006008 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006009 }
6010
6011 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6012 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6013 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6014 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006015 DAG.getConstant(CnstVal, dl, MVT::i32),
6016 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006017 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006018 }
6019
6020 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6021 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6022 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6023 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006024 DAG.getConstant(CnstVal, dl, MVT::i32),
6025 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006026 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006027 }
6028
6029 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6030 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6031 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6032 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006033 DAG.getConstant(CnstVal, dl, MVT::i32),
6034 DAG.getConstant(16, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006035 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006036 }
6037
6038 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6039 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6040 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6041 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006042 DAG.getConstant(CnstVal, dl, MVT::i32),
6043 DAG.getConstant(24, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006044 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006045 }
6046
6047 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6048 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6049 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6050 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006051 DAG.getConstant(CnstVal, dl, MVT::i32),
6052 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006053 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006054 }
6055
6056 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6057 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6058 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6059 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006060 DAG.getConstant(CnstVal, dl, MVT::i32),
6061 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006062 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006063 }
6064
6065 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6066 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6067 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6068 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006069 DAG.getConstant(CnstVal, dl, MVT::i32),
6070 DAG.getConstant(264, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006071 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006072 }
6073
6074 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6075 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6076 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6077 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006078 DAG.getConstant(CnstVal, dl, MVT::i32),
6079 DAG.getConstant(272, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006080 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006081 }
6082
6083 if (AArch64_AM::isAdvSIMDModImmType9(CnstVal)) {
6084 CnstVal = AArch64_AM::encodeAdvSIMDModImmType9(CnstVal);
6085 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
6086 SDValue Mov = DAG.getNode(AArch64ISD::MOVI, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006087 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006088 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006089 }
6090
6091 // The few faces of FMOV...
6092 if (AArch64_AM::isAdvSIMDModImmType11(CnstVal)) {
6093 CnstVal = AArch64_AM::encodeAdvSIMDModImmType11(CnstVal);
6094 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32;
6095 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006096 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006097 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006098 }
6099
6100 if (AArch64_AM::isAdvSIMDModImmType12(CnstVal) &&
6101 VT.getSizeInBits() == 128) {
6102 CnstVal = AArch64_AM::encodeAdvSIMDModImmType12(CnstVal);
6103 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MVT::v2f64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006104 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006105 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006106 }
6107
6108 // The many faces of MVNI...
6109 CnstVal = ~CnstVal;
6110 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6111 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6112 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6113 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006114 DAG.getConstant(CnstVal, dl, MVT::i32),
6115 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006116 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006117 }
6118
6119 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6120 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6121 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6122 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006123 DAG.getConstant(CnstVal, dl, MVT::i32),
6124 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006125 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006126 }
6127
6128 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6129 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6130 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6131 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006132 DAG.getConstant(CnstVal, dl, MVT::i32),
6133 DAG.getConstant(16, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006134 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006135 }
6136
6137 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6138 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6139 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6140 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006141 DAG.getConstant(CnstVal, dl, MVT::i32),
6142 DAG.getConstant(24, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006143 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006144 }
6145
6146 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6147 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6148 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6149 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006150 DAG.getConstant(CnstVal, dl, MVT::i32),
6151 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006152 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006153 }
6154
6155 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6156 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6157 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6158 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006159 DAG.getConstant(CnstVal, dl, MVT::i32),
6160 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006161 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006162 }
6163
6164 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6165 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6166 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6167 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006168 DAG.getConstant(CnstVal, dl, MVT::i32),
6169 DAG.getConstant(264, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006170 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006171 }
6172
6173 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6174 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6175 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6176 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006177 DAG.getConstant(CnstVal, dl, MVT::i32),
6178 DAG.getConstant(272, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006179 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006180 }
6181 }
6182
6183 if (SecondTry)
6184 goto FailedModImm;
6185 SecondTry = true;
6186 CnstBits = UndefBits;
6187 goto AttemptModImm;
6188 }
6189FailedModImm:
6190
6191 // Scan through the operands to find some interesting properties we can
6192 // exploit:
6193 // 1) If only one value is used, we can use a DUP, or
6194 // 2) if only the low element is not undef, we can just insert that, or
6195 // 3) if only one constant value is used (w/ some non-constant lanes),
6196 // we can splat the constant value into the whole vector then fill
6197 // in the non-constant lanes.
6198 // 4) FIXME: If different constant values are used, but we can intelligently
6199 // select the values we'll be overwriting for the non-constant
6200 // lanes such that we can directly materialize the vector
6201 // some other way (MOVI, e.g.), we can be sneaky.
6202 unsigned NumElts = VT.getVectorNumElements();
6203 bool isOnlyLowElement = true;
6204 bool usesOnlyOneValue = true;
6205 bool usesOnlyOneConstantValue = true;
6206 bool isConstant = true;
6207 unsigned NumConstantLanes = 0;
6208 SDValue Value;
6209 SDValue ConstantValue;
6210 for (unsigned i = 0; i < NumElts; ++i) {
6211 SDValue V = Op.getOperand(i);
6212 if (V.getOpcode() == ISD::UNDEF)
6213 continue;
6214 if (i > 0)
6215 isOnlyLowElement = false;
6216 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6217 isConstant = false;
6218
6219 if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
6220 ++NumConstantLanes;
6221 if (!ConstantValue.getNode())
6222 ConstantValue = V;
6223 else if (ConstantValue != V)
6224 usesOnlyOneConstantValue = false;
6225 }
6226
6227 if (!Value.getNode())
6228 Value = V;
6229 else if (V != Value)
6230 usesOnlyOneValue = false;
6231 }
6232
6233 if (!Value.getNode())
6234 return DAG.getUNDEF(VT);
6235
6236 if (isOnlyLowElement)
6237 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
6238
6239 // Use DUP for non-constant splats. For f32 constant splats, reduce to
6240 // i32 and try again.
6241 if (usesOnlyOneValue) {
6242 if (!isConstant) {
6243 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6244 Value.getValueType() != VT)
6245 return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
6246
6247 // This is actually a DUPLANExx operation, which keeps everything vectory.
6248
6249 // DUPLANE works on 128-bit vectors, widen it if necessary.
6250 SDValue Lane = Value.getOperand(1);
6251 Value = Value.getOperand(0);
6252 if (Value.getValueType().getSizeInBits() == 64)
6253 Value = WidenVector(Value, DAG);
6254
6255 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
6256 return DAG.getNode(Opcode, dl, VT, Value, Lane);
6257 }
6258
6259 if (VT.getVectorElementType().isFloatingPoint()) {
6260 SmallVector<SDValue, 8> Ops;
Pirama Arumuga Nainar12aeefc2015-03-17 23:10:29 +00006261 EVT EltTy = VT.getVectorElementType();
6262 assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
6263 "Unsupported floating-point vector type");
6264 MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00006265 for (unsigned i = 0; i < NumElts; ++i)
6266 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
6267 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
6268 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
6269 Val = LowerBUILD_VECTOR(Val, DAG);
6270 if (Val.getNode())
6271 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6272 }
6273 }
6274
6275 // If there was only one constant value used and for more than one lane,
6276 // start by splatting that value, then replace the non-constant lanes. This
6277 // is better than the default, which will perform a separate initialization
6278 // for each lane.
6279 if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
6280 SDValue Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
6281 // Now insert the non-constant lanes.
6282 for (unsigned i = 0; i < NumElts; ++i) {
6283 SDValue V = Op.getOperand(i);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006284 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006285 if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) {
6286 // Note that type legalization likely mucked about with the VT of the
6287 // source operand, so we may have to convert it here before inserting.
6288 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
6289 }
6290 }
6291 return Val;
6292 }
6293
6294 // If all elements are constants and the case above didn't get hit, fall back
6295 // to the default expansion, which will generate a load from the constant
6296 // pool.
6297 if (isConstant)
6298 return SDValue();
6299
6300 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6301 if (NumElts >= 4) {
Ahmed Bougacha239d6352015-08-04 00:48:02 +00006302 if (SDValue shuffle = ReconstructShuffle(Op, DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00006303 return shuffle;
6304 }
6305
6306 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6307 // know the default expansion would otherwise fall back on something even
6308 // worse. For a vector with one or two non-undef values, that's
6309 // scalar_to_vector for the elements followed by a shuffle (provided the
6310 // shuffle is valid for the target) and materialization element by element
6311 // on the stack followed by a load for everything else.
6312 if (!isConstant && !usesOnlyOneValue) {
6313 SDValue Vec = DAG.getUNDEF(VT);
6314 SDValue Op0 = Op.getOperand(0);
6315 unsigned ElemSize = VT.getVectorElementType().getSizeInBits();
6316 unsigned i = 0;
6317 // For 32 and 64 bit types, use INSERT_SUBREG for lane zero to
6318 // a) Avoid a RMW dependency on the full vector register, and
6319 // b) Allow the register coalescer to fold away the copy if the
6320 // value is already in an S or D register.
Matthias Braun0acbd082015-08-31 18:25:15 +00006321 // Do not do this for UNDEF/LOAD nodes because we have better patterns
6322 // for those avoiding the SCALAR_TO_VECTOR/BUILD_VECTOR.
6323 if (Op0.getOpcode() != ISD::UNDEF && Op0.getOpcode() != ISD::LOAD &&
6324 (ElemSize == 32 || ElemSize == 64)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006325 unsigned SubIdx = ElemSize == 32 ? AArch64::ssub : AArch64::dsub;
6326 MachineSDNode *N =
6327 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl, VT, Vec, Op0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006328 DAG.getTargetConstant(SubIdx, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006329 Vec = SDValue(N, 0);
6330 ++i;
6331 }
6332 for (; i < NumElts; ++i) {
6333 SDValue V = Op.getOperand(i);
6334 if (V.getOpcode() == ISD::UNDEF)
6335 continue;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006336 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006337 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6338 }
6339 return Vec;
6340 }
6341
6342 // Just use the default expansion. We failed to find a better alternative.
6343 return SDValue();
6344}
6345
6346SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
6347 SelectionDAG &DAG) const {
6348 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
6349
Tim Northovere4b8e132014-07-15 10:00:26 +00006350 // Check for non-constant or out of range lane.
6351 EVT VT = Op.getOperand(0).getValueType();
6352 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
6353 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
Tim Northover3b0846e2014-05-24 12:50:23 +00006354 return SDValue();
6355
Tim Northover3b0846e2014-05-24 12:50:23 +00006356
6357 // Insertion/extraction are legal for V128 types.
6358 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
Oliver Stannard89d15422014-08-27 16:16:04 +00006359 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6360 VT == MVT::v8f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006361 return Op;
6362
6363 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
Oliver Stannard89d15422014-08-27 16:16:04 +00006364 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006365 return SDValue();
6366
6367 // For V64 types, we perform insertion by expanding the value
6368 // to a V128 type and perform the insertion on that.
6369 SDLoc DL(Op);
6370 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6371 EVT WideTy = WideVec.getValueType();
6372
6373 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
6374 Op.getOperand(1), Op.getOperand(2));
6375 // Re-narrow the resultant vector.
6376 return NarrowVector(Node, DAG);
6377}
6378
6379SDValue
6380AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6381 SelectionDAG &DAG) const {
6382 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
6383
Tim Northovere4b8e132014-07-15 10:00:26 +00006384 // Check for non-constant or out of range lane.
6385 EVT VT = Op.getOperand(0).getValueType();
6386 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6387 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
Tim Northover3b0846e2014-05-24 12:50:23 +00006388 return SDValue();
6389
Tim Northover3b0846e2014-05-24 12:50:23 +00006390
6391 // Insertion/extraction are legal for V128 types.
6392 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
Oliver Stannard89d15422014-08-27 16:16:04 +00006393 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6394 VT == MVT::v8f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006395 return Op;
6396
6397 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
Oliver Stannard89d15422014-08-27 16:16:04 +00006398 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006399 return SDValue();
6400
6401 // For V64 types, we perform extraction by expanding the value
6402 // to a V128 type and perform the extraction on that.
6403 SDLoc DL(Op);
6404 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6405 EVT WideTy = WideVec.getValueType();
6406
6407 EVT ExtrTy = WideTy.getVectorElementType();
6408 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
6409 ExtrTy = MVT::i32;
6410
6411 // For extractions, we just return the result directly.
6412 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
6413 Op.getOperand(1));
6414}
6415
6416SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
6417 SelectionDAG &DAG) const {
6418 EVT VT = Op.getOperand(0).getValueType();
6419 SDLoc dl(Op);
6420 // Just in case...
6421 if (!VT.isVector())
6422 return SDValue();
6423
6424 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6425 if (!Cst)
6426 return SDValue();
6427 unsigned Val = Cst->getZExtValue();
6428
6429 unsigned Size = Op.getValueType().getSizeInBits();
Charlie Turner7b7b06f2015-11-09 12:45:11 +00006430
6431 // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
6432 if (Val == 0)
6433 return Op;
6434
Tim Northover3b0846e2014-05-24 12:50:23 +00006435 // If this is extracting the upper 64-bits of a 128-bit vector, we match
6436 // that directly.
6437 if (Size == 64 && Val * VT.getVectorElementType().getSizeInBits() == 64)
6438 return Op;
6439
6440 return SDValue();
6441}
6442
6443bool AArch64TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
6444 EVT VT) const {
6445 if (VT.getVectorNumElements() == 4 &&
6446 (VT.is128BitVector() || VT.is64BitVector())) {
6447 unsigned PFIndexes[4];
6448 for (unsigned i = 0; i != 4; ++i) {
6449 if (M[i] < 0)
6450 PFIndexes[i] = 8;
6451 else
6452 PFIndexes[i] = M[i];
6453 }
6454
6455 // Compute the index in the perfect shuffle table.
6456 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6457 PFIndexes[2] * 9 + PFIndexes[3];
6458 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6459 unsigned Cost = (PFEntry >> 30);
6460
6461 if (Cost <= 4)
6462 return true;
6463 }
6464
6465 bool DummyBool;
6466 int DummyInt;
6467 unsigned DummyUnsigned;
6468
6469 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
6470 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
6471 isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
6472 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
6473 isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
6474 isZIPMask(M, VT, DummyUnsigned) ||
6475 isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
6476 isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
6477 isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
6478 isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
6479 isConcatMask(M, VT, VT.getSizeInBits() == 128));
6480}
6481
6482/// getVShiftImm - Check if this is a valid build_vector for the immediate
6483/// operand of a vector shift operation, where all the elements of the
6484/// build_vector must have the same constant integer value.
6485static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
6486 // Ignore bit_converts.
6487 while (Op.getOpcode() == ISD::BITCAST)
6488 Op = Op.getOperand(0);
6489 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6490 APInt SplatBits, SplatUndef;
6491 unsigned SplatBitSize;
6492 bool HasAnyUndefs;
6493 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
6494 HasAnyUndefs, ElementBits) ||
6495 SplatBitSize > ElementBits)
6496 return false;
6497 Cnt = SplatBits.getSExtValue();
6498 return true;
6499}
6500
6501/// isVShiftLImm - Check if this is a valid build_vector for the immediate
6502/// operand of a vector shift left operation. That value must be in the range:
6503/// 0 <= Value < ElementBits for a left shift; or
6504/// 0 <= Value <= ElementBits for a long left shift.
6505static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
6506 assert(VT.isVector() && "vector shift count is not a vector type");
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00006507 int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00006508 if (!getVShiftImm(Op, ElementBits, Cnt))
6509 return false;
6510 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
6511}
6512
6513/// isVShiftRImm - Check if this is a valid build_vector for the immediate
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00006514/// operand of a vector shift right operation. The value must be in the range:
6515/// 1 <= Value <= ElementBits for a right shift; or
6516static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006517 assert(VT.isVector() && "vector shift count is not a vector type");
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00006518 int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00006519 if (!getVShiftImm(Op, ElementBits, Cnt))
6520 return false;
Tim Northover3b0846e2014-05-24 12:50:23 +00006521 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
6522}
6523
6524SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
6525 SelectionDAG &DAG) const {
6526 EVT VT = Op.getValueType();
6527 SDLoc DL(Op);
6528 int64_t Cnt;
6529
6530 if (!Op.getOperand(1).getValueType().isVector())
6531 return Op;
6532 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6533
6534 switch (Op.getOpcode()) {
6535 default:
6536 llvm_unreachable("unexpected shift opcode");
6537
6538 case ISD::SHL:
6539 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006540 return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
6541 DAG.getConstant(Cnt, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006542 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006543 DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
6544 MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00006545 Op.getOperand(0), Op.getOperand(1));
6546 case ISD::SRA:
6547 case ISD::SRL:
6548 // Right shift immediate
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00006549 if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006550 unsigned Opc =
6551 (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006552 return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
6553 DAG.getConstant(Cnt, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006554 }
6555
6556 // Right shift register. Note, there is not a shift right register
6557 // instruction, but the shift left register instruction takes a signed
6558 // value, where negative numbers specify a right shift.
6559 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
6560 : Intrinsic::aarch64_neon_ushl;
6561 // negate the shift amount
6562 SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
6563 SDValue NegShiftLeft =
6564 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006565 DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
6566 NegShift);
Tim Northover3b0846e2014-05-24 12:50:23 +00006567 return NegShiftLeft;
6568 }
6569
6570 return SDValue();
6571}
6572
6573static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
6574 AArch64CC::CondCode CC, bool NoNans, EVT VT,
6575 SDLoc dl, SelectionDAG &DAG) {
6576 EVT SrcVT = LHS.getValueType();
Tim Northover45aa89c2015-02-08 00:50:47 +00006577 assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
6578 "function only supposed to emit natural comparisons");
Tim Northover3b0846e2014-05-24 12:50:23 +00006579
6580 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
6581 APInt CnstBits(VT.getSizeInBits(), 0);
6582 APInt UndefBits(VT.getSizeInBits(), 0);
6583 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
6584 bool IsZero = IsCnst && (CnstBits == 0);
6585
6586 if (SrcVT.getVectorElementType().isFloatingPoint()) {
6587 switch (CC) {
6588 default:
6589 return SDValue();
6590 case AArch64CC::NE: {
6591 SDValue Fcmeq;
6592 if (IsZero)
6593 Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6594 else
6595 Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6596 return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
6597 }
6598 case AArch64CC::EQ:
6599 if (IsZero)
6600 return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6601 return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6602 case AArch64CC::GE:
6603 if (IsZero)
6604 return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
6605 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
6606 case AArch64CC::GT:
6607 if (IsZero)
6608 return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
6609 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
6610 case AArch64CC::LS:
6611 if (IsZero)
6612 return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
6613 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
6614 case AArch64CC::LT:
6615 if (!NoNans)
6616 return SDValue();
6617 // If we ignore NaNs then we can use to the MI implementation.
6618 // Fallthrough.
6619 case AArch64CC::MI:
6620 if (IsZero)
6621 return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
6622 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
6623 }
6624 }
6625
6626 switch (CC) {
6627 default:
6628 return SDValue();
6629 case AArch64CC::NE: {
6630 SDValue Cmeq;
6631 if (IsZero)
6632 Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6633 else
6634 Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6635 return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
6636 }
6637 case AArch64CC::EQ:
6638 if (IsZero)
6639 return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6640 return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6641 case AArch64CC::GE:
6642 if (IsZero)
6643 return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
6644 return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
6645 case AArch64CC::GT:
6646 if (IsZero)
6647 return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
6648 return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
6649 case AArch64CC::LE:
6650 if (IsZero)
6651 return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
6652 return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
6653 case AArch64CC::LS:
6654 return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
6655 case AArch64CC::LO:
6656 return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
6657 case AArch64CC::LT:
6658 if (IsZero)
6659 return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
6660 return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
6661 case AArch64CC::HI:
6662 return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
6663 case AArch64CC::HS:
6664 return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
6665 }
6666}
6667
6668SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
6669 SelectionDAG &DAG) const {
6670 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6671 SDValue LHS = Op.getOperand(0);
6672 SDValue RHS = Op.getOperand(1);
Tim Northover45aa89c2015-02-08 00:50:47 +00006673 EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
Tim Northover3b0846e2014-05-24 12:50:23 +00006674 SDLoc dl(Op);
6675
6676 if (LHS.getValueType().getVectorElementType().isInteger()) {
6677 assert(LHS.getValueType() == RHS.getValueType());
6678 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
Tim Northover45aa89c2015-02-08 00:50:47 +00006679 SDValue Cmp =
6680 EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
6681 return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00006682 }
6683
6684 assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
6685 LHS.getValueType().getVectorElementType() == MVT::f64);
6686
6687 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
6688 // clean. Some of them require two branches to implement.
6689 AArch64CC::CondCode CC1, CC2;
6690 bool ShouldInvert;
6691 changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
6692
6693 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
6694 SDValue Cmp =
Tim Northover45aa89c2015-02-08 00:50:47 +00006695 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00006696 if (!Cmp.getNode())
6697 return SDValue();
6698
6699 if (CC2 != AArch64CC::AL) {
6700 SDValue Cmp2 =
Tim Northover45aa89c2015-02-08 00:50:47 +00006701 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00006702 if (!Cmp2.getNode())
6703 return SDValue();
6704
Tim Northover45aa89c2015-02-08 00:50:47 +00006705 Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
Tim Northover3b0846e2014-05-24 12:50:23 +00006706 }
6707
Tim Northover45aa89c2015-02-08 00:50:47 +00006708 Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
6709
Tim Northover3b0846e2014-05-24 12:50:23 +00006710 if (ShouldInvert)
6711 return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
6712
6713 return Cmp;
6714}
6715
6716/// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
6717/// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
6718/// specified in the intrinsic calls.
6719bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
6720 const CallInst &I,
6721 unsigned Intrinsic) const {
Mehdi Aminia749f2a2015-07-09 02:09:52 +00006722 auto &DL = I.getModule()->getDataLayout();
Tim Northover3b0846e2014-05-24 12:50:23 +00006723 switch (Intrinsic) {
6724 case Intrinsic::aarch64_neon_ld2:
6725 case Intrinsic::aarch64_neon_ld3:
6726 case Intrinsic::aarch64_neon_ld4:
6727 case Intrinsic::aarch64_neon_ld1x2:
6728 case Intrinsic::aarch64_neon_ld1x3:
6729 case Intrinsic::aarch64_neon_ld1x4:
6730 case Intrinsic::aarch64_neon_ld2lane:
6731 case Intrinsic::aarch64_neon_ld3lane:
6732 case Intrinsic::aarch64_neon_ld4lane:
6733 case Intrinsic::aarch64_neon_ld2r:
6734 case Intrinsic::aarch64_neon_ld3r:
6735 case Intrinsic::aarch64_neon_ld4r: {
6736 Info.opc = ISD::INTRINSIC_W_CHAIN;
6737 // Conservatively set memVT to the entire set of vectors loaded.
Ahmed Bougacha97564c32015-12-09 01:19:50 +00006738 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00006739 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6740 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6741 Info.offset = 0;
6742 Info.align = 0;
6743 Info.vol = false; // volatile loads with NEON intrinsics not supported
6744 Info.readMem = true;
6745 Info.writeMem = false;
6746 return true;
6747 }
6748 case Intrinsic::aarch64_neon_st2:
6749 case Intrinsic::aarch64_neon_st3:
6750 case Intrinsic::aarch64_neon_st4:
6751 case Intrinsic::aarch64_neon_st1x2:
6752 case Intrinsic::aarch64_neon_st1x3:
6753 case Intrinsic::aarch64_neon_st1x4:
6754 case Intrinsic::aarch64_neon_st2lane:
6755 case Intrinsic::aarch64_neon_st3lane:
6756 case Intrinsic::aarch64_neon_st4lane: {
6757 Info.opc = ISD::INTRINSIC_VOID;
6758 // Conservatively set memVT to the entire set of vectors stored.
6759 unsigned NumElts = 0;
6760 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
6761 Type *ArgTy = I.getArgOperand(ArgI)->getType();
6762 if (!ArgTy->isVectorTy())
6763 break;
Ahmed Bougacha97564c32015-12-09 01:19:50 +00006764 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00006765 }
6766 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6767 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6768 Info.offset = 0;
6769 Info.align = 0;
6770 Info.vol = false; // volatile stores with NEON intrinsics not supported
6771 Info.readMem = false;
6772 Info.writeMem = true;
6773 return true;
6774 }
6775 case Intrinsic::aarch64_ldaxr:
6776 case Intrinsic::aarch64_ldxr: {
6777 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
6778 Info.opc = ISD::INTRINSIC_W_CHAIN;
6779 Info.memVT = MVT::getVT(PtrTy->getElementType());
6780 Info.ptrVal = I.getArgOperand(0);
6781 Info.offset = 0;
Mehdi Aminia749f2a2015-07-09 02:09:52 +00006782 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
Tim Northover3b0846e2014-05-24 12:50:23 +00006783 Info.vol = true;
6784 Info.readMem = true;
6785 Info.writeMem = false;
6786 return true;
6787 }
6788 case Intrinsic::aarch64_stlxr:
6789 case Intrinsic::aarch64_stxr: {
6790 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
6791 Info.opc = ISD::INTRINSIC_W_CHAIN;
6792 Info.memVT = MVT::getVT(PtrTy->getElementType());
6793 Info.ptrVal = I.getArgOperand(1);
6794 Info.offset = 0;
Mehdi Aminia749f2a2015-07-09 02:09:52 +00006795 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
Tim Northover3b0846e2014-05-24 12:50:23 +00006796 Info.vol = true;
6797 Info.readMem = false;
6798 Info.writeMem = true;
6799 return true;
6800 }
6801 case Intrinsic::aarch64_ldaxp:
6802 case Intrinsic::aarch64_ldxp: {
6803 Info.opc = ISD::INTRINSIC_W_CHAIN;
6804 Info.memVT = MVT::i128;
6805 Info.ptrVal = I.getArgOperand(0);
6806 Info.offset = 0;
6807 Info.align = 16;
6808 Info.vol = true;
6809 Info.readMem = true;
6810 Info.writeMem = false;
6811 return true;
6812 }
6813 case Intrinsic::aarch64_stlxp:
6814 case Intrinsic::aarch64_stxp: {
6815 Info.opc = ISD::INTRINSIC_W_CHAIN;
6816 Info.memVT = MVT::i128;
6817 Info.ptrVal = I.getArgOperand(2);
6818 Info.offset = 0;
6819 Info.align = 16;
6820 Info.vol = true;
6821 Info.readMem = false;
6822 Info.writeMem = true;
6823 return true;
6824 }
6825 default:
6826 break;
6827 }
6828
6829 return false;
6830}
6831
6832// Truncations from 64-bit GPR to 32-bit GPR is free.
6833bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
6834 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6835 return false;
6836 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6837 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00006838 return NumBits1 > NumBits2;
Tim Northover3b0846e2014-05-24 12:50:23 +00006839}
6840bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
Hao Liu40914502014-05-29 09:19:07 +00006841 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00006842 return false;
6843 unsigned NumBits1 = VT1.getSizeInBits();
6844 unsigned NumBits2 = VT2.getSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00006845 return NumBits1 > NumBits2;
Tim Northover3b0846e2014-05-24 12:50:23 +00006846}
6847
Chad Rosier54390052015-02-23 19:15:16 +00006848/// Check if it is profitable to hoist instruction in then/else to if.
6849/// Not profitable if I and it's user can form a FMA instruction
6850/// because we prefer FMSUB/FMADD.
6851bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
6852 if (I->getOpcode() != Instruction::FMul)
6853 return true;
6854
6855 if (I->getNumUses() != 1)
6856 return true;
6857
6858 Instruction *User = I->user_back();
6859
6860 if (User &&
6861 !(User->getOpcode() == Instruction::FSub ||
6862 User->getOpcode() == Instruction::FAdd))
6863 return true;
6864
6865 const TargetOptions &Options = getTargetMachine().Options;
Mehdi Amini44ede332015-07-09 02:09:04 +00006866 const DataLayout &DL = I->getModule()->getDataLayout();
6867 EVT VT = getValueType(DL, User->getOperand(0)->getType());
Chad Rosier54390052015-02-23 19:15:16 +00006868
6869 if (isFMAFasterThanFMulAndFAdd(VT) &&
6870 isOperationLegalOrCustom(ISD::FMA, VT) &&
6871 (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath))
6872 return false;
6873
6874 return true;
6875}
6876
Tim Northover3b0846e2014-05-24 12:50:23 +00006877// All 32-bit GPR operations implicitly zero the high-half of the corresponding
6878// 64-bit GPR.
6879bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
6880 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6881 return false;
6882 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6883 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00006884 return NumBits1 == 32 && NumBits2 == 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00006885}
6886bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
Hao Liu40914502014-05-29 09:19:07 +00006887 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00006888 return false;
6889 unsigned NumBits1 = VT1.getSizeInBits();
6890 unsigned NumBits2 = VT2.getSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00006891 return NumBits1 == 32 && NumBits2 == 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00006892}
6893
6894bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
6895 EVT VT1 = Val.getValueType();
6896 if (isZExtFree(VT1, VT2)) {
6897 return true;
6898 }
6899
6900 if (Val.getOpcode() != ISD::LOAD)
6901 return false;
6902
6903 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
Hao Liu40914502014-05-29 09:19:07 +00006904 return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
6905 VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
6906 VT1.getSizeInBits() <= 32);
Tim Northover3b0846e2014-05-24 12:50:23 +00006907}
6908
Quentin Colombet6843ac42015-03-31 20:52:32 +00006909bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
6910 if (isa<FPExtInst>(Ext))
6911 return false;
6912
6913 // Vector types are next free.
6914 if (Ext->getType()->isVectorTy())
6915 return false;
6916
6917 for (const Use &U : Ext->uses()) {
6918 // The extension is free if we can fold it with a left shift in an
6919 // addressing mode or an arithmetic operation: add, sub, and cmp.
6920
6921 // Is there a shift?
6922 const Instruction *Instr = cast<Instruction>(U.getUser());
6923
6924 // Is this a constant shift?
6925 switch (Instr->getOpcode()) {
6926 case Instruction::Shl:
6927 if (!isa<ConstantInt>(Instr->getOperand(1)))
6928 return false;
6929 break;
6930 case Instruction::GetElementPtr: {
6931 gep_type_iterator GTI = gep_type_begin(Instr);
Mehdi Aminia749f2a2015-07-09 02:09:52 +00006932 auto &DL = Ext->getModule()->getDataLayout();
Quentin Colombet6843ac42015-03-31 20:52:32 +00006933 std::advance(GTI, U.getOperandNo());
6934 Type *IdxTy = *GTI;
6935 // This extension will end up with a shift because of the scaling factor.
6936 // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
6937 // Get the shift amount based on the scaling factor:
6938 // log2(sizeof(IdxTy)) - log2(8).
6939 uint64_t ShiftAmt =
Mehdi Aminia749f2a2015-07-09 02:09:52 +00006940 countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3;
Quentin Colombet6843ac42015-03-31 20:52:32 +00006941 // Is the constant foldable in the shift of the addressing mode?
6942 // I.e., shift amount is between 1 and 4 inclusive.
6943 if (ShiftAmt == 0 || ShiftAmt > 4)
6944 return false;
6945 break;
6946 }
6947 case Instruction::Trunc:
6948 // Check if this is a noop.
6949 // trunc(sext ty1 to ty2) to ty1.
6950 if (Instr->getType() == Ext->getOperand(0)->getType())
6951 continue;
6952 // FALL THROUGH.
6953 default:
6954 return false;
6955 }
6956
6957 // At this point we can use the bfm family, so this extension is free
6958 // for that use.
6959 }
6960 return true;
6961}
6962
Tim Northover3b0846e2014-05-24 12:50:23 +00006963bool AArch64TargetLowering::hasPairedLoad(Type *LoadedType,
6964 unsigned &RequiredAligment) const {
6965 if (!LoadedType->isIntegerTy() && !LoadedType->isFloatTy())
6966 return false;
6967 // Cyclone supports unaligned accesses.
6968 RequiredAligment = 0;
6969 unsigned NumBits = LoadedType->getPrimitiveSizeInBits();
6970 return NumBits == 32 || NumBits == 64;
6971}
6972
6973bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
6974 unsigned &RequiredAligment) const {
6975 if (!LoadedType.isSimple() ||
6976 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
6977 return false;
6978 // Cyclone supports unaligned accesses.
6979 RequiredAligment = 0;
6980 unsigned NumBits = LoadedType.getSizeInBits();
6981 return NumBits == 32 || NumBits == 64;
6982}
6983
Hao Liu7ec8ee32015-06-26 02:32:07 +00006984/// \brief Lower an interleaved load into a ldN intrinsic.
6985///
6986/// E.g. Lower an interleaved load (Factor = 2):
6987/// %wide.vec = load <8 x i32>, <8 x i32>* %ptr
6988/// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
6989/// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
6990///
6991/// Into:
6992/// %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
6993/// %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
6994/// %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
6995bool AArch64TargetLowering::lowerInterleavedLoad(
6996 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
6997 ArrayRef<unsigned> Indices, unsigned Factor) const {
6998 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
6999 "Invalid interleave factor");
7000 assert(!Shuffles.empty() && "Empty shufflevector input");
7001 assert(Shuffles.size() == Indices.size() &&
7002 "Unmatched number of shufflevectors and indices");
7003
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007004 const DataLayout &DL = LI->getModule()->getDataLayout();
Hao Liu7ec8ee32015-06-26 02:32:07 +00007005
7006 VectorType *VecTy = Shuffles[0]->getType();
Ahmed Bougacha97564c32015-12-09 01:19:50 +00007007 unsigned VecSize = DL.getTypeSizeInBits(VecTy);
Hao Liu7ec8ee32015-06-26 02:32:07 +00007008
Jeroen Ketemaaebca092015-10-07 14:53:29 +00007009 // Skip if we do not have NEON and skip illegal vector types.
7010 if (!Subtarget->hasNEON() || (VecSize != 64 && VecSize != 128))
Hao Liu7ec8ee32015-06-26 02:32:07 +00007011 return false;
7012
7013 // A pointer vector can not be the return type of the ldN intrinsics. Need to
7014 // load integer vectors first and then convert to pointer vectors.
7015 Type *EltTy = VecTy->getVectorElementType();
7016 if (EltTy->isPointerTy())
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007017 VecTy =
7018 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
Hao Liu7ec8ee32015-06-26 02:32:07 +00007019
7020 Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
7021 Type *Tys[2] = {VecTy, PtrTy};
7022 static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
7023 Intrinsic::aarch64_neon_ld3,
7024 Intrinsic::aarch64_neon_ld4};
7025 Function *LdNFunc =
7026 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
7027
7028 IRBuilder<> Builder(LI);
7029 Value *Ptr = Builder.CreateBitCast(LI->getPointerOperand(), PtrTy);
7030
7031 CallInst *LdN = Builder.CreateCall(LdNFunc, Ptr, "ldN");
7032
7033 // Replace uses of each shufflevector with the corresponding vector loaded
7034 // by ldN.
7035 for (unsigned i = 0; i < Shuffles.size(); i++) {
7036 ShuffleVectorInst *SVI = Shuffles[i];
7037 unsigned Index = Indices[i];
7038
7039 Value *SubVec = Builder.CreateExtractValue(LdN, Index);
7040
7041 // Convert the integer vector to pointer vector if the element is pointer.
7042 if (EltTy->isPointerTy())
7043 SubVec = Builder.CreateIntToPtr(SubVec, SVI->getType());
7044
7045 SVI->replaceAllUsesWith(SubVec);
7046 }
7047
7048 return true;
7049}
7050
7051/// \brief Get a mask consisting of sequential integers starting from \p Start.
7052///
7053/// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
7054static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
7055 unsigned NumElts) {
7056 SmallVector<Constant *, 16> Mask;
7057 for (unsigned i = 0; i < NumElts; i++)
7058 Mask.push_back(Builder.getInt32(Start + i));
7059
7060 return ConstantVector::get(Mask);
7061}
7062
7063/// \brief Lower an interleaved store into a stN intrinsic.
7064///
7065/// E.g. Lower an interleaved store (Factor = 3):
7066/// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
7067/// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
7068/// store <12 x i32> %i.vec, <12 x i32>* %ptr
7069///
7070/// Into:
7071/// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
7072/// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
7073/// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
7074/// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
7075///
7076/// Note that the new shufflevectors will be removed and we'll only generate one
7077/// st3 instruction in CodeGen.
7078bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
7079 ShuffleVectorInst *SVI,
7080 unsigned Factor) const {
7081 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7082 "Invalid interleave factor");
7083
7084 VectorType *VecTy = SVI->getType();
7085 assert(VecTy->getVectorNumElements() % Factor == 0 &&
7086 "Invalid interleaved store");
7087
7088 unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
7089 Type *EltTy = VecTy->getVectorElementType();
7090 VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
7091
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007092 const DataLayout &DL = SI->getModule()->getDataLayout();
Ahmed Bougacha97564c32015-12-09 01:19:50 +00007093 unsigned SubVecSize = DL.getTypeSizeInBits(SubVecTy);
Hao Liu7ec8ee32015-06-26 02:32:07 +00007094
Jeroen Ketemaaebca092015-10-07 14:53:29 +00007095 // Skip if we do not have NEON and skip illegal vector types.
7096 if (!Subtarget->hasNEON() || (SubVecSize != 64 && SubVecSize != 128))
Hao Liu7ec8ee32015-06-26 02:32:07 +00007097 return false;
7098
7099 Value *Op0 = SVI->getOperand(0);
7100 Value *Op1 = SVI->getOperand(1);
7101 IRBuilder<> Builder(SI);
7102
7103 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
7104 // vectors to integer vectors.
7105 if (EltTy->isPointerTy()) {
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007106 Type *IntTy = DL.getIntPtrType(EltTy);
Hao Liu7ec8ee32015-06-26 02:32:07 +00007107 unsigned NumOpElts =
7108 dyn_cast<VectorType>(Op0->getType())->getVectorNumElements();
7109
7110 // Convert to the corresponding integer vector.
7111 Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
7112 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
7113 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
7114
7115 SubVecTy = VectorType::get(IntTy, NumSubElts);
7116 }
7117
7118 Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
7119 Type *Tys[2] = {SubVecTy, PtrTy};
7120 static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
7121 Intrinsic::aarch64_neon_st3,
7122 Intrinsic::aarch64_neon_st4};
7123 Function *StNFunc =
7124 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
7125
7126 SmallVector<Value *, 5> Ops;
7127
7128 // Split the shufflevector operands into sub vectors for the new stN call.
7129 for (unsigned i = 0; i < Factor; i++)
7130 Ops.push_back(Builder.CreateShuffleVector(
7131 Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
7132
7133 Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), PtrTy));
7134 Builder.CreateCall(StNFunc, Ops);
7135 return true;
7136}
7137
Tim Northover3b0846e2014-05-24 12:50:23 +00007138static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
7139 unsigned AlignCheck) {
7140 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
7141 (DstAlign == 0 || DstAlign % AlignCheck == 0));
7142}
7143
7144EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
7145 unsigned SrcAlign, bool IsMemset,
7146 bool ZeroMemset,
7147 bool MemcpyStrSrc,
7148 MachineFunction &MF) const {
7149 // Don't use AdvSIMD to implement 16-byte memset. It would have taken one
7150 // instruction to materialize the v2i64 zero and one store (with restrictive
7151 // addressing mode). Just do two i64 store of zero-registers.
7152 bool Fast;
7153 const Function *F = MF.getFunction();
7154 if (Subtarget->hasFPARMv8() && !IsMemset && Size >= 16 &&
Duncan P. N. Exon Smith003bb7d2015-02-14 02:09:06 +00007155 !F->hasFnAttribute(Attribute::NoImplicitFloat) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00007156 (memOpAlign(SrcAlign, DstAlign, 16) ||
Matt Arsenault6f2a5262014-07-27 17:46:40 +00007157 (allowsMisalignedMemoryAccesses(MVT::f128, 0, 1, &Fast) && Fast)))
Tim Northover3b0846e2014-05-24 12:50:23 +00007158 return MVT::f128;
7159
Lang Hames90333852015-04-09 03:40:33 +00007160 if (Size >= 8 &&
7161 (memOpAlign(SrcAlign, DstAlign, 8) ||
7162 (allowsMisalignedMemoryAccesses(MVT::i64, 0, 1, &Fast) && Fast)))
7163 return MVT::i64;
7164
7165 if (Size >= 4 &&
7166 (memOpAlign(SrcAlign, DstAlign, 4) ||
7167 (allowsMisalignedMemoryAccesses(MVT::i32, 0, 1, &Fast) && Fast)))
Lang Hames522bf132015-04-09 05:34:57 +00007168 return MVT::i32;
Lang Hames90333852015-04-09 03:40:33 +00007169
7170 return MVT::Other;
Tim Northover3b0846e2014-05-24 12:50:23 +00007171}
7172
7173// 12-bit optionally shifted immediates are legal for adds.
7174bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
7175 if ((Immed >> 12) == 0 || ((Immed & 0xfff) == 0 && Immed >> 24 == 0))
7176 return true;
7177 return false;
7178}
7179
7180// Integer comparisons are implemented with ADDS/SUBS, so the range of valid
7181// immediates is the same as for an add or a sub.
7182bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
7183 if (Immed < 0)
7184 Immed *= -1;
7185 return isLegalAddImmediate(Immed);
7186}
7187
7188/// isLegalAddressingMode - Return true if the addressing mode represented
7189/// by AM is legal for this target, for a load/store of the specified type.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00007190bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
7191 const AddrMode &AM, Type *Ty,
Matt Arsenaultbd7d80a2015-06-01 05:31:59 +00007192 unsigned AS) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00007193 // AArch64 has five basic addressing modes:
7194 // reg
7195 // reg + 9-bit signed offset
7196 // reg + SIZE_IN_BYTES * 12-bit unsigned offset
7197 // reg1 + reg2
7198 // reg + SIZE_IN_BYTES * reg
7199
7200 // No global is ever allowed as a base.
7201 if (AM.BaseGV)
7202 return false;
7203
7204 // No reg+reg+imm addressing.
7205 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
7206 return false;
7207
7208 // check reg + imm case:
7209 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
7210 uint64_t NumBytes = 0;
7211 if (Ty->isSized()) {
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00007212 uint64_t NumBits = DL.getTypeSizeInBits(Ty);
Tim Northover3b0846e2014-05-24 12:50:23 +00007213 NumBytes = NumBits / 8;
7214 if (!isPowerOf2_64(NumBits))
7215 NumBytes = 0;
7216 }
7217
7218 if (!AM.Scale) {
7219 int64_t Offset = AM.BaseOffs;
7220
7221 // 9-bit signed offset
7222 if (Offset >= -(1LL << 9) && Offset <= (1LL << 9) - 1)
7223 return true;
7224
7225 // 12-bit unsigned offset
7226 unsigned shift = Log2_64(NumBytes);
7227 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
7228 // Must be a multiple of NumBytes (NumBytes is a power of 2)
7229 (Offset >> shift) << shift == Offset)
7230 return true;
7231 return false;
7232 }
7233
7234 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
7235
7236 if (!AM.Scale || AM.Scale == 1 ||
7237 (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes))
7238 return true;
7239 return false;
7240}
7241
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00007242int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
7243 const AddrMode &AM, Type *Ty,
Matt Arsenaultbd7d80a2015-06-01 05:31:59 +00007244 unsigned AS) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00007245 // Scaling factors are not free at all.
7246 // Operands | Rt Latency
7247 // -------------------------------------------
7248 // Rt, [Xn, Xm] | 4
7249 // -------------------------------------------
7250 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5
7251 // Rt, [Xn, Wm, <extend> #imm] |
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00007252 if (isLegalAddressingMode(DL, AM, Ty, AS))
Tim Northover3b0846e2014-05-24 12:50:23 +00007253 // Scale represents reg2 * scale, thus account for 1 if
7254 // it is not equal to 0 or 1.
7255 return AM.Scale != 0 && AM.Scale != 1;
7256 return -1;
7257}
7258
7259bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
7260 VT = VT.getScalarType();
7261
7262 if (!VT.isSimple())
7263 return false;
7264
7265 switch (VT.getSimpleVT().SimpleTy) {
7266 case MVT::f32:
7267 case MVT::f64:
7268 return true;
7269 default:
7270 break;
7271 }
7272
7273 return false;
7274}
7275
7276const MCPhysReg *
7277AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
7278 // LR is a callee-save register, but we must treat it as clobbered by any call
7279 // site. Hence we include LR in the scratch registers, which are in turn added
7280 // as implicit-defs for stackmaps and patchpoints.
7281 static const MCPhysReg ScratchRegs[] = {
7282 AArch64::X16, AArch64::X17, AArch64::LR, 0
7283 };
7284 return ScratchRegs;
7285}
7286
7287bool
7288AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N) const {
7289 EVT VT = N->getValueType(0);
7290 // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
7291 // it with shift to let it be lowered to UBFX.
7292 if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
7293 isa<ConstantSDNode>(N->getOperand(1))) {
7294 uint64_t TruncMask = N->getConstantOperandVal(1);
7295 if (isMask_64(TruncMask) &&
7296 N->getOperand(0).getOpcode() == ISD::SRL &&
7297 isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
7298 return false;
7299 }
7300 return true;
7301}
7302
7303bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
7304 Type *Ty) const {
7305 assert(Ty->isIntegerTy());
7306
7307 unsigned BitSize = Ty->getPrimitiveSizeInBits();
7308 if (BitSize == 0)
7309 return false;
7310
7311 int64_t Val = Imm.getSExtValue();
7312 if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
7313 return true;
7314
7315 if ((int64_t)Val < 0)
7316 Val = ~Val;
7317 if (BitSize == 32)
7318 Val &= (1LL << 32) - 1;
7319
7320 unsigned LZ = countLeadingZeros((uint64_t)Val);
7321 unsigned Shift = (63 - LZ) / 16;
7322 // MOVZ is free so return true for one or fewer MOVK.
David Blaikie186d2cb2015-03-24 16:24:01 +00007323 return Shift < 3;
Tim Northover3b0846e2014-05-24 12:50:23 +00007324}
7325
7326// Generate SUBS and CSEL for integer abs.
7327static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
7328 EVT VT = N->getValueType(0);
7329
7330 SDValue N0 = N->getOperand(0);
7331 SDValue N1 = N->getOperand(1);
7332 SDLoc DL(N);
7333
7334 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
7335 // and change it to SUB and CSEL.
7336 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
7337 N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
7338 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
7339 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
7340 if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007341 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
Tim Northover3b0846e2014-05-24 12:50:23 +00007342 N0.getOperand(0));
7343 // Generate SUBS & CSEL.
7344 SDValue Cmp =
7345 DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007346 N0.getOperand(0), DAG.getConstant(0, DL, VT));
Tim Northover3b0846e2014-05-24 12:50:23 +00007347 return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007348 DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00007349 SDValue(Cmp.getNode(), 1));
7350 }
7351 return SDValue();
7352}
7353
7354// performXorCombine - Attempts to handle integer ABS.
7355static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
7356 TargetLowering::DAGCombinerInfo &DCI,
7357 const AArch64Subtarget *Subtarget) {
7358 if (DCI.isBeforeLegalizeOps())
7359 return SDValue();
7360
7361 return performIntegerAbsCombine(N, DAG);
7362}
7363
Chad Rosier17020f92014-07-23 14:57:52 +00007364SDValue
7365AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
7366 SelectionDAG &DAG,
7367 std::vector<SDNode *> *Created) const {
7368 // fold (sdiv X, pow2)
7369 EVT VT = N->getValueType(0);
7370 if ((VT != MVT::i32 && VT != MVT::i64) ||
7371 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
7372 return SDValue();
7373
7374 SDLoc DL(N);
7375 SDValue N0 = N->getOperand(0);
7376 unsigned Lg2 = Divisor.countTrailingZeros();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007377 SDValue Zero = DAG.getConstant(0, DL, VT);
7378 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
Chad Rosier17020f92014-07-23 14:57:52 +00007379
7380 // Add (N0 < 0) ? Pow2 - 1 : 0;
7381 SDValue CCVal;
7382 SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
7383 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
7384 SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
7385
7386 if (Created) {
7387 Created->push_back(Cmp.getNode());
7388 Created->push_back(Add.getNode());
7389 Created->push_back(CSel.getNode());
7390 }
7391
7392 // Divide by pow2.
7393 SDValue SRA =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007394 DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
Chad Rosier17020f92014-07-23 14:57:52 +00007395
7396 // If we're dividing by a positive value, we're done. Otherwise, we must
7397 // negate the result.
7398 if (Divisor.isNonNegative())
7399 return SRA;
7400
7401 if (Created)
7402 Created->push_back(SRA.getNode());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007403 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
Chad Rosier17020f92014-07-23 14:57:52 +00007404}
7405
Tim Northover3b0846e2014-05-24 12:50:23 +00007406static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
7407 TargetLowering::DAGCombinerInfo &DCI,
7408 const AArch64Subtarget *Subtarget) {
7409 if (DCI.isBeforeLegalizeOps())
7410 return SDValue();
7411
7412 // Multiplication of a power of two plus/minus one can be done more
7413 // cheaply as as shift+add/sub. For now, this is true unilaterally. If
7414 // future CPUs have a cheaper MADD instruction, this may need to be
7415 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
7416 // 64-bit is 5 cycles, so this is always a win.
7417 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
7418 APInt Value = C->getAPIntValue();
7419 EVT VT = N->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007420 SDLoc DL(N);
Chad Rosiere6b87612014-06-30 14:51:14 +00007421 if (Value.isNonNegative()) {
7422 // (mul x, 2^N + 1) => (add (shl x, N), x)
7423 APInt VM1 = Value - 1;
7424 if (VM1.isPowerOf2()) {
7425 SDValue ShiftedVal =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007426 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7427 DAG.getConstant(VM1.logBase2(), DL, MVT::i64));
7428 return DAG.getNode(ISD::ADD, DL, VT, ShiftedVal,
Chad Rosiere6b87612014-06-30 14:51:14 +00007429 N->getOperand(0));
7430 }
7431 // (mul x, 2^N - 1) => (sub (shl x, N), x)
7432 APInt VP1 = Value + 1;
7433 if (VP1.isPowerOf2()) {
7434 SDValue ShiftedVal =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007435 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7436 DAG.getConstant(VP1.logBase2(), DL, MVT::i64));
7437 return DAG.getNode(ISD::SUB, DL, VT, ShiftedVal,
Chad Rosiere6b87612014-06-30 14:51:14 +00007438 N->getOperand(0));
7439 }
7440 } else {
Chad Rosier8e38f302015-03-03 17:31:01 +00007441 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7442 APInt VNP1 = -Value + 1;
7443 if (VNP1.isPowerOf2()) {
7444 SDValue ShiftedVal =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007445 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7446 DAG.getConstant(VNP1.logBase2(), DL, MVT::i64));
7447 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0),
Chad Rosier8e38f302015-03-03 17:31:01 +00007448 ShiftedVal);
7449 }
Chad Rosiere6b87612014-06-30 14:51:14 +00007450 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7451 APInt VNM1 = -Value - 1;
7452 if (VNM1.isPowerOf2()) {
7453 SDValue ShiftedVal =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007454 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7455 DAG.getConstant(VNM1.logBase2(), DL, MVT::i64));
Chad Rosiere6b87612014-06-30 14:51:14 +00007456 SDValue Add =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007457 DAG.getNode(ISD::ADD, DL, VT, ShiftedVal, N->getOperand(0));
7458 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Add);
Chad Rosiere6b87612014-06-30 14:51:14 +00007459 }
Chad Rosierd96e9f12014-06-09 01:25:51 +00007460 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007461 }
7462 return SDValue();
7463}
7464
Jim Grosbachf7502c42014-07-18 00:40:52 +00007465static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
7466 SelectionDAG &DAG) {
7467 // Take advantage of vector comparisons producing 0 or -1 in each lane to
7468 // optimize away operation when it's from a constant.
7469 //
7470 // The general transformation is:
7471 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
7472 // AND(VECTOR_CMP(x,y), constant2)
7473 // constant2 = UNARYOP(constant)
7474
Jim Grosbach8f6f0852014-07-23 20:41:38 +00007475 // Early exit if this isn't a vector operation, the operand of the
7476 // unary operation isn't a bitwise AND, or if the sizes of the operations
7477 // aren't the same.
Jim Grosbachf7502c42014-07-18 00:40:52 +00007478 EVT VT = N->getValueType(0);
7479 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
Jim Grosbach8f6f0852014-07-23 20:41:38 +00007480 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
7481 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
Jim Grosbachf7502c42014-07-18 00:40:52 +00007482 return SDValue();
7483
Jim Grosbach724e4382014-07-23 20:41:43 +00007484 // Now check that the other operand of the AND is a constant. We could
Jim Grosbachf7502c42014-07-18 00:40:52 +00007485 // make the transformation for non-constant splats as well, but it's unclear
7486 // that would be a benefit as it would not eliminate any operations, just
7487 // perform one more step in scalar code before moving to the vector unit.
7488 if (BuildVectorSDNode *BV =
7489 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
Jim Grosbach724e4382014-07-23 20:41:43 +00007490 // Bail out if the vector isn't a constant.
7491 if (!BV->isConstant())
Jim Grosbachf7502c42014-07-18 00:40:52 +00007492 return SDValue();
7493
7494 // Everything checks out. Build up the new and improved node.
7495 SDLoc DL(N);
7496 EVT IntVT = BV->getValueType(0);
7497 // Create a new constant of the appropriate type for the transformed
7498 // DAG.
7499 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
7500 // The AND node needs bitcasts to/from an integer vector type around it.
7501 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
7502 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
7503 N->getOperand(0)->getOperand(0), MaskConst);
7504 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
7505 return Res;
7506 }
7507
7508 return SDValue();
7509}
7510
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00007511static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
7512 const AArch64Subtarget *Subtarget) {
Jim Grosbachf7502c42014-07-18 00:40:52 +00007513 // First try to optimize away the conversion when it's conditionally from
7514 // a constant. Vectors only.
Ahmed Bougacha239d6352015-08-04 00:48:02 +00007515 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
Jim Grosbachf7502c42014-07-18 00:40:52 +00007516 return Res;
7517
Tim Northover3b0846e2014-05-24 12:50:23 +00007518 EVT VT = N->getValueType(0);
7519 if (VT != MVT::f32 && VT != MVT::f64)
7520 return SDValue();
Jim Grosbachf7502c42014-07-18 00:40:52 +00007521
Tim Northover3b0846e2014-05-24 12:50:23 +00007522 // Only optimize when the source and destination types have the same width.
7523 if (VT.getSizeInBits() != N->getOperand(0).getValueType().getSizeInBits())
7524 return SDValue();
7525
7526 // If the result of an integer load is only used by an integer-to-float
7527 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
Chad Rosier1f385612015-10-02 16:42:59 +00007528 // This eliminates an "integer-to-vector-move" UOP and improves throughput.
Tim Northover3b0846e2014-05-24 12:50:23 +00007529 SDValue N0 = N->getOperand(0);
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00007530 if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Tim Northover3b0846e2014-05-24 12:50:23 +00007531 // Do not change the width of a volatile load.
7532 !cast<LoadSDNode>(N0)->isVolatile()) {
7533 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7534 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
7535 LN0->getPointerInfo(), LN0->isVolatile(),
7536 LN0->isNonTemporal(), LN0->isInvariant(),
7537 LN0->getAlignment());
7538
7539 // Make sure successors of the original load stay after it by updating them
7540 // to use the new Chain.
7541 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
7542
7543 unsigned Opcode =
7544 (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
7545 return DAG.getNode(Opcode, SDLoc(N), VT, Load);
7546 }
7547
7548 return SDValue();
7549}
7550
Chad Rosierfa30c9b2015-10-07 17:39:18 +00007551/// Fold a floating-point multiply by power of two into floating-point to
7552/// fixed-point conversion.
7553static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
7554 const AArch64Subtarget *Subtarget) {
7555 if (!Subtarget->hasNEON())
7556 return SDValue();
7557
7558 SDValue Op = N->getOperand(0);
7559 if (!Op.getValueType().isVector() || Op.getOpcode() != ISD::FMUL)
7560 return SDValue();
7561
7562 SDValue ConstVec = Op->getOperand(1);
7563 if (!isa<BuildVectorSDNode>(ConstVec))
7564 return SDValue();
7565
7566 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
7567 uint32_t FloatBits = FloatTy.getSizeInBits();
7568 if (FloatBits != 32 && FloatBits != 64)
7569 return SDValue();
7570
7571 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
7572 uint32_t IntBits = IntTy.getSizeInBits();
7573 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
7574 return SDValue();
7575
7576 // Avoid conversions where iN is larger than the float (e.g., float -> i64).
7577 if (IntBits > FloatBits)
7578 return SDValue();
7579
7580 BitVector UndefElements;
7581 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
7582 int32_t Bits = IntBits == 64 ? 64 : 32;
7583 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
7584 if (C == -1 || C == 0 || C > Bits)
7585 return SDValue();
7586
7587 MVT ResTy;
7588 unsigned NumLanes = Op.getValueType().getVectorNumElements();
7589 switch (NumLanes) {
7590 default:
7591 return SDValue();
7592 case 2:
7593 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
7594 break;
7595 case 4:
7596 ResTy = MVT::v4i32;
7597 break;
7598 }
7599
7600 SDLoc DL(N);
7601 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
7602 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
7603 : Intrinsic::aarch64_neon_vcvtfp2fxu;
7604 SDValue FixConv =
7605 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
7606 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
7607 Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
7608 // We can handle smaller integers by generating an extra trunc.
7609 if (IntBits < FloatBits)
7610 FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
7611
7612 return FixConv;
7613}
7614
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00007615/// Fold a floating-point divide by power of two into fixed-point to
7616/// floating-point conversion.
7617static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
7618 const AArch64Subtarget *Subtarget) {
7619 if (!Subtarget->hasNEON())
7620 return SDValue();
7621
7622 SDValue Op = N->getOperand(0);
7623 unsigned Opc = Op->getOpcode();
7624 if (!Op.getValueType().isVector() ||
7625 (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
7626 return SDValue();
7627
7628 SDValue ConstVec = N->getOperand(1);
7629 if (!isa<BuildVectorSDNode>(ConstVec))
7630 return SDValue();
7631
7632 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
7633 int32_t IntBits = IntTy.getSizeInBits();
7634 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
7635 return SDValue();
7636
7637 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
7638 int32_t FloatBits = FloatTy.getSizeInBits();
7639 if (FloatBits != 32 && FloatBits != 64)
7640 return SDValue();
7641
7642 // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
7643 if (IntBits > FloatBits)
7644 return SDValue();
7645
7646 BitVector UndefElements;
7647 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
7648 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
7649 if (C == -1 || C == 0 || C > FloatBits)
7650 return SDValue();
7651
7652 MVT ResTy;
7653 unsigned NumLanes = Op.getValueType().getVectorNumElements();
7654 switch (NumLanes) {
7655 default:
7656 return SDValue();
7657 case 2:
7658 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
7659 break;
7660 case 4:
7661 ResTy = MVT::v4i32;
7662 break;
7663 }
7664
7665 SDLoc DL(N);
7666 SDValue ConvInput = Op.getOperand(0);
7667 bool IsSigned = Opc == ISD::SINT_TO_FP;
7668 if (IntBits < FloatBits)
7669 ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
7670 ResTy, ConvInput);
7671
7672 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
7673 : Intrinsic::aarch64_neon_vcvtfxu2fp;
7674 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
7675 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
7676 DAG.getConstant(C, DL, MVT::i32));
7677}
7678
Tim Northover3b0846e2014-05-24 12:50:23 +00007679/// An EXTR instruction is made up of two shifts, ORed together. This helper
7680/// searches for and classifies those shifts.
7681static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
7682 bool &FromHi) {
7683 if (N.getOpcode() == ISD::SHL)
7684 FromHi = false;
7685 else if (N.getOpcode() == ISD::SRL)
7686 FromHi = true;
7687 else
7688 return false;
7689
7690 if (!isa<ConstantSDNode>(N.getOperand(1)))
7691 return false;
7692
7693 ShiftAmount = N->getConstantOperandVal(1);
7694 Src = N->getOperand(0);
7695 return true;
7696}
7697
7698/// EXTR instruction extracts a contiguous chunk of bits from two existing
7699/// registers viewed as a high/low pair. This function looks for the pattern:
7700/// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an
7701/// EXTR. Can't quite be done in TableGen because the two immediates aren't
7702/// independent.
7703static SDValue tryCombineToEXTR(SDNode *N,
7704 TargetLowering::DAGCombinerInfo &DCI) {
7705 SelectionDAG &DAG = DCI.DAG;
7706 SDLoc DL(N);
7707 EVT VT = N->getValueType(0);
7708
7709 assert(N->getOpcode() == ISD::OR && "Unexpected root");
7710
7711 if (VT != MVT::i32 && VT != MVT::i64)
7712 return SDValue();
7713
7714 SDValue LHS;
7715 uint32_t ShiftLHS = 0;
7716 bool LHSFromHi = 0;
7717 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
7718 return SDValue();
7719
7720 SDValue RHS;
7721 uint32_t ShiftRHS = 0;
7722 bool RHSFromHi = 0;
7723 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
7724 return SDValue();
7725
7726 // If they're both trying to come from the high part of the register, they're
7727 // not really an EXTR.
7728 if (LHSFromHi == RHSFromHi)
7729 return SDValue();
7730
7731 if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
7732 return SDValue();
7733
7734 if (LHSFromHi) {
7735 std::swap(LHS, RHS);
7736 std::swap(ShiftLHS, ShiftRHS);
7737 }
7738
7739 return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007740 DAG.getConstant(ShiftRHS, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00007741}
7742
7743static SDValue tryCombineToBSL(SDNode *N,
7744 TargetLowering::DAGCombinerInfo &DCI) {
7745 EVT VT = N->getValueType(0);
7746 SelectionDAG &DAG = DCI.DAG;
7747 SDLoc DL(N);
7748
7749 if (!VT.isVector())
7750 return SDValue();
7751
7752 SDValue N0 = N->getOperand(0);
7753 if (N0.getOpcode() != ISD::AND)
7754 return SDValue();
7755
7756 SDValue N1 = N->getOperand(1);
7757 if (N1.getOpcode() != ISD::AND)
7758 return SDValue();
7759
7760 // We only have to look for constant vectors here since the general, variable
7761 // case can be handled in TableGen.
7762 unsigned Bits = VT.getVectorElementType().getSizeInBits();
7763 uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
7764 for (int i = 1; i >= 0; --i)
7765 for (int j = 1; j >= 0; --j) {
7766 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
7767 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
7768 if (!BVN0 || !BVN1)
7769 continue;
7770
7771 bool FoundMatch = true;
7772 for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
7773 ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
7774 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
7775 if (!CN0 || !CN1 ||
7776 CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
7777 FoundMatch = false;
7778 break;
7779 }
7780 }
7781
7782 if (FoundMatch)
7783 return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
7784 N0->getOperand(1 - i), N1->getOperand(1 - j));
7785 }
7786
7787 return SDValue();
7788}
7789
7790static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
7791 const AArch64Subtarget *Subtarget) {
7792 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
7793 if (!EnableAArch64ExtrGeneration)
7794 return SDValue();
7795 SelectionDAG &DAG = DCI.DAG;
7796 EVT VT = N->getValueType(0);
7797
7798 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7799 return SDValue();
7800
7801 SDValue Res = tryCombineToEXTR(N, DCI);
7802 if (Res.getNode())
7803 return Res;
7804
7805 Res = tryCombineToBSL(N, DCI);
7806 if (Res.getNode())
7807 return Res;
7808
7809 return SDValue();
7810}
7811
7812static SDValue performBitcastCombine(SDNode *N,
7813 TargetLowering::DAGCombinerInfo &DCI,
7814 SelectionDAG &DAG) {
7815 // Wait 'til after everything is legalized to try this. That way we have
7816 // legal vector types and such.
7817 if (DCI.isBeforeLegalizeOps())
7818 return SDValue();
7819
7820 // Remove extraneous bitcasts around an extract_subvector.
7821 // For example,
7822 // (v4i16 (bitconvert
7823 // (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
7824 // becomes
7825 // (extract_subvector ((v8i16 ...), (i64 4)))
7826
7827 // Only interested in 64-bit vectors as the ultimate result.
7828 EVT VT = N->getValueType(0);
7829 if (!VT.isVector())
7830 return SDValue();
7831 if (VT.getSimpleVT().getSizeInBits() != 64)
7832 return SDValue();
7833 // Is the operand an extract_subvector starting at the beginning or halfway
7834 // point of the vector? A low half may also come through as an
7835 // EXTRACT_SUBREG, so look for that, too.
7836 SDValue Op0 = N->getOperand(0);
7837 if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
7838 !(Op0->isMachineOpcode() &&
7839 Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
7840 return SDValue();
7841 uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
7842 if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
7843 if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
7844 return SDValue();
7845 } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
7846 if (idx != AArch64::dsub)
7847 return SDValue();
7848 // The dsub reference is equivalent to a lane zero subvector reference.
7849 idx = 0;
7850 }
7851 // Look through the bitcast of the input to the extract.
7852 if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
7853 return SDValue();
7854 SDValue Source = Op0->getOperand(0)->getOperand(0);
7855 // If the source type has twice the number of elements as our destination
7856 // type, we know this is an extract of the high or low half of the vector.
7857 EVT SVT = Source->getValueType(0);
7858 if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
7859 return SDValue();
7860
7861 DEBUG(dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
7862
7863 // Create the simplified form to just extract the low or high half of the
7864 // vector directly rather than bothering with the bitcasts.
7865 SDLoc dl(N);
7866 unsigned NumElements = VT.getVectorNumElements();
7867 if (idx) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007868 SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00007869 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
7870 } else {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007871 SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00007872 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
7873 Source, SubReg),
7874 0);
7875 }
7876}
7877
7878static SDValue performConcatVectorsCombine(SDNode *N,
7879 TargetLowering::DAGCombinerInfo &DCI,
7880 SelectionDAG &DAG) {
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00007881 SDLoc dl(N);
7882 EVT VT = N->getValueType(0);
7883 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
7884
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00007885 // Optimize concat_vectors of truncated vectors, where the intermediate
7886 // type is illegal, to avoid said illegality, e.g.,
7887 // (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
7888 // (v2i16 (truncate (v2i64)))))
7889 // ->
Ahmed Bougachae6bb09a2015-03-21 01:08:39 +00007890 // (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
7891 // (v4i32 (bitcast (v2i64))),
7892 // <0, 2, 4, 6>)))
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00007893 // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
7894 // on both input and result type, so we might generate worse code.
7895 // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
7896 if (N->getNumOperands() == 2 &&
7897 N0->getOpcode() == ISD::TRUNCATE &&
7898 N1->getOpcode() == ISD::TRUNCATE) {
7899 SDValue N00 = N0->getOperand(0);
7900 SDValue N10 = N1->getOperand(0);
7901 EVT N00VT = N00.getValueType();
7902
7903 if (N00VT == N10.getValueType() &&
7904 (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
7905 N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
Ahmed Bougachae6bb09a2015-03-21 01:08:39 +00007906 MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
7907 SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
7908 for (size_t i = 0; i < Mask.size(); ++i)
7909 Mask[i] = i * 2;
7910 return DAG.getNode(ISD::TRUNCATE, dl, VT,
7911 DAG.getVectorShuffle(
7912 MidVT, dl,
7913 DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
7914 DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00007915 }
7916 }
7917
Tim Northover3b0846e2014-05-24 12:50:23 +00007918 // Wait 'til after everything is legalized to try this. That way we have
7919 // legal vector types and such.
7920 if (DCI.isBeforeLegalizeOps())
7921 return SDValue();
7922
Tim Northover3b0846e2014-05-24 12:50:23 +00007923 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
7924 // splat. The indexed instructions are going to be expecting a DUPLANE64, so
7925 // canonicalise to that.
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00007926 if (N0 == N1 && VT.getVectorNumElements() == 2) {
Tim Northover3b0846e2014-05-24 12:50:23 +00007927 assert(VT.getVectorElementType().getSizeInBits() == 64);
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00007928 return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007929 DAG.getConstant(0, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00007930 }
7931
7932 // Canonicalise concat_vectors so that the right-hand vector has as few
7933 // bit-casts as possible before its real operation. The primary matching
7934 // destination for these operations will be the narrowing "2" instructions,
7935 // which depend on the operation being performed on this right-hand vector.
7936 // For example,
7937 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS))))
7938 // becomes
7939 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
7940
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00007941 if (N1->getOpcode() != ISD::BITCAST)
Tim Northover3b0846e2014-05-24 12:50:23 +00007942 return SDValue();
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00007943 SDValue RHS = N1->getOperand(0);
Tim Northover3b0846e2014-05-24 12:50:23 +00007944 MVT RHSTy = RHS.getValueType().getSimpleVT();
7945 // If the RHS is not a vector, this is not the pattern we're looking for.
7946 if (!RHSTy.isVector())
7947 return SDValue();
7948
7949 DEBUG(dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
7950
7951 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
7952 RHSTy.getVectorNumElements() * 2);
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00007953 return DAG.getNode(ISD::BITCAST, dl, VT,
7954 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
7955 DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
7956 RHS));
Tim Northover3b0846e2014-05-24 12:50:23 +00007957}
7958
7959static SDValue tryCombineFixedPointConvert(SDNode *N,
7960 TargetLowering::DAGCombinerInfo &DCI,
7961 SelectionDAG &DAG) {
7962 // Wait 'til after everything is legalized to try this. That way we have
7963 // legal vector types and such.
7964 if (DCI.isBeforeLegalizeOps())
7965 return SDValue();
7966 // Transform a scalar conversion of a value from a lane extract into a
7967 // lane extract of a vector conversion. E.g., from foo1 to foo2:
7968 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
7969 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
7970 //
7971 // The second form interacts better with instruction selection and the
7972 // register allocator to avoid cross-class register copies that aren't
7973 // coalescable due to a lane reference.
7974
7975 // Check the operand and see if it originates from a lane extract.
7976 SDValue Op1 = N->getOperand(1);
7977 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
7978 // Yep, no additional predication needed. Perform the transform.
7979 SDValue IID = N->getOperand(0);
7980 SDValue Shift = N->getOperand(2);
7981 SDValue Vec = Op1.getOperand(0);
7982 SDValue Lane = Op1.getOperand(1);
7983 EVT ResTy = N->getValueType(0);
7984 EVT VecResTy;
7985 SDLoc DL(N);
7986
7987 // The vector width should be 128 bits by the time we get here, even
7988 // if it started as 64 bits (the extract_vector handling will have
7989 // done so).
7990 assert(Vec.getValueType().getSizeInBits() == 128 &&
7991 "unexpected vector size on extract_vector_elt!");
7992 if (Vec.getValueType() == MVT::v4i32)
7993 VecResTy = MVT::v4f32;
7994 else if (Vec.getValueType() == MVT::v2i64)
7995 VecResTy = MVT::v2f64;
7996 else
Craig Topper2a30d782014-06-18 05:05:13 +00007997 llvm_unreachable("unexpected vector type!");
Tim Northover3b0846e2014-05-24 12:50:23 +00007998
7999 SDValue Convert =
8000 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
8001 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
8002 }
8003 return SDValue();
8004}
8005
8006// AArch64 high-vector "long" operations are formed by performing the non-high
8007// version on an extract_subvector of each operand which gets the high half:
8008//
8009// (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
8010//
8011// However, there are cases which don't have an extract_high explicitly, but
8012// have another operation that can be made compatible with one for free. For
8013// example:
8014//
8015// (dupv64 scalar) --> (extract_high (dup128 scalar))
8016//
8017// This routine does the actual conversion of such DUPs, once outer routines
8018// have determined that everything else is in order.
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008019// It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
8020// similarly here.
Tim Northover3b0846e2014-05-24 12:50:23 +00008021static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00008022 switch (N.getOpcode()) {
8023 case AArch64ISD::DUP:
Tim Northover3b0846e2014-05-24 12:50:23 +00008024 case AArch64ISD::DUPLANE8:
8025 case AArch64ISD::DUPLANE16:
8026 case AArch64ISD::DUPLANE32:
8027 case AArch64ISD::DUPLANE64:
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008028 case AArch64ISD::MOVI:
8029 case AArch64ISD::MOVIshift:
8030 case AArch64ISD::MOVIedit:
8031 case AArch64ISD::MOVImsl:
8032 case AArch64ISD::MVNIshift:
8033 case AArch64ISD::MVNImsl:
Tim Northover3b0846e2014-05-24 12:50:23 +00008034 break;
8035 default:
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008036 // FMOV could be supported, but isn't very useful, as it would only occur
8037 // if you passed a bitcast' floating point immediate to an eligible long
8038 // integer op (addl, smull, ...).
Tim Northover3b0846e2014-05-24 12:50:23 +00008039 return SDValue();
8040 }
8041
8042 MVT NarrowTy = N.getSimpleValueType();
8043 if (!NarrowTy.is64BitVector())
8044 return SDValue();
8045
8046 MVT ElementTy = NarrowTy.getVectorElementType();
8047 unsigned NumElems = NarrowTy.getVectorNumElements();
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008048 MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
Tim Northover3b0846e2014-05-24 12:50:23 +00008049
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008050 SDLoc dl(N);
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008051 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
8052 DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008053 DAG.getConstant(NumElems, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008054}
8055
8056static bool isEssentiallyExtractSubvector(SDValue N) {
8057 if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
8058 return true;
8059
8060 return N.getOpcode() == ISD::BITCAST &&
8061 N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
8062}
8063
8064/// \brief Helper structure to keep track of ISD::SET_CC operands.
8065struct GenericSetCCInfo {
8066 const SDValue *Opnd0;
8067 const SDValue *Opnd1;
8068 ISD::CondCode CC;
8069};
8070
8071/// \brief Helper structure to keep track of a SET_CC lowered into AArch64 code.
8072struct AArch64SetCCInfo {
8073 const SDValue *Cmp;
8074 AArch64CC::CondCode CC;
8075};
8076
8077/// \brief Helper structure to keep track of SetCC information.
8078union SetCCInfo {
8079 GenericSetCCInfo Generic;
8080 AArch64SetCCInfo AArch64;
8081};
8082
8083/// \brief Helper structure to be able to read SetCC information. If set to
8084/// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
8085/// GenericSetCCInfo.
8086struct SetCCInfoAndKind {
8087 SetCCInfo Info;
8088 bool IsAArch64;
8089};
8090
8091/// \brief Check whether or not \p Op is a SET_CC operation, either a generic or
8092/// an
8093/// AArch64 lowered one.
8094/// \p SetCCInfo is filled accordingly.
8095/// \post SetCCInfo is meanginfull only when this function returns true.
8096/// \return True when Op is a kind of SET_CC operation.
8097static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
8098 // If this is a setcc, this is straight forward.
8099 if (Op.getOpcode() == ISD::SETCC) {
8100 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
8101 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
8102 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8103 SetCCInfo.IsAArch64 = false;
8104 return true;
8105 }
8106 // Otherwise, check if this is a matching csel instruction.
8107 // In other words:
8108 // - csel 1, 0, cc
8109 // - csel 0, 1, !cc
8110 if (Op.getOpcode() != AArch64ISD::CSEL)
8111 return false;
8112 // Set the information about the operands.
8113 // TODO: we want the operands of the Cmp not the csel
8114 SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
8115 SetCCInfo.IsAArch64 = true;
8116 SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
8117 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
8118
8119 // Check that the operands matches the constraints:
8120 // (1) Both operands must be constants.
8121 // (2) One must be 1 and the other must be 0.
8122 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
8123 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8124
8125 // Check (1).
8126 if (!TValue || !FValue)
8127 return false;
8128
8129 // Check (2).
8130 if (!TValue->isOne()) {
8131 // Update the comparison when we are interested in !cc.
8132 std::swap(TValue, FValue);
8133 SetCCInfo.Info.AArch64.CC =
8134 AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
8135 }
8136 return TValue->isOne() && FValue->isNullValue();
8137}
8138
8139// Returns true if Op is setcc or zext of setcc.
8140static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
8141 if (isSetCC(Op, Info))
8142 return true;
8143 return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
8144 isSetCC(Op->getOperand(0), Info));
8145}
8146
8147// The folding we want to perform is:
8148// (add x, [zext] (setcc cc ...) )
8149// -->
8150// (csel x, (add x, 1), !cc ...)
8151//
8152// The latter will get matched to a CSINC instruction.
8153static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
8154 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
8155 SDValue LHS = Op->getOperand(0);
8156 SDValue RHS = Op->getOperand(1);
8157 SetCCInfoAndKind InfoAndKind;
8158
8159 // If neither operand is a SET_CC, give up.
8160 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
8161 std::swap(LHS, RHS);
8162 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
8163 return SDValue();
8164 }
8165
8166 // FIXME: This could be generatized to work for FP comparisons.
8167 EVT CmpVT = InfoAndKind.IsAArch64
8168 ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
8169 : InfoAndKind.Info.Generic.Opnd0->getValueType();
8170 if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
8171 return SDValue();
8172
8173 SDValue CCVal;
8174 SDValue Cmp;
8175 SDLoc dl(Op);
8176 if (InfoAndKind.IsAArch64) {
8177 CCVal = DAG.getConstant(
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008178 AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
8179 MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00008180 Cmp = *InfoAndKind.Info.AArch64.Cmp;
8181 } else
8182 Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
8183 *InfoAndKind.Info.Generic.Opnd1,
8184 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
8185 CCVal, DAG, dl);
8186
8187 EVT VT = Op->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008188 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
Tim Northover3b0846e2014-05-24 12:50:23 +00008189 return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
8190}
8191
8192// The basic add/sub long vector instructions have variants with "2" on the end
8193// which act on the high-half of their inputs. They are normally matched by
8194// patterns like:
8195//
8196// (add (zeroext (extract_high LHS)),
8197// (zeroext (extract_high RHS)))
8198// -> uaddl2 vD, vN, vM
8199//
8200// However, if one of the extracts is something like a duplicate, this
8201// instruction can still be used profitably. This function puts the DAG into a
8202// more appropriate form for those patterns to trigger.
8203static SDValue performAddSubLongCombine(SDNode *N,
8204 TargetLowering::DAGCombinerInfo &DCI,
8205 SelectionDAG &DAG) {
8206 if (DCI.isBeforeLegalizeOps())
8207 return SDValue();
8208
8209 MVT VT = N->getSimpleValueType(0);
8210 if (!VT.is128BitVector()) {
8211 if (N->getOpcode() == ISD::ADD)
8212 return performSetccAddFolding(N, DAG);
8213 return SDValue();
8214 }
8215
8216 // Make sure both branches are extended in the same way.
8217 SDValue LHS = N->getOperand(0);
8218 SDValue RHS = N->getOperand(1);
8219 if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
8220 LHS.getOpcode() != ISD::SIGN_EXTEND) ||
8221 LHS.getOpcode() != RHS.getOpcode())
8222 return SDValue();
8223
8224 unsigned ExtType = LHS.getOpcode();
8225
8226 // It's not worth doing if at least one of the inputs isn't already an
8227 // extract, but we don't know which it'll be so we have to try both.
8228 if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
8229 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
8230 if (!RHS.getNode())
8231 return SDValue();
8232
8233 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
8234 } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
8235 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
8236 if (!LHS.getNode())
8237 return SDValue();
8238
8239 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
8240 }
8241
8242 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
8243}
8244
8245// Massage DAGs which we can use the high-half "long" operations on into
8246// something isel will recognize better. E.g.
8247//
8248// (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
8249// (aarch64_neon_umull (extract_high (v2i64 vec)))
8250// (extract_high (v2i64 (dup128 scalar)))))
8251//
Hal Finkelcd8664c2015-12-11 23:11:52 +00008252static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
Tim Northover3b0846e2014-05-24 12:50:23 +00008253 TargetLowering::DAGCombinerInfo &DCI,
8254 SelectionDAG &DAG) {
8255 if (DCI.isBeforeLegalizeOps())
8256 return SDValue();
8257
Hal Finkelcd8664c2015-12-11 23:11:52 +00008258 SDValue LHS = N->getOperand(1);
8259 SDValue RHS = N->getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00008260 assert(LHS.getValueType().is64BitVector() &&
8261 RHS.getValueType().is64BitVector() &&
8262 "unexpected shape for long operation");
8263
8264 // Either node could be a DUP, but it's not worth doing both of them (you'd
8265 // just as well use the non-high version) so look for a corresponding extract
8266 // operation on the other "wing".
8267 if (isEssentiallyExtractSubvector(LHS)) {
8268 RHS = tryExtendDUPToExtractHigh(RHS, DAG);
8269 if (!RHS.getNode())
8270 return SDValue();
8271 } else if (isEssentiallyExtractSubvector(RHS)) {
8272 LHS = tryExtendDUPToExtractHigh(LHS, DAG);
8273 if (!LHS.getNode())
8274 return SDValue();
8275 }
8276
Hal Finkelcd8664c2015-12-11 23:11:52 +00008277 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
8278 N->getOperand(0), LHS, RHS);
Tim Northover3b0846e2014-05-24 12:50:23 +00008279}
8280
8281static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
8282 MVT ElemTy = N->getSimpleValueType(0).getScalarType();
8283 unsigned ElemBits = ElemTy.getSizeInBits();
8284
8285 int64_t ShiftAmount;
8286 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
8287 APInt SplatValue, SplatUndef;
8288 unsigned SplatBitSize;
8289 bool HasAnyUndefs;
8290 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
8291 HasAnyUndefs, ElemBits) ||
8292 SplatBitSize != ElemBits)
8293 return SDValue();
8294
8295 ShiftAmount = SplatValue.getSExtValue();
8296 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
8297 ShiftAmount = CVN->getSExtValue();
8298 } else
8299 return SDValue();
8300
8301 unsigned Opcode;
8302 bool IsRightShift;
8303 switch (IID) {
8304 default:
8305 llvm_unreachable("Unknown shift intrinsic");
8306 case Intrinsic::aarch64_neon_sqshl:
8307 Opcode = AArch64ISD::SQSHL_I;
8308 IsRightShift = false;
8309 break;
8310 case Intrinsic::aarch64_neon_uqshl:
8311 Opcode = AArch64ISD::UQSHL_I;
8312 IsRightShift = false;
8313 break;
8314 case Intrinsic::aarch64_neon_srshl:
8315 Opcode = AArch64ISD::SRSHR_I;
8316 IsRightShift = true;
8317 break;
8318 case Intrinsic::aarch64_neon_urshl:
8319 Opcode = AArch64ISD::URSHR_I;
8320 IsRightShift = true;
8321 break;
8322 case Intrinsic::aarch64_neon_sqshlu:
8323 Opcode = AArch64ISD::SQSHLU_I;
8324 IsRightShift = false;
8325 break;
8326 }
8327
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008328 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
8329 SDLoc dl(N);
8330 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8331 DAG.getConstant(-ShiftAmount, dl, MVT::i32));
8332 } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
8333 SDLoc dl(N);
8334 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8335 DAG.getConstant(ShiftAmount, dl, MVT::i32));
8336 }
Tim Northover3b0846e2014-05-24 12:50:23 +00008337
8338 return SDValue();
8339}
8340
8341// The CRC32[BH] instructions ignore the high bits of their data operand. Since
8342// the intrinsics must be legal and take an i32, this means there's almost
8343// certainly going to be a zext in the DAG which we can eliminate.
8344static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
8345 SDValue AndN = N->getOperand(2);
8346 if (AndN.getOpcode() != ISD::AND)
8347 return SDValue();
8348
8349 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
8350 if (!CMask || CMask->getZExtValue() != Mask)
8351 return SDValue();
8352
8353 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
8354 N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
8355}
8356
Ahmed Bougachafab58922015-03-10 20:45:38 +00008357static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
8358 SelectionDAG &DAG) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008359 SDLoc dl(N);
8360 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
8361 DAG.getNode(Opc, dl,
Ahmed Bougachafab58922015-03-10 20:45:38 +00008362 N->getOperand(1).getSimpleValueType(),
8363 N->getOperand(1)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008364 DAG.getConstant(0, dl, MVT::i64));
Ahmed Bougachafab58922015-03-10 20:45:38 +00008365}
8366
Tim Northover3b0846e2014-05-24 12:50:23 +00008367static SDValue performIntrinsicCombine(SDNode *N,
8368 TargetLowering::DAGCombinerInfo &DCI,
8369 const AArch64Subtarget *Subtarget) {
8370 SelectionDAG &DAG = DCI.DAG;
8371 unsigned IID = getIntrinsicID(N);
8372 switch (IID) {
8373 default:
8374 break;
8375 case Intrinsic::aarch64_neon_vcvtfxs2fp:
8376 case Intrinsic::aarch64_neon_vcvtfxu2fp:
8377 return tryCombineFixedPointConvert(N, DCI, DAG);
Ahmed Bougachafab58922015-03-10 20:45:38 +00008378 case Intrinsic::aarch64_neon_saddv:
8379 return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
8380 case Intrinsic::aarch64_neon_uaddv:
8381 return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
8382 case Intrinsic::aarch64_neon_sminv:
8383 return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
8384 case Intrinsic::aarch64_neon_uminv:
8385 return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
8386 case Intrinsic::aarch64_neon_smaxv:
8387 return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
8388 case Intrinsic::aarch64_neon_umaxv:
8389 return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00008390 case Intrinsic::aarch64_neon_fmax:
James Molloyedf38f02015-08-11 12:06:33 +00008391 return DAG.getNode(ISD::FMAXNAN, SDLoc(N), N->getValueType(0),
Tim Northover3b0846e2014-05-24 12:50:23 +00008392 N->getOperand(1), N->getOperand(2));
8393 case Intrinsic::aarch64_neon_fmin:
James Molloyedf38f02015-08-11 12:06:33 +00008394 return DAG.getNode(ISD::FMINNAN, SDLoc(N), N->getValueType(0),
Tim Northover3b0846e2014-05-24 12:50:23 +00008395 N->getOperand(1), N->getOperand(2));
James Molloyb7b2a1e2015-08-11 12:06:37 +00008396 case Intrinsic::aarch64_neon_fmaxnm:
8397 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
8398 N->getOperand(1), N->getOperand(2));
8399 case Intrinsic::aarch64_neon_fminnm:
8400 return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
8401 N->getOperand(1), N->getOperand(2));
Tim Northover3b0846e2014-05-24 12:50:23 +00008402 case Intrinsic::aarch64_neon_smull:
8403 case Intrinsic::aarch64_neon_umull:
8404 case Intrinsic::aarch64_neon_pmull:
8405 case Intrinsic::aarch64_neon_sqdmull:
Hal Finkelcd8664c2015-12-11 23:11:52 +00008406 return tryCombineLongOpWithDup(IID, N, DCI, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00008407 case Intrinsic::aarch64_neon_sqshl:
8408 case Intrinsic::aarch64_neon_uqshl:
8409 case Intrinsic::aarch64_neon_sqshlu:
8410 case Intrinsic::aarch64_neon_srshl:
8411 case Intrinsic::aarch64_neon_urshl:
8412 return tryCombineShiftImm(IID, N, DAG);
8413 case Intrinsic::aarch64_crc32b:
8414 case Intrinsic::aarch64_crc32cb:
8415 return tryCombineCRC32(0xff, N, DAG);
8416 case Intrinsic::aarch64_crc32h:
8417 case Intrinsic::aarch64_crc32ch:
8418 return tryCombineCRC32(0xffff, N, DAG);
8419 }
8420 return SDValue();
8421}
8422
8423static SDValue performExtendCombine(SDNode *N,
8424 TargetLowering::DAGCombinerInfo &DCI,
8425 SelectionDAG &DAG) {
8426 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
8427 // we can convert that DUP into another extract_high (of a bigger DUP), which
8428 // helps the backend to decide that an sabdl2 would be useful, saving a real
8429 // extract_high operation.
8430 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
Hal Finkelcd8664c2015-12-11 23:11:52 +00008431 N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
Tim Northover3b0846e2014-05-24 12:50:23 +00008432 SDNode *ABDNode = N->getOperand(0).getNode();
Hal Finkelcd8664c2015-12-11 23:11:52 +00008433 unsigned IID = getIntrinsicID(ABDNode);
8434 if (IID == Intrinsic::aarch64_neon_sabd ||
8435 IID == Intrinsic::aarch64_neon_uabd) {
8436 SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
8437 if (!NewABD.getNode())
8438 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00008439
Hal Finkelcd8664c2015-12-11 23:11:52 +00008440 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
8441 NewABD);
8442 }
Tim Northover3b0846e2014-05-24 12:50:23 +00008443 }
8444
8445 // This is effectively a custom type legalization for AArch64.
8446 //
8447 // Type legalization will split an extend of a small, legal, type to a larger
8448 // illegal type by first splitting the destination type, often creating
8449 // illegal source types, which then get legalized in isel-confusing ways,
8450 // leading to really terrible codegen. E.g.,
8451 // %result = v8i32 sext v8i8 %value
8452 // becomes
8453 // %losrc = extract_subreg %value, ...
8454 // %hisrc = extract_subreg %value, ...
8455 // %lo = v4i32 sext v4i8 %losrc
8456 // %hi = v4i32 sext v4i8 %hisrc
8457 // Things go rapidly downhill from there.
8458 //
8459 // For AArch64, the [sz]ext vector instructions can only go up one element
8460 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
8461 // take two instructions.
8462 //
8463 // This implies that the most efficient way to do the extend from v8i8
8464 // to two v4i32 values is to first extend the v8i8 to v8i16, then do
8465 // the normal splitting to happen for the v8i16->v8i32.
8466
8467 // This is pre-legalization to catch some cases where the default
8468 // type legalization will create ill-tempered code.
8469 if (!DCI.isBeforeLegalizeOps())
8470 return SDValue();
8471
8472 // We're only interested in cleaning things up for non-legal vector types
8473 // here. If both the source and destination are legal, things will just
8474 // work naturally without any fiddling.
8475 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8476 EVT ResVT = N->getValueType(0);
8477 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
8478 return SDValue();
8479 // If the vector type isn't a simple VT, it's beyond the scope of what
8480 // we're worried about here. Let legalization do its thing and hope for
8481 // the best.
Jim Grosbachec2b0d02014-08-28 22:08:28 +00008482 SDValue Src = N->getOperand(0);
8483 EVT SrcVT = Src->getValueType(0);
8484 if (!ResVT.isSimple() || !SrcVT.isSimple())
Tim Northover3b0846e2014-05-24 12:50:23 +00008485 return SDValue();
8486
Tim Northover3b0846e2014-05-24 12:50:23 +00008487 // If the source VT is a 64-bit vector, we can play games and get the
8488 // better results we want.
8489 if (SrcVT.getSizeInBits() != 64)
8490 return SDValue();
8491
8492 unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits();
8493 unsigned ElementCount = SrcVT.getVectorNumElements();
8494 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
8495 SDLoc DL(N);
8496 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
8497
8498 // Now split the rest of the operation into two halves, each with a 64
8499 // bit source.
8500 EVT LoVT, HiVT;
8501 SDValue Lo, Hi;
8502 unsigned NumElements = ResVT.getVectorNumElements();
8503 assert(!(NumElements & 1) && "Splitting vector, but not in half!");
8504 LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
8505 ResVT.getVectorElementType(), NumElements / 2);
8506
8507 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
8508 LoVT.getVectorNumElements());
8509 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008510 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008511 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008512 DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008513 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
8514 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
8515
8516 // Now combine the parts back together so we still have a single result
8517 // like the combiner expects.
8518 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
8519}
8520
8521/// Replace a splat of a scalar to a vector store by scalar stores of the scalar
8522/// value. The load store optimizer pass will merge them to store pair stores.
8523/// This has better performance than a splat of the scalar followed by a split
8524/// vector store. Even if the stores are not merged it is four stores vs a dup,
8525/// followed by an ext.b and two stores.
8526static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode *St) {
8527 SDValue StVal = St->getValue();
8528 EVT VT = StVal.getValueType();
8529
8530 // Don't replace floating point stores, they possibly won't be transformed to
8531 // stp because of the store pair suppress pass.
8532 if (VT.isFloatingPoint())
8533 return SDValue();
8534
8535 // Check for insert vector elements.
8536 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
8537 return SDValue();
8538
8539 // We can express a splat as store pair(s) for 2 or 4 elements.
8540 unsigned NumVecElts = VT.getVectorNumElements();
8541 if (NumVecElts != 4 && NumVecElts != 2)
8542 return SDValue();
8543 SDValue SplatVal = StVal.getOperand(1);
8544 unsigned RemainInsertElts = NumVecElts - 1;
8545
8546 // Check that this is a splat.
8547 while (--RemainInsertElts) {
8548 SDValue NextInsertElt = StVal.getOperand(0);
8549 if (NextInsertElt.getOpcode() != ISD::INSERT_VECTOR_ELT)
8550 return SDValue();
8551 if (NextInsertElt.getOperand(1) != SplatVal)
8552 return SDValue();
8553 StVal = NextInsertElt;
8554 }
8555 unsigned OrigAlignment = St->getAlignment();
8556 unsigned EltOffset = NumVecElts == 4 ? 4 : 8;
8557 unsigned Alignment = std::min(OrigAlignment, EltOffset);
8558
8559 // Create scalar stores. This is at least as good as the code sequence for a
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00008560 // split unaligned store which is a dup.s, ext.b, and two stores.
Tim Northover3b0846e2014-05-24 12:50:23 +00008561 // Most of the time the three stores should be replaced by store pair
8562 // instructions (stp).
8563 SDLoc DL(St);
8564 SDValue BasePtr = St->getBasePtr();
8565 SDValue NewST1 =
8566 DAG.getStore(St->getChain(), DL, SplatVal, BasePtr, St->getPointerInfo(),
8567 St->isVolatile(), St->isNonTemporal(), St->getAlignment());
8568
8569 unsigned Offset = EltOffset;
8570 while (--NumVecElts) {
8571 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008572 DAG.getConstant(Offset, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008573 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
8574 St->getPointerInfo(), St->isVolatile(),
8575 St->isNonTemporal(), Alignment);
8576 Offset += EltOffset;
8577 }
8578 return NewST1;
8579}
8580
Tim Northover339c83e2015-11-10 00:44:23 +00008581static SDValue split16BStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
8582 SelectionDAG &DAG,
8583 const AArch64Subtarget *Subtarget) {
Tim Northover3b0846e2014-05-24 12:50:23 +00008584 if (!DCI.isBeforeLegalize())
8585 return SDValue();
8586
8587 StoreSDNode *S = cast<StoreSDNode>(N);
8588 if (S->isVolatile())
8589 return SDValue();
8590
Sanjay Patelbbbf9a12015-09-25 21:49:48 +00008591 // FIXME: The logic for deciding if an unaligned store should be split should
8592 // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
8593 // a call to that function here.
8594
Tim Northover3b0846e2014-05-24 12:50:23 +00008595 // Cyclone has bad performance on unaligned 16B stores when crossing line and
Sanjay Patel08efcd92015-01-28 22:37:32 +00008596 // page boundaries. We want to split such stores.
Tim Northover3b0846e2014-05-24 12:50:23 +00008597 if (!Subtarget->isCyclone())
8598 return SDValue();
8599
Sanjay Patel924879a2015-08-04 15:49:57 +00008600 // Don't split at -Oz.
8601 if (DAG.getMachineFunction().getFunction()->optForMinSize())
Tim Northover3b0846e2014-05-24 12:50:23 +00008602 return SDValue();
8603
8604 SDValue StVal = S->getValue();
8605 EVT VT = StVal.getValueType();
8606
8607 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
8608 // those up regresses performance on micro-benchmarks and olden/bh.
8609 if (!VT.isVector() || VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
8610 return SDValue();
8611
8612 // Split unaligned 16B stores. They are terrible for performance.
8613 // Don't split stores with alignment of 1 or 2. Code that uses clang vector
8614 // extensions can use this to mark that it does not want splitting to happen
8615 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
8616 // eliminating alignment hazards is only 1 in 8 for alignment of 2.
8617 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
8618 S->getAlignment() <= 2)
8619 return SDValue();
8620
8621 // If we get a splat of a scalar convert this vector store to a store of
8622 // scalars. They will be merged into store pairs thereby removing two
8623 // instructions.
Ahmed Bougacha239d6352015-08-04 00:48:02 +00008624 if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, S))
Tim Northover3b0846e2014-05-24 12:50:23 +00008625 return ReplacedSplat;
8626
8627 SDLoc DL(S);
8628 unsigned NumElts = VT.getVectorNumElements() / 2;
8629 // Split VT into two.
8630 EVT HalfVT =
8631 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
8632 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008633 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008634 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008635 DAG.getConstant(NumElts, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008636 SDValue BasePtr = S->getBasePtr();
8637 SDValue NewST1 =
8638 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
8639 S->isVolatile(), S->isNonTemporal(), S->getAlignment());
8640 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008641 DAG.getConstant(8, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008642 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
8643 S->getPointerInfo(), S->isVolatile(), S->isNonTemporal(),
8644 S->getAlignment());
8645}
8646
8647/// Target-specific DAG combine function for post-increment LD1 (lane) and
8648/// post-increment LD1R.
8649static SDValue performPostLD1Combine(SDNode *N,
8650 TargetLowering::DAGCombinerInfo &DCI,
8651 bool IsLaneOp) {
8652 if (DCI.isBeforeLegalizeOps())
8653 return SDValue();
8654
8655 SelectionDAG &DAG = DCI.DAG;
8656 EVT VT = N->getValueType(0);
8657
8658 unsigned LoadIdx = IsLaneOp ? 1 : 0;
8659 SDNode *LD = N->getOperand(LoadIdx).getNode();
8660 // If it is not LOAD, can not do such combine.
8661 if (LD->getOpcode() != ISD::LOAD)
8662 return SDValue();
8663
8664 LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
8665 EVT MemVT = LoadSDN->getMemoryVT();
8666 // Check if memory operand is the same type as the vector element.
8667 if (MemVT != VT.getVectorElementType())
8668 return SDValue();
8669
8670 // Check if there are other uses. If so, do not combine as it will introduce
8671 // an extra load.
8672 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
8673 ++UI) {
8674 if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
8675 continue;
8676 if (*UI != N)
8677 return SDValue();
8678 }
8679
8680 SDValue Addr = LD->getOperand(1);
8681 SDValue Vector = N->getOperand(0);
8682 // Search for a use of the address operand that is an increment.
8683 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
8684 Addr.getNode()->use_end(); UI != UE; ++UI) {
8685 SDNode *User = *UI;
8686 if (User->getOpcode() != ISD::ADD
8687 || UI.getUse().getResNo() != Addr.getResNo())
8688 continue;
8689
8690 // Check that the add is independent of the load. Otherwise, folding it
8691 // would create a cycle.
8692 if (User->isPredecessorOf(LD) || LD->isPredecessorOf(User))
8693 continue;
8694 // Also check that add is not used in the vector operand. This would also
8695 // create a cycle.
8696 if (User->isPredecessorOf(Vector.getNode()))
8697 continue;
8698
8699 // If the increment is a constant, it must match the memory ref size.
8700 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8701 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8702 uint32_t IncVal = CInc->getZExtValue();
8703 unsigned NumBytes = VT.getScalarSizeInBits() / 8;
8704 if (IncVal != NumBytes)
8705 continue;
8706 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
8707 }
8708
Ahmed Bougacha2448ef52015-04-17 21:02:30 +00008709 // Finally, check that the vector doesn't depend on the load.
8710 // Again, this would create a cycle.
8711 // The load depending on the vector is fine, as that's the case for the
8712 // LD1*post we'll eventually generate anyway.
8713 if (LoadSDN->isPredecessorOf(Vector.getNode()))
8714 continue;
8715
Tim Northover3b0846e2014-05-24 12:50:23 +00008716 SmallVector<SDValue, 8> Ops;
8717 Ops.push_back(LD->getOperand(0)); // Chain
8718 if (IsLaneOp) {
8719 Ops.push_back(Vector); // The vector to be inserted
8720 Ops.push_back(N->getOperand(2)); // The lane to be inserted in the vector
8721 }
8722 Ops.push_back(Addr);
8723 Ops.push_back(Inc);
8724
8725 EVT Tys[3] = { VT, MVT::i64, MVT::Other };
Craig Toppere1d12942014-08-27 05:25:25 +00008726 SDVTList SDTys = DAG.getVTList(Tys);
Tim Northover3b0846e2014-05-24 12:50:23 +00008727 unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
8728 SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
8729 MemVT,
8730 LoadSDN->getMemOperand());
8731
8732 // Update the uses.
Ahmed Bougacha4c2b0782015-02-19 23:13:10 +00008733 SmallVector<SDValue, 2> NewResults;
Tim Northover3b0846e2014-05-24 12:50:23 +00008734 NewResults.push_back(SDValue(LD, 0)); // The result of load
8735 NewResults.push_back(SDValue(UpdN.getNode(), 2)); // Chain
8736 DCI.CombineTo(LD, NewResults);
8737 DCI.CombineTo(N, SDValue(UpdN.getNode(), 0)); // Dup/Inserted Result
8738 DCI.CombineTo(User, SDValue(UpdN.getNode(), 1)); // Write back register
8739
8740 break;
8741 }
8742 return SDValue();
8743}
8744
Tim Northover339c83e2015-11-10 00:44:23 +00008745/// Simplify \Addr given that the top byte of it is ignored by HW during
8746/// address translation.
8747static bool performTBISimplification(SDValue Addr,
8748 TargetLowering::DAGCombinerInfo &DCI,
8749 SelectionDAG &DAG) {
8750 APInt DemandedMask = APInt::getLowBitsSet(64, 56);
8751 APInt KnownZero, KnownOne;
8752 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
8753 DCI.isBeforeLegalizeOps());
8754 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8755 if (TLI.SimplifyDemandedBits(Addr, DemandedMask, KnownZero, KnownOne, TLO)) {
8756 DCI.CommitTargetLoweringOpt(TLO);
8757 return true;
8758 }
8759 return false;
8760}
8761
8762static SDValue performSTORECombine(SDNode *N,
8763 TargetLowering::DAGCombinerInfo &DCI,
8764 SelectionDAG &DAG,
8765 const AArch64Subtarget *Subtarget) {
8766 SDValue Split = split16BStores(N, DCI, DAG, Subtarget);
8767 if (Split.getNode())
8768 return Split;
8769
8770 if (Subtarget->supportsAddressTopByteIgnored() &&
8771 performTBISimplification(N->getOperand(2), DCI, DAG))
8772 return SDValue(N, 0);
8773
8774 return SDValue();
8775}
8776
8777 /// This function handles the log2-shuffle pattern produced by the
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008778/// LoopVectorizer for the across vector reduction. It consists of
8779/// log2(NumVectorElements) steps and, in each step, 2^(s) elements
8780/// are reduced, where s is an induction variable from 0 to
8781/// log2(NumVectorElements).
8782static SDValue tryMatchAcrossLaneShuffleForReduction(SDNode *N, SDValue OpV,
8783 unsigned Op,
8784 SelectionDAG &DAG) {
8785 EVT VTy = OpV->getOperand(0).getValueType();
8786 if (!VTy.isVector())
Chad Rosier6c36eff2015-09-03 18:13:57 +00008787 return SDValue();
8788
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008789 int NumVecElts = VTy.getVectorNumElements();
Jun Bum Lim0aace132015-10-09 14:11:25 +00008790 if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) {
8791 if (NumVecElts != 4)
8792 return SDValue();
8793 } else {
8794 if (NumVecElts != 4 && NumVecElts != 8 && NumVecElts != 16)
8795 return SDValue();
8796 }
Chad Rosier6c36eff2015-09-03 18:13:57 +00008797
8798 int NumExpectedSteps = APInt(8, NumVecElts).logBase2();
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008799 SDValue PreOp = OpV;
Chad Rosier6c36eff2015-09-03 18:13:57 +00008800 // Iterate over each step of the across vector reduction.
8801 for (int CurStep = 0; CurStep != NumExpectedSteps; ++CurStep) {
Chad Rosier6c36eff2015-09-03 18:13:57 +00008802 SDValue CurOp = PreOp.getOperand(0);
8803 SDValue Shuffle = PreOp.getOperand(1);
8804 if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE) {
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008805 // Try to swap the 1st and 2nd operand as add and min/max instructions
8806 // are commutative.
Chad Rosier6c36eff2015-09-03 18:13:57 +00008807 CurOp = PreOp.getOperand(1);
8808 Shuffle = PreOp.getOperand(0);
8809 if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE)
8810 return SDValue();
8811 }
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008812
8813 // Check if the input vector is fed by the operator we want to handle,
8814 // except the last step; the very first input vector is not necessarily
8815 // the same operator we are handling.
8816 if (CurOp.getOpcode() != Op && (CurStep != (NumExpectedSteps - 1)))
8817 return SDValue();
8818
Chad Rosier6c36eff2015-09-03 18:13:57 +00008819 // Check if it forms one step of the across vector reduction.
8820 // E.g.,
8821 // %cur = add %1, %0
8822 // %shuffle = vector_shuffle %cur, <2, 3, u, u>
8823 // %pre = add %cur, %shuffle
8824 if (Shuffle.getOperand(0) != CurOp)
8825 return SDValue();
8826
8827 int NumMaskElts = 1 << CurStep;
8828 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Shuffle)->getMask();
8829 // Check mask values in each step.
8830 // We expect the shuffle mask in each step follows a specific pattern
8831 // denoted here by the <M, U> form, where M is a sequence of integers
8832 // starting from NumMaskElts, increasing by 1, and the number integers
8833 // in M should be NumMaskElts. U is a sequence of UNDEFs and the number
8834 // of undef in U should be NumVecElts - NumMaskElts.
8835 // E.g., for <8 x i16>, mask values in each step should be :
8836 // step 0 : <1,u,u,u,u,u,u,u>
8837 // step 1 : <2,3,u,u,u,u,u,u>
8838 // step 2 : <4,5,6,7,u,u,u,u>
8839 for (int i = 0; i < NumVecElts; ++i)
8840 if ((i < NumMaskElts && Mask[i] != (NumMaskElts + i)) ||
8841 (i >= NumMaskElts && !(Mask[i] < 0)))
8842 return SDValue();
8843
8844 PreOp = CurOp;
8845 }
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008846 unsigned Opcode;
Jun Bum Lim0aace132015-10-09 14:11:25 +00008847 bool IsIntrinsic = false;
8848
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008849 switch (Op) {
8850 default:
8851 llvm_unreachable("Unexpected operator for across vector reduction");
8852 case ISD::ADD:
8853 Opcode = AArch64ISD::UADDV;
8854 break;
8855 case ISD::SMAX:
8856 Opcode = AArch64ISD::SMAXV;
8857 break;
8858 case ISD::UMAX:
8859 Opcode = AArch64ISD::UMAXV;
8860 break;
8861 case ISD::SMIN:
8862 Opcode = AArch64ISD::SMINV;
8863 break;
8864 case ISD::UMIN:
8865 Opcode = AArch64ISD::UMINV;
8866 break;
Jun Bum Lim0aace132015-10-09 14:11:25 +00008867 case ISD::FMAXNUM:
8868 Opcode = Intrinsic::aarch64_neon_fmaxnmv;
8869 IsIntrinsic = true;
8870 break;
8871 case ISD::FMINNUM:
8872 Opcode = Intrinsic::aarch64_neon_fminnmv;
8873 IsIntrinsic = true;
8874 break;
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008875 }
Chad Rosier6c36eff2015-09-03 18:13:57 +00008876 SDLoc DL(N);
Jun Bum Lim0aace132015-10-09 14:11:25 +00008877
8878 return IsIntrinsic
8879 ? DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, N->getValueType(0),
8880 DAG.getConstant(Opcode, DL, MVT::i32), PreOp)
8881 : DAG.getNode(
8882 ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0),
8883 DAG.getNode(Opcode, DL, PreOp.getSimpleValueType(), PreOp),
8884 DAG.getConstant(0, DL, MVT::i64));
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008885}
8886
8887/// Target-specific DAG combine for the across vector min/max reductions.
8888/// This function specifically handles the final clean-up step of the vector
8889/// min/max reductions produced by the LoopVectorizer. It is the log2-shuffle
8890/// pattern, which narrows down and finds the final min/max value from all
8891/// elements of the vector.
8892/// For example, for a <16 x i8> vector :
8893/// svn0 = vector_shuffle %0, undef<8,9,10,11,12,13,14,15,u,u,u,u,u,u,u,u>
8894/// %smax0 = smax %arr, svn0
8895/// %svn1 = vector_shuffle %smax0, undef<4,5,6,7,u,u,u,u,u,u,u,u,u,u,u,u>
8896/// %smax1 = smax %smax0, %svn1
8897/// %svn2 = vector_shuffle %smax1, undef<2,3,u,u,u,u,u,u,u,u,u,u,u,u,u,u>
8898/// %smax2 = smax %smax1, svn2
8899/// %svn3 = vector_shuffle %smax2, undef<1,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u>
8900/// %sc = setcc %smax2, %svn3, gt
8901/// %n0 = extract_vector_elt %sc, #0
8902/// %n1 = extract_vector_elt %smax2, #0
8903/// %n2 = extract_vector_elt $smax2, #1
8904/// %result = select %n0, %n1, n2
8905/// becomes :
8906/// %1 = smaxv %0
8907/// %result = extract_vector_elt %1, 0
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008908static SDValue
8909performAcrossLaneMinMaxReductionCombine(SDNode *N, SelectionDAG &DAG,
8910 const AArch64Subtarget *Subtarget) {
8911 if (!Subtarget->hasNEON())
8912 return SDValue();
8913
8914 SDValue N0 = N->getOperand(0);
8915 SDValue IfTrue = N->getOperand(1);
8916 SDValue IfFalse = N->getOperand(2);
8917
8918 // Check if the SELECT merges up the final result of the min/max
8919 // from a vector.
8920 if (N0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
8921 IfTrue.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
8922 IfFalse.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
8923 return SDValue();
8924
8925 // Expect N0 is fed by SETCC.
8926 SDValue SetCC = N0.getOperand(0);
8927 EVT SetCCVT = SetCC.getValueType();
8928 if (SetCC.getOpcode() != ISD::SETCC || !SetCCVT.isVector() ||
8929 SetCCVT.getVectorElementType() != MVT::i1)
8930 return SDValue();
8931
8932 SDValue VectorOp = SetCC.getOperand(0);
8933 unsigned Op = VectorOp->getOpcode();
8934 // Check if the input vector is fed by the operator we want to handle.
Jun Bum Lim0aace132015-10-09 14:11:25 +00008935 if (Op != ISD::SMAX && Op != ISD::UMAX && Op != ISD::SMIN &&
8936 Op != ISD::UMIN && Op != ISD::FMAXNUM && Op != ISD::FMINNUM)
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008937 return SDValue();
8938
8939 EVT VTy = VectorOp.getValueType();
8940 if (!VTy.isVector())
8941 return SDValue();
8942
Jun Bum Lim0aace132015-10-09 14:11:25 +00008943 if (VTy.getSizeInBits() < 64)
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008944 return SDValue();
8945
Jun Bum Lim0aace132015-10-09 14:11:25 +00008946 EVT EltTy = VTy.getVectorElementType();
8947 if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) {
8948 if (EltTy != MVT::f32)
8949 return SDValue();
8950 } else {
8951 if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8)
8952 return SDValue();
8953 }
8954
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008955 // Check if extracting from the same vector.
8956 // For example,
8957 // %sc = setcc %vector, %svn1, gt
8958 // %n0 = extract_vector_elt %sc, #0
8959 // %n1 = extract_vector_elt %vector, #0
8960 // %n2 = extract_vector_elt $vector, #1
8961 if (!(VectorOp == IfTrue->getOperand(0) &&
8962 VectorOp == IfFalse->getOperand(0)))
8963 return SDValue();
8964
8965 // Check if the condition code is matched with the operator type.
8966 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get();
8967 if ((Op == ISD::SMAX && CC != ISD::SETGT && CC != ISD::SETGE) ||
8968 (Op == ISD::UMAX && CC != ISD::SETUGT && CC != ISD::SETUGE) ||
8969 (Op == ISD::SMIN && CC != ISD::SETLT && CC != ISD::SETLE) ||
Jun Bum Lim0aace132015-10-09 14:11:25 +00008970 (Op == ISD::UMIN && CC != ISD::SETULT && CC != ISD::SETULE) ||
8971 (Op == ISD::FMAXNUM && CC != ISD::SETOGT && CC != ISD::SETOGE &&
8972 CC != ISD::SETUGT && CC != ISD::SETUGE && CC != ISD::SETGT &&
8973 CC != ISD::SETGE) ||
8974 (Op == ISD::FMINNUM && CC != ISD::SETOLT && CC != ISD::SETOLE &&
8975 CC != ISD::SETULT && CC != ISD::SETULE && CC != ISD::SETLT &&
8976 CC != ISD::SETLE))
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008977 return SDValue();
8978
8979 // Expect to check only lane 0 from the vector SETCC.
Artyom Skrobov314ee042015-11-25 19:41:11 +00008980 if (!isNullConstant(N0.getOperand(1)))
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008981 return SDValue();
8982
8983 // Expect to extract the true value from lane 0.
Artyom Skrobov314ee042015-11-25 19:41:11 +00008984 if (!isNullConstant(IfTrue.getOperand(1)))
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008985 return SDValue();
8986
8987 // Expect to extract the false value from lane 1.
Artyom Skrobov314ee042015-11-25 19:41:11 +00008988 if (!isOneConstant(IfFalse.getOperand(1)))
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008989 return SDValue();
8990
8991 return tryMatchAcrossLaneShuffleForReduction(N, SetCC, Op, DAG);
8992}
8993
8994/// Target-specific DAG combine for the across vector add reduction.
8995/// This function specifically handles the final clean-up step of the vector
8996/// add reduction produced by the LoopVectorizer. It is the log2-shuffle
8997/// pattern, which adds all elements of a vector together.
8998/// For example, for a <4 x i32> vector :
8999/// %1 = vector_shuffle %0, <2,3,u,u>
9000/// %2 = add %0, %1
9001/// %3 = vector_shuffle %2, <1,u,u,u>
9002/// %4 = add %2, %3
9003/// %result = extract_vector_elt %4, 0
9004/// becomes :
9005/// %0 = uaddv %0
9006/// %result = extract_vector_elt %0, 0
9007static SDValue
9008performAcrossLaneAddReductionCombine(SDNode *N, SelectionDAG &DAG,
9009 const AArch64Subtarget *Subtarget) {
9010 if (!Subtarget->hasNEON())
9011 return SDValue();
9012 SDValue N0 = N->getOperand(0);
9013 SDValue N1 = N->getOperand(1);
9014
9015 // Check if the input vector is fed by the ADD.
9016 if (N0->getOpcode() != ISD::ADD)
9017 return SDValue();
9018
9019 // The vector extract idx must constant zero because we only expect the final
9020 // result of the reduction is placed in lane 0.
Artyom Skrobov314ee042015-11-25 19:41:11 +00009021 if (!isNullConstant(N1))
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009022 return SDValue();
9023
9024 EVT VTy = N0.getValueType();
9025 if (!VTy.isVector())
9026 return SDValue();
9027
9028 EVT EltTy = VTy.getVectorElementType();
9029 if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8)
9030 return SDValue();
9031
Jun Bum Lim0aace132015-10-09 14:11:25 +00009032 if (VTy.getSizeInBits() < 64)
9033 return SDValue();
9034
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009035 return tryMatchAcrossLaneShuffleForReduction(N, N0, ISD::ADD, DAG);
Chad Rosier6c36eff2015-09-03 18:13:57 +00009036}
9037
Tim Northover3b0846e2014-05-24 12:50:23 +00009038/// Target-specific DAG combine function for NEON load/store intrinsics
9039/// to merge base address updates.
9040static SDValue performNEONPostLDSTCombine(SDNode *N,
9041 TargetLowering::DAGCombinerInfo &DCI,
9042 SelectionDAG &DAG) {
9043 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9044 return SDValue();
9045
9046 unsigned AddrOpIdx = N->getNumOperands() - 1;
9047 SDValue Addr = N->getOperand(AddrOpIdx);
9048
9049 // Search for a use of the address operand that is an increment.
9050 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9051 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9052 SDNode *User = *UI;
9053 if (User->getOpcode() != ISD::ADD ||
9054 UI.getUse().getResNo() != Addr.getResNo())
9055 continue;
9056
9057 // Check that the add is independent of the load/store. Otherwise, folding
9058 // it would create a cycle.
9059 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9060 continue;
9061
9062 // Find the new opcode for the updating load/store.
9063 bool IsStore = false;
9064 bool IsLaneOp = false;
9065 bool IsDupOp = false;
9066 unsigned NewOpc = 0;
9067 unsigned NumVecs = 0;
9068 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9069 switch (IntNo) {
9070 default: llvm_unreachable("unexpected intrinsic for Neon base update");
9071 case Intrinsic::aarch64_neon_ld2: NewOpc = AArch64ISD::LD2post;
9072 NumVecs = 2; break;
9073 case Intrinsic::aarch64_neon_ld3: NewOpc = AArch64ISD::LD3post;
9074 NumVecs = 3; break;
9075 case Intrinsic::aarch64_neon_ld4: NewOpc = AArch64ISD::LD4post;
9076 NumVecs = 4; break;
9077 case Intrinsic::aarch64_neon_st2: NewOpc = AArch64ISD::ST2post;
9078 NumVecs = 2; IsStore = true; break;
9079 case Intrinsic::aarch64_neon_st3: NewOpc = AArch64ISD::ST3post;
9080 NumVecs = 3; IsStore = true; break;
9081 case Intrinsic::aarch64_neon_st4: NewOpc = AArch64ISD::ST4post;
9082 NumVecs = 4; IsStore = true; break;
9083 case Intrinsic::aarch64_neon_ld1x2: NewOpc = AArch64ISD::LD1x2post;
9084 NumVecs = 2; break;
9085 case Intrinsic::aarch64_neon_ld1x3: NewOpc = AArch64ISD::LD1x3post;
9086 NumVecs = 3; break;
9087 case Intrinsic::aarch64_neon_ld1x4: NewOpc = AArch64ISD::LD1x4post;
9088 NumVecs = 4; break;
9089 case Intrinsic::aarch64_neon_st1x2: NewOpc = AArch64ISD::ST1x2post;
9090 NumVecs = 2; IsStore = true; break;
9091 case Intrinsic::aarch64_neon_st1x3: NewOpc = AArch64ISD::ST1x3post;
9092 NumVecs = 3; IsStore = true; break;
9093 case Intrinsic::aarch64_neon_st1x4: NewOpc = AArch64ISD::ST1x4post;
9094 NumVecs = 4; IsStore = true; break;
9095 case Intrinsic::aarch64_neon_ld2r: NewOpc = AArch64ISD::LD2DUPpost;
9096 NumVecs = 2; IsDupOp = true; break;
9097 case Intrinsic::aarch64_neon_ld3r: NewOpc = AArch64ISD::LD3DUPpost;
9098 NumVecs = 3; IsDupOp = true; break;
9099 case Intrinsic::aarch64_neon_ld4r: NewOpc = AArch64ISD::LD4DUPpost;
9100 NumVecs = 4; IsDupOp = true; break;
9101 case Intrinsic::aarch64_neon_ld2lane: NewOpc = AArch64ISD::LD2LANEpost;
9102 NumVecs = 2; IsLaneOp = true; break;
9103 case Intrinsic::aarch64_neon_ld3lane: NewOpc = AArch64ISD::LD3LANEpost;
9104 NumVecs = 3; IsLaneOp = true; break;
9105 case Intrinsic::aarch64_neon_ld4lane: NewOpc = AArch64ISD::LD4LANEpost;
9106 NumVecs = 4; IsLaneOp = true; break;
9107 case Intrinsic::aarch64_neon_st2lane: NewOpc = AArch64ISD::ST2LANEpost;
9108 NumVecs = 2; IsStore = true; IsLaneOp = true; break;
9109 case Intrinsic::aarch64_neon_st3lane: NewOpc = AArch64ISD::ST3LANEpost;
9110 NumVecs = 3; IsStore = true; IsLaneOp = true; break;
9111 case Intrinsic::aarch64_neon_st4lane: NewOpc = AArch64ISD::ST4LANEpost;
9112 NumVecs = 4; IsStore = true; IsLaneOp = true; break;
9113 }
9114
9115 EVT VecTy;
9116 if (IsStore)
9117 VecTy = N->getOperand(2).getValueType();
9118 else
9119 VecTy = N->getValueType(0);
9120
9121 // If the increment is a constant, it must match the memory ref size.
9122 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9123 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9124 uint32_t IncVal = CInc->getZExtValue();
9125 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9126 if (IsLaneOp || IsDupOp)
9127 NumBytes /= VecTy.getVectorNumElements();
9128 if (IncVal != NumBytes)
9129 continue;
9130 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
9131 }
9132 SmallVector<SDValue, 8> Ops;
9133 Ops.push_back(N->getOperand(0)); // Incoming chain
9134 // Load lane and store have vector list as input.
9135 if (IsLaneOp || IsStore)
9136 for (unsigned i = 2; i < AddrOpIdx; ++i)
9137 Ops.push_back(N->getOperand(i));
9138 Ops.push_back(Addr); // Base register
9139 Ops.push_back(Inc);
9140
9141 // Return Types.
9142 EVT Tys[6];
9143 unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
9144 unsigned n;
9145 for (n = 0; n < NumResultVecs; ++n)
9146 Tys[n] = VecTy;
9147 Tys[n++] = MVT::i64; // Type of write back register
9148 Tys[n] = MVT::Other; // Type of the chain
Craig Toppere1d12942014-08-27 05:25:25 +00009149 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
Tim Northover3b0846e2014-05-24 12:50:23 +00009150
9151 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9152 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
9153 MemInt->getMemoryVT(),
9154 MemInt->getMemOperand());
9155
9156 // Update the uses.
9157 std::vector<SDValue> NewResults;
9158 for (unsigned i = 0; i < NumResultVecs; ++i) {
9159 NewResults.push_back(SDValue(UpdN.getNode(), i));
9160 }
9161 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
9162 DCI.CombineTo(N, NewResults);
9163 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9164
9165 break;
9166 }
9167 return SDValue();
9168}
9169
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009170// Checks to see if the value is the prescribed width and returns information
9171// about its extension mode.
9172static
9173bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
9174 ExtType = ISD::NON_EXTLOAD;
9175 switch(V.getNode()->getOpcode()) {
9176 default:
9177 return false;
9178 case ISD::LOAD: {
9179 LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
9180 if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
9181 || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
9182 ExtType = LoadNode->getExtensionType();
9183 return true;
9184 }
9185 return false;
9186 }
9187 case ISD::AssertSext: {
9188 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9189 if ((TypeNode->getVT() == MVT::i8 && width == 8)
9190 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9191 ExtType = ISD::SEXTLOAD;
9192 return true;
9193 }
9194 return false;
9195 }
9196 case ISD::AssertZext: {
9197 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9198 if ((TypeNode->getVT() == MVT::i8 && width == 8)
9199 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9200 ExtType = ISD::ZEXTLOAD;
9201 return true;
9202 }
9203 return false;
9204 }
9205 case ISD::Constant:
9206 case ISD::TargetConstant: {
Reid Kleckner39ad7c92014-08-29 22:14:26 +00009207 if (std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
Aaron Ballman8ca53882014-09-02 12:19:02 +00009208 1LL << (width - 1))
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009209 return true;
9210 return false;
9211 }
9212 }
9213
9214 return true;
9215}
9216
9217// This function does a whole lot of voodoo to determine if the tests are
9218// equivalent without and with a mask. Essentially what happens is that given a
9219// DAG resembling:
9220//
9221// +-------------+ +-------------+ +-------------+ +-------------+
9222// | Input | | AddConstant | | CompConstant| | CC |
9223// +-------------+ +-------------+ +-------------+ +-------------+
9224// | | | |
9225// V V | +----------+
9226// +-------------+ +----+ | |
9227// | ADD | |0xff| | |
9228// +-------------+ +----+ | |
9229// | | | |
9230// V V | |
9231// +-------------+ | |
9232// | AND | | |
9233// +-------------+ | |
9234// | | |
9235// +-----+ | |
9236// | | |
9237// V V V
9238// +-------------+
9239// | CMP |
9240// +-------------+
9241//
9242// The AND node may be safely removed for some combinations of inputs. In
9243// particular we need to take into account the extension type of the Input,
9244// the exact values of AddConstant, CompConstant, and CC, along with the nominal
9245// width of the input (this can work for any width inputs, the above graph is
9246// specific to 8 bits.
9247//
9248// The specific equations were worked out by generating output tables for each
9249// AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
9250// problem was simplified by working with 4 bit inputs, which means we only
9251// needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
9252// extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
9253// patterns present in both extensions (0,7). For every distinct set of
9254// AddConstant and CompConstants bit patterns we can consider the masked and
9255// unmasked versions to be equivalent if the result of this function is true for
9256// all 16 distinct bit patterns of for the current extension type of Input (w0).
9257//
9258// sub w8, w0, w1
9259// and w10, w8, #0x0f
9260// cmp w8, w2
9261// cset w9, AArch64CC
9262// cmp w10, w2
9263// cset w11, AArch64CC
9264// cmp w9, w11
9265// cset w0, eq
9266// ret
9267//
9268// Since the above function shows when the outputs are equivalent it defines
9269// when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
9270// would be expensive to run during compiles. The equations below were written
9271// in a test harness that confirmed they gave equivalent outputs to the above
9272// for all inputs function, so they can be used determine if the removal is
9273// legal instead.
9274//
9275// isEquivalentMaskless() is the code for testing if the AND can be removed
9276// factored out of the DAG recognition as the DAG can take several forms.
9277
9278static
9279bool isEquivalentMaskless(unsigned CC, unsigned width,
9280 ISD::LoadExtType ExtType, signed AddConstant,
9281 signed CompConstant) {
9282 // By being careful about our equations and only writing the in term
9283 // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
9284 // make them generally applicable to all bit widths.
9285 signed MaxUInt = (1 << width);
9286
9287 // For the purposes of these comparisons sign extending the type is
9288 // equivalent to zero extending the add and displacing it by half the integer
9289 // width. Provided we are careful and make sure our equations are valid over
9290 // the whole range we can just adjust the input and avoid writing equations
9291 // for sign extended inputs.
9292 if (ExtType == ISD::SEXTLOAD)
9293 AddConstant -= (1 << (width-1));
9294
9295 switch(CC) {
9296 case AArch64CC::LE:
9297 case AArch64CC::GT: {
9298 if ((AddConstant == 0) ||
9299 (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
9300 (AddConstant >= 0 && CompConstant < 0) ||
9301 (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
9302 return true;
9303 } break;
9304 case AArch64CC::LT:
9305 case AArch64CC::GE: {
9306 if ((AddConstant == 0) ||
9307 (AddConstant >= 0 && CompConstant <= 0) ||
9308 (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
9309 return true;
9310 } break;
9311 case AArch64CC::HI:
9312 case AArch64CC::LS: {
9313 if ((AddConstant >= 0 && CompConstant < 0) ||
9314 (AddConstant <= 0 && CompConstant >= -1 &&
9315 CompConstant < AddConstant + MaxUInt))
9316 return true;
9317 } break;
9318 case AArch64CC::PL:
9319 case AArch64CC::MI: {
9320 if ((AddConstant == 0) ||
9321 (AddConstant > 0 && CompConstant <= 0) ||
9322 (AddConstant < 0 && CompConstant <= AddConstant))
9323 return true;
9324 } break;
9325 case AArch64CC::LO:
9326 case AArch64CC::HS: {
9327 if ((AddConstant >= 0 && CompConstant <= 0) ||
9328 (AddConstant <= 0 && CompConstant >= 0 &&
9329 CompConstant <= AddConstant + MaxUInt))
9330 return true;
9331 } break;
9332 case AArch64CC::EQ:
9333 case AArch64CC::NE: {
9334 if ((AddConstant > 0 && CompConstant < 0) ||
9335 (AddConstant < 0 && CompConstant >= 0 &&
9336 CompConstant < AddConstant + MaxUInt) ||
9337 (AddConstant >= 0 && CompConstant >= 0 &&
9338 CompConstant >= AddConstant) ||
9339 (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
9340
9341 return true;
9342 } break;
9343 case AArch64CC::VS:
9344 case AArch64CC::VC:
9345 case AArch64CC::AL:
9346 case AArch64CC::NV:
9347 return true;
9348 case AArch64CC::Invalid:
9349 break;
9350 }
9351
9352 return false;
9353}
9354
9355static
9356SDValue performCONDCombine(SDNode *N,
9357 TargetLowering::DAGCombinerInfo &DCI,
9358 SelectionDAG &DAG, unsigned CCIndex,
9359 unsigned CmpIndex) {
9360 unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
9361 SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
9362 unsigned CondOpcode = SubsNode->getOpcode();
9363
9364 if (CondOpcode != AArch64ISD::SUBS)
9365 return SDValue();
9366
9367 // There is a SUBS feeding this condition. Is it fed by a mask we can
9368 // use?
9369
9370 SDNode *AndNode = SubsNode->getOperand(0).getNode();
9371 unsigned MaskBits = 0;
9372
9373 if (AndNode->getOpcode() != ISD::AND)
9374 return SDValue();
9375
9376 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
9377 uint32_t CNV = CN->getZExtValue();
9378 if (CNV == 255)
9379 MaskBits = 8;
9380 else if (CNV == 65535)
9381 MaskBits = 16;
9382 }
9383
9384 if (!MaskBits)
9385 return SDValue();
9386
9387 SDValue AddValue = AndNode->getOperand(0);
9388
9389 if (AddValue.getOpcode() != ISD::ADD)
9390 return SDValue();
9391
9392 // The basic dag structure is correct, grab the inputs and validate them.
9393
9394 SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
9395 SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
9396 SDValue SubsInputValue = SubsNode->getOperand(1);
9397
9398 // The mask is present and the provenance of all the values is a smaller type,
9399 // lets see if the mask is superfluous.
9400
9401 if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
9402 !isa<ConstantSDNode>(SubsInputValue.getNode()))
9403 return SDValue();
9404
9405 ISD::LoadExtType ExtType;
9406
9407 if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
9408 !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
9409 !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
9410 return SDValue();
9411
9412 if(!isEquivalentMaskless(CC, MaskBits, ExtType,
9413 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
9414 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
9415 return SDValue();
9416
9417 // The AND is not necessary, remove it.
9418
9419 SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
9420 SubsNode->getValueType(1));
9421 SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
9422
9423 SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
9424 DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
9425
9426 return SDValue(N, 0);
9427}
9428
Tim Northover3b0846e2014-05-24 12:50:23 +00009429// Optimize compare with zero and branch.
9430static SDValue performBRCONDCombine(SDNode *N,
9431 TargetLowering::DAGCombinerInfo &DCI,
9432 SelectionDAG &DAG) {
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009433 SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3);
9434 if (NV.getNode())
9435 N = NV.getNode();
Tim Northover3b0846e2014-05-24 12:50:23 +00009436 SDValue Chain = N->getOperand(0);
9437 SDValue Dest = N->getOperand(1);
9438 SDValue CCVal = N->getOperand(2);
9439 SDValue Cmp = N->getOperand(3);
9440
9441 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
9442 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
9443 if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
9444 return SDValue();
9445
9446 unsigned CmpOpc = Cmp.getOpcode();
9447 if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
9448 return SDValue();
9449
9450 // Only attempt folding if there is only one use of the flag and no use of the
9451 // value.
9452 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
9453 return SDValue();
9454
9455 SDValue LHS = Cmp.getOperand(0);
9456 SDValue RHS = Cmp.getOperand(1);
9457
9458 assert(LHS.getValueType() == RHS.getValueType() &&
9459 "Expected the value type to be the same for both operands!");
9460 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
9461 return SDValue();
9462
Artyom Skrobov314ee042015-11-25 19:41:11 +00009463 if (isNullConstant(LHS))
Tim Northover3b0846e2014-05-24 12:50:23 +00009464 std::swap(LHS, RHS);
9465
Artyom Skrobov314ee042015-11-25 19:41:11 +00009466 if (!isNullConstant(RHS))
Tim Northover3b0846e2014-05-24 12:50:23 +00009467 return SDValue();
9468
9469 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
9470 LHS.getOpcode() == ISD::SRL)
9471 return SDValue();
9472
9473 // Fold the compare into the branch instruction.
9474 SDValue BR;
9475 if (CC == AArch64CC::EQ)
9476 BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9477 else
9478 BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9479
9480 // Do not add new nodes to DAG combiner worklist.
9481 DCI.CombineTo(N, BR, false);
9482
9483 return SDValue();
9484}
9485
9486// vselect (v1i1 setcc) ->
9487// vselect (v1iXX setcc) (XX is the size of the compared operand type)
9488// FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
9489// condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
9490// such VSELECT.
9491static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
9492 SDValue N0 = N->getOperand(0);
9493 EVT CCVT = N0.getValueType();
9494
9495 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
9496 CCVT.getVectorElementType() != MVT::i1)
9497 return SDValue();
9498
9499 EVT ResVT = N->getValueType(0);
9500 EVT CmpVT = N0.getOperand(0).getValueType();
9501 // Only combine when the result type is of the same size as the compared
9502 // operands.
9503 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
9504 return SDValue();
9505
9506 SDValue IfTrue = N->getOperand(1);
9507 SDValue IfFalse = N->getOperand(2);
9508 SDValue SetCC =
9509 DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
9510 N0.getOperand(0), N0.getOperand(1),
9511 cast<CondCodeSDNode>(N0.getOperand(2))->get());
9512 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
9513 IfTrue, IfFalse);
9514}
9515
9516/// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
9517/// the compare-mask instructions rather than going via NZCV, even if LHS and
9518/// RHS are really scalar. This replaces any scalar setcc in the above pattern
9519/// with a vector one followed by a DUP shuffle on the result.
Ahmed Bougachac004c602015-04-27 21:43:12 +00009520static SDValue performSelectCombine(SDNode *N,
9521 TargetLowering::DAGCombinerInfo &DCI) {
9522 SelectionDAG &DAG = DCI.DAG;
Tim Northover3b0846e2014-05-24 12:50:23 +00009523 SDValue N0 = N->getOperand(0);
9524 EVT ResVT = N->getValueType(0);
Tim Northover3c0915e2014-08-29 15:34:58 +00009525
Ahmed Bougachac004c602015-04-27 21:43:12 +00009526 if (N0.getOpcode() != ISD::SETCC)
Tim Northover3c0915e2014-08-29 15:34:58 +00009527 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00009528
Ahmed Bougachac004c602015-04-27 21:43:12 +00009529 // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
9530 // scalar SetCCResultType. We also don't expect vectors, because we assume
9531 // that selects fed by vector SETCCs are canonicalized to VSELECT.
9532 assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
9533 "Scalar-SETCC feeding SELECT has unexpected result type!");
9534
Tim Northoverc1c05ae2014-08-29 13:05:18 +00009535 // If NumMaskElts == 0, the comparison is larger than select result. The
9536 // largest real NEON comparison is 64-bits per lane, which means the result is
9537 // at most 32-bits and an illegal vector. Just bail out for now.
Tim Northover3c0915e2014-08-29 15:34:58 +00009538 EVT SrcVT = N0.getOperand(0).getValueType();
Ahmed Bougachad0ce0582014-12-01 20:59:00 +00009539
9540 // Don't try to do this optimization when the setcc itself has i1 operands.
9541 // There are no legal vectors of i1, so this would be pointless.
9542 if (SrcVT == MVT::i1)
9543 return SDValue();
9544
Tim Northover3c0915e2014-08-29 15:34:58 +00009545 int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
Tim Northoverc1c05ae2014-08-29 13:05:18 +00009546 if (!ResVT.isVector() || NumMaskElts == 0)
Tim Northover3b0846e2014-05-24 12:50:23 +00009547 return SDValue();
9548
Tim Northoverc1c05ae2014-08-29 13:05:18 +00009549 SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
Tim Northover3b0846e2014-05-24 12:50:23 +00009550 EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
9551
Ahmed Bougacha89bba612015-04-27 21:01:20 +00009552 // Also bail out if the vector CCVT isn't the same size as ResVT.
9553 // This can happen if the SETCC operand size doesn't divide the ResVT size
9554 // (e.g., f64 vs v3f32).
9555 if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
9556 return SDValue();
9557
Ahmed Bougachac004c602015-04-27 21:43:12 +00009558 // Make sure we didn't create illegal types, if we're not supposed to.
9559 assert(DCI.isBeforeLegalize() ||
9560 DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
9561
Tim Northover3b0846e2014-05-24 12:50:23 +00009562 // First perform a vector comparison, where lane 0 is the one we're interested
9563 // in.
Tim Northoverc1c05ae2014-08-29 13:05:18 +00009564 SDLoc DL(N0);
Tim Northover3b0846e2014-05-24 12:50:23 +00009565 SDValue LHS =
9566 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
9567 SDValue RHS =
9568 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
9569 SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
9570
9571 // Now duplicate the comparison mask we want across all other lanes.
9572 SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
9573 SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask.data());
Tim Northoverc1c05ae2014-08-29 13:05:18 +00009574 Mask = DAG.getNode(ISD::BITCAST, DL,
9575 ResVT.changeVectorElementTypeToInteger(), Mask);
Tim Northover3b0846e2014-05-24 12:50:23 +00009576
9577 return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
9578}
9579
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009580/// Get rid of unnecessary NVCASTs (that don't change the type).
9581static SDValue performNVCASTCombine(SDNode *N) {
9582 if (N->getValueType(0) == N->getOperand(0).getValueType())
9583 return N->getOperand(0);
9584
9585 return SDValue();
9586}
9587
Tim Northover3b0846e2014-05-24 12:50:23 +00009588SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
9589 DAGCombinerInfo &DCI) const {
9590 SelectionDAG &DAG = DCI.DAG;
9591 switch (N->getOpcode()) {
9592 default:
9593 break;
9594 case ISD::ADD:
9595 case ISD::SUB:
9596 return performAddSubLongCombine(N, DCI, DAG);
9597 case ISD::XOR:
9598 return performXorCombine(N, DAG, DCI, Subtarget);
9599 case ISD::MUL:
9600 return performMulCombine(N, DAG, DCI, Subtarget);
9601 case ISD::SINT_TO_FP:
9602 case ISD::UINT_TO_FP:
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00009603 return performIntToFpCombine(N, DAG, Subtarget);
Chad Rosierfa30c9b2015-10-07 17:39:18 +00009604 case ISD::FP_TO_SINT:
9605 case ISD::FP_TO_UINT:
9606 return performFpToIntCombine(N, DAG, Subtarget);
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00009607 case ISD::FDIV:
9608 return performFDivCombine(N, DAG, Subtarget);
Tim Northover3b0846e2014-05-24 12:50:23 +00009609 case ISD::OR:
9610 return performORCombine(N, DCI, Subtarget);
9611 case ISD::INTRINSIC_WO_CHAIN:
9612 return performIntrinsicCombine(N, DCI, Subtarget);
9613 case ISD::ANY_EXTEND:
9614 case ISD::ZERO_EXTEND:
9615 case ISD::SIGN_EXTEND:
9616 return performExtendCombine(N, DCI, DAG);
9617 case ISD::BITCAST:
9618 return performBitcastCombine(N, DCI, DAG);
9619 case ISD::CONCAT_VECTORS:
9620 return performConcatVectorsCombine(N, DCI, DAG);
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009621 case ISD::SELECT: {
9622 SDValue RV = performSelectCombine(N, DCI);
9623 if (!RV.getNode())
9624 RV = performAcrossLaneMinMaxReductionCombine(N, DAG, Subtarget);
9625 return RV;
9626 }
Tim Northover3b0846e2014-05-24 12:50:23 +00009627 case ISD::VSELECT:
9628 return performVSelectCombine(N, DCI.DAG);
Tim Northover339c83e2015-11-10 00:44:23 +00009629 case ISD::LOAD:
9630 if (performTBISimplification(N->getOperand(1), DCI, DAG))
9631 return SDValue(N, 0);
9632 break;
Tim Northover3b0846e2014-05-24 12:50:23 +00009633 case ISD::STORE:
9634 return performSTORECombine(N, DCI, DAG, Subtarget);
9635 case AArch64ISD::BRCOND:
9636 return performBRCONDCombine(N, DCI, DAG);
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009637 case AArch64ISD::CSEL:
9638 return performCONDCombine(N, DCI, DAG, 2, 3);
Tim Northover3b0846e2014-05-24 12:50:23 +00009639 case AArch64ISD::DUP:
9640 return performPostLD1Combine(N, DCI, false);
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009641 case AArch64ISD::NVCAST:
9642 return performNVCASTCombine(N);
Tim Northover3b0846e2014-05-24 12:50:23 +00009643 case ISD::INSERT_VECTOR_ELT:
9644 return performPostLD1Combine(N, DCI, true);
Chad Rosier6c36eff2015-09-03 18:13:57 +00009645 case ISD::EXTRACT_VECTOR_ELT:
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009646 return performAcrossLaneAddReductionCombine(N, DAG, Subtarget);
Tim Northover3b0846e2014-05-24 12:50:23 +00009647 case ISD::INTRINSIC_VOID:
9648 case ISD::INTRINSIC_W_CHAIN:
9649 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9650 case Intrinsic::aarch64_neon_ld2:
9651 case Intrinsic::aarch64_neon_ld3:
9652 case Intrinsic::aarch64_neon_ld4:
9653 case Intrinsic::aarch64_neon_ld1x2:
9654 case Intrinsic::aarch64_neon_ld1x3:
9655 case Intrinsic::aarch64_neon_ld1x4:
9656 case Intrinsic::aarch64_neon_ld2lane:
9657 case Intrinsic::aarch64_neon_ld3lane:
9658 case Intrinsic::aarch64_neon_ld4lane:
9659 case Intrinsic::aarch64_neon_ld2r:
9660 case Intrinsic::aarch64_neon_ld3r:
9661 case Intrinsic::aarch64_neon_ld4r:
9662 case Intrinsic::aarch64_neon_st2:
9663 case Intrinsic::aarch64_neon_st3:
9664 case Intrinsic::aarch64_neon_st4:
9665 case Intrinsic::aarch64_neon_st1x2:
9666 case Intrinsic::aarch64_neon_st1x3:
9667 case Intrinsic::aarch64_neon_st1x4:
9668 case Intrinsic::aarch64_neon_st2lane:
9669 case Intrinsic::aarch64_neon_st3lane:
9670 case Intrinsic::aarch64_neon_st4lane:
9671 return performNEONPostLDSTCombine(N, DCI, DAG);
9672 default:
9673 break;
9674 }
9675 }
9676 return SDValue();
9677}
9678
9679// Check if the return value is used as only a return value, as otherwise
9680// we can't perform a tail-call. In particular, we need to check for
9681// target ISD nodes that are returns and any other "odd" constructs
9682// that the generic analysis code won't necessarily catch.
9683bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
9684 SDValue &Chain) const {
9685 if (N->getNumValues() != 1)
9686 return false;
9687 if (!N->hasNUsesOfValue(1, 0))
9688 return false;
9689
9690 SDValue TCChain = Chain;
9691 SDNode *Copy = *N->use_begin();
9692 if (Copy->getOpcode() == ISD::CopyToReg) {
9693 // If the copy has a glue operand, we conservatively assume it isn't safe to
9694 // perform a tail call.
9695 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
9696 MVT::Glue)
9697 return false;
9698 TCChain = Copy->getOperand(0);
9699 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
9700 return false;
9701
9702 bool HasRet = false;
9703 for (SDNode *Node : Copy->uses()) {
9704 if (Node->getOpcode() != AArch64ISD::RET_FLAG)
9705 return false;
9706 HasRet = true;
9707 }
9708
9709 if (!HasRet)
9710 return false;
9711
9712 Chain = TCChain;
9713 return true;
9714}
9715
9716// Return whether the an instruction can potentially be optimized to a tail
9717// call. This will cause the optimizers to attempt to move, or duplicate,
9718// return instructions to help enable tail call optimizations for this
9719// instruction.
9720bool AArch64TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
9721 if (!CI->isTailCall())
9722 return false;
9723
9724 return true;
9725}
9726
9727bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
9728 SDValue &Offset,
9729 ISD::MemIndexedMode &AM,
9730 bool &IsInc,
9731 SelectionDAG &DAG) const {
9732 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
9733 return false;
9734
9735 Base = Op->getOperand(0);
9736 // All of the indexed addressing mode instructions take a signed
9737 // 9 bit immediate offset.
9738 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
9739 int64_t RHSC = (int64_t)RHS->getZExtValue();
9740 if (RHSC >= 256 || RHSC <= -256)
9741 return false;
9742 IsInc = (Op->getOpcode() == ISD::ADD);
9743 Offset = Op->getOperand(1);
9744 return true;
9745 }
9746 return false;
9747}
9748
9749bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
9750 SDValue &Offset,
9751 ISD::MemIndexedMode &AM,
9752 SelectionDAG &DAG) const {
9753 EVT VT;
9754 SDValue Ptr;
9755 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9756 VT = LD->getMemoryVT();
9757 Ptr = LD->getBasePtr();
9758 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9759 VT = ST->getMemoryVT();
9760 Ptr = ST->getBasePtr();
9761 } else
9762 return false;
9763
9764 bool IsInc;
9765 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
9766 return false;
9767 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
9768 return true;
9769}
9770
9771bool AArch64TargetLowering::getPostIndexedAddressParts(
9772 SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
9773 ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
9774 EVT VT;
9775 SDValue Ptr;
9776 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9777 VT = LD->getMemoryVT();
9778 Ptr = LD->getBasePtr();
9779 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9780 VT = ST->getMemoryVT();
9781 Ptr = ST->getBasePtr();
9782 } else
9783 return false;
9784
9785 bool IsInc;
9786 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
9787 return false;
9788 // Post-indexing updates the base, so it's not a valid transform
9789 // if that's not the same as the load's pointer.
9790 if (Ptr != Base)
9791 return false;
9792 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
9793 return true;
9794}
9795
Tim Northoverf8bfe212014-07-18 13:07:05 +00009796static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
9797 SelectionDAG &DAG) {
Tim Northoverf8bfe212014-07-18 13:07:05 +00009798 SDLoc DL(N);
9799 SDValue Op = N->getOperand(0);
Ahmed Bougacha87946322014-12-01 20:52:32 +00009800
9801 if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
9802 return;
9803
Tim Northoverf8bfe212014-07-18 13:07:05 +00009804 Op = SDValue(
9805 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
9806 DAG.getUNDEF(MVT::i32), Op,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009807 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
Tim Northoverf8bfe212014-07-18 13:07:05 +00009808 0);
9809 Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
9810 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
9811}
9812
Charlie Turner434d4592015-10-16 15:38:25 +00009813static void ReplaceReductionResults(SDNode *N,
9814 SmallVectorImpl<SDValue> &Results,
9815 SelectionDAG &DAG, unsigned InterOp,
9816 unsigned AcrossOp) {
9817 EVT LoVT, HiVT;
9818 SDValue Lo, Hi;
9819 SDLoc dl(N);
9820 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
9821 std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
9822 SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
9823 SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
9824 Results.push_back(SplitVal);
9825}
9826
Tim Northover3b0846e2014-05-24 12:50:23 +00009827void AArch64TargetLowering::ReplaceNodeResults(
9828 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
9829 switch (N->getOpcode()) {
9830 default:
9831 llvm_unreachable("Don't know how to custom expand this");
Tim Northoverf8bfe212014-07-18 13:07:05 +00009832 case ISD::BITCAST:
9833 ReplaceBITCASTResults(N, Results, DAG);
9834 return;
Charlie Turner434d4592015-10-16 15:38:25 +00009835 case AArch64ISD::SADDV:
9836 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
9837 return;
9838 case AArch64ISD::UADDV:
9839 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
9840 return;
9841 case AArch64ISD::SMINV:
9842 ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
9843 return;
9844 case AArch64ISD::UMINV:
9845 ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
9846 return;
9847 case AArch64ISD::SMAXV:
9848 ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
9849 return;
9850 case AArch64ISD::UMAXV:
9851 ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
9852 return;
Tim Northover3b0846e2014-05-24 12:50:23 +00009853 case ISD::FP_TO_UINT:
9854 case ISD::FP_TO_SINT:
9855 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
9856 // Let normal code take care of it by not adding anything to Results.
9857 return;
9858 }
9859}
9860
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +00009861bool AArch64TargetLowering::useLoadStackGuardNode() const {
9862 return true;
9863}
9864
Sanjay Patel1dd15592015-07-28 23:05:48 +00009865unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
Hao Liu44e5d7a2014-11-21 06:39:58 +00009866 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
9867 // reciprocal if there are three or more FDIVs.
Sanjay Patel1dd15592015-07-28 23:05:48 +00009868 return 3;
Hao Liu44e5d7a2014-11-21 06:39:58 +00009869}
9870
Chandler Carruth9d010ff2014-07-03 00:23:43 +00009871TargetLoweringBase::LegalizeTypeAction
9872AArch64TargetLowering::getPreferredVectorAction(EVT VT) const {
9873 MVT SVT = VT.getSimpleVT();
9874 // During type legalization, we prefer to widen v1i8, v1i16, v1i32 to v8i8,
9875 // v4i16, v2i32 instead of to promote.
9876 if (SVT == MVT::v1i8 || SVT == MVT::v1i16 || SVT == MVT::v1i32
9877 || SVT == MVT::v1f32)
9878 return TypeWidenVector;
9879
9880 return TargetLoweringBase::getPreferredVectorAction(VT);
9881}
9882
Robin Morisseted3d48f2014-09-03 21:29:59 +00009883// Loads and stores less than 128-bits are already atomic; ones above that
9884// are doomed anyway, so defer to the default libcall and blame the OS when
9885// things go wrong.
9886bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
9887 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
9888 return Size == 128;
9889}
9890
9891// Loads and stores less than 128-bits are already atomic; ones above that
9892// are doomed anyway, so defer to the default libcall and blame the OS when
9893// things go wrong.
Ahmed Bougacha52468672015-09-11 17:08:28 +00009894TargetLowering::AtomicExpansionKind
9895AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
Robin Morisseted3d48f2014-09-03 21:29:59 +00009896 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
Ahmed Bougacha52468672015-09-11 17:08:28 +00009897 return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
Robin Morisseted3d48f2014-09-03 21:29:59 +00009898}
9899
9900// For the real atomic operations, we have ldxr/stxr up to 128 bits,
Ahmed Bougacha52468672015-09-11 17:08:28 +00009901TargetLowering::AtomicExpansionKind
JF Bastienf14889e2015-03-04 15:47:57 +00009902AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
Robin Morisseted3d48f2014-09-03 21:29:59 +00009903 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
Ahmed Bougacha9d677132015-09-11 17:08:17 +00009904 return Size <= 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
Robin Morisseted3d48f2014-09-03 21:29:59 +00009905}
9906
Ahmed Bougacha52468672015-09-11 17:08:28 +00009907bool AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
9908 AtomicCmpXchgInst *AI) const {
Robin Morisset25c8e312014-09-17 00:06:58 +00009909 return true;
9910}
9911
Tim Northover3b0846e2014-05-24 12:50:23 +00009912Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
9913 AtomicOrdering Ord) const {
9914 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
9915 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
Robin Morissetb155f522014-08-18 16:48:58 +00009916 bool IsAcquire = isAtLeastAcquire(Ord);
Tim Northover3b0846e2014-05-24 12:50:23 +00009917
9918 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
9919 // intrinsic must return {i64, i64} and we have to recombine them into a
9920 // single i128 here.
9921 if (ValTy->getPrimitiveSizeInBits() == 128) {
9922 Intrinsic::ID Int =
9923 IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
9924 Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int);
9925
9926 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
9927 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
9928
9929 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
9930 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
9931 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
9932 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
9933 return Builder.CreateOr(
9934 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
9935 }
9936
9937 Type *Tys[] = { Addr->getType() };
9938 Intrinsic::ID Int =
9939 IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
9940 Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int, Tys);
9941
9942 return Builder.CreateTruncOrBitCast(
9943 Builder.CreateCall(Ldxr, Addr),
9944 cast<PointerType>(Addr->getType())->getElementType());
9945}
9946
Ahmed Bougacha07a844d2015-09-22 17:21:44 +00009947void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
9948 IRBuilder<> &Builder) const {
9949 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
9950 Builder.CreateCall(
9951 llvm::Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
9952}
9953
Tim Northover3b0846e2014-05-24 12:50:23 +00009954Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
9955 Value *Val, Value *Addr,
9956 AtomicOrdering Ord) const {
9957 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
Robin Morissetb155f522014-08-18 16:48:58 +00009958 bool IsRelease = isAtLeastRelease(Ord);
Tim Northover3b0846e2014-05-24 12:50:23 +00009959
9960 // Since the intrinsics must have legal type, the i128 intrinsics take two
9961 // parameters: "i64, i64". We must marshal Val into the appropriate form
9962 // before the call.
9963 if (Val->getType()->getPrimitiveSizeInBits() == 128) {
9964 Intrinsic::ID Int =
9965 IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
9966 Function *Stxr = Intrinsic::getDeclaration(M, Int);
9967 Type *Int64Ty = Type::getInt64Ty(M->getContext());
9968
9969 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
9970 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
9971 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
David Blaikieff6409d2015-05-18 22:13:54 +00009972 return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
Tim Northover3b0846e2014-05-24 12:50:23 +00009973 }
9974
9975 Intrinsic::ID Int =
9976 IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
9977 Type *Tys[] = { Addr->getType() };
9978 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
9979
David Blaikieff6409d2015-05-18 22:13:54 +00009980 return Builder.CreateCall(Stxr,
9981 {Builder.CreateZExtOrBitCast(
9982 Val, Stxr->getFunctionType()->getParamType(0)),
9983 Addr});
Tim Northover3b0846e2014-05-24 12:50:23 +00009984}
Tim Northover3c55cca2014-11-27 21:02:42 +00009985
9986bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
9987 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
9988 return Ty->isArrayTy();
9989}
Matthias Braunaf7d7702015-07-16 20:02:37 +00009990
9991bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
9992 EVT) const {
9993 return false;
9994}
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +00009995
9996Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
9997 if (!Subtarget->isTargetAndroid())
9998 return TargetLowering::getSafeStackPointerLocation(IRB);
9999
10000 // Android provides a fixed TLS slot for the SafeStack pointer. See the
10001 // definition of TLS_SLOT_SAFESTACK in
10002 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
10003 const unsigned TlsOffset = 0x48;
10004 Module *M = IRB.GetInsertBlock()->getParent()->getParent();
10005 Function *ThreadPointerFunc =
10006 Intrinsic::getDeclaration(M, Intrinsic::aarch64_thread_pointer);
10007 return IRB.CreatePointerCast(
10008 IRB.CreateConstGEP1_32(IRB.CreateCall(ThreadPointerFunc), TlsOffset),
10009 Type::getInt8PtrTy(IRB.getContext())->getPointerTo(0));
10010}