blob: 5bea916ad2ab44454fcb135d29d59e3c302a887a [file] [log] [blame]
Tim Northover3b0846e2014-05-24 12:50:23 +00001//===-- AArch64ISelLowering.cpp - AArch64 DAG Lowering Implementation ----===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the AArch64TargetLowering class.
11//
12//===----------------------------------------------------------------------===//
13
14#include "AArch64ISelLowering.h"
Tim Northover3c55cca2014-11-27 21:02:42 +000015#include "AArch64CallingConvention.h"
Benjamin Kramer1f8930e2014-07-25 11:42:14 +000016#include "AArch64MachineFunctionInfo.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000017#include "AArch64PerfectShuffle.h"
18#include "AArch64Subtarget.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000019#include "AArch64TargetMachine.h"
20#include "AArch64TargetObjectFile.h"
21#include "MCTargetDesc/AArch64AddressingModes.h"
22#include "llvm/ADT/Statistic.h"
23#include "llvm/CodeGen/CallingConvLower.h"
24#include "llvm/CodeGen/MachineFrameInfo.h"
25#include "llvm/CodeGen/MachineInstrBuilder.h"
26#include "llvm/CodeGen/MachineRegisterInfo.h"
27#include "llvm/IR/Function.h"
David Blaikie457343d2015-05-21 21:12:43 +000028#include "llvm/IR/GetElementPtrTypeIterator.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000029#include "llvm/IR/Intrinsics.h"
30#include "llvm/IR/Type.h"
31#include "llvm/Support/CommandLine.h"
32#include "llvm/Support/Debug.h"
33#include "llvm/Support/ErrorHandling.h"
34#include "llvm/Support/raw_ostream.h"
35#include "llvm/Target/TargetOptions.h"
36using namespace llvm;
37
38#define DEBUG_TYPE "aarch64-lower"
39
40STATISTIC(NumTailCalls, "Number of tail calls");
41STATISTIC(NumShiftInserts, "Number of vector shift inserts");
42
Tim Northover3b0846e2014-05-24 12:50:23 +000043static cl::opt<bool>
44EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden,
Kristof Beylsaea84612015-03-04 09:12:08 +000045 cl::desc("Allow AArch64 SLI/SRI formation"),
46 cl::init(false));
47
48// FIXME: The necessary dtprel relocations don't seem to be supported
49// well in the GNU bfd and gold linkers at the moment. Therefore, by
50// default, for now, fall back to GeneralDynamic code generation.
51cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration(
52 "aarch64-elf-ldtls-generation", cl::Hidden,
53 cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
54 cl::init(false));
Tim Northover3b0846e2014-05-24 12:50:23 +000055
Matthias Braunaf7d7702015-07-16 20:02:37 +000056/// Value type used for condition codes.
57static const MVT MVT_CC = MVT::i32;
58
Eric Christopher905f12d2015-01-29 00:19:42 +000059AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
60 const AArch64Subtarget &STI)
61 : TargetLowering(TM), Subtarget(&STI) {
Tim Northover3b0846e2014-05-24 12:50:23 +000062
63 // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
64 // we have to make something up. Arbitrarily, choose ZeroOrOne.
65 setBooleanContents(ZeroOrOneBooleanContent);
66 // When comparing vectors the result sets the different elements in the
67 // vector to all-one or all-zero.
68 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
69
70 // Set up the register classes.
71 addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
72 addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
73
74 if (Subtarget->hasFPARMv8()) {
75 addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
76 addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
77 addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
78 addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
79 }
80
81 if (Subtarget->hasNEON()) {
82 addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
83 addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
84 // Someone set us up the NEON.
85 addDRTypeForNEON(MVT::v2f32);
86 addDRTypeForNEON(MVT::v8i8);
87 addDRTypeForNEON(MVT::v4i16);
88 addDRTypeForNEON(MVT::v2i32);
89 addDRTypeForNEON(MVT::v1i64);
90 addDRTypeForNEON(MVT::v1f64);
Oliver Stannard89d15422014-08-27 16:16:04 +000091 addDRTypeForNEON(MVT::v4f16);
Tim Northover3b0846e2014-05-24 12:50:23 +000092
93 addQRTypeForNEON(MVT::v4f32);
94 addQRTypeForNEON(MVT::v2f64);
95 addQRTypeForNEON(MVT::v16i8);
96 addQRTypeForNEON(MVT::v8i16);
97 addQRTypeForNEON(MVT::v4i32);
98 addQRTypeForNEON(MVT::v2i64);
Oliver Stannard89d15422014-08-27 16:16:04 +000099 addQRTypeForNEON(MVT::v8f16);
Tim Northover3b0846e2014-05-24 12:50:23 +0000100 }
101
102 // Compute derived properties from the register classes
Eric Christopher23a3a7c2015-02-26 00:00:24 +0000103 computeRegisterProperties(Subtarget->getRegisterInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +0000104
105 // Provide all sorts of operation actions
106 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
107 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
108 setOperationAction(ISD::SETCC, MVT::i32, Custom);
109 setOperationAction(ISD::SETCC, MVT::i64, Custom);
110 setOperationAction(ISD::SETCC, MVT::f32, Custom);
111 setOperationAction(ISD::SETCC, MVT::f64, Custom);
112 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
113 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
114 setOperationAction(ISD::BR_CC, MVT::i64, Custom);
115 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
116 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
117 setOperationAction(ISD::SELECT, MVT::i32, Custom);
118 setOperationAction(ISD::SELECT, MVT::i64, Custom);
119 setOperationAction(ISD::SELECT, MVT::f32, Custom);
120 setOperationAction(ISD::SELECT, MVT::f64, Custom);
121 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
122 setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
123 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
124 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
125 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
126 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
127
128 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
129 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
130 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
131
132 setOperationAction(ISD::FREM, MVT::f32, Expand);
133 setOperationAction(ISD::FREM, MVT::f64, Expand);
134 setOperationAction(ISD::FREM, MVT::f80, Expand);
135
136 // Custom lowering hooks are needed for XOR
137 // to fold it into CSINC/CSINV.
138 setOperationAction(ISD::XOR, MVT::i32, Custom);
139 setOperationAction(ISD::XOR, MVT::i64, Custom);
140
141 // Virtually no operation on f128 is legal, but LLVM can't expand them when
142 // there's a valid register class, so we need custom operations in most cases.
143 setOperationAction(ISD::FABS, MVT::f128, Expand);
144 setOperationAction(ISD::FADD, MVT::f128, Custom);
145 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
146 setOperationAction(ISD::FCOS, MVT::f128, Expand);
147 setOperationAction(ISD::FDIV, MVT::f128, Custom);
148 setOperationAction(ISD::FMA, MVT::f128, Expand);
149 setOperationAction(ISD::FMUL, MVT::f128, Custom);
150 setOperationAction(ISD::FNEG, MVT::f128, Expand);
151 setOperationAction(ISD::FPOW, MVT::f128, Expand);
152 setOperationAction(ISD::FREM, MVT::f128, Expand);
153 setOperationAction(ISD::FRINT, MVT::f128, Expand);
154 setOperationAction(ISD::FSIN, MVT::f128, Expand);
155 setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
156 setOperationAction(ISD::FSQRT, MVT::f128, Expand);
157 setOperationAction(ISD::FSUB, MVT::f128, Custom);
158 setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
159 setOperationAction(ISD::SETCC, MVT::f128, Custom);
160 setOperationAction(ISD::BR_CC, MVT::f128, Custom);
161 setOperationAction(ISD::SELECT, MVT::f128, Custom);
162 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
163 setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
164
165 // Lowering for many of the conversions is actually specified by the non-f128
166 // type. The LowerXXX function will be trivial when f128 isn't involved.
167 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
168 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
169 setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
170 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
171 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
172 setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
173 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
174 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
175 setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
176 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
177 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
178 setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
179 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
180 setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
181
182 // Variable arguments.
183 setOperationAction(ISD::VASTART, MVT::Other, Custom);
184 setOperationAction(ISD::VAARG, MVT::Other, Custom);
185 setOperationAction(ISD::VACOPY, MVT::Other, Custom);
186 setOperationAction(ISD::VAEND, MVT::Other, Expand);
187
188 // Variable-sized objects.
189 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
190 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
191 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
192
Tim Northover3b0846e2014-05-24 12:50:23 +0000193 // Constant pool entries
194 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
195
196 // BlockAddress
197 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
198
199 // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
200 setOperationAction(ISD::ADDC, MVT::i32, Custom);
201 setOperationAction(ISD::ADDE, MVT::i32, Custom);
202 setOperationAction(ISD::SUBC, MVT::i32, Custom);
203 setOperationAction(ISD::SUBE, MVT::i32, Custom);
204 setOperationAction(ISD::ADDC, MVT::i64, Custom);
205 setOperationAction(ISD::ADDE, MVT::i64, Custom);
206 setOperationAction(ISD::SUBC, MVT::i64, Custom);
207 setOperationAction(ISD::SUBE, MVT::i64, Custom);
208
209 // AArch64 lacks both left-rotate and popcount instructions.
210 setOperationAction(ISD::ROTL, MVT::i32, Expand);
211 setOperationAction(ISD::ROTL, MVT::i64, Expand);
Charlie Turner458e79b2015-10-27 10:25:20 +0000212 for (MVT VT : MVT::vector_valuetypes()) {
213 setOperationAction(ISD::ROTL, VT, Expand);
214 setOperationAction(ISD::ROTR, VT, Expand);
215 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000216
217 // AArch64 doesn't have {U|S}MUL_LOHI.
218 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
219 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
220
221
Tim Northover3b0846e2014-05-24 12:50:23 +0000222 setOperationAction(ISD::CTPOP, MVT::i32, Custom);
223 setOperationAction(ISD::CTPOP, MVT::i64, Custom);
224
225 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
226 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
Chad Rosierf3491492015-12-04 21:38:44 +0000227 for (MVT VT : MVT::vector_valuetypes()) {
228 setOperationAction(ISD::SDIVREM, VT, Expand);
229 setOperationAction(ISD::UDIVREM, VT, Expand);
230 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000231 setOperationAction(ISD::SREM, MVT::i32, Expand);
232 setOperationAction(ISD::SREM, MVT::i64, Expand);
233 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
234 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
235 setOperationAction(ISD::UREM, MVT::i32, Expand);
236 setOperationAction(ISD::UREM, MVT::i64, Expand);
237
238 // Custom lower Add/Sub/Mul with overflow.
239 setOperationAction(ISD::SADDO, MVT::i32, Custom);
240 setOperationAction(ISD::SADDO, MVT::i64, Custom);
241 setOperationAction(ISD::UADDO, MVT::i32, Custom);
242 setOperationAction(ISD::UADDO, MVT::i64, Custom);
243 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
244 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
245 setOperationAction(ISD::USUBO, MVT::i32, Custom);
246 setOperationAction(ISD::USUBO, MVT::i64, Custom);
247 setOperationAction(ISD::SMULO, MVT::i32, Custom);
248 setOperationAction(ISD::SMULO, MVT::i64, Custom);
249 setOperationAction(ISD::UMULO, MVT::i32, Custom);
250 setOperationAction(ISD::UMULO, MVT::i64, Custom);
251
252 setOperationAction(ISD::FSIN, MVT::f32, Expand);
253 setOperationAction(ISD::FSIN, MVT::f64, Expand);
254 setOperationAction(ISD::FCOS, MVT::f32, Expand);
255 setOperationAction(ISD::FCOS, MVT::f64, Expand);
256 setOperationAction(ISD::FPOW, MVT::f32, Expand);
257 setOperationAction(ISD::FPOW, MVT::f64, Expand);
258 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
259 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
260
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +0000261 // f16 is a storage-only type, always promote it to f32.
262 setOperationAction(ISD::SETCC, MVT::f16, Promote);
263 setOperationAction(ISD::BR_CC, MVT::f16, Promote);
264 setOperationAction(ISD::SELECT_CC, MVT::f16, Promote);
265 setOperationAction(ISD::SELECT, MVT::f16, Promote);
266 setOperationAction(ISD::FADD, MVT::f16, Promote);
267 setOperationAction(ISD::FSUB, MVT::f16, Promote);
268 setOperationAction(ISD::FMUL, MVT::f16, Promote);
269 setOperationAction(ISD::FDIV, MVT::f16, Promote);
270 setOperationAction(ISD::FREM, MVT::f16, Promote);
271 setOperationAction(ISD::FMA, MVT::f16, Promote);
272 setOperationAction(ISD::FNEG, MVT::f16, Promote);
273 setOperationAction(ISD::FABS, MVT::f16, Promote);
274 setOperationAction(ISD::FCEIL, MVT::f16, Promote);
275 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote);
276 setOperationAction(ISD::FCOS, MVT::f16, Promote);
277 setOperationAction(ISD::FFLOOR, MVT::f16, Promote);
278 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote);
279 setOperationAction(ISD::FPOW, MVT::f16, Promote);
280 setOperationAction(ISD::FPOWI, MVT::f16, Promote);
281 setOperationAction(ISD::FRINT, MVT::f16, Promote);
282 setOperationAction(ISD::FSIN, MVT::f16, Promote);
283 setOperationAction(ISD::FSINCOS, MVT::f16, Promote);
284 setOperationAction(ISD::FSQRT, MVT::f16, Promote);
285 setOperationAction(ISD::FEXP, MVT::f16, Promote);
286 setOperationAction(ISD::FEXP2, MVT::f16, Promote);
287 setOperationAction(ISD::FLOG, MVT::f16, Promote);
288 setOperationAction(ISD::FLOG2, MVT::f16, Promote);
289 setOperationAction(ISD::FLOG10, MVT::f16, Promote);
290 setOperationAction(ISD::FROUND, MVT::f16, Promote);
291 setOperationAction(ISD::FTRUNC, MVT::f16, Promote);
292 setOperationAction(ISD::FMINNUM, MVT::f16, Promote);
293 setOperationAction(ISD::FMAXNUM, MVT::f16, Promote);
James Molloy63be1982015-08-14 09:08:50 +0000294 setOperationAction(ISD::FMINNAN, MVT::f16, Promote);
295 setOperationAction(ISD::FMAXNAN, MVT::f16, Promote);
Oliver Stannardf5469be2014-08-18 14:22:39 +0000296
Oliver Stannard89d15422014-08-27 16:16:04 +0000297 // v4f16 is also a storage-only type, so promote it to v4f32 when that is
298 // known to be safe.
299 setOperationAction(ISD::FADD, MVT::v4f16, Promote);
300 setOperationAction(ISD::FSUB, MVT::v4f16, Promote);
301 setOperationAction(ISD::FMUL, MVT::v4f16, Promote);
302 setOperationAction(ISD::FDIV, MVT::v4f16, Promote);
303 setOperationAction(ISD::FP_EXTEND, MVT::v4f16, Promote);
304 setOperationAction(ISD::FP_ROUND, MVT::v4f16, Promote);
305 AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32);
306 AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32);
307 AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32);
308 AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32);
309 AddPromotedToType(ISD::FP_EXTEND, MVT::v4f16, MVT::v4f32);
310 AddPromotedToType(ISD::FP_ROUND, MVT::v4f16, MVT::v4f32);
311
312 // Expand all other v4f16 operations.
313 // FIXME: We could generate better code by promoting some operations to
314 // a pair of v4f32s
315 setOperationAction(ISD::FABS, MVT::v4f16, Expand);
316 setOperationAction(ISD::FCEIL, MVT::v4f16, Expand);
317 setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand);
318 setOperationAction(ISD::FCOS, MVT::v4f16, Expand);
319 setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand);
320 setOperationAction(ISD::FMA, MVT::v4f16, Expand);
321 setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand);
322 setOperationAction(ISD::FNEG, MVT::v4f16, Expand);
323 setOperationAction(ISD::FPOW, MVT::v4f16, Expand);
324 setOperationAction(ISD::FPOWI, MVT::v4f16, Expand);
325 setOperationAction(ISD::FREM, MVT::v4f16, Expand);
326 setOperationAction(ISD::FROUND, MVT::v4f16, Expand);
327 setOperationAction(ISD::FRINT, MVT::v4f16, Expand);
328 setOperationAction(ISD::FSIN, MVT::v4f16, Expand);
329 setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand);
330 setOperationAction(ISD::FSQRT, MVT::v4f16, Expand);
331 setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand);
332 setOperationAction(ISD::SETCC, MVT::v4f16, Expand);
333 setOperationAction(ISD::BR_CC, MVT::v4f16, Expand);
334 setOperationAction(ISD::SELECT, MVT::v4f16, Expand);
335 setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand);
336 setOperationAction(ISD::FEXP, MVT::v4f16, Expand);
337 setOperationAction(ISD::FEXP2, MVT::v4f16, Expand);
338 setOperationAction(ISD::FLOG, MVT::v4f16, Expand);
339 setOperationAction(ISD::FLOG2, MVT::v4f16, Expand);
340 setOperationAction(ISD::FLOG10, MVT::v4f16, Expand);
341
342
343 // v8f16 is also a storage-only type, so expand it.
344 setOperationAction(ISD::FABS, MVT::v8f16, Expand);
345 setOperationAction(ISD::FADD, MVT::v8f16, Expand);
346 setOperationAction(ISD::FCEIL, MVT::v8f16, Expand);
347 setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand);
348 setOperationAction(ISD::FCOS, MVT::v8f16, Expand);
349 setOperationAction(ISD::FDIV, MVT::v8f16, Expand);
350 setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand);
351 setOperationAction(ISD::FMA, MVT::v8f16, Expand);
352 setOperationAction(ISD::FMUL, MVT::v8f16, Expand);
353 setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand);
354 setOperationAction(ISD::FNEG, MVT::v8f16, Expand);
355 setOperationAction(ISD::FPOW, MVT::v8f16, Expand);
356 setOperationAction(ISD::FPOWI, MVT::v8f16, Expand);
357 setOperationAction(ISD::FREM, MVT::v8f16, Expand);
358 setOperationAction(ISD::FROUND, MVT::v8f16, Expand);
359 setOperationAction(ISD::FRINT, MVT::v8f16, Expand);
360 setOperationAction(ISD::FSIN, MVT::v8f16, Expand);
361 setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
362 setOperationAction(ISD::FSQRT, MVT::v8f16, Expand);
363 setOperationAction(ISD::FSUB, MVT::v8f16, Expand);
364 setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand);
365 setOperationAction(ISD::SETCC, MVT::v8f16, Expand);
366 setOperationAction(ISD::BR_CC, MVT::v8f16, Expand);
367 setOperationAction(ISD::SELECT, MVT::v8f16, Expand);
368 setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand);
369 setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand);
370 setOperationAction(ISD::FEXP, MVT::v8f16, Expand);
371 setOperationAction(ISD::FEXP2, MVT::v8f16, Expand);
372 setOperationAction(ISD::FLOG, MVT::v8f16, Expand);
373 setOperationAction(ISD::FLOG2, MVT::v8f16, Expand);
374 setOperationAction(ISD::FLOG10, MVT::v8f16, Expand);
375
Tim Northover3b0846e2014-05-24 12:50:23 +0000376 // AArch64 has implementations of a lot of rounding-like FP operations.
Benjamin Kramer57a3d082015-03-08 16:07:39 +0000377 for (MVT Ty : {MVT::f32, MVT::f64}) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000378 setOperationAction(ISD::FFLOOR, Ty, Legal);
379 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
380 setOperationAction(ISD::FCEIL, Ty, Legal);
381 setOperationAction(ISD::FRINT, Ty, Legal);
382 setOperationAction(ISD::FTRUNC, Ty, Legal);
383 setOperationAction(ISD::FROUND, Ty, Legal);
James Molloyb7b2a1e2015-08-11 12:06:37 +0000384 setOperationAction(ISD::FMINNUM, Ty, Legal);
385 setOperationAction(ISD::FMAXNUM, Ty, Legal);
James Molloy88edc822015-08-17 07:13:20 +0000386 setOperationAction(ISD::FMINNAN, Ty, Legal);
387 setOperationAction(ISD::FMAXNAN, Ty, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000388 }
389
390 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
391
Tim Northovercdf15292016-04-14 17:03:29 +0000392 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
393
Ahmed Bougachab0ff6432015-09-01 16:23:45 +0000394 // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
395 // This requires the Performance Monitors extension.
396 if (Subtarget->hasPerfMon())
397 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
398
Tim Northover3b0846e2014-05-24 12:50:23 +0000399 if (Subtarget->isTargetMachO()) {
400 // For iOS, we don't want to the normal expansion of a libcall to
401 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
402 // traffic.
403 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
404 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
405 } else {
406 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
407 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
408 }
409
Juergen Ributzka23266502014-12-10 19:43:32 +0000410 // Make floating-point constants legal for the large code model, so they don't
411 // become loads from the constant pool.
412 if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
413 setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
414 setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
415 }
416
Tim Northover3b0846e2014-05-24 12:50:23 +0000417 // AArch64 does not have floating-point extending loads, i1 sign-extending
418 // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000419 for (MVT VT : MVT::fp_valuetypes()) {
420 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
421 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
422 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
423 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
424 }
425 for (MVT VT : MVT::integer_valuetypes())
426 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
427
Tim Northover3b0846e2014-05-24 12:50:23 +0000428 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
429 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
430 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
431 setTruncStoreAction(MVT::f128, MVT::f80, Expand);
432 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
433 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
434 setTruncStoreAction(MVT::f128, MVT::f16, Expand);
Tim Northoverf8bfe212014-07-18 13:07:05 +0000435
436 setOperationAction(ISD::BITCAST, MVT::i16, Custom);
437 setOperationAction(ISD::BITCAST, MVT::f16, Custom);
438
Tim Northover3b0846e2014-05-24 12:50:23 +0000439 // Indexed loads and stores are supported.
440 for (unsigned im = (unsigned)ISD::PRE_INC;
441 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
442 setIndexedLoadAction(im, MVT::i8, Legal);
443 setIndexedLoadAction(im, MVT::i16, Legal);
444 setIndexedLoadAction(im, MVT::i32, Legal);
445 setIndexedLoadAction(im, MVT::i64, Legal);
446 setIndexedLoadAction(im, MVT::f64, Legal);
447 setIndexedLoadAction(im, MVT::f32, Legal);
Ahmed Bougachae0e12db2015-08-04 01:29:38 +0000448 setIndexedLoadAction(im, MVT::f16, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000449 setIndexedStoreAction(im, MVT::i8, Legal);
450 setIndexedStoreAction(im, MVT::i16, Legal);
451 setIndexedStoreAction(im, MVT::i32, Legal);
452 setIndexedStoreAction(im, MVT::i64, Legal);
453 setIndexedStoreAction(im, MVT::f64, Legal);
454 setIndexedStoreAction(im, MVT::f32, Legal);
Ahmed Bougachae0e12db2015-08-04 01:29:38 +0000455 setIndexedStoreAction(im, MVT::f16, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000456 }
457
458 // Trap.
459 setOperationAction(ISD::TRAP, MVT::Other, Legal);
460
461 // We combine OR nodes for bitfield operations.
462 setTargetDAGCombine(ISD::OR);
463
464 // Vector add and sub nodes may conceal a high-half opportunity.
465 // Also, try to fold ADD into CSINC/CSINV..
466 setTargetDAGCombine(ISD::ADD);
467 setTargetDAGCombine(ISD::SUB);
Chad Rosier14aa2ad2016-05-26 19:41:33 +0000468 setTargetDAGCombine(ISD::SRL);
Tim Northover3b0846e2014-05-24 12:50:23 +0000469 setTargetDAGCombine(ISD::XOR);
470 setTargetDAGCombine(ISD::SINT_TO_FP);
471 setTargetDAGCombine(ISD::UINT_TO_FP);
472
Chad Rosierfa30c9b2015-10-07 17:39:18 +0000473 setTargetDAGCombine(ISD::FP_TO_SINT);
474 setTargetDAGCombine(ISD::FP_TO_UINT);
Chad Rosier7c6ac2b2015-10-07 17:51:37 +0000475 setTargetDAGCombine(ISD::FDIV);
Chad Rosierfa30c9b2015-10-07 17:39:18 +0000476
Tim Northover3b0846e2014-05-24 12:50:23 +0000477 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
478
479 setTargetDAGCombine(ISD::ANY_EXTEND);
480 setTargetDAGCombine(ISD::ZERO_EXTEND);
481 setTargetDAGCombine(ISD::SIGN_EXTEND);
482 setTargetDAGCombine(ISD::BITCAST);
483 setTargetDAGCombine(ISD::CONCAT_VECTORS);
484 setTargetDAGCombine(ISD::STORE);
Tim Northover339c83e2015-11-10 00:44:23 +0000485 if (Subtarget->supportsAddressTopByteIgnored())
486 setTargetDAGCombine(ISD::LOAD);
Tim Northover3b0846e2014-05-24 12:50:23 +0000487
488 setTargetDAGCombine(ISD::MUL);
489
490 setTargetDAGCombine(ISD::SELECT);
491 setTargetDAGCombine(ISD::VSELECT);
492
493 setTargetDAGCombine(ISD::INTRINSIC_VOID);
494 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
495 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
Chad Rosier6c36eff2015-09-03 18:13:57 +0000496 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
Tim Northover3b0846e2014-05-24 12:50:23 +0000497
498 MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 8;
499 MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 4;
500 MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = 4;
501
502 setStackPointerRegisterToSaveRestore(AArch64::SP);
503
504 setSchedulingPreference(Sched::Hybrid);
505
506 // Enable TBZ/TBNZ
507 MaskAndBranchFoldingIsLegal = true;
Quentin Colombet6843ac42015-03-31 20:52:32 +0000508 EnableExtLdPromotion = true;
Tim Northover3b0846e2014-05-24 12:50:23 +0000509
Evandro Menezesa3a0a602016-06-10 16:00:18 +0000510 // Set required alignment.
Tim Northover3b0846e2014-05-24 12:50:23 +0000511 setMinFunctionAlignment(2);
Evandro Menezesa3a0a602016-06-10 16:00:18 +0000512 // Set preferred alignments.
513 setPrefFunctionAlignment(STI.getPrefFunctionAlignment());
514 setPrefLoopAlignment(STI.getPrefLoopAlignment());
Tim Northover3b0846e2014-05-24 12:50:23 +0000515
Evandro Menezese45de8a2016-09-26 15:32:33 +0000516 // Only change the limit for entries in a jump table if specified by
517 // the subtarget, but not at the command line.
518 unsigned MaxJT = STI.getMaximumJumpTableSize();
519 if (MaxJT && getMaximumJumpTableSize() == 0)
520 setMaximumJumpTableSize(MaxJT);
521
Tim Northover3b0846e2014-05-24 12:50:23 +0000522 setHasExtractBitsInsn(true);
523
Adhemerval Zanella7bc33192015-07-28 13:03:31 +0000524 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
525
Tim Northover3b0846e2014-05-24 12:50:23 +0000526 if (Subtarget->hasNEON()) {
527 // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
528 // silliness like this:
529 setOperationAction(ISD::FABS, MVT::v1f64, Expand);
530 setOperationAction(ISD::FADD, MVT::v1f64, Expand);
531 setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
532 setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
533 setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
534 setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
535 setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
536 setOperationAction(ISD::FMA, MVT::v1f64, Expand);
537 setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
538 setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
539 setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
540 setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
541 setOperationAction(ISD::FREM, MVT::v1f64, Expand);
542 setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
543 setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
544 setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
545 setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
546 setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
547 setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
548 setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
549 setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
550 setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
551 setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
552 setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
553 setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
554
555 setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
556 setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
557 setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
558 setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
559 setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
560
561 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
562
563 // AArch64 doesn't have a direct vector ->f32 conversion instructions for
564 // elements smaller than i32, so promote the input to i32 first.
565 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Promote);
566 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Promote);
567 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Promote);
568 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Promote);
Pirama Arumuga Nainarb1881532015-04-23 17:16:27 +0000569 // i8 and i16 vector elements also need promotion to i32 for v8i8 or v8i16
570 // -> v8f16 conversions.
571 setOperationAction(ISD::SINT_TO_FP, MVT::v8i8, Promote);
572 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Promote);
573 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
574 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Promote);
Tim Northover3b0846e2014-05-24 12:50:23 +0000575 // Similarly, there is no direct i32 -> f64 vector conversion instruction.
576 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
577 setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
578 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
579 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
Pirama Arumuga Nainarb1881532015-04-23 17:16:27 +0000580 // Or, direct i32 -> f16 vector conversion. Set it so custom, so the
581 // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
582 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
583 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000584
Craig Topperc5551bf2016-04-26 05:26:51 +0000585 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand);
586 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand);
587
Craig Topper3b4842b2016-04-28 01:58:21 +0000588 setOperationAction(ISD::CTTZ, MVT::v2i8, Expand);
589 setOperationAction(ISD::CTTZ, MVT::v4i16, Expand);
590 setOperationAction(ISD::CTTZ, MVT::v2i32, Expand);
591 setOperationAction(ISD::CTTZ, MVT::v1i64, Expand);
592 setOperationAction(ISD::CTTZ, MVT::v16i8, Expand);
593 setOperationAction(ISD::CTTZ, MVT::v8i16, Expand);
594 setOperationAction(ISD::CTTZ, MVT::v4i32, Expand);
595 setOperationAction(ISD::CTTZ, MVT::v2i64, Expand);
596
Tim Northover3b0846e2014-05-24 12:50:23 +0000597 // AArch64 doesn't have MUL.2d:
598 setOperationAction(ISD::MUL, MVT::v2i64, Expand);
Chad Rosierd9d0f862014-10-08 02:31:24 +0000599 // Custom handling for some quad-vector types to detect MULL.
600 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
601 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
602 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
603
Tim Northover3b0846e2014-05-24 12:50:23 +0000604 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
605 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
606 // Likewise, narrowing and extending vector loads/stores aren't handled
607 // directly.
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000608 for (MVT VT : MVT::vector_valuetypes()) {
609 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000610
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000611 setOperationAction(ISD::MULHS, VT, Expand);
612 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
613 setOperationAction(ISD::MULHU, VT, Expand);
614 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000615
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000616 setOperationAction(ISD::BSWAP, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000617
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000618 for (MVT InnerVT : MVT::vector_valuetypes()) {
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000619 setTruncStoreAction(VT, InnerVT, Expand);
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000620 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
621 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
622 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
623 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000624 }
625
626 // AArch64 has implementations of a lot of rounding-like FP operations.
Benjamin Kramer57a3d082015-03-08 16:07:39 +0000627 for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000628 setOperationAction(ISD::FFLOOR, Ty, Legal);
629 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
630 setOperationAction(ISD::FCEIL, Ty, Legal);
631 setOperationAction(ISD::FRINT, Ty, Legal);
632 setOperationAction(ISD::FTRUNC, Ty, Legal);
633 setOperationAction(ISD::FROUND, Ty, Legal);
634 }
635 }
James Molloyf089ab72014-08-06 10:42:18 +0000636
Matthias Braun651cff42016-06-02 18:03:53 +0000637 PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive();
Tim Northover3b0846e2014-05-24 12:50:23 +0000638}
639
Craig Topper18e69f42016-04-15 06:20:21 +0000640void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) {
Jiangning Liu08f4cda2014-08-29 01:31:42 +0000641 if (VT == MVT::v2f32 || VT == MVT::v4f16) {
Craig Topper18e69f42016-04-15 06:20:21 +0000642 setOperationAction(ISD::LOAD, VT, Promote);
643 AddPromotedToType(ISD::LOAD, VT, MVT::v2i32);
Tim Northover3b0846e2014-05-24 12:50:23 +0000644
Craig Topper18e69f42016-04-15 06:20:21 +0000645 setOperationAction(ISD::STORE, VT, Promote);
646 AddPromotedToType(ISD::STORE, VT, MVT::v2i32);
Jiangning Liu08f4cda2014-08-29 01:31:42 +0000647 } else if (VT == MVT::v2f64 || VT == MVT::v4f32 || VT == MVT::v8f16) {
Craig Topper18e69f42016-04-15 06:20:21 +0000648 setOperationAction(ISD::LOAD, VT, Promote);
649 AddPromotedToType(ISD::LOAD, VT, MVT::v2i64);
Tim Northover3b0846e2014-05-24 12:50:23 +0000650
Craig Topper18e69f42016-04-15 06:20:21 +0000651 setOperationAction(ISD::STORE, VT, Promote);
652 AddPromotedToType(ISD::STORE, VT, MVT::v2i64);
Tim Northover3b0846e2014-05-24 12:50:23 +0000653 }
654
655 // Mark vector float intrinsics as expand.
656 if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
Craig Topper18e69f42016-04-15 06:20:21 +0000657 setOperationAction(ISD::FSIN, VT, Expand);
658 setOperationAction(ISD::FCOS, VT, Expand);
659 setOperationAction(ISD::FPOWI, VT, Expand);
660 setOperationAction(ISD::FPOW, VT, Expand);
661 setOperationAction(ISD::FLOG, VT, Expand);
662 setOperationAction(ISD::FLOG2, VT, Expand);
663 setOperationAction(ISD::FLOG10, VT, Expand);
664 setOperationAction(ISD::FEXP, VT, Expand);
665 setOperationAction(ISD::FEXP2, VT, Expand);
Ahmed Bougachab0ae36f2015-08-04 00:42:34 +0000666
667 // But we do support custom-lowering for FCOPYSIGN.
Craig Topper18e69f42016-04-15 06:20:21 +0000668 setOperationAction(ISD::FCOPYSIGN, VT, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000669 }
670
Craig Topper18e69f42016-04-15 06:20:21 +0000671 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
672 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
673 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
674 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
675 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
676 setOperationAction(ISD::SRA, VT, Custom);
677 setOperationAction(ISD::SRL, VT, Custom);
678 setOperationAction(ISD::SHL, VT, Custom);
679 setOperationAction(ISD::AND, VT, Custom);
680 setOperationAction(ISD::OR, VT, Custom);
681 setOperationAction(ISD::SETCC, VT, Custom);
682 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000683
Craig Topper18e69f42016-04-15 06:20:21 +0000684 setOperationAction(ISD::SELECT, VT, Expand);
685 setOperationAction(ISD::SELECT_CC, VT, Expand);
686 setOperationAction(ISD::VSELECT, VT, Expand);
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000687 for (MVT InnerVT : MVT::all_valuetypes())
Craig Topper18e69f42016-04-15 06:20:21 +0000688 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000689
690 // CNT supports only B element sizes.
691 if (VT != MVT::v8i8 && VT != MVT::v16i8)
Craig Topper18e69f42016-04-15 06:20:21 +0000692 setOperationAction(ISD::CTPOP, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000693
Craig Topper18e69f42016-04-15 06:20:21 +0000694 setOperationAction(ISD::UDIV, VT, Expand);
695 setOperationAction(ISD::SDIV, VT, Expand);
696 setOperationAction(ISD::UREM, VT, Expand);
697 setOperationAction(ISD::SREM, VT, Expand);
698 setOperationAction(ISD::FREM, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000699
Craig Topper18e69f42016-04-15 06:20:21 +0000700 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
701 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000702
Hal Finkelcd8664c2015-12-11 23:11:52 +0000703 // [SU][MIN|MAX] are available for all NEON types apart from i64.
Craig Topper18e69f42016-04-15 06:20:21 +0000704 if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64)
Hal Finkelcd8664c2015-12-11 23:11:52 +0000705 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
Craig Topper18e69f42016-04-15 06:20:21 +0000706 setOperationAction(Opcode, VT, Legal);
James Molloycfb04432015-05-15 16:15:57 +0000707
James Molloy63be1982015-08-14 09:08:50 +0000708 // F[MIN|MAX][NUM|NAN] are available for all FP NEON types (not f16 though!).
709 if (VT.isFloatingPoint() && VT.getVectorElementType() != MVT::f16)
James Molloyb7b2a1e2015-08-11 12:06:37 +0000710 for (unsigned Opcode : {ISD::FMINNAN, ISD::FMAXNAN,
711 ISD::FMINNUM, ISD::FMAXNUM})
Craig Topper18e69f42016-04-15 06:20:21 +0000712 setOperationAction(Opcode, VT, Legal);
James Molloyedf38f02015-08-11 12:06:33 +0000713
Tim Northover3b0846e2014-05-24 12:50:23 +0000714 if (Subtarget->isLittleEndian()) {
715 for (unsigned im = (unsigned)ISD::PRE_INC;
716 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
Craig Topper18e69f42016-04-15 06:20:21 +0000717 setIndexedLoadAction(im, VT, Legal);
718 setIndexedStoreAction(im, VT, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000719 }
720 }
721}
722
723void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
724 addRegisterClass(VT, &AArch64::FPR64RegClass);
725 addTypeForNEON(VT, MVT::v2i32);
726}
727
728void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
729 addRegisterClass(VT, &AArch64::FPR128RegClass);
730 addTypeForNEON(VT, MVT::v4i32);
731}
732
Mehdi Amini44ede332015-07-09 02:09:04 +0000733EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
734 EVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +0000735 if (!VT.isVector())
736 return MVT::i32;
737 return VT.changeVectorElementTypeToInteger();
738}
739
740/// computeKnownBitsForTargetNode - Determine which of the bits specified in
741/// Mask are known to be either zero or one and return them in the
742/// KnownZero/KnownOne bitsets.
743void AArch64TargetLowering::computeKnownBitsForTargetNode(
744 const SDValue Op, APInt &KnownZero, APInt &KnownOne,
745 const SelectionDAG &DAG, unsigned Depth) const {
746 switch (Op.getOpcode()) {
747 default:
748 break;
749 case AArch64ISD::CSEL: {
750 APInt KnownZero2, KnownOne2;
751 DAG.computeKnownBits(Op->getOperand(0), KnownZero, KnownOne, Depth + 1);
752 DAG.computeKnownBits(Op->getOperand(1), KnownZero2, KnownOne2, Depth + 1);
753 KnownZero &= KnownZero2;
754 KnownOne &= KnownOne2;
755 break;
756 }
757 case ISD::INTRINSIC_W_CHAIN: {
Jun Bum Lim4d3c5982015-09-08 16:11:22 +0000758 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +0000759 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
760 switch (IntID) {
761 default: return;
762 case Intrinsic::aarch64_ldaxr:
763 case Intrinsic::aarch64_ldxr: {
764 unsigned BitWidth = KnownOne.getBitWidth();
765 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
Sanjay Patelbd6fca12016-09-14 15:21:00 +0000766 unsigned MemBits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +0000767 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
768 return;
769 }
770 }
771 break;
772 }
773 case ISD::INTRINSIC_WO_CHAIN:
774 case ISD::INTRINSIC_VOID: {
775 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
776 switch (IntNo) {
777 default:
778 break;
779 case Intrinsic::aarch64_neon_umaxv:
780 case Intrinsic::aarch64_neon_uminv: {
781 // Figure out the datatype of the vector operand. The UMINV instruction
782 // will zero extend the result, so we can mark as known zero all the
783 // bits larger than the element datatype. 32-bit or larget doesn't need
784 // this as those are legal types and will be handled by isel directly.
785 MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
786 unsigned BitWidth = KnownZero.getBitWidth();
787 if (VT == MVT::v8i8 || VT == MVT::v16i8) {
788 assert(BitWidth >= 8 && "Unexpected width!");
789 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
790 KnownZero |= Mask;
791 } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
792 assert(BitWidth >= 16 && "Unexpected width!");
793 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
794 KnownZero |= Mask;
795 }
796 break;
797 } break;
798 }
799 }
800 }
801}
802
Mehdi Aminieaabc512015-07-09 15:12:23 +0000803MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
804 EVT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +0000805 return MVT::i64;
806}
807
Akira Hatanakaf53b0402015-07-29 14:17:26 +0000808bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
809 unsigned AddrSpace,
810 unsigned Align,
811 bool *Fast) const {
812 if (Subtarget->requiresStrictAlign())
813 return false;
Sanjay Patelbbbf9a12015-09-25 21:49:48 +0000814
Sanjay Patelbbbf9a12015-09-25 21:49:48 +0000815 if (Fast) {
Matthias Braun651cff42016-06-02 18:03:53 +0000816 // Some CPUs are fine with unaligned stores except for 128-bit ones.
817 *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 ||
Sanjay Patelbbbf9a12015-09-25 21:49:48 +0000818 // See comments in performSTORECombine() for more details about
819 // these conditions.
820
821 // Code that uses clang vector extensions can mark that it
822 // wants unaligned accesses to be treated as fast by
823 // underspecifying alignment to be 1 or 2.
824 Align <= 2 ||
825
826 // Disregard v2i64. Memcpy lowering produces those and splitting
827 // them regresses performance on micro-benchmarks and olden/bh.
828 VT == MVT::v2i64;
829 }
Akira Hatanakaf53b0402015-07-29 14:17:26 +0000830 return true;
831}
832
Tim Northover3b0846e2014-05-24 12:50:23 +0000833FastISel *
834AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
835 const TargetLibraryInfo *libInfo) const {
836 return AArch64::createFastISel(funcInfo, libInfo);
837}
838
839const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
Matthias Braund04893f2015-05-07 21:33:59 +0000840 switch ((AArch64ISD::NodeType)Opcode) {
841 case AArch64ISD::FIRST_NUMBER: break;
Tim Northover3b0846e2014-05-24 12:50:23 +0000842 case AArch64ISD::CALL: return "AArch64ISD::CALL";
843 case AArch64ISD::ADRP: return "AArch64ISD::ADRP";
844 case AArch64ISD::ADDlow: return "AArch64ISD::ADDlow";
845 case AArch64ISD::LOADgot: return "AArch64ISD::LOADgot";
846 case AArch64ISD::RET_FLAG: return "AArch64ISD::RET_FLAG";
847 case AArch64ISD::BRCOND: return "AArch64ISD::BRCOND";
848 case AArch64ISD::CSEL: return "AArch64ISD::CSEL";
849 case AArch64ISD::FCSEL: return "AArch64ISD::FCSEL";
850 case AArch64ISD::CSINV: return "AArch64ISD::CSINV";
851 case AArch64ISD::CSNEG: return "AArch64ISD::CSNEG";
852 case AArch64ISD::CSINC: return "AArch64ISD::CSINC";
853 case AArch64ISD::THREAD_POINTER: return "AArch64ISD::THREAD_POINTER";
Kristof Beylsaea84612015-03-04 09:12:08 +0000854 case AArch64ISD::TLSDESC_CALLSEQ: return "AArch64ISD::TLSDESC_CALLSEQ";
Tim Northover3b0846e2014-05-24 12:50:23 +0000855 case AArch64ISD::ADC: return "AArch64ISD::ADC";
856 case AArch64ISD::SBC: return "AArch64ISD::SBC";
857 case AArch64ISD::ADDS: return "AArch64ISD::ADDS";
858 case AArch64ISD::SUBS: return "AArch64ISD::SUBS";
859 case AArch64ISD::ADCS: return "AArch64ISD::ADCS";
860 case AArch64ISD::SBCS: return "AArch64ISD::SBCS";
861 case AArch64ISD::ANDS: return "AArch64ISD::ANDS";
Matthias Braunaf7d7702015-07-16 20:02:37 +0000862 case AArch64ISD::CCMP: return "AArch64ISD::CCMP";
863 case AArch64ISD::CCMN: return "AArch64ISD::CCMN";
864 case AArch64ISD::FCCMP: return "AArch64ISD::FCCMP";
Tim Northover3b0846e2014-05-24 12:50:23 +0000865 case AArch64ISD::FCMP: return "AArch64ISD::FCMP";
Tim Northover3b0846e2014-05-24 12:50:23 +0000866 case AArch64ISD::DUP: return "AArch64ISD::DUP";
867 case AArch64ISD::DUPLANE8: return "AArch64ISD::DUPLANE8";
868 case AArch64ISD::DUPLANE16: return "AArch64ISD::DUPLANE16";
869 case AArch64ISD::DUPLANE32: return "AArch64ISD::DUPLANE32";
870 case AArch64ISD::DUPLANE64: return "AArch64ISD::DUPLANE64";
871 case AArch64ISD::MOVI: return "AArch64ISD::MOVI";
872 case AArch64ISD::MOVIshift: return "AArch64ISD::MOVIshift";
873 case AArch64ISD::MOVIedit: return "AArch64ISD::MOVIedit";
874 case AArch64ISD::MOVImsl: return "AArch64ISD::MOVImsl";
875 case AArch64ISD::FMOV: return "AArch64ISD::FMOV";
876 case AArch64ISD::MVNIshift: return "AArch64ISD::MVNIshift";
877 case AArch64ISD::MVNImsl: return "AArch64ISD::MVNImsl";
878 case AArch64ISD::BICi: return "AArch64ISD::BICi";
879 case AArch64ISD::ORRi: return "AArch64ISD::ORRi";
880 case AArch64ISD::BSL: return "AArch64ISD::BSL";
881 case AArch64ISD::NEG: return "AArch64ISD::NEG";
882 case AArch64ISD::EXTR: return "AArch64ISD::EXTR";
883 case AArch64ISD::ZIP1: return "AArch64ISD::ZIP1";
884 case AArch64ISD::ZIP2: return "AArch64ISD::ZIP2";
885 case AArch64ISD::UZP1: return "AArch64ISD::UZP1";
886 case AArch64ISD::UZP2: return "AArch64ISD::UZP2";
887 case AArch64ISD::TRN1: return "AArch64ISD::TRN1";
888 case AArch64ISD::TRN2: return "AArch64ISD::TRN2";
889 case AArch64ISD::REV16: return "AArch64ISD::REV16";
890 case AArch64ISD::REV32: return "AArch64ISD::REV32";
891 case AArch64ISD::REV64: return "AArch64ISD::REV64";
892 case AArch64ISD::EXT: return "AArch64ISD::EXT";
893 case AArch64ISD::VSHL: return "AArch64ISD::VSHL";
894 case AArch64ISD::VLSHR: return "AArch64ISD::VLSHR";
895 case AArch64ISD::VASHR: return "AArch64ISD::VASHR";
896 case AArch64ISD::CMEQ: return "AArch64ISD::CMEQ";
897 case AArch64ISD::CMGE: return "AArch64ISD::CMGE";
898 case AArch64ISD::CMGT: return "AArch64ISD::CMGT";
899 case AArch64ISD::CMHI: return "AArch64ISD::CMHI";
900 case AArch64ISD::CMHS: return "AArch64ISD::CMHS";
901 case AArch64ISD::FCMEQ: return "AArch64ISD::FCMEQ";
902 case AArch64ISD::FCMGE: return "AArch64ISD::FCMGE";
903 case AArch64ISD::FCMGT: return "AArch64ISD::FCMGT";
904 case AArch64ISD::CMEQz: return "AArch64ISD::CMEQz";
905 case AArch64ISD::CMGEz: return "AArch64ISD::CMGEz";
906 case AArch64ISD::CMGTz: return "AArch64ISD::CMGTz";
907 case AArch64ISD::CMLEz: return "AArch64ISD::CMLEz";
908 case AArch64ISD::CMLTz: return "AArch64ISD::CMLTz";
909 case AArch64ISD::FCMEQz: return "AArch64ISD::FCMEQz";
910 case AArch64ISD::FCMGEz: return "AArch64ISD::FCMGEz";
911 case AArch64ISD::FCMGTz: return "AArch64ISD::FCMGTz";
912 case AArch64ISD::FCMLEz: return "AArch64ISD::FCMLEz";
913 case AArch64ISD::FCMLTz: return "AArch64ISD::FCMLTz";
Ahmed Bougachafab58922015-03-10 20:45:38 +0000914 case AArch64ISD::SADDV: return "AArch64ISD::SADDV";
915 case AArch64ISD::UADDV: return "AArch64ISD::UADDV";
916 case AArch64ISD::SMINV: return "AArch64ISD::SMINV";
917 case AArch64ISD::UMINV: return "AArch64ISD::UMINV";
918 case AArch64ISD::SMAXV: return "AArch64ISD::SMAXV";
919 case AArch64ISD::UMAXV: return "AArch64ISD::UMAXV";
Tim Northover3b0846e2014-05-24 12:50:23 +0000920 case AArch64ISD::NOT: return "AArch64ISD::NOT";
921 case AArch64ISD::BIT: return "AArch64ISD::BIT";
922 case AArch64ISD::CBZ: return "AArch64ISD::CBZ";
923 case AArch64ISD::CBNZ: return "AArch64ISD::CBNZ";
924 case AArch64ISD::TBZ: return "AArch64ISD::TBZ";
925 case AArch64ISD::TBNZ: return "AArch64ISD::TBNZ";
926 case AArch64ISD::TC_RETURN: return "AArch64ISD::TC_RETURN";
Matthias Braund04893f2015-05-07 21:33:59 +0000927 case AArch64ISD::PREFETCH: return "AArch64ISD::PREFETCH";
Tim Northover3b0846e2014-05-24 12:50:23 +0000928 case AArch64ISD::SITOF: return "AArch64ISD::SITOF";
929 case AArch64ISD::UITOF: return "AArch64ISD::UITOF";
Asiri Rathnayake530b3ed2014-10-01 09:59:45 +0000930 case AArch64ISD::NVCAST: return "AArch64ISD::NVCAST";
Tim Northover3b0846e2014-05-24 12:50:23 +0000931 case AArch64ISD::SQSHL_I: return "AArch64ISD::SQSHL_I";
932 case AArch64ISD::UQSHL_I: return "AArch64ISD::UQSHL_I";
933 case AArch64ISD::SRSHR_I: return "AArch64ISD::SRSHR_I";
934 case AArch64ISD::URSHR_I: return "AArch64ISD::URSHR_I";
935 case AArch64ISD::SQSHLU_I: return "AArch64ISD::SQSHLU_I";
936 case AArch64ISD::WrapperLarge: return "AArch64ISD::WrapperLarge";
937 case AArch64ISD::LD2post: return "AArch64ISD::LD2post";
938 case AArch64ISD::LD3post: return "AArch64ISD::LD3post";
939 case AArch64ISD::LD4post: return "AArch64ISD::LD4post";
940 case AArch64ISD::ST2post: return "AArch64ISD::ST2post";
941 case AArch64ISD::ST3post: return "AArch64ISD::ST3post";
942 case AArch64ISD::ST4post: return "AArch64ISD::ST4post";
943 case AArch64ISD::LD1x2post: return "AArch64ISD::LD1x2post";
944 case AArch64ISD::LD1x3post: return "AArch64ISD::LD1x3post";
945 case AArch64ISD::LD1x4post: return "AArch64ISD::LD1x4post";
946 case AArch64ISD::ST1x2post: return "AArch64ISD::ST1x2post";
947 case AArch64ISD::ST1x3post: return "AArch64ISD::ST1x3post";
948 case AArch64ISD::ST1x4post: return "AArch64ISD::ST1x4post";
949 case AArch64ISD::LD1DUPpost: return "AArch64ISD::LD1DUPpost";
950 case AArch64ISD::LD2DUPpost: return "AArch64ISD::LD2DUPpost";
951 case AArch64ISD::LD3DUPpost: return "AArch64ISD::LD3DUPpost";
952 case AArch64ISD::LD4DUPpost: return "AArch64ISD::LD4DUPpost";
953 case AArch64ISD::LD1LANEpost: return "AArch64ISD::LD1LANEpost";
954 case AArch64ISD::LD2LANEpost: return "AArch64ISD::LD2LANEpost";
955 case AArch64ISD::LD3LANEpost: return "AArch64ISD::LD3LANEpost";
956 case AArch64ISD::LD4LANEpost: return "AArch64ISD::LD4LANEpost";
957 case AArch64ISD::ST2LANEpost: return "AArch64ISD::ST2LANEpost";
958 case AArch64ISD::ST3LANEpost: return "AArch64ISD::ST3LANEpost";
959 case AArch64ISD::ST4LANEpost: return "AArch64ISD::ST4LANEpost";
Chad Rosierd9d0f862014-10-08 02:31:24 +0000960 case AArch64ISD::SMULL: return "AArch64ISD::SMULL";
961 case AArch64ISD::UMULL: return "AArch64ISD::UMULL";
Evandro Menezeseff2bd92016-10-24 16:14:58 +0000962 case AArch64ISD::FRSQRTE: return "AArch64ISD::FRSQRTE";
963 case AArch64ISD::FRECPE: return "AArch64ISD::FRECPE";
Tim Northover3b0846e2014-05-24 12:50:23 +0000964 }
Matthias Braund04893f2015-05-07 21:33:59 +0000965 return nullptr;
Tim Northover3b0846e2014-05-24 12:50:23 +0000966}
967
968MachineBasicBlock *
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +0000969AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI,
Tim Northover3b0846e2014-05-24 12:50:23 +0000970 MachineBasicBlock *MBB) const {
971 // We materialise the F128CSEL pseudo-instruction as some control flow and a
972 // phi node:
973
974 // OrigBB:
975 // [... previous instrs leading to comparison ...]
976 // b.ne TrueBB
977 // b EndBB
978 // TrueBB:
979 // ; Fallthrough
980 // EndBB:
981 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
982
Tim Northover3b0846e2014-05-24 12:50:23 +0000983 MachineFunction *MF = MBB->getParent();
Eric Christopher905f12d2015-01-29 00:19:42 +0000984 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +0000985 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +0000986 DebugLoc DL = MI.getDebugLoc();
Duncan P. N. Exon Smithd3b9df02015-10-13 20:02:15 +0000987 MachineFunction::iterator It = ++MBB->getIterator();
Tim Northover3b0846e2014-05-24 12:50:23 +0000988
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +0000989 unsigned DestReg = MI.getOperand(0).getReg();
990 unsigned IfTrueReg = MI.getOperand(1).getReg();
991 unsigned IfFalseReg = MI.getOperand(2).getReg();
992 unsigned CondCode = MI.getOperand(3).getImm();
993 bool NZCVKilled = MI.getOperand(4).isKill();
Tim Northover3b0846e2014-05-24 12:50:23 +0000994
995 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
996 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
997 MF->insert(It, TrueBB);
998 MF->insert(It, EndBB);
999
1000 // Transfer rest of current basic-block to EndBB
1001 EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
1002 MBB->end());
1003 EndBB->transferSuccessorsAndUpdatePHIs(MBB);
1004
1005 BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
1006 BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
1007 MBB->addSuccessor(TrueBB);
1008 MBB->addSuccessor(EndBB);
1009
1010 // TrueBB falls through to the end.
1011 TrueBB->addSuccessor(EndBB);
1012
1013 if (!NZCVKilled) {
1014 TrueBB->addLiveIn(AArch64::NZCV);
1015 EndBB->addLiveIn(AArch64::NZCV);
1016 }
1017
1018 BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
1019 .addReg(IfTrueReg)
1020 .addMBB(TrueBB)
1021 .addReg(IfFalseReg)
1022 .addMBB(MBB);
1023
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001024 MI.eraseFromParent();
Tim Northover3b0846e2014-05-24 12:50:23 +00001025 return EndBB;
1026}
1027
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001028MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter(
1029 MachineInstr &MI, MachineBasicBlock *BB) const {
1030 switch (MI.getOpcode()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001031 default:
1032#ifndef NDEBUG
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001033 MI.dump();
Tim Northover3b0846e2014-05-24 12:50:23 +00001034#endif
Craig Topper35b2f752014-06-19 06:10:58 +00001035 llvm_unreachable("Unexpected instruction for custom inserter!");
Tim Northover3b0846e2014-05-24 12:50:23 +00001036
1037 case AArch64::F128CSEL:
1038 return EmitF128CSEL(MI, BB);
1039
1040 case TargetOpcode::STACKMAP:
1041 case TargetOpcode::PATCHPOINT:
1042 return emitPatchPoint(MI, BB);
1043 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001044}
1045
1046//===----------------------------------------------------------------------===//
1047// AArch64 Lowering private implementation.
1048//===----------------------------------------------------------------------===//
1049
1050//===----------------------------------------------------------------------===//
1051// Lowering Code
1052//===----------------------------------------------------------------------===//
1053
1054/// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1055/// CC
1056static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1057 switch (CC) {
1058 default:
1059 llvm_unreachable("Unknown condition code!");
1060 case ISD::SETNE:
1061 return AArch64CC::NE;
1062 case ISD::SETEQ:
1063 return AArch64CC::EQ;
1064 case ISD::SETGT:
1065 return AArch64CC::GT;
1066 case ISD::SETGE:
1067 return AArch64CC::GE;
1068 case ISD::SETLT:
1069 return AArch64CC::LT;
1070 case ISD::SETLE:
1071 return AArch64CC::LE;
1072 case ISD::SETUGT:
1073 return AArch64CC::HI;
1074 case ISD::SETUGE:
1075 return AArch64CC::HS;
1076 case ISD::SETULT:
1077 return AArch64CC::LO;
1078 case ISD::SETULE:
1079 return AArch64CC::LS;
1080 }
1081}
1082
1083/// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1084static void changeFPCCToAArch64CC(ISD::CondCode CC,
1085 AArch64CC::CondCode &CondCode,
1086 AArch64CC::CondCode &CondCode2) {
1087 CondCode2 = AArch64CC::AL;
1088 switch (CC) {
1089 default:
1090 llvm_unreachable("Unknown FP condition!");
1091 case ISD::SETEQ:
1092 case ISD::SETOEQ:
1093 CondCode = AArch64CC::EQ;
1094 break;
1095 case ISD::SETGT:
1096 case ISD::SETOGT:
1097 CondCode = AArch64CC::GT;
1098 break;
1099 case ISD::SETGE:
1100 case ISD::SETOGE:
1101 CondCode = AArch64CC::GE;
1102 break;
1103 case ISD::SETOLT:
1104 CondCode = AArch64CC::MI;
1105 break;
1106 case ISD::SETOLE:
1107 CondCode = AArch64CC::LS;
1108 break;
1109 case ISD::SETONE:
1110 CondCode = AArch64CC::MI;
1111 CondCode2 = AArch64CC::GT;
1112 break;
1113 case ISD::SETO:
1114 CondCode = AArch64CC::VC;
1115 break;
1116 case ISD::SETUO:
1117 CondCode = AArch64CC::VS;
1118 break;
1119 case ISD::SETUEQ:
1120 CondCode = AArch64CC::EQ;
1121 CondCode2 = AArch64CC::VS;
1122 break;
1123 case ISD::SETUGT:
1124 CondCode = AArch64CC::HI;
1125 break;
1126 case ISD::SETUGE:
1127 CondCode = AArch64CC::PL;
1128 break;
1129 case ISD::SETLT:
1130 case ISD::SETULT:
1131 CondCode = AArch64CC::LT;
1132 break;
1133 case ISD::SETLE:
1134 case ISD::SETULE:
1135 CondCode = AArch64CC::LE;
1136 break;
1137 case ISD::SETNE:
1138 case ISD::SETUNE:
1139 CondCode = AArch64CC::NE;
1140 break;
1141 }
1142}
1143
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001144/// Convert a DAG fp condition code to an AArch64 CC.
1145/// This differs from changeFPCCToAArch64CC in that it returns cond codes that
1146/// should be AND'ed instead of OR'ed.
1147static void changeFPCCToANDAArch64CC(ISD::CondCode CC,
1148 AArch64CC::CondCode &CondCode,
1149 AArch64CC::CondCode &CondCode2) {
1150 CondCode2 = AArch64CC::AL;
1151 switch (CC) {
1152 default:
1153 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1154 assert(CondCode2 == AArch64CC::AL);
1155 break;
1156 case ISD::SETONE:
1157 // (a one b)
1158 // == ((a olt b) || (a ogt b))
1159 // == ((a ord b) && (a une b))
1160 CondCode = AArch64CC::VC;
1161 CondCode2 = AArch64CC::NE;
1162 break;
1163 case ISD::SETUEQ:
1164 // (a ueq b)
1165 // == ((a uno b) || (a oeq b))
1166 // == ((a ule b) && (a uge b))
1167 CondCode = AArch64CC::PL;
1168 CondCode2 = AArch64CC::LE;
1169 break;
1170 }
1171}
1172
Tim Northover3b0846e2014-05-24 12:50:23 +00001173/// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1174/// CC usable with the vector instructions. Fewer operations are available
1175/// without a real NZCV register, so we have to use less efficient combinations
1176/// to get the same effect.
1177static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1178 AArch64CC::CondCode &CondCode,
1179 AArch64CC::CondCode &CondCode2,
1180 bool &Invert) {
1181 Invert = false;
1182 switch (CC) {
1183 default:
1184 // Mostly the scalar mappings work fine.
1185 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1186 break;
1187 case ISD::SETUO:
Justin Bognerb03fd122016-08-17 05:10:15 +00001188 Invert = true;
1189 LLVM_FALLTHROUGH;
Tim Northover3b0846e2014-05-24 12:50:23 +00001190 case ISD::SETO:
1191 CondCode = AArch64CC::MI;
1192 CondCode2 = AArch64CC::GE;
1193 break;
1194 case ISD::SETUEQ:
1195 case ISD::SETULT:
1196 case ISD::SETULE:
1197 case ISD::SETUGT:
1198 case ISD::SETUGE:
1199 // All of the compare-mask comparisons are ordered, but we can switch
1200 // between the two by a double inversion. E.g. ULE == !OGT.
1201 Invert = true;
1202 changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1203 break;
1204 }
1205}
1206
1207static bool isLegalArithImmed(uint64_t C) {
1208 // Matches AArch64DAGToDAGISel::SelectArithImmed().
1209 return (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1210}
1211
1212static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00001213 const SDLoc &dl, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001214 EVT VT = LHS.getValueType();
1215
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001216 if (VT.isFloatingPoint()) {
1217 assert(VT != MVT::f128);
1218 if (VT == MVT::f16) {
1219 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
1220 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
Weiming Zhao095c2712016-05-11 01:26:32 +00001221 VT = MVT::f32;
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001222 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001223 return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001224 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001225
1226 // The CMP instruction is just an alias for SUBS, and representing it as
1227 // SUBS means that it's possible to get CSE with subtract operations.
1228 // A later phase can perform the optimization of setting the destination
1229 // register to WZR/XZR if it ends up being unused.
1230 unsigned Opcode = AArch64ISD::SUBS;
1231
Artyom Skrobov314ee042015-11-25 19:41:11 +00001232 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001233 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1234 // We'd like to combine a (CMP op1, (sub 0, op2) into a CMN instruction on
1235 // the grounds that "op1 - (-op2) == op1 + op2". However, the C and V flags
1236 // can be set differently by this operation. It comes down to whether
1237 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1238 // everything is fine. If not then the optimization is wrong. Thus general
1239 // comparisons are only valid if op2 != 0.
1240
1241 // So, finally, the only LLVM-native comparisons that don't mention C and V
1242 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1243 // the absence of information about op2.
1244 Opcode = AArch64ISD::ADDS;
1245 RHS = RHS.getOperand(1);
Artyom Skrobov314ee042015-11-25 19:41:11 +00001246 } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001247 !isUnsignedIntSetCC(CC)) {
1248 // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1249 // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1250 // of the signed comparisons.
1251 Opcode = AArch64ISD::ANDS;
1252 RHS = LHS.getOperand(1);
1253 LHS = LHS.getOperand(0);
1254 }
1255
Matthias Braunaf7d7702015-07-16 20:02:37 +00001256 return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
Tim Northover3b0846e2014-05-24 12:50:23 +00001257 .getValue(1);
1258}
1259
Matthias Braunaf7d7702015-07-16 20:02:37 +00001260/// \defgroup AArch64CCMP CMP;CCMP matching
1261///
1262/// These functions deal with the formation of CMP;CCMP;... sequences.
1263/// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1264/// a comparison. They set the NZCV flags to a predefined value if their
1265/// predicate is false. This allows to express arbitrary conjunctions, for
1266/// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B))))"
1267/// expressed as:
1268/// cmp A
1269/// ccmp B, inv(CB), CA
1270/// check for CB flags
1271///
1272/// In general we can create code for arbitrary "... (and (and A B) C)"
1273/// sequences. We can also implement some "or" expressions, because "(or A B)"
1274/// is equivalent to "not (and (not A) (not B))" and we can implement some
1275/// negation operations:
1276/// We can negate the results of a single comparison by inverting the flags
1277/// used when the predicate fails and inverting the flags tested in the next
1278/// instruction; We can also negate the results of the whole previous
1279/// conditional compare sequence by inverting the flags tested in the next
1280/// instruction. However there is no way to negate the result of a partial
1281/// sequence.
1282///
1283/// Therefore on encountering an "or" expression we can negate the subtree on
1284/// one side and have to be able to push the negate to the leafs of the subtree
1285/// on the other side (see also the comments in code). As complete example:
1286/// "or (or (setCA (cmp A)) (setCB (cmp B)))
1287/// (and (setCC (cmp C)) (setCD (cmp D)))"
1288/// is transformed to
1289/// "not (and (not (and (setCC (cmp C)) (setCC (cmp D))))
1290/// (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1291/// and implemented as:
1292/// cmp C
1293/// ccmp D, inv(CD), CC
1294/// ccmp A, CA, inv(CD)
1295/// ccmp B, CB, inv(CA)
1296/// check for CB flags
1297/// A counterexample is "or (and A B) (and C D)" which cannot be implemented
1298/// by conditional compare sequences.
1299/// @{
1300
Geoff Berrye41c2df2015-07-20 22:03:52 +00001301/// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001302static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1303 ISD::CondCode CC, SDValue CCOp,
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001304 AArch64CC::CondCode Predicate,
1305 AArch64CC::CondCode OutCC,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00001306 const SDLoc &DL, SelectionDAG &DAG) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001307 unsigned Opcode = 0;
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001308 if (LHS.getValueType().isFloatingPoint()) {
1309 assert(LHS.getValueType() != MVT::f128);
1310 if (LHS.getValueType() == MVT::f16) {
1311 LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS);
1312 RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS);
1313 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001314 Opcode = AArch64ISD::FCCMP;
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001315 } else if (RHS.getOpcode() == ISD::SUB) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001316 SDValue SubOp0 = RHS.getOperand(0);
Artyom Skrobov314ee042015-11-25 19:41:11 +00001317 if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
Matthias Braunfd13c142016-01-23 04:05:16 +00001318 // See emitComparison() on why we can only do this for SETEQ and SETNE.
1319 Opcode = AArch64ISD::CCMN;
1320 RHS = RHS.getOperand(1);
1321 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001322 }
1323 if (Opcode == 0)
1324 Opcode = AArch64ISD::CCMP;
1325
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001326 SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC);
1327 AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1328 unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001329 SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1330 return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1331}
1332
1333/// Returns true if @p Val is a tree of AND/OR/SETCC operations.
1334/// CanPushNegate is set to true if we can push a negate operation through
1335/// the tree in a was that we are left with AND operations and negate operations
1336/// at the leafs only. i.e. "not (or (or x y) z)" can be changed to
1337/// "and (and (not x) (not y)) (not z)"; "not (or (and x y) z)" cannot be
1338/// brought into such a form.
Matthias Braunfdef49b2016-01-23 04:05:22 +00001339static bool isConjunctionDisjunctionTree(const SDValue Val, bool &CanNegate,
Matthias Braunaf7d7702015-07-16 20:02:37 +00001340 unsigned Depth = 0) {
1341 if (!Val.hasOneUse())
1342 return false;
1343 unsigned Opcode = Val->getOpcode();
1344 if (Opcode == ISD::SETCC) {
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001345 if (Val->getOperand(0).getValueType() == MVT::f128)
1346 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001347 CanNegate = true;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001348 return true;
1349 }
Matthias Braun985bdf92016-01-23 04:05:18 +00001350 // Protect against exponential runtime and stack overflow.
1351 if (Depth > 6)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001352 return false;
1353 if (Opcode == ISD::AND || Opcode == ISD::OR) {
1354 SDValue O0 = Val->getOperand(0);
1355 SDValue O1 = Val->getOperand(1);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001356 bool CanNegateL;
1357 if (!isConjunctionDisjunctionTree(O0, CanNegateL, Depth+1))
Matthias Braunaf7d7702015-07-16 20:02:37 +00001358 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001359 bool CanNegateR;
1360 if (!isConjunctionDisjunctionTree(O1, CanNegateR, Depth+1))
Matthias Braunaf7d7702015-07-16 20:02:37 +00001361 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001362
1363 if (Opcode == ISD::OR) {
1364 // For an OR expression we need to be able to negate at least one side or
1365 // we cannot do the transformation at all.
1366 if (!CanNegateL && !CanNegateR)
1367 return false;
1368 // We can however change a (not (or x y)) to (and (not x) (not y)) if we
1369 // can negate the x and y subtrees.
1370 CanNegate = CanNegateL && CanNegateR;
1371 } else {
1372 // If the operands are OR expressions then we finally need to negate their
1373 // outputs, we can only do that for the operand with emitted last by
1374 // negating OutCC, not for both operands.
1375 bool NeedsNegOutL = O0->getOpcode() == ISD::OR;
1376 bool NeedsNegOutR = O1->getOpcode() == ISD::OR;
1377 if (NeedsNegOutL && NeedsNegOutR)
1378 return false;
1379 // We cannot negate an AND operation (it would become an OR),
1380 CanNegate = false;
1381 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001382 return true;
1383 }
1384 return false;
1385}
1386
1387/// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1388/// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1389/// Tries to transform the given i1 producing node @p Val to a series compare
1390/// and conditional compare operations. @returns an NZCV flags producing node
1391/// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1392/// transformation was not possible.
1393/// On recursive invocations @p PushNegate may be set to true to have negation
1394/// effects pushed to the tree leafs; @p Predicate is an NZCV flag predicate
1395/// for the comparisons in the current subtree; @p Depth limits the search
1396/// depth to avoid stack overflow.
Matthias Braunfdef49b2016-01-23 04:05:22 +00001397static SDValue emitConjunctionDisjunctionTreeRec(SelectionDAG &DAG, SDValue Val,
1398 AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp,
1399 AArch64CC::CondCode Predicate) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001400 // We're at a tree leaf, produce a conditional comparison operation.
1401 unsigned Opcode = Val->getOpcode();
1402 if (Opcode == ISD::SETCC) {
1403 SDValue LHS = Val->getOperand(0);
1404 SDValue RHS = Val->getOperand(1);
1405 ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1406 bool isInteger = LHS.getValueType().isInteger();
Matthias Braunfdef49b2016-01-23 04:05:22 +00001407 if (Negate)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001408 CC = getSetCCInverse(CC, isInteger);
1409 SDLoc DL(Val);
1410 // Determine OutCC and handle FP special case.
1411 if (isInteger) {
1412 OutCC = changeIntCCToAArch64CC(CC);
1413 } else {
1414 assert(LHS.getValueType().isFloatingPoint());
1415 AArch64CC::CondCode ExtraCC;
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001416 changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
1417 // Some floating point conditions can't be tested with a single condition
1418 // code. Construct an additional comparison in this case.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001419 if (ExtraCC != AArch64CC::AL) {
1420 SDValue ExtraCmp;
1421 if (!CCOp.getNode())
1422 ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001423 else
1424 ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate,
1425 ExtraCC, DL, DAG);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001426 CCOp = ExtraCmp;
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001427 Predicate = ExtraCC;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001428 }
1429 }
1430
1431 // Produce a normal comparison if we are first in the chain
Matthias Braunfdef49b2016-01-23 04:05:22 +00001432 if (!CCOp)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001433 return emitComparison(LHS, RHS, CC, DL, DAG);
1434 // Otherwise produce a ccmp.
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001435 return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL,
Matthias Braunaf7d7702015-07-16 20:02:37 +00001436 DAG);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001437 }
Junmo Park3ca3e192016-01-25 10:17:17 +00001438 assert((Opcode == ISD::AND || (Opcode == ISD::OR && Val->hasOneUse())) &&
1439 "Valid conjunction/disjunction tree");
Matthias Braunaf7d7702015-07-16 20:02:37 +00001440
1441 // Check if both sides can be transformed.
1442 SDValue LHS = Val->getOperand(0);
1443 SDValue RHS = Val->getOperand(1);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001444
Matthias Braunfdef49b2016-01-23 04:05:22 +00001445 // In case of an OR we need to negate our operands and the result.
1446 // (A v B) <=> not(not(A) ^ not(B))
1447 bool NegateOpsAndResult = Opcode == ISD::OR;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001448 // We can negate the results of all previous operations by inverting the
Matthias Braunfdef49b2016-01-23 04:05:22 +00001449 // predicate flags giving us a free negation for one side. The other side
1450 // must be negatable by itself.
1451 if (NegateOpsAndResult) {
1452 // See which side we can negate.
1453 bool CanNegateL;
1454 bool isValidL = isConjunctionDisjunctionTree(LHS, CanNegateL);
1455 assert(isValidL && "Valid conjunction/disjunction tree");
1456 (void)isValidL;
1457
1458#ifndef NDEBUG
1459 bool CanNegateR;
1460 bool isValidR = isConjunctionDisjunctionTree(RHS, CanNegateR);
1461 assert(isValidR && "Valid conjunction/disjunction tree");
1462 assert((CanNegateL || CanNegateR) && "Valid conjunction/disjunction tree");
1463#endif
1464
1465 // Order the side which we cannot negate to RHS so we can emit it first.
1466 if (!CanNegateL)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001467 std::swap(LHS, RHS);
Matthias Braun46e56392015-08-20 23:33:34 +00001468 } else {
1469 bool NeedsNegOutL = LHS->getOpcode() == ISD::OR;
Matthias Braun327bca72016-01-23 06:49:29 +00001470 assert((!NeedsNegOutL || RHS->getOpcode() != ISD::OR) &&
Matthias Braunfdef49b2016-01-23 04:05:22 +00001471 "Valid conjunction/disjunction tree");
Matthias Braun46e56392015-08-20 23:33:34 +00001472 // Order the side where we need to negate the output flags to RHS so it
1473 // gets emitted first.
1474 if (NeedsNegOutL)
1475 std::swap(LHS, RHS);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001476 }
1477
1478 // Emit RHS. If we want to negate the tree we only need to push a negate
1479 // through if we are already in a PushNegate case, otherwise we can negate
1480 // the "flags to test" afterwards.
1481 AArch64CC::CondCode RHSCC;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001482 SDValue CmpR = emitConjunctionDisjunctionTreeRec(DAG, RHS, RHSCC, Negate,
1483 CCOp, Predicate);
1484 if (NegateOpsAndResult && !Negate)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001485 RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001486 // Emit LHS. We may need to negate it.
1487 SDValue CmpL = emitConjunctionDisjunctionTreeRec(DAG, LHS, OutCC,
1488 NegateOpsAndResult, CmpR,
1489 RHSCC);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001490 // If we transformed an OR to and AND then we have to negate the result
Matthias Braunfdef49b2016-01-23 04:05:22 +00001491 // (or absorb the Negate parameter).
1492 if (NegateOpsAndResult && !Negate)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001493 OutCC = AArch64CC::getInvertedCondCode(OutCC);
1494 return CmpL;
1495}
1496
Matthias Braunfdef49b2016-01-23 04:05:22 +00001497/// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1498/// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1499/// \see emitConjunctionDisjunctionTreeRec().
1500static SDValue emitConjunctionDisjunctionTree(SelectionDAG &DAG, SDValue Val,
1501 AArch64CC::CondCode &OutCC) {
1502 bool CanNegate;
1503 if (!isConjunctionDisjunctionTree(Val, CanNegate))
1504 return SDValue();
1505
1506 return emitConjunctionDisjunctionTreeRec(DAG, Val, OutCC, false, SDValue(),
1507 AArch64CC::AL);
1508}
1509
Matthias Braunaf7d7702015-07-16 20:02:37 +00001510/// @}
1511
Tim Northover3b0846e2014-05-24 12:50:23 +00001512static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00001513 SDValue &AArch64cc, SelectionDAG &DAG,
1514 const SDLoc &dl) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001515 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1516 EVT VT = RHS.getValueType();
1517 uint64_t C = RHSC->getZExtValue();
1518 if (!isLegalArithImmed(C)) {
1519 // Constant does not fit, try adjusting it by one?
1520 switch (CC) {
1521 default:
1522 break;
1523 case ISD::SETLT:
1524 case ISD::SETGE:
1525 if ((VT == MVT::i32 && C != 0x80000000 &&
1526 isLegalArithImmed((uint32_t)(C - 1))) ||
1527 (VT == MVT::i64 && C != 0x80000000ULL &&
1528 isLegalArithImmed(C - 1ULL))) {
1529 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1530 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001531 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001532 }
1533 break;
1534 case ISD::SETULT:
1535 case ISD::SETUGE:
1536 if ((VT == MVT::i32 && C != 0 &&
1537 isLegalArithImmed((uint32_t)(C - 1))) ||
1538 (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1539 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1540 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001541 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001542 }
1543 break;
1544 case ISD::SETLE:
1545 case ISD::SETGT:
Oliver Stannard269a275c2014-11-03 15:28:40 +00001546 if ((VT == MVT::i32 && C != INT32_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001547 isLegalArithImmed((uint32_t)(C + 1))) ||
Oliver Stannard269a275c2014-11-03 15:28:40 +00001548 (VT == MVT::i64 && C != INT64_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001549 isLegalArithImmed(C + 1ULL))) {
1550 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1551 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001552 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001553 }
1554 break;
1555 case ISD::SETULE:
1556 case ISD::SETUGT:
Oliver Stannard269a275c2014-11-03 15:28:40 +00001557 if ((VT == MVT::i32 && C != UINT32_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001558 isLegalArithImmed((uint32_t)(C + 1))) ||
Oliver Stannard269a275c2014-11-03 15:28:40 +00001559 (VT == MVT::i64 && C != UINT64_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001560 isLegalArithImmed(C + 1ULL))) {
1561 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1562 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001563 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001564 }
1565 break;
1566 }
1567 }
1568 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001569 SDValue Cmp;
1570 AArch64CC::CondCode AArch64CC;
David Xuee978202014-08-28 04:59:53 +00001571 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001572 const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
1573
1574 // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
1575 // For the i8 operand, the largest immediate is 255, so this can be easily
1576 // encoded in the compare instruction. For the i16 operand, however, the
1577 // largest immediate cannot be encoded in the compare.
1578 // Therefore, use a sign extending load and cmn to avoid materializing the
1579 // -1 constant. For example,
1580 // movz w1, #65535
1581 // ldrh w0, [x0, #0]
1582 // cmp w0, w1
1583 // >
1584 // ldrsh w0, [x0, #0]
1585 // cmn w0, #1
1586 // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
1587 // if and only if (sext LHS) == (sext RHS). The checks are in place to
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001588 // ensure both the LHS and RHS are truly zero extended and to make sure the
Matthias Braunaf7d7702015-07-16 20:02:37 +00001589 // transformation is profitable.
1590 if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
1591 cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
1592 cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
1593 LHS.getNode()->hasNUsesOfValue(1, 0)) {
1594 int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
1595 if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
1596 SDValue SExt =
1597 DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
1598 DAG.getValueType(MVT::i16));
1599 Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
1600 RHS.getValueType()),
1601 CC, dl, DAG);
1602 AArch64CC = changeIntCCToAArch64CC(CC);
1603 }
1604 }
1605
1606 if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
1607 if ((Cmp = emitConjunctionDisjunctionTree(DAG, LHS, AArch64CC))) {
1608 if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
1609 AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
David Xuee978202014-08-28 04:59:53 +00001610 }
1611 }
1612 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001613
1614 if (!Cmp) {
1615 Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
1616 AArch64CC = changeIntCCToAArch64CC(CC);
1617 }
1618 AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
Tim Northover3b0846e2014-05-24 12:50:23 +00001619 return Cmp;
1620}
1621
1622static std::pair<SDValue, SDValue>
1623getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
1624 assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
1625 "Unsupported value type");
1626 SDValue Value, Overflow;
1627 SDLoc DL(Op);
1628 SDValue LHS = Op.getOperand(0);
1629 SDValue RHS = Op.getOperand(1);
1630 unsigned Opc = 0;
1631 switch (Op.getOpcode()) {
1632 default:
1633 llvm_unreachable("Unknown overflow instruction!");
1634 case ISD::SADDO:
1635 Opc = AArch64ISD::ADDS;
1636 CC = AArch64CC::VS;
1637 break;
1638 case ISD::UADDO:
1639 Opc = AArch64ISD::ADDS;
1640 CC = AArch64CC::HS;
1641 break;
1642 case ISD::SSUBO:
1643 Opc = AArch64ISD::SUBS;
1644 CC = AArch64CC::VS;
1645 break;
1646 case ISD::USUBO:
1647 Opc = AArch64ISD::SUBS;
1648 CC = AArch64CC::LO;
1649 break;
1650 // Multiply needs a little bit extra work.
1651 case ISD::SMULO:
1652 case ISD::UMULO: {
1653 CC = AArch64CC::NE;
David Blaikie186d2cb2015-03-24 16:24:01 +00001654 bool IsSigned = Op.getOpcode() == ISD::SMULO;
Tim Northover3b0846e2014-05-24 12:50:23 +00001655 if (Op.getValueType() == MVT::i32) {
1656 unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1657 // For a 32 bit multiply with overflow check we want the instruction
1658 // selector to generate a widening multiply (SMADDL/UMADDL). For that we
1659 // need to generate the following pattern:
1660 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
1661 LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
1662 RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
1663 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1664 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001665 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001666 // On AArch64 the upper 32 bits are always zero extended for a 32 bit
1667 // operation. We need to clear out the upper 32 bits, because we used a
1668 // widening multiply that wrote all 64 bits. In the end this should be a
1669 // noop.
1670 Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
1671 if (IsSigned) {
1672 // The signed overflow check requires more than just a simple check for
1673 // any bit set in the upper 32 bits of the result. These bits could be
1674 // just the sign bits of a negative number. To perform the overflow
1675 // check we have to arithmetic shift right the 32nd bit of the result by
1676 // 31 bits. Then we compare the result to the upper 32 bits.
1677 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001678 DAG.getConstant(32, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001679 UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
1680 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001681 DAG.getConstant(31, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001682 // It is important that LowerBits is last, otherwise the arithmetic
1683 // shift will not be folded into the compare (SUBS).
1684 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
1685 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1686 .getValue(1);
1687 } else {
1688 // The overflow check for unsigned multiply is easy. We only need to
1689 // check if any of the upper 32 bits are set. This can be done with a
1690 // CMP (shifted register). For that we need to generate the following
1691 // pattern:
1692 // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
1693 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001694 DAG.getConstant(32, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001695 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1696 Overflow =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001697 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1698 DAG.getConstant(0, DL, MVT::i64),
Tim Northover3b0846e2014-05-24 12:50:23 +00001699 UpperBits).getValue(1);
1700 }
1701 break;
1702 }
1703 assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
1704 // For the 64 bit multiply
1705 Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1706 if (IsSigned) {
1707 SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
1708 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001709 DAG.getConstant(63, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001710 // It is important that LowerBits is last, otherwise the arithmetic
1711 // shift will not be folded into the compare (SUBS).
1712 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1713 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1714 .getValue(1);
1715 } else {
1716 SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
1717 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1718 Overflow =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001719 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1720 DAG.getConstant(0, DL, MVT::i64),
Tim Northover3b0846e2014-05-24 12:50:23 +00001721 UpperBits).getValue(1);
1722 }
1723 break;
1724 }
1725 } // switch (...)
1726
1727 if (Opc) {
1728 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
1729
1730 // Emit the AArch64 operation with overflow check.
1731 Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
1732 Overflow = Value.getValue(1);
1733 }
1734 return std::make_pair(Value, Overflow);
1735}
1736
1737SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
1738 RTLIB::Libcall Call) const {
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00001739 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
Craig Topper8fe40e02015-10-22 17:05:00 +00001740 return makeLibCall(DAG, Call, MVT::f128, Ops, false, SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00001741}
1742
1743static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
1744 SDValue Sel = Op.getOperand(0);
1745 SDValue Other = Op.getOperand(1);
1746
1747 // If neither operand is a SELECT_CC, give up.
1748 if (Sel.getOpcode() != ISD::SELECT_CC)
1749 std::swap(Sel, Other);
1750 if (Sel.getOpcode() != ISD::SELECT_CC)
1751 return Op;
1752
1753 // The folding we want to perform is:
1754 // (xor x, (select_cc a, b, cc, 0, -1) )
1755 // -->
1756 // (csel x, (xor x, -1), cc ...)
1757 //
1758 // The latter will get matched to a CSINV instruction.
1759
1760 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
1761 SDValue LHS = Sel.getOperand(0);
1762 SDValue RHS = Sel.getOperand(1);
1763 SDValue TVal = Sel.getOperand(2);
1764 SDValue FVal = Sel.getOperand(3);
1765 SDLoc dl(Sel);
1766
1767 // FIXME: This could be generalized to non-integer comparisons.
1768 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
1769 return Op;
1770
1771 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
1772 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
1773
Eric Christopher572e03a2015-06-19 01:53:21 +00001774 // The values aren't constants, this isn't the pattern we're looking for.
Tim Northover3b0846e2014-05-24 12:50:23 +00001775 if (!CFVal || !CTVal)
1776 return Op;
1777
1778 // We can commute the SELECT_CC by inverting the condition. This
1779 // might be needed to make this fit into a CSINV pattern.
1780 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
1781 std::swap(TVal, FVal);
1782 std::swap(CTVal, CFVal);
1783 CC = ISD::getSetCCInverse(CC, true);
1784 }
1785
1786 // If the constants line up, perform the transform!
1787 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
1788 SDValue CCVal;
1789 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
1790
1791 FVal = Other;
1792 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001793 DAG.getConstant(-1ULL, dl, Other.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00001794
1795 return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
1796 CCVal, Cmp);
1797 }
1798
1799 return Op;
1800}
1801
1802static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
1803 EVT VT = Op.getValueType();
1804
1805 // Let legalize expand this if it isn't a legal type yet.
1806 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
1807 return SDValue();
1808
1809 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
1810
1811 unsigned Opc;
1812 bool ExtraOp = false;
1813 switch (Op.getOpcode()) {
1814 default:
Craig Topper2a30d782014-06-18 05:05:13 +00001815 llvm_unreachable("Invalid code");
Tim Northover3b0846e2014-05-24 12:50:23 +00001816 case ISD::ADDC:
1817 Opc = AArch64ISD::ADDS;
1818 break;
1819 case ISD::SUBC:
1820 Opc = AArch64ISD::SUBS;
1821 break;
1822 case ISD::ADDE:
1823 Opc = AArch64ISD::ADCS;
1824 ExtraOp = true;
1825 break;
1826 case ISD::SUBE:
1827 Opc = AArch64ISD::SBCS;
1828 ExtraOp = true;
1829 break;
1830 }
1831
1832 if (!ExtraOp)
1833 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
1834 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
1835 Op.getOperand(2));
1836}
1837
1838static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
1839 // Let legalize expand this if it isn't a legal type yet.
1840 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
1841 return SDValue();
1842
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001843 SDLoc dl(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00001844 AArch64CC::CondCode CC;
1845 // The actual operation that sets the overflow or carry flag.
1846 SDValue Value, Overflow;
1847 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
1848
1849 // We use 0 and 1 as false and true values.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001850 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
1851 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00001852
1853 // We use an inverted condition, because the conditional select is inverted
1854 // too. This will allow it to be selected to a single instruction:
1855 // CSINC Wd, WZR, WZR, invert(cond).
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001856 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
1857 Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
Tim Northover3b0846e2014-05-24 12:50:23 +00001858 CCVal, Overflow);
1859
1860 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001861 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
Tim Northover3b0846e2014-05-24 12:50:23 +00001862}
1863
1864// Prefetch operands are:
1865// 1: Address to prefetch
1866// 2: bool isWrite
1867// 3: int locality (0 = no locality ... 3 = extreme locality)
1868// 4: bool isDataCache
1869static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
1870 SDLoc DL(Op);
1871 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
1872 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
Yi Konge56de692014-08-05 12:46:47 +00001873 unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00001874
1875 bool IsStream = !Locality;
1876 // When the locality number is set
1877 if (Locality) {
1878 // The front-end should have filtered out the out-of-range values
1879 assert(Locality <= 3 && "Prefetch locality out-of-range");
1880 // The locality degree is the opposite of the cache speed.
1881 // Put the number the other way around.
1882 // The encoding starts at 0 for level 1
1883 Locality = 3 - Locality;
1884 }
1885
1886 // built the mask value encoding the expected behavior.
1887 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit
Yi Konge56de692014-08-05 12:46:47 +00001888 (!IsData << 3) | // IsDataCache bit
Tim Northover3b0846e2014-05-24 12:50:23 +00001889 (Locality << 1) | // Cache level bits
1890 (unsigned)IsStream; // Stream bit
1891 return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001892 DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00001893}
1894
1895SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
1896 SelectionDAG &DAG) const {
1897 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
1898
1899 RTLIB::Libcall LC;
1900 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
1901
1902 return LowerF128Call(Op, DAG, LC);
1903}
1904
1905SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
1906 SelectionDAG &DAG) const {
1907 if (Op.getOperand(0).getValueType() != MVT::f128) {
1908 // It's legal except when f128 is involved
1909 return Op;
1910 }
1911
1912 RTLIB::Libcall LC;
1913 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
1914
1915 // FP_ROUND node has a second operand indicating whether it is known to be
1916 // precise. That doesn't take part in the LibCall so we can't directly use
1917 // LowerF128Call.
1918 SDValue SrcVal = Op.getOperand(0);
Craig Topper8fe40e02015-10-22 17:05:00 +00001919 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
1920 SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00001921}
1922
1923static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
1924 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1925 // Any additional optimization in this function should be recorded
1926 // in the cost tables.
1927 EVT InVT = Op.getOperand(0).getValueType();
1928 EVT VT = Op.getValueType();
Pirama Arumuga Nainar1317d5f2015-12-10 17:16:49 +00001929 unsigned NumElts = InVT.getVectorNumElements();
1930
1931 // f16 vectors are promoted to f32 before a conversion.
1932 if (InVT.getVectorElementType() == MVT::f16) {
1933 MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
1934 SDLoc dl(Op);
1935 return DAG.getNode(
1936 Op.getOpcode(), dl, Op.getValueType(),
1937 DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
1938 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001939
Tim Northoverdbecc3b2014-06-15 09:27:15 +00001940 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001941 SDLoc dl(Op);
1942 SDValue Cv =
1943 DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
1944 Op.getOperand(0));
1945 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
Tim Northoverdbecc3b2014-06-15 09:27:15 +00001946 }
1947
1948 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001949 SDLoc dl(Op);
Oliver Stannard89d15422014-08-27 16:16:04 +00001950 MVT ExtVT =
1951 MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
1952 VT.getVectorNumElements());
1953 SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
Tim Northover3b0846e2014-05-24 12:50:23 +00001954 return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
1955 }
1956
1957 // Type changing conversions are illegal.
Tim Northoverdbecc3b2014-06-15 09:27:15 +00001958 return Op;
Tim Northover3b0846e2014-05-24 12:50:23 +00001959}
1960
1961SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
1962 SelectionDAG &DAG) const {
1963 if (Op.getOperand(0).getValueType().isVector())
1964 return LowerVectorFP_TO_INT(Op, DAG);
1965
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00001966 // f16 conversions are promoted to f32.
1967 if (Op.getOperand(0).getValueType() == MVT::f16) {
1968 SDLoc dl(Op);
1969 return DAG.getNode(
1970 Op.getOpcode(), dl, Op.getValueType(),
1971 DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
1972 }
1973
Tim Northover3b0846e2014-05-24 12:50:23 +00001974 if (Op.getOperand(0).getValueType() != MVT::f128) {
1975 // It's legal except when f128 is involved
1976 return Op;
1977 }
1978
1979 RTLIB::Libcall LC;
1980 if (Op.getOpcode() == ISD::FP_TO_SINT)
1981 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
1982 else
1983 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
1984
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00001985 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
Craig Topper8fe40e02015-10-22 17:05:00 +00001986 return makeLibCall(DAG, LC, Op.getValueType(), Ops, false, SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00001987}
1988
1989static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
1990 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1991 // Any additional optimization in this function should be recorded
1992 // in the cost tables.
1993 EVT VT = Op.getValueType();
1994 SDLoc dl(Op);
1995 SDValue In = Op.getOperand(0);
1996 EVT InVT = In.getValueType();
1997
Tim Northoveref0d7602014-06-15 09:27:06 +00001998 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
1999 MVT CastVT =
2000 MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
2001 InVT.getVectorNumElements());
2002 In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002003 return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
Tim Northover3b0846e2014-05-24 12:50:23 +00002004 }
2005
Tim Northoveref0d7602014-06-15 09:27:06 +00002006 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2007 unsigned CastOpc =
2008 Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2009 EVT CastVT = VT.changeVectorElementTypeToInteger();
2010 In = DAG.getNode(CastOpc, dl, CastVT, In);
2011 return DAG.getNode(Op.getOpcode(), dl, VT, In);
Tim Northover3b0846e2014-05-24 12:50:23 +00002012 }
2013
Tim Northoveref0d7602014-06-15 09:27:06 +00002014 return Op;
Tim Northover3b0846e2014-05-24 12:50:23 +00002015}
2016
2017SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
2018 SelectionDAG &DAG) const {
2019 if (Op.getValueType().isVector())
2020 return LowerVectorINT_TO_FP(Op, DAG);
2021
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00002022 // f16 conversions are promoted to f32.
2023 if (Op.getValueType() == MVT::f16) {
2024 SDLoc dl(Op);
2025 return DAG.getNode(
2026 ISD::FP_ROUND, dl, MVT::f16,
2027 DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002028 DAG.getIntPtrConstant(0, dl));
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00002029 }
2030
Tim Northover3b0846e2014-05-24 12:50:23 +00002031 // i128 conversions are libcalls.
2032 if (Op.getOperand(0).getValueType() == MVT::i128)
2033 return SDValue();
2034
2035 // Other conversions are legal, unless it's to the completely software-based
2036 // fp128.
2037 if (Op.getValueType() != MVT::f128)
2038 return Op;
2039
2040 RTLIB::Libcall LC;
2041 if (Op.getOpcode() == ISD::SINT_TO_FP)
2042 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2043 else
2044 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2045
2046 return LowerF128Call(Op, DAG, LC);
2047}
2048
2049SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
2050 SelectionDAG &DAG) const {
2051 // For iOS, we want to call an alternative entry point: __sincos_stret,
2052 // which returns the values in two S / D registers.
2053 SDLoc dl(Op);
2054 SDValue Arg = Op.getOperand(0);
2055 EVT ArgVT = Arg.getValueType();
2056 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2057
2058 ArgListTy Args;
2059 ArgListEntry Entry;
2060
2061 Entry.Node = Arg;
2062 Entry.Ty = ArgTy;
2063 Entry.isSExt = false;
2064 Entry.isZExt = false;
2065 Args.push_back(Entry);
2066
2067 const char *LibcallName =
2068 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
Mehdi Amini44ede332015-07-09 02:09:04 +00002069 SDValue Callee =
2070 DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00002071
Reid Kleckner343c3952014-11-20 23:51:47 +00002072 StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
Tim Northover3b0846e2014-05-24 12:50:23 +00002073 TargetLowering::CallLoweringInfo CLI(DAG);
2074 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
Krzysztof Parzyszeke116d5002016-06-22 12:54:25 +00002075 .setCallee(CallingConv::Fast, RetTy, Callee, std::move(Args));
Tim Northover3b0846e2014-05-24 12:50:23 +00002076
2077 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2078 return CallResult.first;
2079}
2080
Tim Northoverf8bfe212014-07-18 13:07:05 +00002081static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
2082 if (Op.getValueType() != MVT::f16)
2083 return SDValue();
2084
2085 assert(Op.getOperand(0).getValueType() == MVT::i16);
2086 SDLoc DL(Op);
2087
2088 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
2089 Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
2090 return SDValue(
2091 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002092 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
Tim Northoverf8bfe212014-07-18 13:07:05 +00002093 0);
2094}
2095
Chad Rosierd9d0f862014-10-08 02:31:24 +00002096static EVT getExtensionTo64Bits(const EVT &OrigVT) {
2097 if (OrigVT.getSizeInBits() >= 64)
2098 return OrigVT;
2099
2100 assert(OrigVT.isSimple() && "Expecting a simple value type");
2101
2102 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
2103 switch (OrigSimpleTy) {
2104 default: llvm_unreachable("Unexpected Vector Type");
2105 case MVT::v2i8:
2106 case MVT::v2i16:
2107 return MVT::v2i32;
2108 case MVT::v4i8:
2109 return MVT::v4i16;
2110 }
2111}
2112
2113static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2114 const EVT &OrigTy,
2115 const EVT &ExtTy,
2116 unsigned ExtOpcode) {
2117 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2118 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2119 // 64-bits we need to insert a new extension so that it will be 64-bits.
2120 assert(ExtTy.is128BitVector() && "Unexpected extension size");
2121 if (OrigTy.getSizeInBits() >= 64)
2122 return N;
2123
2124 // Must extend size to at least 64 bits to be used as an operand for VMULL.
2125 EVT NewVT = getExtensionTo64Bits(OrigTy);
2126
2127 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2128}
2129
2130static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2131 bool isSigned) {
2132 EVT VT = N->getValueType(0);
2133
2134 if (N->getOpcode() != ISD::BUILD_VECTOR)
2135 return false;
2136
Pete Cooper3af9a252015-06-26 18:17:36 +00002137 for (const SDValue &Elt : N->op_values()) {
Chad Rosierd9d0f862014-10-08 02:31:24 +00002138 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
Sanjay Patel1ed771f2016-09-14 16:37:15 +00002139 unsigned EltSize = VT.getScalarSizeInBits();
Chad Rosierd9d0f862014-10-08 02:31:24 +00002140 unsigned HalfSize = EltSize / 2;
2141 if (isSigned) {
2142 if (!isIntN(HalfSize, C->getSExtValue()))
2143 return false;
2144 } else {
2145 if (!isUIntN(HalfSize, C->getZExtValue()))
2146 return false;
2147 }
2148 continue;
2149 }
2150 return false;
2151 }
2152
2153 return true;
2154}
2155
2156static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2157 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2158 return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2159 N->getOperand(0)->getValueType(0),
2160 N->getValueType(0),
2161 N->getOpcode());
2162
2163 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2164 EVT VT = N->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002165 SDLoc dl(N);
Sanjay Patel1ed771f2016-09-14 16:37:15 +00002166 unsigned EltSize = VT.getScalarSizeInBits() / 2;
Chad Rosierd9d0f862014-10-08 02:31:24 +00002167 unsigned NumElts = VT.getVectorNumElements();
2168 MVT TruncVT = MVT::getIntegerVT(EltSize);
2169 SmallVector<SDValue, 8> Ops;
2170 for (unsigned i = 0; i != NumElts; ++i) {
2171 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2172 const APInt &CInt = C->getAPIntValue();
2173 // Element types smaller than 32 bits are not legal, so use i32 elements.
2174 // The values are implicitly truncated so sext vs. zext doesn't matter.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002175 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
Chad Rosierd9d0f862014-10-08 02:31:24 +00002176 }
Ahmed Bougacha128f8732016-04-26 21:15:30 +00002177 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002178}
2179
2180static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
2181 if (N->getOpcode() == ISD::SIGN_EXTEND)
2182 return true;
2183 if (isExtendedBUILD_VECTOR(N, DAG, true))
2184 return true;
2185 return false;
2186}
2187
2188static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
2189 if (N->getOpcode() == ISD::ZERO_EXTEND)
2190 return true;
2191 if (isExtendedBUILD_VECTOR(N, DAG, false))
2192 return true;
2193 return false;
2194}
2195
2196static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2197 unsigned Opcode = N->getOpcode();
2198 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2199 SDNode *N0 = N->getOperand(0).getNode();
2200 SDNode *N1 = N->getOperand(1).getNode();
2201 return N0->hasOneUse() && N1->hasOneUse() &&
2202 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2203 }
2204 return false;
2205}
2206
2207static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2208 unsigned Opcode = N->getOpcode();
2209 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2210 SDNode *N0 = N->getOperand(0).getNode();
2211 SDNode *N1 = N->getOperand(1).getNode();
2212 return N0->hasOneUse() && N1->hasOneUse() &&
2213 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2214 }
2215 return false;
2216}
2217
2218static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2219 // Multiplications are only custom-lowered for 128-bit vectors so that
2220 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
2221 EVT VT = Op.getValueType();
2222 assert(VT.is128BitVector() && VT.isInteger() &&
2223 "unexpected type for custom-lowering ISD::MUL");
2224 SDNode *N0 = Op.getOperand(0).getNode();
2225 SDNode *N1 = Op.getOperand(1).getNode();
2226 unsigned NewOpc = 0;
2227 bool isMLA = false;
2228 bool isN0SExt = isSignExtended(N0, DAG);
2229 bool isN1SExt = isSignExtended(N1, DAG);
2230 if (isN0SExt && isN1SExt)
2231 NewOpc = AArch64ISD::SMULL;
2232 else {
2233 bool isN0ZExt = isZeroExtended(N0, DAG);
2234 bool isN1ZExt = isZeroExtended(N1, DAG);
2235 if (isN0ZExt && isN1ZExt)
2236 NewOpc = AArch64ISD::UMULL;
2237 else if (isN1SExt || isN1ZExt) {
2238 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2239 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2240 if (isN1SExt && isAddSubSExt(N0, DAG)) {
2241 NewOpc = AArch64ISD::SMULL;
2242 isMLA = true;
2243 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2244 NewOpc = AArch64ISD::UMULL;
2245 isMLA = true;
2246 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2247 std::swap(N0, N1);
2248 NewOpc = AArch64ISD::UMULL;
2249 isMLA = true;
2250 }
2251 }
2252
2253 if (!NewOpc) {
2254 if (VT == MVT::v2i64)
2255 // Fall through to expand this. It is not legal.
2256 return SDValue();
2257 else
2258 // Other vector multiplications are legal.
2259 return Op;
2260 }
2261 }
2262
2263 // Legalize to a S/UMULL instruction
2264 SDLoc DL(Op);
2265 SDValue Op0;
2266 SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2267 if (!isMLA) {
2268 Op0 = skipExtensionForVectorMULL(N0, DAG);
2269 assert(Op0.getValueType().is64BitVector() &&
2270 Op1.getValueType().is64BitVector() &&
2271 "unexpected types for extended operands to VMULL");
2272 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2273 }
2274 // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2275 // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2276 // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2277 SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2278 SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2279 EVT Op1VT = Op1.getValueType();
2280 return DAG.getNode(N0->getOpcode(), DL, VT,
2281 DAG.getNode(NewOpc, DL, VT,
2282 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2283 DAG.getNode(NewOpc, DL, VT,
2284 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2285}
Tim Northoverf8bfe212014-07-18 13:07:05 +00002286
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002287SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2288 SelectionDAG &DAG) const {
2289 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2290 SDLoc dl(Op);
2291 switch (IntNo) {
2292 default: return SDValue(); // Don't custom lower most intrinsics.
Marcin Koscielnicki3fdc2572016-04-19 20:51:05 +00002293 case Intrinsic::thread_pointer: {
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002294 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2295 return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
2296 }
Silviu Barangadb1ddb32015-08-26 11:11:14 +00002297 case Intrinsic::aarch64_neon_smax:
2298 return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
2299 Op.getOperand(1), Op.getOperand(2));
2300 case Intrinsic::aarch64_neon_umax:
2301 return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
2302 Op.getOperand(1), Op.getOperand(2));
2303 case Intrinsic::aarch64_neon_smin:
2304 return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
2305 Op.getOperand(1), Op.getOperand(2));
2306 case Intrinsic::aarch64_neon_umin:
2307 return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
2308 Op.getOperand(1), Op.getOperand(2));
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002309 }
2310}
2311
Tim Northover3b0846e2014-05-24 12:50:23 +00002312SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
2313 SelectionDAG &DAG) const {
2314 switch (Op.getOpcode()) {
2315 default:
2316 llvm_unreachable("unimplemented operand");
2317 return SDValue();
Tim Northoverf8bfe212014-07-18 13:07:05 +00002318 case ISD::BITCAST:
2319 return LowerBITCAST(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002320 case ISD::GlobalAddress:
2321 return LowerGlobalAddress(Op, DAG);
2322 case ISD::GlobalTLSAddress:
2323 return LowerGlobalTLSAddress(Op, DAG);
2324 case ISD::SETCC:
2325 return LowerSETCC(Op, DAG);
2326 case ISD::BR_CC:
2327 return LowerBR_CC(Op, DAG);
2328 case ISD::SELECT:
2329 return LowerSELECT(Op, DAG);
2330 case ISD::SELECT_CC:
2331 return LowerSELECT_CC(Op, DAG);
2332 case ISD::JumpTable:
2333 return LowerJumpTable(Op, DAG);
2334 case ISD::ConstantPool:
2335 return LowerConstantPool(Op, DAG);
2336 case ISD::BlockAddress:
2337 return LowerBlockAddress(Op, DAG);
2338 case ISD::VASTART:
2339 return LowerVASTART(Op, DAG);
2340 case ISD::VACOPY:
2341 return LowerVACOPY(Op, DAG);
2342 case ISD::VAARG:
2343 return LowerVAARG(Op, DAG);
2344 case ISD::ADDC:
2345 case ISD::ADDE:
2346 case ISD::SUBC:
2347 case ISD::SUBE:
2348 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
2349 case ISD::SADDO:
2350 case ISD::UADDO:
2351 case ISD::SSUBO:
2352 case ISD::USUBO:
2353 case ISD::SMULO:
2354 case ISD::UMULO:
2355 return LowerXALUO(Op, DAG);
2356 case ISD::FADD:
2357 return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
2358 case ISD::FSUB:
2359 return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
2360 case ISD::FMUL:
2361 return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
2362 case ISD::FDIV:
2363 return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
2364 case ISD::FP_ROUND:
2365 return LowerFP_ROUND(Op, DAG);
2366 case ISD::FP_EXTEND:
2367 return LowerFP_EXTEND(Op, DAG);
2368 case ISD::FRAMEADDR:
2369 return LowerFRAMEADDR(Op, DAG);
2370 case ISD::RETURNADDR:
2371 return LowerRETURNADDR(Op, DAG);
2372 case ISD::INSERT_VECTOR_ELT:
2373 return LowerINSERT_VECTOR_ELT(Op, DAG);
2374 case ISD::EXTRACT_VECTOR_ELT:
2375 return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2376 case ISD::BUILD_VECTOR:
2377 return LowerBUILD_VECTOR(Op, DAG);
2378 case ISD::VECTOR_SHUFFLE:
2379 return LowerVECTOR_SHUFFLE(Op, DAG);
2380 case ISD::EXTRACT_SUBVECTOR:
2381 return LowerEXTRACT_SUBVECTOR(Op, DAG);
2382 case ISD::SRA:
2383 case ISD::SRL:
2384 case ISD::SHL:
2385 return LowerVectorSRA_SRL_SHL(Op, DAG);
2386 case ISD::SHL_PARTS:
2387 return LowerShiftLeftParts(Op, DAG);
2388 case ISD::SRL_PARTS:
2389 case ISD::SRA_PARTS:
2390 return LowerShiftRightParts(Op, DAG);
2391 case ISD::CTPOP:
2392 return LowerCTPOP(Op, DAG);
2393 case ISD::FCOPYSIGN:
2394 return LowerFCOPYSIGN(Op, DAG);
2395 case ISD::AND:
Balaram Makamd4acd7e2016-07-05 20:24:05 +00002396 return LowerVectorAND(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002397 case ISD::OR:
Balaram Makamd4acd7e2016-07-05 20:24:05 +00002398 return LowerVectorOR(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002399 case ISD::XOR:
2400 return LowerXOR(Op, DAG);
2401 case ISD::PREFETCH:
2402 return LowerPREFETCH(Op, DAG);
2403 case ISD::SINT_TO_FP:
2404 case ISD::UINT_TO_FP:
2405 return LowerINT_TO_FP(Op, DAG);
2406 case ISD::FP_TO_SINT:
2407 case ISD::FP_TO_UINT:
2408 return LowerFP_TO_INT(Op, DAG);
2409 case ISD::FSINCOS:
2410 return LowerFSINCOS(Op, DAG);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002411 case ISD::MUL:
2412 return LowerMUL(Op, DAG);
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002413 case ISD::INTRINSIC_WO_CHAIN:
2414 return LowerINTRINSIC_WO_CHAIN(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002415 }
2416}
2417
Tim Northover3b0846e2014-05-24 12:50:23 +00002418//===----------------------------------------------------------------------===//
2419// Calling Convention Implementation
2420//===----------------------------------------------------------------------===//
2421
2422#include "AArch64GenCallingConv.inc"
2423
Robin Morisset039781e2014-08-29 21:53:01 +00002424/// Selects the correct CCAssignFn for a given CallingConvention value.
Tim Northover3b0846e2014-05-24 12:50:23 +00002425CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2426 bool IsVarArg) const {
2427 switch (CC) {
2428 default:
2429 llvm_unreachable("Unsupported calling convention.");
2430 case CallingConv::WebKit_JS:
2431 return CC_AArch64_WebKit_JS;
Greg Fitzgeraldfa78d082015-01-19 17:40:05 +00002432 case CallingConv::GHC:
2433 return CC_AArch64_GHC;
Tim Northover3b0846e2014-05-24 12:50:23 +00002434 case CallingConv::C:
2435 case CallingConv::Fast:
Roman Levenstein2792b3f2016-03-10 04:35:09 +00002436 case CallingConv::PreserveMost:
Manman Ren2828c572016-03-18 23:38:49 +00002437 case CallingConv::CXX_FAST_TLS:
Manman Ren66b54e92016-08-26 19:28:17 +00002438 case CallingConv::Swift:
Tim Northover3b0846e2014-05-24 12:50:23 +00002439 if (!Subtarget->isTargetDarwin())
2440 return CC_AArch64_AAPCS;
2441 return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
2442 }
2443}
2444
Tim Northover406024a2016-08-10 21:44:01 +00002445CCAssignFn *
2446AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const {
2447 return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
2448 : RetCC_AArch64_AAPCS;
2449}
2450
Tim Northover3b0846e2014-05-24 12:50:23 +00002451SDValue AArch64TargetLowering::LowerFormalArguments(
2452 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00002453 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2454 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00002455 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braun941a7052016-07-28 18:40:00 +00002456 MachineFrameInfo &MFI = MF.getFrameInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00002457
2458 // Assign locations to all of the incoming arguments.
2459 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002460 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2461 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002462
2463 // At this point, Ins[].VT may already be promoted to i32. To correctly
2464 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2465 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2466 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
2467 // we use a special version of AnalyzeFormalArguments to pass in ValVT and
2468 // LocVT.
2469 unsigned NumArgs = Ins.size();
2470 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2471 unsigned CurArgIdx = 0;
2472 for (unsigned i = 0; i != NumArgs; ++i) {
2473 MVT ValVT = Ins[i].VT;
Andrew Trick05938a52015-02-16 18:10:47 +00002474 if (Ins[i].isOrigArg()) {
2475 std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
2476 CurArgIdx = Ins[i].getOrigArgIndex();
Tim Northover3b0846e2014-05-24 12:50:23 +00002477
Andrew Trick05938a52015-02-16 18:10:47 +00002478 // Get type of the original argument.
Mehdi Amini44ede332015-07-09 02:09:04 +00002479 EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
2480 /*AllowUnknown*/ true);
Andrew Trick05938a52015-02-16 18:10:47 +00002481 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
2482 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2483 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2484 ValVT = MVT::i8;
2485 else if (ActualMVT == MVT::i16)
2486 ValVT = MVT::i16;
2487 }
Tim Northover3b0846e2014-05-24 12:50:23 +00002488 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2489 bool Res =
Tim Northover47e003c2014-05-26 17:21:53 +00002490 AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00002491 assert(!Res && "Call operand has unhandled type");
2492 (void)Res;
2493 }
2494 assert(ArgLocs.size() == Ins.size());
2495 SmallVector<SDValue, 16> ArgValues;
2496 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2497 CCValAssign &VA = ArgLocs[i];
2498
2499 if (Ins[i].Flags.isByVal()) {
2500 // Byval is used for HFAs in the PCS, but the system should work in a
2501 // non-compliant manner for larger structs.
Mehdi Amini44ede332015-07-09 02:09:04 +00002502 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00002503 int Size = Ins[i].Flags.getByValSize();
2504 unsigned NumRegs = (Size + 7) / 8;
2505
2506 // FIXME: This works on big-endian for composite byvals, which are the common
2507 // case. It should also work for fundamental types too.
2508 unsigned FrameIdx =
Matthias Braun941a7052016-07-28 18:40:00 +00002509 MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
Mehdi Amini44ede332015-07-09 02:09:04 +00002510 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00002511 InVals.push_back(FrameIdxN);
2512
2513 continue;
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002514 }
Junmo Park3b8c7152016-01-05 09:36:47 +00002515
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002516 if (VA.isRegLoc()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00002517 // Arguments stored in registers.
2518 EVT RegVT = VA.getLocVT();
2519
2520 SDValue ArgValue;
2521 const TargetRegisterClass *RC;
2522
2523 if (RegVT == MVT::i32)
2524 RC = &AArch64::GPR32RegClass;
2525 else if (RegVT == MVT::i64)
2526 RC = &AArch64::GPR64RegClass;
Oliver Stannard6eda6ff2014-07-11 13:33:46 +00002527 else if (RegVT == MVT::f16)
2528 RC = &AArch64::FPR16RegClass;
Tim Northover3b0846e2014-05-24 12:50:23 +00002529 else if (RegVT == MVT::f32)
2530 RC = &AArch64::FPR32RegClass;
2531 else if (RegVT == MVT::f64 || RegVT.is64BitVector())
2532 RC = &AArch64::FPR64RegClass;
2533 else if (RegVT == MVT::f128 || RegVT.is128BitVector())
2534 RC = &AArch64::FPR128RegClass;
2535 else
2536 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2537
2538 // Transform the arguments in physical registers into virtual ones.
2539 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2540 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2541
2542 // If this is an 8, 16 or 32-bit value, it is really passed promoted
2543 // to 64 bits. Insert an assert[sz]ext to capture this, then
2544 // truncate to the right size.
2545 switch (VA.getLocInfo()) {
2546 default:
2547 llvm_unreachable("Unknown loc info!");
2548 case CCValAssign::Full:
2549 break;
2550 case CCValAssign::BCvt:
2551 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
2552 break;
Tim Northover47e003c2014-05-26 17:21:53 +00002553 case CCValAssign::AExt:
Tim Northover3b0846e2014-05-24 12:50:23 +00002554 case CCValAssign::SExt:
Tim Northover3b0846e2014-05-24 12:50:23 +00002555 case CCValAssign::ZExt:
Tim Northover47e003c2014-05-26 17:21:53 +00002556 // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
2557 // nodes after our lowering.
2558 assert(RegVT == Ins[i].VT && "incorrect register location selected");
Tim Northover3b0846e2014-05-24 12:50:23 +00002559 break;
2560 }
2561
2562 InVals.push_back(ArgValue);
2563
2564 } else { // VA.isRegLoc()
2565 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
2566 unsigned ArgOffset = VA.getLocMemOffset();
Amara Emerson82da7d02014-08-15 14:29:57 +00002567 unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
Tim Northover3b0846e2014-05-24 12:50:23 +00002568
2569 uint32_t BEAlign = 0;
Tim Northover293d4142014-12-03 17:49:26 +00002570 if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
2571 !Ins[i].Flags.isInConsecutiveRegs())
Tim Northover3b0846e2014-05-24 12:50:23 +00002572 BEAlign = 8 - ArgSize;
2573
Matthias Braun941a7052016-07-28 18:40:00 +00002574 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
Tim Northover3b0846e2014-05-24 12:50:23 +00002575
2576 // Create load nodes to retrieve arguments from the stack.
Mehdi Amini44ede332015-07-09 02:09:04 +00002577 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00002578 SDValue ArgValue;
2579
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002580 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
Tim Northover47e003c2014-05-26 17:21:53 +00002581 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002582 MVT MemVT = VA.getValVT();
2583
Tim Northover47e003c2014-05-26 17:21:53 +00002584 switch (VA.getLocInfo()) {
2585 default:
2586 break;
Tim Northover6890add2014-06-03 13:54:53 +00002587 case CCValAssign::BCvt:
2588 MemVT = VA.getLocVT();
2589 break;
Tim Northover47e003c2014-05-26 17:21:53 +00002590 case CCValAssign::SExt:
2591 ExtType = ISD::SEXTLOAD;
2592 break;
2593 case CCValAssign::ZExt:
2594 ExtType = ISD::ZEXTLOAD;
2595 break;
2596 case CCValAssign::AExt:
2597 ExtType = ISD::EXTLOAD;
2598 break;
Tim Northover3b0846e2014-05-24 12:50:23 +00002599 }
2600
Alex Lorenze40c8a22015-08-11 23:09:45 +00002601 ArgValue = DAG.getExtLoad(
2602 ExtType, DL, VA.getLocVT(), Chain, FIN,
2603 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
Justin Lebar9c375812016-07-15 18:27:10 +00002604 MemVT);
Tim Northover47e003c2014-05-26 17:21:53 +00002605
Tim Northover3b0846e2014-05-24 12:50:23 +00002606 InVals.push_back(ArgValue);
2607 }
2608 }
2609
2610 // varargs
Matthias Braundff243e2016-04-12 02:16:13 +00002611 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Tim Northover3b0846e2014-05-24 12:50:23 +00002612 if (isVarArg) {
2613 if (!Subtarget->isTargetDarwin()) {
2614 // The AAPCS variadic function ABI is identical to the non-variadic
2615 // one. As a result there may be more arguments in registers and we should
2616 // save them for future reference.
2617 saveVarArgRegisters(CCInfo, DAG, DL, Chain);
2618 }
2619
Tim Northover3b0846e2014-05-24 12:50:23 +00002620 // This will point to the next argument passed via stack.
2621 unsigned StackOffset = CCInfo.getNextStackOffset();
2622 // We currently pass all varargs at 8-byte alignment.
2623 StackOffset = ((StackOffset + 7) & ~7);
Matthias Braun941a7052016-07-28 18:40:00 +00002624 FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true));
Tim Northover3b0846e2014-05-24 12:50:23 +00002625 }
2626
Tim Northover3b0846e2014-05-24 12:50:23 +00002627 unsigned StackArgSize = CCInfo.getNextStackOffset();
2628 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2629 if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
2630 // This is a non-standard ABI so by fiat I say we're allowed to make full
2631 // use of the stack area to be popped, which must be aligned to 16 bytes in
2632 // any case:
Rui Ueyamada00f2f2016-01-14 21:06:47 +00002633 StackArgSize = alignTo(StackArgSize, 16);
Tim Northover3b0846e2014-05-24 12:50:23 +00002634
2635 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
2636 // a multiple of 16.
2637 FuncInfo->setArgumentStackToRestore(StackArgSize);
2638
2639 // This realignment carries over to the available bytes below. Our own
2640 // callers will guarantee the space is free by giving an aligned value to
2641 // CALLSEQ_START.
2642 }
2643 // Even if we're not expected to free up the space, it's useful to know how
2644 // much is there while considering tail calls (because we can reuse it).
2645 FuncInfo->setBytesInStackArgArea(StackArgSize);
2646
2647 return Chain;
2648}
2649
2650void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00002651 SelectionDAG &DAG,
2652 const SDLoc &DL,
Tim Northover3b0846e2014-05-24 12:50:23 +00002653 SDValue &Chain) const {
2654 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braun941a7052016-07-28 18:40:00 +00002655 MachineFrameInfo &MFI = MF.getFrameInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00002656 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Mehdi Amini44ede332015-07-09 02:09:04 +00002657 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00002658
2659 SmallVector<SDValue, 8> MemOps;
2660
2661 static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
2662 AArch64::X3, AArch64::X4, AArch64::X5,
2663 AArch64::X6, AArch64::X7 };
2664 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
Tim Northover3b6b7ca2015-02-21 02:11:17 +00002665 unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
Tim Northover3b0846e2014-05-24 12:50:23 +00002666
2667 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
2668 int GPRIdx = 0;
2669 if (GPRSaveSize != 0) {
Matthias Braun941a7052016-07-28 18:40:00 +00002670 GPRIdx = MFI.CreateStackObject(GPRSaveSize, 8, false);
Tim Northover3b0846e2014-05-24 12:50:23 +00002671
Mehdi Amini44ede332015-07-09 02:09:04 +00002672 SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00002673
2674 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
2675 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
2676 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
Alex Lorenze40c8a22015-08-11 23:09:45 +00002677 SDValue Store = DAG.getStore(
2678 Val.getValue(1), DL, Val, FIN,
Justin Lebar9c375812016-07-15 18:27:10 +00002679 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00002680 MemOps.push_back(Store);
Mehdi Amini44ede332015-07-09 02:09:04 +00002681 FIN =
2682 DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00002683 }
2684 }
2685 FuncInfo->setVarArgsGPRIndex(GPRIdx);
2686 FuncInfo->setVarArgsGPRSize(GPRSaveSize);
2687
2688 if (Subtarget->hasFPARMv8()) {
2689 static const MCPhysReg FPRArgRegs[] = {
2690 AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
2691 AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
2692 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
Tim Northover3b6b7ca2015-02-21 02:11:17 +00002693 unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
Tim Northover3b0846e2014-05-24 12:50:23 +00002694
2695 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
2696 int FPRIdx = 0;
2697 if (FPRSaveSize != 0) {
Matthias Braun941a7052016-07-28 18:40:00 +00002698 FPRIdx = MFI.CreateStackObject(FPRSaveSize, 16, false);
Tim Northover3b0846e2014-05-24 12:50:23 +00002699
Mehdi Amini44ede332015-07-09 02:09:04 +00002700 SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00002701
2702 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
2703 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
2704 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
2705
Alex Lorenze40c8a22015-08-11 23:09:45 +00002706 SDValue Store = DAG.getStore(
2707 Val.getValue(1), DL, Val, FIN,
Justin Lebar9c375812016-07-15 18:27:10 +00002708 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16));
Tim Northover3b0846e2014-05-24 12:50:23 +00002709 MemOps.push_back(Store);
Mehdi Amini44ede332015-07-09 02:09:04 +00002710 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
2711 DAG.getConstant(16, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00002712 }
2713 }
2714 FuncInfo->setVarArgsFPRIndex(FPRIdx);
2715 FuncInfo->setVarArgsFPRSize(FPRSaveSize);
2716 }
2717
2718 if (!MemOps.empty()) {
2719 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
2720 }
2721}
2722
2723/// LowerCallResult - Lower the result values of a call into the
2724/// appropriate copies out of appropriate physical registers.
2725SDValue AArch64TargetLowering::LowerCallResult(
2726 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00002727 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2728 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
Tim Northover3b0846e2014-05-24 12:50:23 +00002729 SDValue ThisVal) const {
2730 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
2731 ? RetCC_AArch64_WebKit_JS
2732 : RetCC_AArch64_AAPCS;
2733 // Assign locations to each value returned by this call.
2734 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002735 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2736 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002737 CCInfo.AnalyzeCallResult(Ins, RetCC);
2738
2739 // Copy all of the result registers out of their specified physreg.
2740 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2741 CCValAssign VA = RVLocs[i];
2742
2743 // Pass 'this' value directly from the argument to return value, to avoid
2744 // reg unit interference
David Majnemer5d261272016-07-20 04:13:01 +00002745 if (i == 0 && isThisReturn) {
Tim Northover3b0846e2014-05-24 12:50:23 +00002746 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
2747 "unexpected return calling convention register assignment");
2748 InVals.push_back(ThisVal);
2749 continue;
2750 }
2751
2752 SDValue Val =
2753 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2754 Chain = Val.getValue(1);
2755 InFlag = Val.getValue(2);
2756
2757 switch (VA.getLocInfo()) {
2758 default:
2759 llvm_unreachable("Unknown loc info!");
2760 case CCValAssign::Full:
2761 break;
2762 case CCValAssign::BCvt:
2763 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2764 break;
2765 }
2766
2767 InVals.push_back(Val);
2768 }
2769
2770 return Chain;
2771}
2772
Matthias Braun1af14142016-09-13 19:27:38 +00002773/// Return true if the calling convention is one that we can guarantee TCO for.
2774static bool canGuaranteeTCO(CallingConv::ID CC) {
2775 return CC == CallingConv::Fast;
2776}
2777
2778/// Return true if we might ever do TCO for calls with this calling convention.
2779static bool mayTailCallThisCC(CallingConv::ID CC) {
2780 switch (CC) {
2781 case CallingConv::C:
2782 case CallingConv::PreserveMost:
2783 case CallingConv::Swift:
2784 return true;
2785 default:
2786 return canGuaranteeTCO(CC);
2787 }
2788}
2789
Tim Northover3b0846e2014-05-24 12:50:23 +00002790bool AArch64TargetLowering::isEligibleForTailCallOptimization(
2791 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
Tim Northover3b0846e2014-05-24 12:50:23 +00002792 const SmallVectorImpl<ISD::OutputArg> &Outs,
2793 const SmallVectorImpl<SDValue> &OutVals,
2794 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
Matthias Braun1af14142016-09-13 19:27:38 +00002795 if (!mayTailCallThisCC(CalleeCC))
Tim Northover3b0846e2014-05-24 12:50:23 +00002796 return false;
2797
Matthias Braun8d414362016-03-30 22:46:04 +00002798 MachineFunction &MF = DAG.getMachineFunction();
Tim Northover3b0846e2014-05-24 12:50:23 +00002799 const Function *CallerF = MF.getFunction();
2800 CallingConv::ID CallerCC = CallerF->getCallingConv();
2801 bool CCMatch = CallerCC == CalleeCC;
2802
2803 // Byval parameters hand the function a pointer directly into the stack area
2804 // we want to reuse during a tail call. Working around this *is* possible (see
2805 // X86) but less efficient and uglier in LowerCall.
2806 for (Function::const_arg_iterator i = CallerF->arg_begin(),
2807 e = CallerF->arg_end();
2808 i != e; ++i)
2809 if (i->hasByValAttr())
2810 return false;
2811
Matthias Braun1af14142016-09-13 19:27:38 +00002812 if (getTargetMachine().Options.GuaranteedTailCallOpt)
2813 return canGuaranteeTCO(CalleeCC) && CCMatch;
Tim Northover3b0846e2014-05-24 12:50:23 +00002814
Oliver Stannard12993dd2014-08-18 12:42:15 +00002815 // Externally-defined functions with weak linkage should not be
2816 // tail-called on AArch64 when the OS does not support dynamic
2817 // pre-emption of symbols, as the AAELF spec requires normal calls
2818 // to undefined weak functions to be replaced with a NOP or jump to the
2819 // next instruction. The behaviour of branch instructions in this
2820 // situation (as used for tail calls) is implementation-defined, so we
2821 // cannot rely on the linker replacing the tail call with a return.
2822 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2823 const GlobalValue *GV = G->getGlobal();
Daniel Sandersc81f4502015-06-16 15:44:21 +00002824 const Triple &TT = getTargetMachine().getTargetTriple();
Saleem Abdulrasool67f72992015-01-03 21:35:00 +00002825 if (GV->hasExternalWeakLinkage() &&
2826 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
Oliver Stannard12993dd2014-08-18 12:42:15 +00002827 return false;
2828 }
2829
Tim Northover3b0846e2014-05-24 12:50:23 +00002830 // Now we search for cases where we can use a tail call without changing the
2831 // ABI. Sibcall is used in some places (particularly gcc) to refer to this
2832 // concept.
2833
2834 // I want anyone implementing a new calling convention to think long and hard
2835 // about this assert.
2836 assert((!isVarArg || CalleeCC == CallingConv::C) &&
2837 "Unexpected variadic calling convention");
2838
Matthias Braun8d414362016-03-30 22:46:04 +00002839 LLVMContext &C = *DAG.getContext();
Tim Northover3b0846e2014-05-24 12:50:23 +00002840 if (isVarArg && !Outs.empty()) {
2841 // At least two cases here: if caller is fastcc then we can't have any
2842 // memory arguments (we'd be expected to clean up the stack afterwards). If
2843 // caller is C then we could potentially use its argument area.
2844
2845 // FIXME: for now we take the most conservative of these in both cases:
2846 // disallow all variadic memory operands.
2847 SmallVector<CCValAssign, 16> ArgLocs;
Matthias Braun8d414362016-03-30 22:46:04 +00002848 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
Tim Northover3b0846e2014-05-24 12:50:23 +00002849
2850 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
Pete Cooper7be8f8f2015-08-03 19:04:32 +00002851 for (const CCValAssign &ArgLoc : ArgLocs)
2852 if (!ArgLoc.isRegLoc())
Tim Northover3b0846e2014-05-24 12:50:23 +00002853 return false;
2854 }
2855
Matthias Braun8d414362016-03-30 22:46:04 +00002856 // Check that the call results are passed in the same way.
2857 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
2858 CCAssignFnForCall(CalleeCC, isVarArg),
2859 CCAssignFnForCall(CallerCC, isVarArg)))
2860 return false;
Matthias Braun870c34f2016-04-04 18:56:13 +00002861 // The callee has to preserve all registers the caller needs to preserve.
Matthias Braun74a0bd32016-04-13 21:43:16 +00002862 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
2863 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
Matthias Braun870c34f2016-04-04 18:56:13 +00002864 if (!CCMatch) {
Matthias Braun74a0bd32016-04-13 21:43:16 +00002865 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2866 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
Matthias Braun870c34f2016-04-04 18:56:13 +00002867 return false;
2868 }
Tim Northover3b0846e2014-05-24 12:50:23 +00002869
2870 // Nothing more to check if the callee is taking no arguments
2871 if (Outs.empty())
2872 return true;
2873
2874 SmallVector<CCValAssign, 16> ArgLocs;
Matthias Braun8d414362016-03-30 22:46:04 +00002875 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
Tim Northover3b0846e2014-05-24 12:50:23 +00002876
2877 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2878
2879 const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2880
Matthias Braun74a0bd32016-04-13 21:43:16 +00002881 // If the stack arguments for this call do not fit into our own save area then
2882 // the call cannot be made tail.
2883 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2884 return false;
2885
Matthias Braun46b0f032016-04-14 01:10:42 +00002886 const MachineRegisterInfo &MRI = MF.getRegInfo();
2887 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
2888 return false;
Matthias Braun74a0bd32016-04-13 21:43:16 +00002889
2890 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +00002891}
2892
2893SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
2894 SelectionDAG &DAG,
Matthias Braun941a7052016-07-28 18:40:00 +00002895 MachineFrameInfo &MFI,
Tim Northover3b0846e2014-05-24 12:50:23 +00002896 int ClobberedFI) const {
2897 SmallVector<SDValue, 8> ArgChains;
Matthias Braun941a7052016-07-28 18:40:00 +00002898 int64_t FirstByte = MFI.getObjectOffset(ClobberedFI);
2899 int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1;
Tim Northover3b0846e2014-05-24 12:50:23 +00002900
2901 // Include the original chain at the beginning of the list. When this is
2902 // used by target LowerCall hooks, this helps legalize find the
2903 // CALLSEQ_BEGIN node.
2904 ArgChains.push_back(Chain);
2905
2906 // Add a chain value for each stack argument corresponding
2907 for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
2908 UE = DAG.getEntryNode().getNode()->use_end();
2909 U != UE; ++U)
2910 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
2911 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
2912 if (FI->getIndex() < 0) {
Matthias Braun941a7052016-07-28 18:40:00 +00002913 int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex());
Tim Northover3b0846e2014-05-24 12:50:23 +00002914 int64_t InLastByte = InFirstByte;
Matthias Braun941a7052016-07-28 18:40:00 +00002915 InLastByte += MFI.getObjectSize(FI->getIndex()) - 1;
Tim Northover3b0846e2014-05-24 12:50:23 +00002916
2917 if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
2918 (FirstByte <= InFirstByte && InFirstByte <= LastByte))
2919 ArgChains.push_back(SDValue(L, 1));
2920 }
2921
2922 // Build a tokenfactor for all the chains.
2923 return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
2924}
2925
2926bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
2927 bool TailCallOpt) const {
2928 return CallCC == CallingConv::Fast && TailCallOpt;
2929}
2930
Tim Northover3b0846e2014-05-24 12:50:23 +00002931/// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
2932/// and add input and output parameter nodes.
2933SDValue
2934AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
2935 SmallVectorImpl<SDValue> &InVals) const {
2936 SelectionDAG &DAG = CLI.DAG;
2937 SDLoc &DL = CLI.DL;
2938 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2939 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2940 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2941 SDValue Chain = CLI.Chain;
2942 SDValue Callee = CLI.Callee;
2943 bool &IsTailCall = CLI.IsTailCall;
2944 CallingConv::ID CallConv = CLI.CallConv;
2945 bool IsVarArg = CLI.IsVarArg;
2946
2947 MachineFunction &MF = DAG.getMachineFunction();
Tim Northover3b0846e2014-05-24 12:50:23 +00002948 bool IsThisReturn = false;
2949
2950 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2951 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2952 bool IsSibCall = false;
2953
2954 if (IsTailCall) {
2955 // Check if it's really possible to do a tail call.
2956 IsTailCall = isEligibleForTailCallOptimization(
Matthias Brauncc7fba42016-04-01 02:49:17 +00002957 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002958 if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
2959 report_fatal_error("failed to perform tail call elimination on a call "
2960 "site marked musttail");
2961
2962 // A sibling call is one where we're under the usual C ABI and not planning
2963 // to change that but can still do a tail call:
2964 if (!TailCallOpt && IsTailCall)
2965 IsSibCall = true;
2966
2967 if (IsTailCall)
2968 ++NumTailCalls;
2969 }
2970
2971 // Analyze operands of the call, assigning locations to each operand.
2972 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002973 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
2974 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002975
2976 if (IsVarArg) {
2977 // Handle fixed and variable vector arguments differently.
2978 // Variable vector arguments always go into memory.
2979 unsigned NumArgs = Outs.size();
2980
2981 for (unsigned i = 0; i != NumArgs; ++i) {
2982 MVT ArgVT = Outs[i].VT;
2983 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2984 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
2985 /*IsVarArg=*/ !Outs[i].IsFixed);
2986 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
2987 assert(!Res && "Call operand has unhandled type");
2988 (void)Res;
2989 }
2990 } else {
2991 // At this point, Outs[].VT may already be promoted to i32. To correctly
2992 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2993 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2994 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
2995 // we use a special version of AnalyzeCallOperands to pass in ValVT and
2996 // LocVT.
2997 unsigned NumArgs = Outs.size();
2998 for (unsigned i = 0; i != NumArgs; ++i) {
2999 MVT ValVT = Outs[i].VT;
3000 // Get type of the original argument.
Mehdi Amini44ede332015-07-09 02:09:04 +00003001 EVT ActualVT = getValueType(DAG.getDataLayout(),
3002 CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
Tim Northover3b0846e2014-05-24 12:50:23 +00003003 /*AllowUnknown*/ true);
3004 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
3005 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3006 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
Tim Northover3b0846e2014-05-24 12:50:23 +00003007 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
Tim Northover47e003c2014-05-26 17:21:53 +00003008 ValVT = MVT::i8;
Tim Northover3b0846e2014-05-24 12:50:23 +00003009 else if (ActualMVT == MVT::i16)
Tim Northover47e003c2014-05-26 17:21:53 +00003010 ValVT = MVT::i16;
Tim Northover3b0846e2014-05-24 12:50:23 +00003011
3012 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
Tim Northover47e003c2014-05-26 17:21:53 +00003013 bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00003014 assert(!Res && "Call operand has unhandled type");
3015 (void)Res;
3016 }
3017 }
3018
3019 // Get a count of how many bytes are to be pushed on the stack.
3020 unsigned NumBytes = CCInfo.getNextStackOffset();
3021
3022 if (IsSibCall) {
3023 // Since we're not changing the ABI to make this a tail call, the memory
3024 // operands are already available in the caller's incoming argument space.
3025 NumBytes = 0;
3026 }
3027
3028 // FPDiff is the byte offset of the call's argument area from the callee's.
3029 // Stores to callee stack arguments will be placed in FixedStackSlots offset
3030 // by this amount for a tail call. In a sibling call it must be 0 because the
3031 // caller will deallocate the entire stack and the callee still expects its
3032 // arguments to begin at SP+0. Completely unused for non-tail calls.
3033 int FPDiff = 0;
3034
3035 if (IsTailCall && !IsSibCall) {
3036 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
3037
3038 // Since callee will pop argument stack as a tail call, we must keep the
3039 // popped size 16-byte aligned.
Rui Ueyamada00f2f2016-01-14 21:06:47 +00003040 NumBytes = alignTo(NumBytes, 16);
Tim Northover3b0846e2014-05-24 12:50:23 +00003041
3042 // FPDiff will be negative if this tail call requires more space than we
3043 // would automatically have in our incoming argument space. Positive if we
3044 // can actually shrink the stack.
3045 FPDiff = NumReusableBytes - NumBytes;
3046
3047 // The stack pointer must be 16-byte aligned at all times it's used for a
3048 // memory operation, which in practice means at *all* times and in
3049 // particular across call boundaries. Therefore our own arguments started at
3050 // a 16-byte aligned SP and the delta applied for the tail call should
3051 // satisfy the same constraint.
3052 assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
3053 }
3054
3055 // Adjust the stack pointer for the new arguments...
3056 // These operations are automatically eliminated by the prolog/epilog pass
3057 if (!IsSibCall)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003058 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, DL,
3059 true),
3060 DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003061
Mehdi Amini44ede332015-07-09 02:09:04 +00003062 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
3063 getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00003064
3065 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3066 SmallVector<SDValue, 8> MemOpChains;
Mehdi Amini44ede332015-07-09 02:09:04 +00003067 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003068
3069 // Walk the register/memloc assignments, inserting copies/loads.
3070 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
3071 ++i, ++realArgIdx) {
3072 CCValAssign &VA = ArgLocs[i];
3073 SDValue Arg = OutVals[realArgIdx];
3074 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
3075
3076 // Promote the value if needed.
3077 switch (VA.getLocInfo()) {
3078 default:
3079 llvm_unreachable("Unknown loc info!");
3080 case CCValAssign::Full:
3081 break;
3082 case CCValAssign::SExt:
3083 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3084 break;
3085 case CCValAssign::ZExt:
3086 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3087 break;
3088 case CCValAssign::AExt:
Tim Northover68ae5032014-05-26 17:22:07 +00003089 if (Outs[realArgIdx].ArgVT == MVT::i1) {
3090 // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
3091 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3092 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
3093 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003094 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3095 break;
3096 case CCValAssign::BCvt:
3097 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3098 break;
3099 case CCValAssign::FPExt:
3100 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3101 break;
3102 }
3103
3104 if (VA.isRegLoc()) {
3105 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i64) {
3106 assert(VA.getLocVT() == MVT::i64 &&
3107 "unexpected calling convention register assignment");
3108 assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
3109 "unexpected use of 'returned'");
3110 IsThisReturn = true;
3111 }
3112 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3113 } else {
3114 assert(VA.isMemLoc());
3115
3116 SDValue DstAddr;
3117 MachinePointerInfo DstInfo;
3118
3119 // FIXME: This works on big-endian for composite byvals, which are the
3120 // common case. It should also work for fundamental types too.
3121 uint32_t BEAlign = 0;
3122 unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
Amara Emerson82da7d02014-08-15 14:29:57 +00003123 : VA.getValVT().getSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00003124 OpSize = (OpSize + 7) / 8;
Tim Northover293d4142014-12-03 17:49:26 +00003125 if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
3126 !Flags.isInConsecutiveRegs()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003127 if (OpSize < 8)
3128 BEAlign = 8 - OpSize;
3129 }
3130 unsigned LocMemOffset = VA.getLocMemOffset();
3131 int32_t Offset = LocMemOffset + BEAlign;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003132 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
Mehdi Amini44ede332015-07-09 02:09:04 +00003133 PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
Tim Northover3b0846e2014-05-24 12:50:23 +00003134
3135 if (IsTailCall) {
3136 Offset = Offset + FPDiff;
Matthias Braun941a7052016-07-28 18:40:00 +00003137 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
Tim Northover3b0846e2014-05-24 12:50:23 +00003138
Mehdi Amini44ede332015-07-09 02:09:04 +00003139 DstAddr = DAG.getFrameIndex(FI, PtrVT);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003140 DstInfo =
3141 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
Tim Northover3b0846e2014-05-24 12:50:23 +00003142
3143 // Make sure any stack arguments overlapping with where we're storing
3144 // are loaded before this eventual operation. Otherwise they'll be
3145 // clobbered.
3146 Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
3147 } else {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003148 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003149
Mehdi Amini44ede332015-07-09 02:09:04 +00003150 DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003151 DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
3152 LocMemOffset);
Tim Northover3b0846e2014-05-24 12:50:23 +00003153 }
3154
3155 if (Outs[i].Flags.isByVal()) {
3156 SDValue SizeNode =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003157 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00003158 SDValue Cpy = DAG.getMemcpy(
3159 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
Krzysztof Parzyszeka46c36b2015-04-13 17:16:45 +00003160 /*isVol = */ false, /*AlwaysInline = */ false,
3161 /*isTailCall = */ false,
3162 DstInfo, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00003163
3164 MemOpChains.push_back(Cpy);
3165 } else {
3166 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
3167 // promoted to a legal register type i32, we should truncate Arg back to
3168 // i1/i8/i16.
Tim Northover6890add2014-06-03 13:54:53 +00003169 if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
3170 VA.getValVT() == MVT::i16)
3171 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
Tim Northover3b0846e2014-05-24 12:50:23 +00003172
Justin Lebar9c375812016-07-15 18:27:10 +00003173 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00003174 MemOpChains.push_back(Store);
3175 }
3176 }
3177 }
3178
3179 if (!MemOpChains.empty())
3180 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3181
3182 // Build a sequence of copy-to-reg nodes chained together with token chain
3183 // and flag operands which copy the outgoing args into the appropriate regs.
3184 SDValue InFlag;
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003185 for (auto &RegToPass : RegsToPass) {
3186 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3187 RegToPass.second, InFlag);
Tim Northover3b0846e2014-05-24 12:50:23 +00003188 InFlag = Chain.getValue(1);
3189 }
3190
3191 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3192 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3193 // node so that legalize doesn't hack it.
3194 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3195 Subtarget->isTargetMachO()) {
3196 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3197 const GlobalValue *GV = G->getGlobal();
3198 bool InternalLinkage = GV->hasInternalLinkage();
3199 if (InternalLinkage)
Mehdi Amini44ede332015-07-09 02:09:04 +00003200 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00003201 else {
Mehdi Amini44ede332015-07-09 02:09:04 +00003202 Callee =
3203 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT);
3204 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
Tim Northover3b0846e2014-05-24 12:50:23 +00003205 }
3206 } else if (ExternalSymbolSDNode *S =
3207 dyn_cast<ExternalSymbolSDNode>(Callee)) {
3208 const char *Sym = S->getSymbol();
Mehdi Amini44ede332015-07-09 02:09:04 +00003209 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
3210 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
Tim Northover3b0846e2014-05-24 12:50:23 +00003211 }
3212 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3213 const GlobalValue *GV = G->getGlobal();
Mehdi Amini44ede332015-07-09 02:09:04 +00003214 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00003215 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3216 const char *Sym = S->getSymbol();
Mehdi Amini44ede332015-07-09 02:09:04 +00003217 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00003218 }
3219
3220 // We don't usually want to end the call-sequence here because we would tidy
3221 // the frame up *after* the call, however in the ABI-changing tail-call case
3222 // we've carefully laid out the parameters so that when sp is reset they'll be
3223 // in the correct location.
3224 if (IsTailCall && !IsSibCall) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003225 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3226 DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003227 InFlag = Chain.getValue(1);
3228 }
3229
3230 std::vector<SDValue> Ops;
3231 Ops.push_back(Chain);
3232 Ops.push_back(Callee);
3233
3234 if (IsTailCall) {
3235 // Each tail call may have to adjust the stack by a different amount, so
3236 // this information must travel along with the operation for eventual
3237 // consumption by emitEpilogue.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003238 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00003239 }
3240
3241 // Add argument registers to the end of the list so that they are known live
3242 // into the call.
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003243 for (auto &RegToPass : RegsToPass)
3244 Ops.push_back(DAG.getRegister(RegToPass.first,
3245 RegToPass.second.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00003246
3247 // Add a register mask operand representing the call-preserved registers.
3248 const uint32_t *Mask;
Eric Christopher905f12d2015-01-29 00:19:42 +00003249 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00003250 if (IsThisReturn) {
3251 // For 'this' returns, use the X0-preserving mask if applicable
Eric Christopher9deb75d2015-03-11 22:42:13 +00003252 Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003253 if (!Mask) {
3254 IsThisReturn = false;
Eric Christopher9deb75d2015-03-11 22:42:13 +00003255 Mask = TRI->getCallPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003256 }
3257 } else
Eric Christopher9deb75d2015-03-11 22:42:13 +00003258 Mask = TRI->getCallPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003259
3260 assert(Mask && "Missing call preserved mask for calling convention");
3261 Ops.push_back(DAG.getRegisterMask(Mask));
3262
3263 if (InFlag.getNode())
3264 Ops.push_back(InFlag);
3265
3266 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3267
3268 // If we're doing a tall call, use a TC_RETURN here rather than an
3269 // actual call instruction.
Arnold Schwaighoferf54b73d2015-05-08 23:52:00 +00003270 if (IsTailCall) {
Matthias Braun941a7052016-07-28 18:40:00 +00003271 MF.getFrameInfo().setHasTailCall();
Tim Northover3b0846e2014-05-24 12:50:23 +00003272 return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
Arnold Schwaighoferf54b73d2015-05-08 23:52:00 +00003273 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003274
3275 // Returns a chain and a flag for retval copy to use.
3276 Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
3277 InFlag = Chain.getValue(1);
3278
Rui Ueyamada00f2f2016-01-14 21:06:47 +00003279 uint64_t CalleePopBytes =
3280 DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00003281
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003282 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3283 DAG.getIntPtrConstant(CalleePopBytes, DL, true),
Tim Northover3b0846e2014-05-24 12:50:23 +00003284 InFlag, DL);
3285 if (!Ins.empty())
3286 InFlag = Chain.getValue(1);
3287
3288 // Handle result values, copying them out of physregs into vregs that we
3289 // return.
3290 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3291 InVals, IsThisReturn,
3292 IsThisReturn ? OutVals[0] : SDValue());
3293}
3294
3295bool AArch64TargetLowering::CanLowerReturn(
3296 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
3297 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
3298 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3299 ? RetCC_AArch64_WebKit_JS
3300 : RetCC_AArch64_AAPCS;
3301 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003302 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
Tim Northover3b0846e2014-05-24 12:50:23 +00003303 return CCInfo.CheckReturn(Outs, RetCC);
3304}
3305
3306SDValue
3307AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3308 bool isVarArg,
3309 const SmallVectorImpl<ISD::OutputArg> &Outs,
3310 const SmallVectorImpl<SDValue> &OutVals,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003311 const SDLoc &DL, SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00003312 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3313 ? RetCC_AArch64_WebKit_JS
3314 : RetCC_AArch64_AAPCS;
3315 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003316 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3317 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00003318 CCInfo.AnalyzeReturn(Outs, RetCC);
3319
3320 // Copy the result values into the output registers.
3321 SDValue Flag;
3322 SmallVector<SDValue, 4> RetOps(1, Chain);
3323 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
3324 ++i, ++realRVLocIdx) {
3325 CCValAssign &VA = RVLocs[i];
3326 assert(VA.isRegLoc() && "Can only return in registers!");
3327 SDValue Arg = OutVals[realRVLocIdx];
3328
3329 switch (VA.getLocInfo()) {
3330 default:
3331 llvm_unreachable("Unknown loc info!");
3332 case CCValAssign::Full:
Tim Northover68ae5032014-05-26 17:22:07 +00003333 if (Outs[i].ArgVT == MVT::i1) {
3334 // AAPCS requires i1 to be zero-extended to i8 by the producer of the
3335 // value. This is strictly redundant on Darwin (which uses "zeroext
3336 // i1"), but will be optimised out before ISel.
3337 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3338 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3339 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003340 break;
3341 case CCValAssign::BCvt:
3342 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3343 break;
3344 }
3345
3346 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
3347 Flag = Chain.getValue(1);
3348 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3349 }
Manman Rencbe4f942015-12-16 21:04:19 +00003350 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3351 const MCPhysReg *I =
3352 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
3353 if (I) {
3354 for (; *I; ++I) {
3355 if (AArch64::GPR64RegClass.contains(*I))
3356 RetOps.push_back(DAG.getRegister(*I, MVT::i64));
3357 else if (AArch64::FPR64RegClass.contains(*I))
3358 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
3359 else
3360 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
3361 }
3362 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003363
3364 RetOps[0] = Chain; // Update chain.
3365
3366 // Add the flag if we have it.
3367 if (Flag.getNode())
3368 RetOps.push_back(Flag);
3369
3370 return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
3371}
3372
3373//===----------------------------------------------------------------------===//
3374// Other Lowering Code
3375//===----------------------------------------------------------------------===//
3376
3377SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
3378 SelectionDAG &DAG) const {
Mehdi Amini44ede332015-07-09 02:09:04 +00003379 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003380 SDLoc DL(Op);
Asiri Rathnayake369c0302014-09-10 13:54:38 +00003381 const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
3382 const GlobalValue *GV = GN->getGlobal();
Tim Northover3b0846e2014-05-24 12:50:23 +00003383 unsigned char OpFlags =
3384 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
3385
3386 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
3387 "unexpected offset in global node");
3388
3389 // This also catched the large code model case for Darwin.
3390 if ((OpFlags & AArch64II::MO_GOT) != 0) {
3391 SDValue GotAddr = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
3392 // FIXME: Once remat is capable of dealing with instructions with register
3393 // operands, expand this into two nodes instead of using a wrapper node.
3394 return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
3395 }
3396
3397 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
3398 const unsigned char MO_NC = AArch64II::MO_NC;
3399 return DAG.getNode(
3400 AArch64ISD::WrapperLarge, DL, PtrVT,
3401 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G3),
3402 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
3403 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
3404 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
3405 } else {
3406 // Use ADRP/ADD or ADRP/LDR for everything else: the small model on ELF and
3407 // the only correct model on Darwin.
3408 SDValue Hi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
3409 OpFlags | AArch64II::MO_PAGE);
3410 unsigned char LoFlags = OpFlags | AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
3411 SDValue Lo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, LoFlags);
3412
3413 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3414 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3415 }
3416}
3417
3418/// \brief Convert a TLS address reference into the correct sequence of loads
3419/// and calls to compute the variable's address (for Darwin, currently) and
3420/// return an SDValue containing the final node.
3421
3422/// Darwin only has one TLS scheme which must be capable of dealing with the
3423/// fully general situation, in the worst case. This means:
3424/// + "extern __thread" declaration.
3425/// + Defined in a possibly unknown dynamic library.
3426///
3427/// The general system is that each __thread variable has a [3 x i64] descriptor
3428/// which contains information used by the runtime to calculate the address. The
3429/// only part of this the compiler needs to know about is the first xword, which
3430/// contains a function pointer that must be called with the address of the
3431/// entire descriptor in "x0".
3432///
3433/// Since this descriptor may be in a different unit, in general even the
3434/// descriptor must be accessed via an indirect load. The "ideal" code sequence
3435/// is:
3436/// adrp x0, _var@TLVPPAGE
3437/// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor
3438/// ldr x1, [x0] ; x1 contains 1st entry of descriptor,
3439/// ; the function pointer
3440/// blr x1 ; Uses descriptor address in x0
3441/// ; Address of _var is now in x0.
3442///
3443/// If the address of _var's descriptor *is* known to the linker, then it can
3444/// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
3445/// a slight efficiency gain.
3446SDValue
3447AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
3448 SelectionDAG &DAG) const {
3449 assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
3450
3451 SDLoc DL(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00003452 MVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003453 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3454
3455 SDValue TLVPAddr =
3456 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3457 SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
3458
3459 // The first entry in the descriptor is a function pointer that we must call
3460 // to obtain the address of the variable.
3461 SDValue Chain = DAG.getEntryNode();
Justin Lebaradbf09e2016-09-11 01:38:58 +00003462 SDValue FuncTLVGet = DAG.getLoad(
3463 MVT::i64, DL, Chain, DescAddr,
3464 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
3465 /* Alignment = */ 8,
3466 MachineMemOperand::MONonTemporal | MachineMemOperand::MOInvariant |
3467 MachineMemOperand::MODereferenceable);
Tim Northover3b0846e2014-05-24 12:50:23 +00003468 Chain = FuncTLVGet.getValue(1);
3469
Matthias Braun941a7052016-07-28 18:40:00 +00003470 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
3471 MFI.setAdjustsStack(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00003472
3473 // TLS calls preserve all registers except those that absolutely must be
3474 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
3475 // silly).
Eric Christopher6c901622015-01-28 03:51:33 +00003476 const uint32_t *Mask =
Eric Christopher905f12d2015-01-29 00:19:42 +00003477 Subtarget->getRegisterInfo()->getTLSCallPreservedMask();
Tim Northover3b0846e2014-05-24 12:50:23 +00003478
3479 // Finally, we can make the call. This is just a degenerate version of a
3480 // normal AArch64 call node: x0 takes the address of the descriptor, and
3481 // returns the address of the variable in this thread.
3482 Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
3483 Chain =
3484 DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3485 Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
3486 DAG.getRegisterMask(Mask), Chain.getValue(1));
3487 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
3488}
3489
3490/// When accessing thread-local variables under either the general-dynamic or
3491/// local-dynamic system, we make a "TLS-descriptor" call. The variable will
3492/// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
Kristof Beylsaea84612015-03-04 09:12:08 +00003493/// is a function pointer to carry out the resolution.
Tim Northover3b0846e2014-05-24 12:50:23 +00003494///
Kristof Beylsaea84612015-03-04 09:12:08 +00003495/// The sequence is:
3496/// adrp x0, :tlsdesc:var
3497/// ldr x1, [x0, #:tlsdesc_lo12:var]
3498/// add x0, x0, #:tlsdesc_lo12:var
3499/// .tlsdesccall var
3500/// blr x1
3501/// (TPIDR_EL0 offset now in x0)
Tim Northover3b0846e2014-05-24 12:50:23 +00003502///
Kristof Beylsaea84612015-03-04 09:12:08 +00003503/// The above sequence must be produced unscheduled, to enable the linker to
3504/// optimize/relax this sequence.
3505/// Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
3506/// above sequence, and expanded really late in the compilation flow, to ensure
3507/// the sequence is produced as per above.
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003508SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr,
3509 const SDLoc &DL,
Kristof Beylsaea84612015-03-04 09:12:08 +00003510 SelectionDAG &DAG) const {
Mehdi Amini44ede332015-07-09 02:09:04 +00003511 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003512
Kristof Beylsaea84612015-03-04 09:12:08 +00003513 SDValue Chain = DAG.getEntryNode();
Tim Northover3b0846e2014-05-24 12:50:23 +00003514 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
Kristof Beylsaea84612015-03-04 09:12:08 +00003515
Benjamin Kramer3bc1edf2016-07-02 11:41:39 +00003516 Chain =
3517 DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr});
Kristof Beylsaea84612015-03-04 09:12:08 +00003518 SDValue Glue = Chain.getValue(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00003519
3520 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
3521}
3522
3523SDValue
3524AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
3525 SelectionDAG &DAG) const {
3526 assert(Subtarget->isTargetELF() && "This function expects an ELF target");
3527 assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
3528 "ELF TLS only supported in small memory model");
Kristof Beylsaea84612015-03-04 09:12:08 +00003529 // Different choices can be made for the maximum size of the TLS area for a
3530 // module. For the small address model, the default TLS size is 16MiB and the
3531 // maximum TLS size is 4GiB.
3532 // FIXME: add -mtls-size command line option and make it control the 16MiB
3533 // vs. 4GiB code sequence generation.
Tim Northover3b0846e2014-05-24 12:50:23 +00003534 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3535
3536 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
Chih-Hung Hsieh1e859582015-07-28 16:24:05 +00003537
3538 if (DAG.getTarget().Options.EmulatedTLS)
3539 return LowerToTLSEmulatedModel(GA, DAG);
3540
Kristof Beylsaea84612015-03-04 09:12:08 +00003541 if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
3542 if (Model == TLSModel::LocalDynamic)
3543 Model = TLSModel::GeneralDynamic;
3544 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003545
3546 SDValue TPOff;
Mehdi Amini44ede332015-07-09 02:09:04 +00003547 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003548 SDLoc DL(Op);
3549 const GlobalValue *GV = GA->getGlobal();
3550
3551 SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
3552
3553 if (Model == TLSModel::LocalExec) {
3554 SDValue HiVar = DAG.getTargetGlobalAddress(
Kristof Beylsaea84612015-03-04 09:12:08 +00003555 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
Tim Northover3b0846e2014-05-24 12:50:23 +00003556 SDValue LoVar = DAG.getTargetGlobalAddress(
3557 GV, DL, PtrVT, 0,
Kristof Beylsaea84612015-03-04 09:12:08 +00003558 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
Tim Northover3b0846e2014-05-24 12:50:23 +00003559
Kristof Beylsaea84612015-03-04 09:12:08 +00003560 SDValue TPWithOff_lo =
3561 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003562 HiVar,
3563 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003564 0);
3565 SDValue TPWithOff =
3566 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003567 LoVar,
3568 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003569 0);
3570 return TPWithOff;
Tim Northover3b0846e2014-05-24 12:50:23 +00003571 } else if (Model == TLSModel::InitialExec) {
3572 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3573 TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
3574 } else if (Model == TLSModel::LocalDynamic) {
3575 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
3576 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
3577 // the beginning of the module's TLS region, followed by a DTPREL offset
3578 // calculation.
3579
3580 // These accesses will need deduplicating if there's more than one.
3581 AArch64FunctionInfo *MFI =
3582 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
3583 MFI->incNumLocalDynamicTLSAccesses();
3584
Tim Northover3b0846e2014-05-24 12:50:23 +00003585 // The call needs a relocation too for linker relaxation. It doesn't make
3586 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3587 // the address.
3588 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
3589 AArch64II::MO_TLS);
3590
3591 // Now we can calculate the offset from TPIDR_EL0 to this module's
3592 // thread-local area.
Kristof Beylsaea84612015-03-04 09:12:08 +00003593 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00003594
3595 // Now use :dtprel_whatever: operations to calculate this variable's offset
3596 // in its thread-storage area.
3597 SDValue HiVar = DAG.getTargetGlobalAddress(
Kristof Beylsaea84612015-03-04 09:12:08 +00003598 GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
Tim Northover3b0846e2014-05-24 12:50:23 +00003599 SDValue LoVar = DAG.getTargetGlobalAddress(
3600 GV, DL, MVT::i64, 0,
Tim Northover3b0846e2014-05-24 12:50:23 +00003601 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3602
Kristof Beylsaea84612015-03-04 09:12:08 +00003603 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003604 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003605 0);
3606 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003607 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003608 0);
3609 } else if (Model == TLSModel::GeneralDynamic) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003610 // The call needs a relocation too for linker relaxation. It doesn't make
3611 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3612 // the address.
3613 SDValue SymAddr =
3614 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3615
3616 // Finally we can make a call to calculate the offset from tpidr_el0.
Kristof Beylsaea84612015-03-04 09:12:08 +00003617 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00003618 } else
3619 llvm_unreachable("Unsupported ELF TLS access model");
3620
3621 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
3622}
3623
3624SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
3625 SelectionDAG &DAG) const {
3626 if (Subtarget->isTargetDarwin())
3627 return LowerDarwinGlobalTLSAddress(Op, DAG);
3628 else if (Subtarget->isTargetELF())
3629 return LowerELFGlobalTLSAddress(Op, DAG);
3630
3631 llvm_unreachable("Unexpected platform trying to use TLS");
3632}
3633SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3634 SDValue Chain = Op.getOperand(0);
3635 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3636 SDValue LHS = Op.getOperand(2);
3637 SDValue RHS = Op.getOperand(3);
3638 SDValue Dest = Op.getOperand(4);
3639 SDLoc dl(Op);
3640
3641 // Handle f128 first, since lowering it will result in comparing the return
3642 // value of a libcall against zero, which is just what the rest of LowerBR_CC
3643 // is expecting to deal with.
3644 if (LHS.getValueType() == MVT::f128) {
3645 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3646
3647 // If softenSetCCOperands returned a scalar, we need to compare the result
3648 // against zero to select between true and false values.
3649 if (!RHS.getNode()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003650 RHS = DAG.getConstant(0, dl, LHS.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00003651 CC = ISD::SETNE;
3652 }
3653 }
3654
3655 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
3656 // instruction.
3657 unsigned Opc = LHS.getOpcode();
Artyom Skrobov314ee042015-11-25 19:41:11 +00003658 if (LHS.getResNo() == 1 && isOneConstant(RHS) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00003659 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3660 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
3661 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
3662 "Unexpected condition code.");
3663 // Only lower legal XALUO ops.
3664 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
3665 return SDValue();
3666
3667 // The actual operation with overflow check.
3668 AArch64CC::CondCode OFCC;
3669 SDValue Value, Overflow;
3670 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
3671
3672 if (CC == ISD::SETNE)
3673 OFCC = getInvertedCondCode(OFCC);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003674 SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003675
Ahmed Bougachadf956a22015-02-06 23:15:39 +00003676 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3677 Overflow);
Tim Northover3b0846e2014-05-24 12:50:23 +00003678 }
3679
3680 if (LHS.getValueType().isInteger()) {
3681 assert((LHS.getValueType() == RHS.getValueType()) &&
3682 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3683
3684 // If the RHS of the comparison is zero, we can potentially fold this
3685 // to a specialized branch.
3686 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
3687 if (RHSC && RHSC->getZExtValue() == 0) {
3688 if (CC == ISD::SETEQ) {
3689 // See if we can use a TBZ to fold in an AND as well.
3690 // TBZ has a smaller branch displacement than CBZ. If the offset is
3691 // out of bounds, a late MI-layer pass rewrites branches.
3692 // 403.gcc is an example that hits this case.
3693 if (LHS.getOpcode() == ISD::AND &&
3694 isa<ConstantSDNode>(LHS.getOperand(1)) &&
3695 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3696 SDValue Test = LHS.getOperand(0);
3697 uint64_t Mask = LHS.getConstantOperandVal(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00003698 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003699 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3700 Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00003701 }
3702
3703 return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
3704 } else if (CC == ISD::SETNE) {
3705 // See if we can use a TBZ to fold in an AND as well.
3706 // TBZ has a smaller branch displacement than CBZ. If the offset is
3707 // out of bounds, a late MI-layer pass rewrites branches.
3708 // 403.gcc is an example that hits this case.
3709 if (LHS.getOpcode() == ISD::AND &&
3710 isa<ConstantSDNode>(LHS.getOperand(1)) &&
3711 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3712 SDValue Test = LHS.getOperand(0);
3713 uint64_t Mask = LHS.getConstantOperandVal(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00003714 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003715 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3716 Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00003717 }
3718
3719 return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
Chad Rosier579c02c2014-08-01 14:48:56 +00003720 } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
3721 // Don't combine AND since emitComparison converts the AND to an ANDS
3722 // (a.k.a. TST) and the test in the test bit and branch instruction
3723 // becomes redundant. This would also increase register pressure.
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00003724 uint64_t Mask = LHS.getValueSizeInBits() - 1;
Chad Rosier579c02c2014-08-01 14:48:56 +00003725 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003726 DAG.getConstant(Mask, dl, MVT::i64), Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00003727 }
3728 }
Chad Rosier579c02c2014-08-01 14:48:56 +00003729 if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
3730 LHS.getOpcode() != ISD::AND) {
3731 // Don't combine AND since emitComparison converts the AND to an ANDS
3732 // (a.k.a. TST) and the test in the test bit and branch instruction
3733 // becomes redundant. This would also increase register pressure.
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00003734 uint64_t Mask = LHS.getValueSizeInBits() - 1;
Chad Rosier579c02c2014-08-01 14:48:56 +00003735 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003736 DAG.getConstant(Mask, dl, MVT::i64), Dest);
Chad Rosier579c02c2014-08-01 14:48:56 +00003737 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003738
3739 SDValue CCVal;
3740 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3741 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3742 Cmp);
3743 }
3744
3745 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3746
3747 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
3748 // clean. Some of them require two branches to implement.
3749 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3750 AArch64CC::CondCode CC1, CC2;
3751 changeFPCCToAArch64CC(CC, CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003752 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003753 SDValue BR1 =
3754 DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
3755 if (CC2 != AArch64CC::AL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003756 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003757 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
3758 Cmp);
3759 }
3760
3761 return BR1;
3762}
3763
3764SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
3765 SelectionDAG &DAG) const {
3766 EVT VT = Op.getValueType();
3767 SDLoc DL(Op);
3768
3769 SDValue In1 = Op.getOperand(0);
3770 SDValue In2 = Op.getOperand(1);
3771 EVT SrcVT = In2.getValueType();
Ahmed Bougacha2a97b1b2015-08-13 01:13:56 +00003772
3773 if (SrcVT.bitsLT(VT))
3774 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
3775 else if (SrcVT.bitsGT(VT))
3776 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
Tim Northover3b0846e2014-05-24 12:50:23 +00003777
3778 EVT VecVT;
3779 EVT EltVT;
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00003780 uint64_t EltMask;
3781 SDValue VecVal1, VecVal2;
Tim Northover3b0846e2014-05-24 12:50:23 +00003782 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
3783 EltVT = MVT::i32;
Ahmed Bougachab0ae36f2015-08-04 00:42:34 +00003784 VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00003785 EltMask = 0x80000000ULL;
Tim Northover3b0846e2014-05-24 12:50:23 +00003786
3787 if (!VT.isVector()) {
3788 VecVal1 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3789 DAG.getUNDEF(VecVT), In1);
3790 VecVal2 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3791 DAG.getUNDEF(VecVT), In2);
3792 } else {
3793 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3794 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3795 }
3796 } else if (VT == MVT::f64 || VT == MVT::v2f64) {
3797 EltVT = MVT::i64;
3798 VecVT = MVT::v2i64;
3799
Eric Christopher572e03a2015-06-19 01:53:21 +00003800 // We want to materialize a mask with the high bit set, but the AdvSIMD
Tim Northover3b0846e2014-05-24 12:50:23 +00003801 // immediate moves cannot materialize that in a single instruction for
3802 // 64-bit elements. Instead, materialize zero and then negate it.
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00003803 EltMask = 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00003804
3805 if (!VT.isVector()) {
3806 VecVal1 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3807 DAG.getUNDEF(VecVT), In1);
3808 VecVal2 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3809 DAG.getUNDEF(VecVT), In2);
3810 } else {
3811 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3812 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3813 }
3814 } else {
3815 llvm_unreachable("Invalid type for copysign!");
3816 }
3817
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003818 SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00003819
3820 // If we couldn't materialize the mask above, then the mask vector will be
3821 // the zero vector, and we need to negate it here.
3822 if (VT == MVT::f64 || VT == MVT::v2f64) {
3823 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
3824 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
3825 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
3826 }
3827
3828 SDValue Sel =
3829 DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
3830
3831 if (VT == MVT::f32)
3832 return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
3833 else if (VT == MVT::f64)
3834 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
3835 else
3836 return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
3837}
3838
3839SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
Duncan P. N. Exon Smith003bb7d2015-02-14 02:09:06 +00003840 if (DAG.getMachineFunction().getFunction()->hasFnAttribute(
3841 Attribute::NoImplicitFloat))
Tim Northover3b0846e2014-05-24 12:50:23 +00003842 return SDValue();
3843
Weiming Zhao7a2d1562014-11-19 00:29:14 +00003844 if (!Subtarget->hasNEON())
3845 return SDValue();
3846
Tim Northover3b0846e2014-05-24 12:50:23 +00003847 // While there is no integer popcount instruction, it can
3848 // be more efficiently lowered to the following sequence that uses
3849 // AdvSIMD registers/instructions as long as the copies to/from
3850 // the AdvSIMD registers are cheap.
3851 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd
3852 // CNT V0.8B, V0.8B // 8xbyte pop-counts
3853 // ADDV B0, V0.8B // sum 8xbyte pop-counts
3854 // UMOV X0, V0.B[0] // copy byte result back to integer reg
3855 SDValue Val = Op.getOperand(0);
3856 SDLoc DL(Op);
3857 EVT VT = Op.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00003858
Hao Liue0335d72015-01-30 02:13:53 +00003859 if (VT == MVT::i32)
3860 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
3861 Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
Tim Northover3b0846e2014-05-24 12:50:23 +00003862
Hao Liue0335d72015-01-30 02:13:53 +00003863 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
Tim Northover3b0846e2014-05-24 12:50:23 +00003864 SDValue UaddLV = DAG.getNode(
3865 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003866 DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
Tim Northover3b0846e2014-05-24 12:50:23 +00003867
3868 if (VT == MVT::i64)
3869 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
3870 return UaddLV;
3871}
3872
3873SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3874
3875 if (Op.getValueType().isVector())
3876 return LowerVSETCC(Op, DAG);
3877
3878 SDValue LHS = Op.getOperand(0);
3879 SDValue RHS = Op.getOperand(1);
3880 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3881 SDLoc dl(Op);
3882
3883 // We chose ZeroOrOneBooleanContents, so use zero and one.
3884 EVT VT = Op.getValueType();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003885 SDValue TVal = DAG.getConstant(1, dl, VT);
3886 SDValue FVal = DAG.getConstant(0, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00003887
3888 // Handle f128 first, since one possible outcome is a normal integer
3889 // comparison which gets picked up by the next if statement.
3890 if (LHS.getValueType() == MVT::f128) {
3891 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3892
3893 // If softenSetCCOperands returned a scalar, use it.
3894 if (!RHS.getNode()) {
3895 assert(LHS.getValueType() == Op.getValueType() &&
3896 "Unexpected setcc expansion!");
3897 return LHS;
3898 }
3899 }
3900
3901 if (LHS.getValueType().isInteger()) {
3902 SDValue CCVal;
3903 SDValue Cmp =
3904 getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
3905
3906 // Note that we inverted the condition above, so we reverse the order of
3907 // the true and false operands here. This will allow the setcc to be
3908 // matched to a single CSINC instruction.
3909 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
3910 }
3911
3912 // Now we know we're dealing with FP values.
3913 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3914
3915 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
3916 // and do the comparison.
3917 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3918
3919 AArch64CC::CondCode CC1, CC2;
3920 changeFPCCToAArch64CC(CC, CC1, CC2);
3921 if (CC2 == AArch64CC::AL) {
3922 changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003923 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003924
3925 // Note that we inverted the condition above, so we reverse the order of
3926 // the true and false operands here. This will allow the setcc to be
3927 // matched to a single CSINC instruction.
3928 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
3929 } else {
3930 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
3931 // totally clean. Some of them require two CSELs to implement. As is in
3932 // this case, we emit the first CSEL and then emit a second using the output
3933 // of the first as the RHS. We're effectively OR'ing the two CC's together.
3934
3935 // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003936 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003937 SDValue CS1 =
3938 DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3939
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003940 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003941 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3942 }
3943}
3944
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00003945SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
3946 SDValue RHS, SDValue TVal,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003947 SDValue FVal, const SDLoc &dl,
Tim Northover3b0846e2014-05-24 12:50:23 +00003948 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00003949 // Handle f128 first, because it will result in a comparison of some RTLIB
3950 // call result against zero.
3951 if (LHS.getValueType() == MVT::f128) {
3952 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3953
3954 // If softenSetCCOperands returned a scalar, we need to compare the result
3955 // against zero to select between true and false values.
3956 if (!RHS.getNode()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003957 RHS = DAG.getConstant(0, dl, LHS.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00003958 CC = ISD::SETNE;
3959 }
3960 }
3961
Ahmed Bougacha88ddeae2015-11-17 16:45:40 +00003962 // Also handle f16, for which we need to do a f32 comparison.
3963 if (LHS.getValueType() == MVT::f16) {
3964 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
3965 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
3966 }
3967
3968 // Next, handle integers.
Tim Northover3b0846e2014-05-24 12:50:23 +00003969 if (LHS.getValueType().isInteger()) {
3970 assert((LHS.getValueType() == RHS.getValueType()) &&
3971 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3972
3973 unsigned Opcode = AArch64ISD::CSEL;
3974
3975 // If both the TVal and the FVal are constants, see if we can swap them in
3976 // order to for a CSINV or CSINC out of them.
3977 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
3978 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
3979
3980 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
3981 std::swap(TVal, FVal);
3982 std::swap(CTVal, CFVal);
3983 CC = ISD::getSetCCInverse(CC, true);
3984 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
3985 std::swap(TVal, FVal);
3986 std::swap(CTVal, CFVal);
3987 CC = ISD::getSetCCInverse(CC, true);
3988 } else if (TVal.getOpcode() == ISD::XOR) {
3989 // If TVal is a NOT we want to swap TVal and FVal so that we can match
3990 // with a CSINV rather than a CSEL.
Artyom Skrobov314ee042015-11-25 19:41:11 +00003991 if (isAllOnesConstant(TVal.getOperand(1))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003992 std::swap(TVal, FVal);
3993 std::swap(CTVal, CFVal);
3994 CC = ISD::getSetCCInverse(CC, true);
3995 }
3996 } else if (TVal.getOpcode() == ISD::SUB) {
3997 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
3998 // that we can match with a CSNEG rather than a CSEL.
Artyom Skrobov314ee042015-11-25 19:41:11 +00003999 if (isNullConstant(TVal.getOperand(0))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004000 std::swap(TVal, FVal);
4001 std::swap(CTVal, CFVal);
4002 CC = ISD::getSetCCInverse(CC, true);
4003 }
4004 } else if (CTVal && CFVal) {
4005 const int64_t TrueVal = CTVal->getSExtValue();
4006 const int64_t FalseVal = CFVal->getSExtValue();
4007 bool Swap = false;
4008
4009 // If both TVal and FVal are constants, see if FVal is the
4010 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
4011 // instead of a CSEL in that case.
4012 if (TrueVal == ~FalseVal) {
4013 Opcode = AArch64ISD::CSINV;
4014 } else if (TrueVal == -FalseVal) {
4015 Opcode = AArch64ISD::CSNEG;
4016 } else if (TVal.getValueType() == MVT::i32) {
4017 // If our operands are only 32-bit wide, make sure we use 32-bit
4018 // arithmetic for the check whether we can use CSINC. This ensures that
4019 // the addition in the check will wrap around properly in case there is
4020 // an overflow (which would not be the case if we do the check with
4021 // 64-bit arithmetic).
4022 const uint32_t TrueVal32 = CTVal->getZExtValue();
4023 const uint32_t FalseVal32 = CFVal->getZExtValue();
4024
4025 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
4026 Opcode = AArch64ISD::CSINC;
4027
4028 if (TrueVal32 > FalseVal32) {
4029 Swap = true;
4030 }
4031 }
4032 // 64-bit check whether we can use CSINC.
4033 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
4034 Opcode = AArch64ISD::CSINC;
4035
4036 if (TrueVal > FalseVal) {
4037 Swap = true;
4038 }
4039 }
4040
4041 // Swap TVal and FVal if necessary.
4042 if (Swap) {
4043 std::swap(TVal, FVal);
4044 std::swap(CTVal, CFVal);
4045 CC = ISD::getSetCCInverse(CC, true);
4046 }
4047
4048 if (Opcode != AArch64ISD::CSEL) {
4049 // Drop FVal since we can get its value by simply inverting/negating
4050 // TVal.
4051 FVal = TVal;
4052 }
4053 }
4054
Chad Rosier58f505b2016-08-26 18:05:50 +00004055 // Avoid materializing a constant when possible by reusing a known value in
4056 // a register. However, don't perform this optimization if the known value
Chad Rosier0c621fd2016-10-26 18:15:32 +00004057 // is one, zero or negative one in the case of a CSEL. We can always
4058 // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the
4059 // FVal, respectively.
Chad Rosier58f505b2016-08-26 18:05:50 +00004060 ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS);
4061 if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() &&
4062 !RHSVal->isNullValue() && !RHSVal->isAllOnesValue()) {
4063 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
4064 // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to
4065 // "a != C ? x : a" to avoid materializing C.
4066 if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ)
4067 TVal = LHS;
4068 else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE)
4069 FVal = LHS;
Chad Rosier0c621fd2016-10-26 18:15:32 +00004070 } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) {
4071 assert (CTVal && CFVal && "Expected constant operands for CSNEG.");
4072 // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to
4073 // avoid materializing C.
4074 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
4075 if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) {
4076 Opcode = AArch64ISD::CSINV;
4077 TVal = LHS;
4078 FVal = DAG.getConstant(0, dl, FVal.getValueType());
4079 }
Chad Rosier58f505b2016-08-26 18:05:50 +00004080 }
4081
Tim Northover3b0846e2014-05-24 12:50:23 +00004082 SDValue CCVal;
4083 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
4084
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004085 EVT VT = TVal.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00004086 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
4087 }
4088
4089 // Now we know we're dealing with FP values.
4090 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
4091 assert(LHS.getValueType() == RHS.getValueType());
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004092 EVT VT = TVal.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00004093 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
4094
4095 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4096 // clean. Some of them require two CSELs to implement.
4097 AArch64CC::CondCode CC1, CC2;
4098 changeFPCCToAArch64CC(CC, CC1, CC2);
Evandro Menezesce8d6012016-10-18 20:37:35 +00004099
4100 if (DAG.getTarget().Options.UnsafeFPMath) {
4101 // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and
4102 // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0.
4103 ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS);
4104 if (RHSVal && RHSVal->isZero()) {
4105 ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal);
4106 ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal);
4107
4108 if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) &&
Roger Ferrer Ibanez80c0f332016-11-08 13:34:41 +00004109 CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType())
Evandro Menezesce8d6012016-10-18 20:37:35 +00004110 TVal = LHS;
4111 else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) &&
Roger Ferrer Ibanez80c0f332016-11-08 13:34:41 +00004112 CFVal && CFVal->isZero() &&
4113 FVal.getValueType() == LHS.getValueType())
Evandro Menezesce8d6012016-10-18 20:37:35 +00004114 FVal = LHS;
4115 }
4116 }
4117
4118 // Emit first, and possibly only, CSEL.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004119 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004120 SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4121
4122 // If we need a second CSEL, emit it, using the output of the first as the
4123 // RHS. We're effectively OR'ing the two CC's together.
4124 if (CC2 != AArch64CC::AL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004125 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004126 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4127 }
4128
4129 // Otherwise, return the output of the first CSEL.
4130 return CS1;
4131}
4132
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004133SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
4134 SelectionDAG &DAG) const {
4135 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4136 SDValue LHS = Op.getOperand(0);
4137 SDValue RHS = Op.getOperand(1);
4138 SDValue TVal = Op.getOperand(2);
4139 SDValue FVal = Op.getOperand(3);
4140 SDLoc DL(Op);
4141 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4142}
4143
4144SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
4145 SelectionDAG &DAG) const {
4146 SDValue CCVal = Op->getOperand(0);
4147 SDValue TVal = Op->getOperand(1);
4148 SDValue FVal = Op->getOperand(2);
4149 SDLoc DL(Op);
4150
4151 unsigned Opc = CCVal.getOpcode();
4152 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
4153 // instruction.
4154 if (CCVal.getResNo() == 1 &&
4155 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4156 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
4157 // Only lower legal XALUO ops.
4158 if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
4159 return SDValue();
4160
4161 AArch64CC::CondCode OFCC;
4162 SDValue Value, Overflow;
4163 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004164 SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004165
4166 return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
4167 CCVal, Overflow);
4168 }
4169
4170 // Lower it the same way as we would lower a SELECT_CC node.
4171 ISD::CondCode CC;
4172 SDValue LHS, RHS;
4173 if (CCVal.getOpcode() == ISD::SETCC) {
4174 LHS = CCVal.getOperand(0);
4175 RHS = CCVal.getOperand(1);
4176 CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
4177 } else {
4178 LHS = CCVal;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004179 RHS = DAG.getConstant(0, DL, CCVal.getValueType());
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004180 CC = ISD::SETNE;
4181 }
4182 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4183}
4184
Tim Northover3b0846e2014-05-24 12:50:23 +00004185SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
4186 SelectionDAG &DAG) const {
4187 // Jump table entries as PC relative offsets. No additional tweaking
4188 // is necessary here. Just get the address of the jump table.
4189 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00004190 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004191 SDLoc DL(Op);
4192
4193 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4194 !Subtarget->isTargetMachO()) {
4195 const unsigned char MO_NC = AArch64II::MO_NC;
4196 return DAG.getNode(
4197 AArch64ISD::WrapperLarge, DL, PtrVT,
4198 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G3),
4199 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G2 | MO_NC),
4200 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G1 | MO_NC),
4201 DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4202 AArch64II::MO_G0 | MO_NC));
4203 }
4204
4205 SDValue Hi =
4206 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_PAGE);
4207 SDValue Lo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4208 AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4209 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4210 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4211}
4212
4213SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
4214 SelectionDAG &DAG) const {
4215 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00004216 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004217 SDLoc DL(Op);
4218
4219 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4220 // Use the GOT for the large code model on iOS.
4221 if (Subtarget->isTargetMachO()) {
4222 SDValue GotAddr = DAG.getTargetConstantPool(
4223 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4224 AArch64II::MO_GOT);
4225 return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
4226 }
4227
4228 const unsigned char MO_NC = AArch64II::MO_NC;
4229 return DAG.getNode(
4230 AArch64ISD::WrapperLarge, DL, PtrVT,
4231 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4232 CP->getOffset(), AArch64II::MO_G3),
4233 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4234 CP->getOffset(), AArch64II::MO_G2 | MO_NC),
4235 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4236 CP->getOffset(), AArch64II::MO_G1 | MO_NC),
4237 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4238 CP->getOffset(), AArch64II::MO_G0 | MO_NC));
4239 } else {
4240 // Use ADRP/ADD or ADRP/LDR for everything else: the small memory model on
4241 // ELF, the only valid one on Darwin.
4242 SDValue Hi =
4243 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4244 CP->getOffset(), AArch64II::MO_PAGE);
4245 SDValue Lo = DAG.getTargetConstantPool(
4246 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4247 AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4248
4249 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4250 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4251 }
4252}
4253
4254SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
4255 SelectionDAG &DAG) const {
4256 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
Mehdi Amini44ede332015-07-09 02:09:04 +00004257 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004258 SDLoc DL(Op);
4259 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4260 !Subtarget->isTargetMachO()) {
4261 const unsigned char MO_NC = AArch64II::MO_NC;
4262 return DAG.getNode(
4263 AArch64ISD::WrapperLarge, DL, PtrVT,
4264 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G3),
4265 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
4266 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
4267 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
4268 } else {
4269 SDValue Hi = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGE);
4270 SDValue Lo = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGEOFF |
4271 AArch64II::MO_NC);
4272 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4273 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4274 }
4275}
4276
4277SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
4278 SelectionDAG &DAG) const {
4279 AArch64FunctionInfo *FuncInfo =
4280 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4281
4282 SDLoc DL(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00004283 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
4284 getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00004285 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4286 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
Justin Lebar9c375812016-07-15 18:27:10 +00004287 MachinePointerInfo(SV));
Tim Northover3b0846e2014-05-24 12:50:23 +00004288}
4289
4290SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
4291 SelectionDAG &DAG) const {
4292 // The layout of the va_list struct is specified in the AArch64 Procedure Call
4293 // Standard, section B.3.
4294 MachineFunction &MF = DAG.getMachineFunction();
4295 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Mehdi Amini44ede332015-07-09 02:09:04 +00004296 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004297 SDLoc DL(Op);
4298
4299 SDValue Chain = Op.getOperand(0);
4300 SDValue VAList = Op.getOperand(1);
4301 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4302 SmallVector<SDValue, 4> MemOps;
4303
4304 // void *__stack at offset 0
Mehdi Amini44ede332015-07-09 02:09:04 +00004305 SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004306 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
Justin Lebar9c375812016-07-15 18:27:10 +00004307 MachinePointerInfo(SV), /* Alignment = */ 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00004308
4309 // void *__gr_top at offset 8
4310 int GPRSize = FuncInfo->getVarArgsGPRSize();
4311 if (GPRSize > 0) {
4312 SDValue GRTop, GRTopAddr;
4313
Mehdi Amini44ede332015-07-09 02:09:04 +00004314 GRTopAddr =
4315 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004316
Mehdi Amini44ede332015-07-09 02:09:04 +00004317 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
4318 GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
4319 DAG.getConstant(GPRSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004320
4321 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
Justin Lebar9c375812016-07-15 18:27:10 +00004322 MachinePointerInfo(SV, 8),
4323 /* Alignment = */ 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00004324 }
4325
4326 // void *__vr_top at offset 16
4327 int FPRSize = FuncInfo->getVarArgsFPRSize();
4328 if (FPRSize > 0) {
4329 SDValue VRTop, VRTopAddr;
Mehdi Amini44ede332015-07-09 02:09:04 +00004330 VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4331 DAG.getConstant(16, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004332
Mehdi Amini44ede332015-07-09 02:09:04 +00004333 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
4334 VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
4335 DAG.getConstant(FPRSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004336
4337 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
Justin Lebar9c375812016-07-15 18:27:10 +00004338 MachinePointerInfo(SV, 16),
4339 /* Alignment = */ 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00004340 }
4341
4342 // int __gr_offs at offset 24
Mehdi Amini44ede332015-07-09 02:09:04 +00004343 SDValue GROffsAddr =
4344 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
Justin Lebar9c375812016-07-15 18:27:10 +00004345 MemOps.push_back(DAG.getStore(
4346 Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32), GROffsAddr,
4347 MachinePointerInfo(SV, 24), /* Alignment = */ 4));
Tim Northover3b0846e2014-05-24 12:50:23 +00004348
4349 // int __vr_offs at offset 28
Mehdi Amini44ede332015-07-09 02:09:04 +00004350 SDValue VROffsAddr =
4351 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
Justin Lebar9c375812016-07-15 18:27:10 +00004352 MemOps.push_back(DAG.getStore(
4353 Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32), VROffsAddr,
4354 MachinePointerInfo(SV, 28), /* Alignment = */ 4));
Tim Northover3b0846e2014-05-24 12:50:23 +00004355
4356 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
4357}
4358
4359SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
4360 SelectionDAG &DAG) const {
4361 return Subtarget->isTargetDarwin() ? LowerDarwin_VASTART(Op, DAG)
4362 : LowerAAPCS_VASTART(Op, DAG);
4363}
4364
4365SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
4366 SelectionDAG &DAG) const {
4367 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
4368 // pointer.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004369 SDLoc DL(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00004370 unsigned VaListSize = Subtarget->isTargetDarwin() ? 8 : 32;
4371 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4372 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4373
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004374 return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1),
4375 Op.getOperand(2),
4376 DAG.getConstant(VaListSize, DL, MVT::i32),
Krzysztof Parzyszeka46c36b2015-04-13 17:16:45 +00004377 8, false, false, false, MachinePointerInfo(DestSV),
Tim Northover3b0846e2014-05-24 12:50:23 +00004378 MachinePointerInfo(SrcSV));
4379}
4380
4381SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
4382 assert(Subtarget->isTargetDarwin() &&
4383 "automatic va_arg instruction only works on Darwin");
4384
4385 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4386 EVT VT = Op.getValueType();
4387 SDLoc DL(Op);
4388 SDValue Chain = Op.getOperand(0);
4389 SDValue Addr = Op.getOperand(1);
4390 unsigned Align = Op.getConstantOperandVal(3);
Mehdi Amini44ede332015-07-09 02:09:04 +00004391 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004392
Justin Lebar9c375812016-07-15 18:27:10 +00004393 SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V));
Tim Northover3b0846e2014-05-24 12:50:23 +00004394 Chain = VAList.getValue(1);
4395
4396 if (Align > 8) {
4397 assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
Mehdi Amini44ede332015-07-09 02:09:04 +00004398 VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4399 DAG.getConstant(Align - 1, DL, PtrVT));
4400 VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
4401 DAG.getConstant(-(int64_t)Align, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004402 }
4403
4404 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
Mehdi Amini44ede332015-07-09 02:09:04 +00004405 uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
Tim Northover3b0846e2014-05-24 12:50:23 +00004406
4407 // Scalar integer and FP values smaller than 64 bits are implicitly extended
4408 // up to 64 bits. At the very least, we have to increase the striding of the
4409 // vaargs list to match this, and for FP values we need to introduce
4410 // FP_ROUND nodes as well.
4411 if (VT.isInteger() && !VT.isVector())
4412 ArgSize = 8;
4413 bool NeedFPTrunc = false;
4414 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
4415 ArgSize = 8;
4416 NeedFPTrunc = true;
4417 }
4418
4419 // Increment the pointer, VAList, to the next vaarg
Mehdi Amini44ede332015-07-09 02:09:04 +00004420 SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4421 DAG.getConstant(ArgSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004422 // Store the incremented VAList to the legalized pointer
Justin Lebar9c375812016-07-15 18:27:10 +00004423 SDValue APStore =
4424 DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V));
Tim Northover3b0846e2014-05-24 12:50:23 +00004425
4426 // Load the actual argument out of the pointer VAList
4427 if (NeedFPTrunc) {
4428 // Load the value as an f64.
Justin Lebar9c375812016-07-15 18:27:10 +00004429 SDValue WideFP =
4430 DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00004431 // Round the value down to an f32.
4432 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004433 DAG.getIntPtrConstant(1, DL));
Tim Northover3b0846e2014-05-24 12:50:23 +00004434 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
4435 // Merge the rounded value with the chain output of the load.
4436 return DAG.getMergeValues(Ops, DL);
4437 }
4438
Justin Lebar9c375812016-07-15 18:27:10 +00004439 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00004440}
4441
4442SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
4443 SelectionDAG &DAG) const {
Matthias Braun941a7052016-07-28 18:40:00 +00004444 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
4445 MFI.setFrameAddressIsTaken(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00004446
4447 EVT VT = Op.getValueType();
4448 SDLoc DL(Op);
4449 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4450 SDValue FrameAddr =
4451 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
4452 while (Depth--)
4453 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
Justin Lebar9c375812016-07-15 18:27:10 +00004454 MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00004455 return FrameAddr;
4456}
4457
4458// FIXME? Maybe this could be a TableGen attribute on some registers and
4459// this table could be generated automatically from RegInfo.
Pat Gavlina717f252015-07-09 17:40:29 +00004460unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT,
4461 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004462 unsigned Reg = StringSwitch<unsigned>(RegName)
4463 .Case("sp", AArch64::SP)
4464 .Default(0);
4465 if (Reg)
4466 return Reg;
Luke Cheeseman85fd06d2015-06-01 12:02:47 +00004467 report_fatal_error(Twine("Invalid register name \""
4468 + StringRef(RegName) + "\"."));
Tim Northover3b0846e2014-05-24 12:50:23 +00004469}
4470
4471SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
4472 SelectionDAG &DAG) const {
4473 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braun941a7052016-07-28 18:40:00 +00004474 MachineFrameInfo &MFI = MF.getFrameInfo();
4475 MFI.setReturnAddressIsTaken(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00004476
4477 EVT VT = Op.getValueType();
4478 SDLoc DL(Op);
4479 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4480 if (Depth) {
4481 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
Mehdi Amini44ede332015-07-09 02:09:04 +00004482 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00004483 return DAG.getLoad(VT, DL, DAG.getEntryNode(),
4484 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
Justin Lebar9c375812016-07-15 18:27:10 +00004485 MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00004486 }
4487
4488 // Return LR, which contains the return address. Mark it an implicit live-in.
4489 unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
4490 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4491}
4492
4493/// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4494/// i64 values and take a 2 x i64 value to shift plus a shift amount.
4495SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
4496 SelectionDAG &DAG) const {
4497 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4498 EVT VT = Op.getValueType();
4499 unsigned VTBits = VT.getSizeInBits();
4500 SDLoc dl(Op);
4501 SDValue ShOpLo = Op.getOperand(0);
4502 SDValue ShOpHi = Op.getOperand(1);
4503 SDValue ShAmt = Op.getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00004504 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4505
4506 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4507
4508 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004509 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
Tim Northoverf3be9d52015-12-02 00:33:54 +00004510 SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4511
4512 // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
4513 // is "undef". We wanted 0, so CSEL it directly.
4514 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
4515 ISD::SETEQ, dl, DAG);
4516 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
4517 HiBitsForLo =
4518 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
4519 HiBitsForLo, CCVal, Cmp);
4520
Tim Northover3b0846e2014-05-24 12:50:23 +00004521 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004522 DAG.getConstant(VTBits, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00004523
Tim Northoverf3be9d52015-12-02 00:33:54 +00004524 SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4525 SDValue LoForNormalShift =
4526 DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
Tim Northover3b0846e2014-05-24 12:50:23 +00004527
Tim Northoverf3be9d52015-12-02 00:33:54 +00004528 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
4529 dl, DAG);
4530 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4531 SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4532 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
4533 LoForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00004534
4535 // AArch64 shifts larger than the register width are wrapped rather than
4536 // clamped, so we can't just emit "hi >> x".
Tim Northoverf3be9d52015-12-02 00:33:54 +00004537 SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4538 SDValue HiForBigShift =
4539 Opc == ISD::SRA
4540 ? DAG.getNode(Opc, dl, VT, ShOpHi,
4541 DAG.getConstant(VTBits - 1, dl, MVT::i64))
4542 : DAG.getConstant(0, dl, VT);
4543 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
4544 HiForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00004545
4546 SDValue Ops[2] = { Lo, Hi };
4547 return DAG.getMergeValues(Ops, dl);
4548}
4549
Tim Northoverf3be9d52015-12-02 00:33:54 +00004550
Tim Northover3b0846e2014-05-24 12:50:23 +00004551/// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4552/// i64 values and take a 2 x i64 value to shift plus a shift amount.
4553SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
Tim Northoverf3be9d52015-12-02 00:33:54 +00004554 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004555 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4556 EVT VT = Op.getValueType();
4557 unsigned VTBits = VT.getSizeInBits();
4558 SDLoc dl(Op);
4559 SDValue ShOpLo = Op.getOperand(0);
4560 SDValue ShOpHi = Op.getOperand(1);
4561 SDValue ShAmt = Op.getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00004562
4563 assert(Op.getOpcode() == ISD::SHL_PARTS);
4564 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004565 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
Tim Northoverf3be9d52015-12-02 00:33:54 +00004566 SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4567
4568 // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
4569 // is "undef". We wanted 0, so CSEL it directly.
4570 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
4571 ISD::SETEQ, dl, DAG);
4572 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
4573 LoBitsForHi =
4574 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
4575 LoBitsForHi, CCVal, Cmp);
4576
Tim Northover3b0846e2014-05-24 12:50:23 +00004577 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004578 DAG.getConstant(VTBits, dl, MVT::i64));
Tim Northoverf3be9d52015-12-02 00:33:54 +00004579 SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4580 SDValue HiForNormalShift =
4581 DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
Tim Northover3b0846e2014-05-24 12:50:23 +00004582
Tim Northoverf3be9d52015-12-02 00:33:54 +00004583 SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
Tim Northover3b0846e2014-05-24 12:50:23 +00004584
Tim Northoverf3be9d52015-12-02 00:33:54 +00004585 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
4586 dl, DAG);
4587 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4588 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
4589 HiForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00004590
4591 // AArch64 shifts of larger than register sizes are wrapped rather than
4592 // clamped, so we can't just emit "lo << a" if a is too big.
Tim Northoverf3be9d52015-12-02 00:33:54 +00004593 SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
4594 SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4595 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
4596 LoForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00004597
4598 SDValue Ops[2] = { Lo, Hi };
4599 return DAG.getMergeValues(Ops, dl);
4600}
4601
4602bool AArch64TargetLowering::isOffsetFoldingLegal(
4603 const GlobalAddressSDNode *GA) const {
4604 // The AArch64 target doesn't support folding offsets into global addresses.
4605 return false;
4606}
4607
4608bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4609 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
4610 // FIXME: We should be able to handle f128 as well with a clever lowering.
4611 if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32))
4612 return true;
4613
4614 if (VT == MVT::f64)
4615 return AArch64_AM::getFP64Imm(Imm) != -1;
4616 else if (VT == MVT::f32)
4617 return AArch64_AM::getFP32Imm(Imm) != -1;
4618 return false;
4619}
4620
4621//===----------------------------------------------------------------------===//
4622// AArch64 Optimization Hooks
4623//===----------------------------------------------------------------------===//
4624
Evandro Menezeseff2bd92016-10-24 16:14:58 +00004625static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode,
4626 SDValue Operand, SelectionDAG &DAG,
4627 int &ExtraSteps) {
4628 EVT VT = Operand.getValueType();
4629 if (ST->hasNEON() &&
4630 (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 ||
4631 VT == MVT::f32 || VT == MVT::v1f32 ||
4632 VT == MVT::v2f32 || VT == MVT::v4f32)) {
4633 if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified)
4634 // For the reciprocal estimates, convergence is quadratic, so the number
4635 // of digits is doubled after each iteration. In ARMv8, the accuracy of
4636 // the initial estimate is 2^-8. Thus the number of extra steps to refine
4637 // the result for float (23 mantissa bits) is 2 and for double (52
4638 // mantissa bits) is 3.
4639 ExtraSteps = VT == MVT::f64 ? 3 : 2;
4640
4641 return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand);
4642 }
4643
4644 return SDValue();
4645}
4646
4647SDValue AArch64TargetLowering::getRsqrtEstimate(SDValue Operand,
4648 SelectionDAG &DAG, int Enabled,
4649 int &ExtraSteps,
4650 bool &UseOneConst) const {
4651 if (Enabled == ReciprocalEstimate::Enabled ||
4652 (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt()))
4653 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, Operand,
4654 DAG, ExtraSteps)) {
4655 UseOneConst = true;
4656 return Estimate;
4657 }
4658
4659 return SDValue();
4660}
4661
4662SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand,
4663 SelectionDAG &DAG, int Enabled,
4664 int &ExtraSteps) const {
4665 if (Enabled == ReciprocalEstimate::Enabled)
4666 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand,
4667 DAG, ExtraSteps))
4668 return Estimate;
4669
4670 return SDValue();
4671}
4672
Tim Northover3b0846e2014-05-24 12:50:23 +00004673//===----------------------------------------------------------------------===//
4674// AArch64 Inline Assembly Support
4675//===----------------------------------------------------------------------===//
4676
4677// Table of Constraints
4678// TODO: This is the current set of constraints supported by ARM for the
4679// compiler, not all of them may make sense, e.g. S may be difficult to support.
4680//
4681// r - A general register
4682// w - An FP/SIMD register of some size in the range v0-v31
4683// x - An FP/SIMD register of some size in the range v0-v15
4684// I - Constant that can be used with an ADD instruction
4685// J - Constant that can be used with a SUB instruction
4686// K - Constant that can be used with a 32-bit logical instruction
4687// L - Constant that can be used with a 64-bit logical instruction
4688// M - Constant that can be used as a 32-bit MOV immediate
4689// N - Constant that can be used as a 64-bit MOV immediate
4690// Q - A memory reference with base register and no offset
4691// S - A symbolic address
4692// Y - Floating point constant zero
4693// Z - Integer constant zero
4694//
4695// Note that general register operands will be output using their 64-bit x
4696// register name, whatever the size of the variable, unless the asm operand
4697// is prefixed by the %w modifier. Floating-point and SIMD register operands
4698// will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
4699// %q modifier.
Silviu Barangaf60be282016-05-09 11:10:44 +00004700const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
4701 // At this point, we have to lower this constraint to something else, so we
4702 // lower it to an "r" or "w". However, by doing this we will force the result
4703 // to be in register, while the X constraint is much more permissive.
4704 //
4705 // Although we are correct (we are free to emit anything, without
4706 // constraints), we might break use cases that would expect us to be more
4707 // efficient and emit something else.
4708 if (!Subtarget->hasFPARMv8())
4709 return "r";
4710
4711 if (ConstraintVT.isFloatingPoint())
4712 return "w";
4713
4714 if (ConstraintVT.isVector() &&
4715 (ConstraintVT.getSizeInBits() == 64 ||
4716 ConstraintVT.getSizeInBits() == 128))
4717 return "w";
4718
4719 return "r";
4720}
Tim Northover3b0846e2014-05-24 12:50:23 +00004721
4722/// getConstraintType - Given a constraint letter, return the type of
4723/// constraint it is for this target.
4724AArch64TargetLowering::ConstraintType
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00004725AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004726 if (Constraint.size() == 1) {
4727 switch (Constraint[0]) {
4728 default:
4729 break;
4730 case 'z':
4731 return C_Other;
4732 case 'x':
4733 case 'w':
4734 return C_RegisterClass;
4735 // An address with a single base register. Due to the way we
4736 // currently handle addresses it is the same as 'r'.
4737 case 'Q':
4738 return C_Memory;
4739 }
4740 }
4741 return TargetLowering::getConstraintType(Constraint);
4742}
4743
4744/// Examine constraint type and operand type and determine a weight value.
4745/// This object must already have been set up with the operand type
4746/// and the current alternative constraint selected.
4747TargetLowering::ConstraintWeight
4748AArch64TargetLowering::getSingleConstraintMatchWeight(
4749 AsmOperandInfo &info, const char *constraint) const {
4750 ConstraintWeight weight = CW_Invalid;
4751 Value *CallOperandVal = info.CallOperandVal;
4752 // If we don't have a value, we can't do a match,
4753 // but allow it at the lowest weight.
4754 if (!CallOperandVal)
4755 return CW_Default;
4756 Type *type = CallOperandVal->getType();
4757 // Look at the constraint type.
4758 switch (*constraint) {
4759 default:
4760 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
4761 break;
4762 case 'x':
4763 case 'w':
4764 if (type->isFloatingPointTy() || type->isVectorTy())
4765 weight = CW_Register;
4766 break;
4767 case 'z':
4768 weight = CW_Constant;
4769 break;
4770 }
4771 return weight;
4772}
4773
4774std::pair<unsigned, const TargetRegisterClass *>
4775AArch64TargetLowering::getRegForInlineAsmConstraint(
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00004776 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004777 if (Constraint.size() == 1) {
4778 switch (Constraint[0]) {
4779 case 'r':
4780 if (VT.getSizeInBits() == 64)
4781 return std::make_pair(0U, &AArch64::GPR64commonRegClass);
4782 return std::make_pair(0U, &AArch64::GPR32commonRegClass);
4783 case 'w':
Amara Emerson614b44b2016-11-07 15:42:12 +00004784 if (VT.getSizeInBits() == 16)
4785 return std::make_pair(0U, &AArch64::FPR16RegClass);
Akira Hatanakab8d28732016-07-21 21:39:05 +00004786 if (VT.getSizeInBits() == 32)
Tim Northover3b0846e2014-05-24 12:50:23 +00004787 return std::make_pair(0U, &AArch64::FPR32RegClass);
4788 if (VT.getSizeInBits() == 64)
4789 return std::make_pair(0U, &AArch64::FPR64RegClass);
4790 if (VT.getSizeInBits() == 128)
4791 return std::make_pair(0U, &AArch64::FPR128RegClass);
4792 break;
4793 // The instructions that this constraint is designed for can
4794 // only take 128-bit registers so just use that regclass.
4795 case 'x':
4796 if (VT.getSizeInBits() == 128)
4797 return std::make_pair(0U, &AArch64::FPR128_loRegClass);
4798 break;
4799 }
4800 }
4801 if (StringRef("{cc}").equals_lower(Constraint))
4802 return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
4803
4804 // Use the default implementation in TargetLowering to convert the register
4805 // constraint into a member of a register class.
4806 std::pair<unsigned, const TargetRegisterClass *> Res;
Eric Christopher11e4df72015-02-26 22:38:43 +00004807 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004808
4809 // Not found as a standard register?
4810 if (!Res.second) {
4811 unsigned Size = Constraint.size();
4812 if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
4813 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00004814 int RegNo;
4815 bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
4816 if (!Failed && RegNo >= 0 && RegNo <= 31) {
Tim Northover9508a702016-05-10 22:26:45 +00004817 // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size.
Tim Northover3b0846e2014-05-24 12:50:23 +00004818 // By default we'll emit v0-v31 for this unless there's a modifier where
4819 // we'll emit the correct register as well.
Tim Northover9508a702016-05-10 22:26:45 +00004820 if (VT != MVT::Other && VT.getSizeInBits() == 64) {
4821 Res.first = AArch64::FPR64RegClass.getRegister(RegNo);
4822 Res.second = &AArch64::FPR64RegClass;
4823 } else {
4824 Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
4825 Res.second = &AArch64::FPR128RegClass;
4826 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004827 }
4828 }
4829 }
4830
4831 return Res;
4832}
4833
4834/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
4835/// vector. If it is invalid, don't add anything to Ops.
4836void AArch64TargetLowering::LowerAsmOperandForConstraint(
4837 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
4838 SelectionDAG &DAG) const {
4839 SDValue Result;
4840
4841 // Currently only support length 1 constraints.
4842 if (Constraint.length() != 1)
4843 return;
4844
4845 char ConstraintLetter = Constraint[0];
4846 switch (ConstraintLetter) {
4847 default:
4848 break;
4849
4850 // This set of constraints deal with valid constants for various instructions.
4851 // Validate and return a target constant for them if we can.
4852 case 'z': {
4853 // 'z' maps to xzr or wzr so it needs an input of 0.
Artyom Skrobov314ee042015-11-25 19:41:11 +00004854 if (!isNullConstant(Op))
Tim Northover3b0846e2014-05-24 12:50:23 +00004855 return;
4856
4857 if (Op.getValueType() == MVT::i64)
4858 Result = DAG.getRegister(AArch64::XZR, MVT::i64);
4859 else
4860 Result = DAG.getRegister(AArch64::WZR, MVT::i32);
4861 break;
4862 }
4863
4864 case 'I':
4865 case 'J':
4866 case 'K':
4867 case 'L':
4868 case 'M':
4869 case 'N':
4870 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4871 if (!C)
4872 return;
4873
4874 // Grab the value and do some validation.
4875 uint64_t CVal = C->getZExtValue();
4876 switch (ConstraintLetter) {
4877 // The I constraint applies only to simple ADD or SUB immediate operands:
4878 // i.e. 0 to 4095 with optional shift by 12
4879 // The J constraint applies only to ADD or SUB immediates that would be
4880 // valid when negated, i.e. if [an add pattern] were to be output as a SUB
4881 // instruction [or vice versa], in other words -1 to -4095 with optional
4882 // left shift by 12.
4883 case 'I':
4884 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
4885 break;
4886 return;
4887 case 'J': {
4888 uint64_t NVal = -C->getSExtValue();
Tim Northover2c46beb2014-07-27 07:10:29 +00004889 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
4890 CVal = C->getSExtValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00004891 break;
Tim Northover2c46beb2014-07-27 07:10:29 +00004892 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004893 return;
4894 }
4895 // The K and L constraints apply *only* to logical immediates, including
4896 // what used to be the MOVI alias for ORR (though the MOVI alias has now
4897 // been removed and MOV should be used). So these constraints have to
4898 // distinguish between bit patterns that are valid 32-bit or 64-bit
4899 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
4900 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
4901 // versa.
4902 case 'K':
4903 if (AArch64_AM::isLogicalImmediate(CVal, 32))
4904 break;
4905 return;
4906 case 'L':
4907 if (AArch64_AM::isLogicalImmediate(CVal, 64))
4908 break;
4909 return;
4910 // The M and N constraints are a superset of K and L respectively, for use
4911 // with the MOV (immediate) alias. As well as the logical immediates they
4912 // also match 32 or 64-bit immediates that can be loaded either using a
4913 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
4914 // (M) or 64-bit 0x1234000000000000 (N) etc.
4915 // As a note some of this code is liberally stolen from the asm parser.
4916 case 'M': {
4917 if (!isUInt<32>(CVal))
4918 return;
4919 if (AArch64_AM::isLogicalImmediate(CVal, 32))
4920 break;
4921 if ((CVal & 0xFFFF) == CVal)
4922 break;
4923 if ((CVal & 0xFFFF0000ULL) == CVal)
4924 break;
4925 uint64_t NCVal = ~(uint32_t)CVal;
4926 if ((NCVal & 0xFFFFULL) == NCVal)
4927 break;
4928 if ((NCVal & 0xFFFF0000ULL) == NCVal)
4929 break;
4930 return;
4931 }
4932 case 'N': {
4933 if (AArch64_AM::isLogicalImmediate(CVal, 64))
4934 break;
4935 if ((CVal & 0xFFFFULL) == CVal)
4936 break;
4937 if ((CVal & 0xFFFF0000ULL) == CVal)
4938 break;
4939 if ((CVal & 0xFFFF00000000ULL) == CVal)
4940 break;
4941 if ((CVal & 0xFFFF000000000000ULL) == CVal)
4942 break;
4943 uint64_t NCVal = ~CVal;
4944 if ((NCVal & 0xFFFFULL) == NCVal)
4945 break;
4946 if ((NCVal & 0xFFFF0000ULL) == NCVal)
4947 break;
4948 if ((NCVal & 0xFFFF00000000ULL) == NCVal)
4949 break;
4950 if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
4951 break;
4952 return;
4953 }
4954 default:
4955 return;
4956 }
4957
4958 // All assembler immediates are 64-bit integers.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004959 Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00004960 break;
4961 }
4962
4963 if (Result.getNode()) {
4964 Ops.push_back(Result);
4965 return;
4966 }
4967
4968 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
4969}
4970
4971//===----------------------------------------------------------------------===//
4972// AArch64 Advanced SIMD Support
4973//===----------------------------------------------------------------------===//
4974
4975/// WidenVector - Given a value in the V64 register class, produce the
4976/// equivalent value in the V128 register class.
4977static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
4978 EVT VT = V64Reg.getValueType();
4979 unsigned NarrowSize = VT.getVectorNumElements();
4980 MVT EltTy = VT.getVectorElementType().getSimpleVT();
4981 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
4982 SDLoc DL(V64Reg);
4983
4984 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004985 V64Reg, DAG.getConstant(0, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00004986}
4987
4988/// getExtFactor - Determine the adjustment factor for the position when
4989/// generating an "extract from vector registers" instruction.
4990static unsigned getExtFactor(SDValue &V) {
4991 EVT EltType = V.getValueType().getVectorElementType();
4992 return EltType.getSizeInBits() / 8;
4993}
4994
4995/// NarrowVector - Given a value in the V128 register class, produce the
4996/// equivalent value in the V64 register class.
4997static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
4998 EVT VT = V128Reg.getValueType();
4999 unsigned WideSize = VT.getVectorNumElements();
5000 MVT EltTy = VT.getVectorElementType().getSimpleVT();
5001 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
5002 SDLoc DL(V128Reg);
5003
5004 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
5005}
5006
5007// Gather data to see if the operation can be modelled as a
5008// shuffle in combination with VEXTs.
5009SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
5010 SelectionDAG &DAG) const {
Kevin Qinf0ec9af2014-06-18 05:54:42 +00005011 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
Tim Northover3b0846e2014-05-24 12:50:23 +00005012 SDLoc dl(Op);
5013 EVT VT = Op.getValueType();
5014 unsigned NumElts = VT.getVectorNumElements();
5015
Tim Northover7324e842014-07-24 15:39:55 +00005016 struct ShuffleSourceInfo {
5017 SDValue Vec;
5018 unsigned MinElt;
5019 unsigned MaxElt;
Tim Northover3b0846e2014-05-24 12:50:23 +00005020
Tim Northover7324e842014-07-24 15:39:55 +00005021 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
5022 // be compatible with the shuffle we intend to construct. As a result
5023 // ShuffleVec will be some sliding window into the original Vec.
5024 SDValue ShuffleVec;
5025
5026 // Code should guarantee that element i in Vec starts at element "WindowBase
5027 // + i * WindowScale in ShuffleVec".
5028 int WindowBase;
5029 int WindowScale;
5030
5031 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
5032 ShuffleSourceInfo(SDValue Vec)
5033 : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
5034 WindowScale(1) {}
5035 };
5036
5037 // First gather all vectors used as an immediate source for this BUILD_VECTOR
5038 // node.
5039 SmallVector<ShuffleSourceInfo, 2> Sources;
Tim Northover3b0846e2014-05-24 12:50:23 +00005040 for (unsigned i = 0; i < NumElts; ++i) {
5041 SDValue V = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00005042 if (V.isUndef())
Tim Northover3b0846e2014-05-24 12:50:23 +00005043 continue;
Ahmed Bougachadfc77352016-01-14 02:12:30 +00005044 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5045 !isa<ConstantSDNode>(V.getOperand(1))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005046 // A shuffle can only come from building a vector from various
Ahmed Bougachadfc77352016-01-14 02:12:30 +00005047 // elements of other vectors, provided their indices are constant.
Tim Northover3b0846e2014-05-24 12:50:23 +00005048 return SDValue();
5049 }
5050
Tim Northover7324e842014-07-24 15:39:55 +00005051 // Add this element source to the list if it's not already there.
Tim Northover3b0846e2014-05-24 12:50:23 +00005052 SDValue SourceVec = V.getOperand(0);
David Majnemer0d955d02016-08-11 22:21:41 +00005053 auto Source = find(Sources, SourceVec);
Tim Northover7324e842014-07-24 15:39:55 +00005054 if (Source == Sources.end())
James Molloyf497d552014-10-17 17:06:31 +00005055 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
Tim Northover3b0846e2014-05-24 12:50:23 +00005056
Tim Northover7324e842014-07-24 15:39:55 +00005057 // Update the minimum and maximum lane number seen.
5058 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5059 Source->MinElt = std::min(Source->MinElt, EltNo);
5060 Source->MaxElt = std::max(Source->MaxElt, EltNo);
Tim Northover3b0846e2014-05-24 12:50:23 +00005061 }
5062
5063 // Currently only do something sane when at most two source vectors
Tim Northover7324e842014-07-24 15:39:55 +00005064 // are involved.
5065 if (Sources.size() > 2)
Tim Northover3b0846e2014-05-24 12:50:23 +00005066 return SDValue();
5067
Kevin Qin9a2a2c52014-07-24 02:05:42 +00005068 // Find out the smallest element size among result and two sources, and use
5069 // it as element size to build the shuffle_vector.
5070 EVT SmallestEltTy = VT.getVectorElementType();
Tim Northover7324e842014-07-24 15:39:55 +00005071 for (auto &Source : Sources) {
5072 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00005073 if (SrcEltTy.bitsLT(SmallestEltTy)) {
5074 SmallestEltTy = SrcEltTy;
5075 }
5076 }
5077 unsigned ResMultiplier =
Sanjay Patel1ed771f2016-09-14 16:37:15 +00005078 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00005079 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
5080 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
Tim Northover3b0846e2014-05-24 12:50:23 +00005081
Tim Northover7324e842014-07-24 15:39:55 +00005082 // If the source vector is too wide or too narrow, we may nevertheless be able
5083 // to construct a compatible shuffle either by concatenating it with UNDEF or
5084 // extracting a suitable range of elements.
5085 for (auto &Src : Sources) {
5086 EVT SrcVT = Src.ShuffleVec.getValueType();
Kevin Qinf0ec9af2014-06-18 05:54:42 +00005087
Tim Northover7324e842014-07-24 15:39:55 +00005088 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
Tim Northover3b0846e2014-05-24 12:50:23 +00005089 continue;
Tim Northover7324e842014-07-24 15:39:55 +00005090
5091 // This stage of the search produces a source with the same element type as
5092 // the original, but with a total width matching the BUILD_VECTOR output.
5093 EVT EltVT = SrcVT.getVectorElementType();
James Molloyf497d552014-10-17 17:06:31 +00005094 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
5095 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
Tim Northover7324e842014-07-24 15:39:55 +00005096
5097 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
5098 assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00005099 // We can pad out the smaller vector for free, so if it's part of a
5100 // shuffle...
Tim Northover7324e842014-07-24 15:39:55 +00005101 Src.ShuffleVec =
5102 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
5103 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00005104 continue;
5105 }
5106
Tim Northover7324e842014-07-24 15:39:55 +00005107 assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00005108
James Molloyf497d552014-10-17 17:06:31 +00005109 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005110 // Span too large for a VEXT to cope
5111 return SDValue();
5112 }
5113
James Molloyf497d552014-10-17 17:06:31 +00005114 if (Src.MinElt >= NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005115 // The extraction can just take the second half
Tim Northover7324e842014-07-24 15:39:55 +00005116 Src.ShuffleVec =
5117 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005118 DAG.getConstant(NumSrcElts, dl, MVT::i64));
James Molloyf497d552014-10-17 17:06:31 +00005119 Src.WindowBase = -NumSrcElts;
5120 } else if (Src.MaxElt < NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005121 // The extraction can just take the first half
Tim Northover5e84fe32014-12-06 00:33:37 +00005122 Src.ShuffleVec =
5123 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005124 DAG.getConstant(0, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005125 } else {
5126 // An actual VEXT is needed
Tim Northover5e84fe32014-12-06 00:33:37 +00005127 SDValue VEXTSrc1 =
5128 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005129 DAG.getConstant(0, dl, MVT::i64));
Tim Northover7324e842014-07-24 15:39:55 +00005130 SDValue VEXTSrc2 =
5131 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005132 DAG.getConstant(NumSrcElts, dl, MVT::i64));
Tim Northover7324e842014-07-24 15:39:55 +00005133 unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
5134
5135 Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005136 VEXTSrc2,
5137 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover7324e842014-07-24 15:39:55 +00005138 Src.WindowBase = -Src.MinElt;
Tim Northover3b0846e2014-05-24 12:50:23 +00005139 }
5140 }
5141
Tim Northover7324e842014-07-24 15:39:55 +00005142 // Another possible incompatibility occurs from the vector element types. We
5143 // can fix this by bitcasting the source vectors to the same type we intend
5144 // for the shuffle.
5145 for (auto &Src : Sources) {
5146 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
5147 if (SrcEltTy == SmallestEltTy)
5148 continue;
5149 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
5150 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
5151 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
5152 Src.WindowBase *= Src.WindowScale;
5153 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005154
Tim Northover7324e842014-07-24 15:39:55 +00005155 // Final sanity check before we try to actually produce a shuffle.
5156 DEBUG(
5157 for (auto Src : Sources)
5158 assert(Src.ShuffleVec.getValueType() == ShuffleVT);
5159 );
5160
5161 // The stars all align, our next step is to produce the mask for the shuffle.
5162 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
Sanjay Patel1ed771f2016-09-14 16:37:15 +00005163 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00005164 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005165 SDValue Entry = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00005166 if (Entry.isUndef())
Tim Northover7324e842014-07-24 15:39:55 +00005167 continue;
Tim Northover3b0846e2014-05-24 12:50:23 +00005168
David Majnemer0d955d02016-08-11 22:21:41 +00005169 auto Src = find(Sources, Entry.getOperand(0));
Tim Northover7324e842014-07-24 15:39:55 +00005170 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
5171
5172 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
5173 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
5174 // segment.
5175 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
Sanjay Patel1ed771f2016-09-14 16:37:15 +00005176 int BitsDefined =
5177 std::min(OrigEltTy.getSizeInBits(), VT.getScalarSizeInBits());
Tim Northover7324e842014-07-24 15:39:55 +00005178 int LanesDefined = BitsDefined / BitsPerShuffleLane;
5179
5180 // This source is expected to fill ResMultiplier lanes of the final shuffle,
5181 // starting at the appropriate offset.
5182 int *LaneMask = &Mask[i * ResMultiplier];
5183
5184 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
5185 ExtractBase += NumElts * (Src - Sources.begin());
5186 for (int j = 0; j < LanesDefined; ++j)
5187 LaneMask[j] = ExtractBase + j;
Tim Northover3b0846e2014-05-24 12:50:23 +00005188 }
5189
5190 // Final check before we try to produce nonsense...
Tim Northover7324e842014-07-24 15:39:55 +00005191 if (!isShuffleMaskLegal(Mask, ShuffleVT))
5192 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00005193
Tim Northover7324e842014-07-24 15:39:55 +00005194 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
5195 for (unsigned i = 0; i < Sources.size(); ++i)
5196 ShuffleOps[i] = Sources[i].ShuffleVec;
5197
5198 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
Craig Topper2bd8b4b2016-07-01 06:54:47 +00005199 ShuffleOps[1], Mask);
Tim Northover7324e842014-07-24 15:39:55 +00005200 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
Tim Northover3b0846e2014-05-24 12:50:23 +00005201}
5202
5203// check if an EXT instruction can handle the shuffle mask when the
5204// vector sources of the shuffle are the same.
5205static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
5206 unsigned NumElts = VT.getVectorNumElements();
5207
5208 // Assume that the first shuffle index is not UNDEF. Fail if it is.
5209 if (M[0] < 0)
5210 return false;
5211
5212 Imm = M[0];
5213
5214 // If this is a VEXT shuffle, the immediate value is the index of the first
5215 // element. The other shuffle indices must be the successive elements after
5216 // the first one.
5217 unsigned ExpectedElt = Imm;
5218 for (unsigned i = 1; i < NumElts; ++i) {
5219 // Increment the expected index. If it wraps around, just follow it
5220 // back to index zero and keep going.
5221 ++ExpectedElt;
5222 if (ExpectedElt == NumElts)
5223 ExpectedElt = 0;
5224
5225 if (M[i] < 0)
5226 continue; // ignore UNDEF indices
5227 if (ExpectedElt != static_cast<unsigned>(M[i]))
5228 return false;
5229 }
5230
5231 return true;
5232}
5233
5234// check if an EXT instruction can handle the shuffle mask when the
5235// vector sources of the shuffle are different.
5236static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
5237 unsigned &Imm) {
5238 // Look for the first non-undef element.
David Majnemer562e8292016-08-12 00:18:03 +00005239 const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; });
Tim Northover3b0846e2014-05-24 12:50:23 +00005240
5241 // Benefit form APInt to handle overflow when calculating expected element.
5242 unsigned NumElts = VT.getVectorNumElements();
5243 unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
5244 APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
5245 // The following shuffle indices must be the successive elements after the
5246 // first real element.
5247 const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
5248 [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
5249 if (FirstWrongElt != M.end())
5250 return false;
5251
5252 // The index of an EXT is the first element if it is not UNDEF.
5253 // Watch out for the beginning UNDEFs. The EXT index should be the expected
Junmo Park3b8c7152016-01-05 09:36:47 +00005254 // value of the first element. E.g.
Tim Northover3b0846e2014-05-24 12:50:23 +00005255 // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
5256 // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
5257 // ExpectedElt is the last mask index plus 1.
5258 Imm = ExpectedElt.getZExtValue();
5259
5260 // There are two difference cases requiring to reverse input vectors.
5261 // For example, for vector <4 x i32> we have the following cases,
5262 // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
5263 // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
5264 // For both cases, we finally use mask <5, 6, 7, 0>, which requires
5265 // to reverse two input vectors.
5266 if (Imm < NumElts)
5267 ReverseEXT = true;
5268 else
5269 Imm -= NumElts;
5270
5271 return true;
5272}
5273
5274/// isREVMask - Check if a vector shuffle corresponds to a REV
5275/// instruction with the specified blocksize. (The order of the elements
5276/// within each block of the vector is reversed.)
5277static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5278 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
5279 "Only possible block sizes for REV are: 16, 32, 64");
5280
Sanjay Patel1ed771f2016-09-14 16:37:15 +00005281 unsigned EltSz = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00005282 if (EltSz == 64)
5283 return false;
5284
5285 unsigned NumElts = VT.getVectorNumElements();
5286 unsigned BlockElts = M[0] + 1;
5287 // If the first shuffle index is UNDEF, be optimistic.
5288 if (M[0] < 0)
5289 BlockElts = BlockSize / EltSz;
5290
5291 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5292 return false;
5293
5294 for (unsigned i = 0; i < NumElts; ++i) {
5295 if (M[i] < 0)
5296 continue; // ignore UNDEF indices
5297 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
5298 return false;
5299 }
5300
5301 return true;
5302}
5303
5304static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5305 unsigned NumElts = VT.getVectorNumElements();
5306 WhichResult = (M[0] == 0 ? 0 : 1);
5307 unsigned Idx = WhichResult * NumElts / 2;
5308 for (unsigned i = 0; i != NumElts; i += 2) {
5309 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5310 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
5311 return false;
5312 Idx += 1;
5313 }
5314
5315 return true;
5316}
5317
5318static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5319 unsigned NumElts = VT.getVectorNumElements();
5320 WhichResult = (M[0] == 0 ? 0 : 1);
5321 for (unsigned i = 0; i != NumElts; ++i) {
5322 if (M[i] < 0)
5323 continue; // ignore UNDEF indices
5324 if ((unsigned)M[i] != 2 * i + WhichResult)
5325 return false;
5326 }
5327
5328 return true;
5329}
5330
5331static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5332 unsigned NumElts = VT.getVectorNumElements();
5333 WhichResult = (M[0] == 0 ? 0 : 1);
5334 for (unsigned i = 0; i < NumElts; i += 2) {
5335 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5336 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
5337 return false;
5338 }
5339 return true;
5340}
5341
5342/// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
5343/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5344/// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5345static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5346 unsigned NumElts = VT.getVectorNumElements();
5347 WhichResult = (M[0] == 0 ? 0 : 1);
5348 unsigned Idx = WhichResult * NumElts / 2;
5349 for (unsigned i = 0; i != NumElts; i += 2) {
5350 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5351 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
5352 return false;
5353 Idx += 1;
5354 }
5355
5356 return true;
5357}
5358
5359/// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
5360/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5361/// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5362static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5363 unsigned Half = VT.getVectorNumElements() / 2;
5364 WhichResult = (M[0] == 0 ? 0 : 1);
5365 for (unsigned j = 0; j != 2; ++j) {
5366 unsigned Idx = WhichResult;
5367 for (unsigned i = 0; i != Half; ++i) {
5368 int MIdx = M[i + j * Half];
5369 if (MIdx >= 0 && (unsigned)MIdx != Idx)
5370 return false;
5371 Idx += 2;
5372 }
5373 }
5374
5375 return true;
5376}
5377
5378/// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
5379/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5380/// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5381static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5382 unsigned NumElts = VT.getVectorNumElements();
5383 WhichResult = (M[0] == 0 ? 0 : 1);
5384 for (unsigned i = 0; i < NumElts; i += 2) {
5385 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5386 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
5387 return false;
5388 }
5389 return true;
5390}
5391
5392static bool isINSMask(ArrayRef<int> M, int NumInputElements,
5393 bool &DstIsLeft, int &Anomaly) {
5394 if (M.size() != static_cast<size_t>(NumInputElements))
5395 return false;
5396
5397 int NumLHSMatch = 0, NumRHSMatch = 0;
5398 int LastLHSMismatch = -1, LastRHSMismatch = -1;
5399
5400 for (int i = 0; i < NumInputElements; ++i) {
5401 if (M[i] == -1) {
5402 ++NumLHSMatch;
5403 ++NumRHSMatch;
5404 continue;
5405 }
5406
5407 if (M[i] == i)
5408 ++NumLHSMatch;
5409 else
5410 LastLHSMismatch = i;
5411
5412 if (M[i] == i + NumInputElements)
5413 ++NumRHSMatch;
5414 else
5415 LastRHSMismatch = i;
5416 }
5417
5418 if (NumLHSMatch == NumInputElements - 1) {
5419 DstIsLeft = true;
5420 Anomaly = LastLHSMismatch;
5421 return true;
5422 } else if (NumRHSMatch == NumInputElements - 1) {
5423 DstIsLeft = false;
5424 Anomaly = LastRHSMismatch;
5425 return true;
5426 }
5427
5428 return false;
5429}
5430
5431static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
5432 if (VT.getSizeInBits() != 128)
5433 return false;
5434
5435 unsigned NumElts = VT.getVectorNumElements();
5436
5437 for (int I = 0, E = NumElts / 2; I != E; I++) {
5438 if (Mask[I] != I)
5439 return false;
5440 }
5441
5442 int Offset = NumElts / 2;
5443 for (int I = NumElts / 2, E = NumElts; I != E; I++) {
5444 if (Mask[I] != I + SplitLHS * Offset)
5445 return false;
5446 }
5447
5448 return true;
5449}
5450
5451static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
5452 SDLoc DL(Op);
5453 EVT VT = Op.getValueType();
5454 SDValue V0 = Op.getOperand(0);
5455 SDValue V1 = Op.getOperand(1);
5456 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
5457
5458 if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
5459 VT.getVectorElementType() != V1.getValueType().getVectorElementType())
5460 return SDValue();
5461
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00005462 bool SplitV0 = V0.getValueSizeInBits() == 128;
Tim Northover3b0846e2014-05-24 12:50:23 +00005463
5464 if (!isConcatMask(Mask, VT, SplitV0))
5465 return SDValue();
5466
5467 EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
5468 VT.getVectorNumElements() / 2);
5469 if (SplitV0) {
5470 V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005471 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005472 }
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00005473 if (V1.getValueSizeInBits() == 128) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005474 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005475 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005476 }
5477 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
5478}
5479
5480/// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5481/// the specified operations to build the shuffle.
5482static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5483 SDValue RHS, SelectionDAG &DAG,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00005484 const SDLoc &dl) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005485 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5486 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
5487 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
5488
5489 enum {
5490 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5491 OP_VREV,
5492 OP_VDUP0,
5493 OP_VDUP1,
5494 OP_VDUP2,
5495 OP_VDUP3,
5496 OP_VEXT1,
5497 OP_VEXT2,
5498 OP_VEXT3,
5499 OP_VUZPL, // VUZP, left result
5500 OP_VUZPR, // VUZP, right result
5501 OP_VZIPL, // VZIP, left result
5502 OP_VZIPR, // VZIP, right result
5503 OP_VTRNL, // VTRN, left result
5504 OP_VTRNR // VTRN, right result
5505 };
5506
5507 if (OpNum == OP_COPY) {
5508 if (LHSID == (1 * 9 + 2) * 9 + 3)
5509 return LHS;
5510 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
5511 return RHS;
5512 }
5513
5514 SDValue OpLHS, OpRHS;
5515 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5516 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5517 EVT VT = OpLHS.getValueType();
5518
5519 switch (OpNum) {
5520 default:
5521 llvm_unreachable("Unknown shuffle opcode!");
5522 case OP_VREV:
5523 // VREV divides the vector in half and swaps within the half.
5524 if (VT.getVectorElementType() == MVT::i32 ||
5525 VT.getVectorElementType() == MVT::f32)
5526 return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
5527 // vrev <4 x i16> -> REV32
Oliver Stannard89d15422014-08-27 16:16:04 +00005528 if (VT.getVectorElementType() == MVT::i16 ||
5529 VT.getVectorElementType() == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00005530 return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
5531 // vrev <4 x i8> -> REV16
5532 assert(VT.getVectorElementType() == MVT::i8);
5533 return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
5534 case OP_VDUP0:
5535 case OP_VDUP1:
5536 case OP_VDUP2:
5537 case OP_VDUP3: {
5538 EVT EltTy = VT.getVectorElementType();
5539 unsigned Opcode;
5540 if (EltTy == MVT::i8)
5541 Opcode = AArch64ISD::DUPLANE8;
Ahmed Bougacha941420d2015-04-16 23:57:07 +00005542 else if (EltTy == MVT::i16 || EltTy == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00005543 Opcode = AArch64ISD::DUPLANE16;
5544 else if (EltTy == MVT::i32 || EltTy == MVT::f32)
5545 Opcode = AArch64ISD::DUPLANE32;
5546 else if (EltTy == MVT::i64 || EltTy == MVT::f64)
5547 Opcode = AArch64ISD::DUPLANE64;
5548 else
5549 llvm_unreachable("Invalid vector element type?");
5550
5551 if (VT.getSizeInBits() == 64)
5552 OpLHS = WidenVector(OpLHS, DAG);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005553 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00005554 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
5555 }
5556 case OP_VEXT1:
5557 case OP_VEXT2:
5558 case OP_VEXT3: {
5559 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
5560 return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005561 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005562 }
5563 case OP_VUZPL:
5564 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
5565 OpRHS);
5566 case OP_VUZPR:
5567 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
5568 OpRHS);
5569 case OP_VZIPL:
5570 return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
5571 OpRHS);
5572 case OP_VZIPR:
5573 return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
5574 OpRHS);
5575 case OP_VTRNL:
5576 return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
5577 OpRHS);
5578 case OP_VTRNR:
5579 return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
5580 OpRHS);
5581 }
5582}
5583
5584static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
5585 SelectionDAG &DAG) {
5586 // Check to see if we can use the TBL instruction.
5587 SDValue V1 = Op.getOperand(0);
5588 SDValue V2 = Op.getOperand(1);
5589 SDLoc DL(Op);
5590
5591 EVT EltVT = Op.getValueType().getVectorElementType();
5592 unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
5593
5594 SmallVector<SDValue, 8> TBLMask;
5595 for (int Val : ShuffleMask) {
5596 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
5597 unsigned Offset = Byte + Val * BytesPerElt;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005598 TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005599 }
5600 }
5601
5602 MVT IndexVT = MVT::v8i8;
5603 unsigned IndexLen = 8;
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00005604 if (Op.getValueSizeInBits() == 128) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005605 IndexVT = MVT::v16i8;
5606 IndexLen = 16;
5607 }
5608
5609 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
5610 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
5611
5612 SDValue Shuffle;
Sanjay Patel57195842016-03-14 17:28:46 +00005613 if (V2.getNode()->isUndef()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005614 if (IndexLen == 8)
5615 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
5616 Shuffle = DAG.getNode(
5617 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005618 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00005619 DAG.getBuildVector(IndexVT, DL,
5620 makeArrayRef(TBLMask.data(), IndexLen)));
Tim Northover3b0846e2014-05-24 12:50:23 +00005621 } else {
5622 if (IndexLen == 8) {
5623 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
5624 Shuffle = DAG.getNode(
5625 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005626 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00005627 DAG.getBuildVector(IndexVT, DL,
5628 makeArrayRef(TBLMask.data(), IndexLen)));
Tim Northover3b0846e2014-05-24 12:50:23 +00005629 } else {
5630 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
5631 // cannot currently represent the register constraints on the input
5632 // table registers.
5633 // Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00005634 // DAG.getBuildVector(IndexVT, DL, &TBLMask[0],
5635 // IndexLen));
Tim Northover3b0846e2014-05-24 12:50:23 +00005636 Shuffle = DAG.getNode(
5637 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00005638 DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst,
5639 V2Cst, DAG.getBuildVector(IndexVT, DL,
5640 makeArrayRef(TBLMask.data(), IndexLen)));
Tim Northover3b0846e2014-05-24 12:50:23 +00005641 }
5642 }
5643 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
5644}
5645
5646static unsigned getDUPLANEOp(EVT EltType) {
5647 if (EltType == MVT::i8)
5648 return AArch64ISD::DUPLANE8;
Oliver Stannard89d15422014-08-27 16:16:04 +00005649 if (EltType == MVT::i16 || EltType == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00005650 return AArch64ISD::DUPLANE16;
5651 if (EltType == MVT::i32 || EltType == MVT::f32)
5652 return AArch64ISD::DUPLANE32;
5653 if (EltType == MVT::i64 || EltType == MVT::f64)
5654 return AArch64ISD::DUPLANE64;
5655
5656 llvm_unreachable("Invalid vector element type?");
5657}
5658
5659SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5660 SelectionDAG &DAG) const {
5661 SDLoc dl(Op);
5662 EVT VT = Op.getValueType();
5663
5664 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5665
5666 // Convert shuffles that are directly supported on NEON to target-specific
5667 // DAG nodes, instead of keeping them as shuffles and matching them again
5668 // during code selection. This is more efficient and avoids the possibility
5669 // of inconsistencies between legalization and selection.
5670 ArrayRef<int> ShuffleMask = SVN->getMask();
5671
5672 SDValue V1 = Op.getOperand(0);
5673 SDValue V2 = Op.getOperand(1);
5674
Craig Topperbc56e3b2016-06-30 04:38:51 +00005675 if (SVN->isSplat()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005676 int Lane = SVN->getSplatIndex();
5677 // If this is undef splat, generate it via "just" vdup, if possible.
5678 if (Lane == -1)
5679 Lane = 0;
5680
5681 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
5682 return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
5683 V1.getOperand(0));
5684 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
5685 // constant. If so, we can just reference the lane's definition directly.
5686 if (V1.getOpcode() == ISD::BUILD_VECTOR &&
5687 !isa<ConstantSDNode>(V1.getOperand(Lane)))
5688 return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
5689
5690 // Otherwise, duplicate from the lane of the input vector.
5691 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
5692
5693 // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
5694 // to make a vector of the same size as this SHUFFLE. We can ignore the
5695 // extract entirely, and canonicalise the concat using WidenVector.
5696 if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
5697 Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
5698 V1 = V1.getOperand(0);
5699 } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
5700 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
5701 Lane -= Idx * VT.getVectorNumElements() / 2;
5702 V1 = WidenVector(V1.getOperand(Idx), DAG);
5703 } else if (VT.getSizeInBits() == 64)
5704 V1 = WidenVector(V1, DAG);
5705
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005706 return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005707 }
5708
5709 if (isREVMask(ShuffleMask, VT, 64))
5710 return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
5711 if (isREVMask(ShuffleMask, VT, 32))
5712 return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
5713 if (isREVMask(ShuffleMask, VT, 16))
5714 return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
5715
5716 bool ReverseEXT = false;
5717 unsigned Imm;
5718 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
5719 if (ReverseEXT)
5720 std::swap(V1, V2);
5721 Imm *= getExtFactor(V1);
5722 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005723 DAG.getConstant(Imm, dl, MVT::i32));
Sanjay Patel57195842016-03-14 17:28:46 +00005724 } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005725 Imm *= getExtFactor(V1);
5726 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005727 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005728 }
5729
5730 unsigned WhichResult;
5731 if (isZIPMask(ShuffleMask, VT, WhichResult)) {
5732 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5733 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5734 }
5735 if (isUZPMask(ShuffleMask, VT, WhichResult)) {
5736 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5737 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5738 }
5739 if (isTRNMask(ShuffleMask, VT, WhichResult)) {
5740 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5741 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5742 }
5743
5744 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5745 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5746 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5747 }
5748 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5749 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5750 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5751 }
5752 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5753 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5754 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5755 }
5756
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00005757 if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00005758 return Concat;
5759
5760 bool DstIsLeft;
5761 int Anomaly;
5762 int NumInputElements = V1.getValueType().getVectorNumElements();
5763 if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
5764 SDValue DstVec = DstIsLeft ? V1 : V2;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005765 SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00005766
5767 SDValue SrcVec = V1;
5768 int SrcLane = ShuffleMask[Anomaly];
5769 if (SrcLane >= NumInputElements) {
5770 SrcVec = V2;
5771 SrcLane -= VT.getVectorNumElements();
5772 }
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005773 SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00005774
5775 EVT ScalarVT = VT.getVectorElementType();
Oliver Stannard89d15422014-08-27 16:16:04 +00005776
5777 if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00005778 ScalarVT = MVT::i32;
5779
5780 return DAG.getNode(
5781 ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5782 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
5783 DstLaneV);
5784 }
5785
5786 // If the shuffle is not directly supported and it has 4 elements, use
5787 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5788 unsigned NumElts = VT.getVectorNumElements();
5789 if (NumElts == 4) {
5790 unsigned PFIndexes[4];
5791 for (unsigned i = 0; i != 4; ++i) {
5792 if (ShuffleMask[i] < 0)
5793 PFIndexes[i] = 8;
5794 else
5795 PFIndexes[i] = ShuffleMask[i];
5796 }
5797
5798 // Compute the index in the perfect shuffle table.
5799 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
5800 PFIndexes[2] * 9 + PFIndexes[3];
5801 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5802 unsigned Cost = (PFEntry >> 30);
5803
5804 if (Cost <= 4)
5805 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5806 }
5807
5808 return GenerateTBL(Op, ShuffleMask, DAG);
5809}
5810
5811static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
5812 APInt &UndefBits) {
5813 EVT VT = BVN->getValueType(0);
5814 APInt SplatBits, SplatUndef;
5815 unsigned SplatBitSize;
5816 bool HasAnyUndefs;
5817 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5818 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
5819
5820 for (unsigned i = 0; i < NumSplats; ++i) {
5821 CnstBits <<= SplatBitSize;
5822 UndefBits <<= SplatBitSize;
5823 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
5824 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
5825 }
5826
5827 return true;
5828 }
5829
5830 return false;
5831}
5832
5833SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op,
5834 SelectionDAG &DAG) const {
5835 BuildVectorSDNode *BVN =
5836 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5837 SDValue LHS = Op.getOperand(0);
5838 SDLoc dl(Op);
5839 EVT VT = Op.getValueType();
5840
5841 if (!BVN)
5842 return Op;
5843
5844 APInt CnstBits(VT.getSizeInBits(), 0);
5845 APInt UndefBits(VT.getSizeInBits(), 0);
5846 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5847 // We only have BIC vector immediate instruction, which is and-not.
5848 CnstBits = ~CnstBits;
5849
5850 // We make use of a little bit of goto ickiness in order to avoid having to
5851 // duplicate the immediate matching logic for the undef toggled case.
5852 bool SecondTry = false;
5853 AttemptModImm:
5854
5855 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5856 CnstBits = CnstBits.zextOrTrunc(64);
5857 uint64_t CnstVal = CnstBits.getZExtValue();
5858
5859 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5860 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5861 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5862 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005863 DAG.getConstant(CnstVal, dl, MVT::i32),
5864 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005865 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005866 }
5867
5868 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5869 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5870 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5871 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005872 DAG.getConstant(CnstVal, dl, MVT::i32),
5873 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005874 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005875 }
5876
5877 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5878 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5879 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5880 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005881 DAG.getConstant(CnstVal, dl, MVT::i32),
5882 DAG.getConstant(16, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005883 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005884 }
5885
5886 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5887 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5888 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5889 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005890 DAG.getConstant(CnstVal, dl, MVT::i32),
5891 DAG.getConstant(24, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005892 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005893 }
5894
5895 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5896 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5897 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5898 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005899 DAG.getConstant(CnstVal, dl, MVT::i32),
5900 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005901 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005902 }
5903
5904 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5905 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5906 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5907 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005908 DAG.getConstant(CnstVal, dl, MVT::i32),
5909 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005910 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005911 }
5912 }
5913
5914 if (SecondTry)
5915 goto FailedModImm;
5916 SecondTry = true;
5917 CnstBits = ~UndefBits;
5918 goto AttemptModImm;
5919 }
5920
5921// We can always fall back to a non-immediate AND.
5922FailedModImm:
5923 return Op;
5924}
5925
5926// Specialized code to quickly find if PotentialBVec is a BuildVector that
5927// consists of only the same constant int value, returned in reference arg
5928// ConstVal
5929static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
5930 uint64_t &ConstVal) {
5931 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
5932 if (!Bvec)
5933 return false;
5934 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
5935 if (!FirstElt)
5936 return false;
5937 EVT VT = Bvec->getValueType(0);
5938 unsigned NumElts = VT.getVectorNumElements();
5939 for (unsigned i = 1; i < NumElts; ++i)
5940 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
5941 return false;
5942 ConstVal = FirstElt->getZExtValue();
5943 return true;
5944}
5945
5946static unsigned getIntrinsicID(const SDNode *N) {
5947 unsigned Opcode = N->getOpcode();
5948 switch (Opcode) {
5949 default:
5950 return Intrinsic::not_intrinsic;
5951 case ISD::INTRINSIC_WO_CHAIN: {
5952 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
5953 if (IID < Intrinsic::num_intrinsics)
5954 return IID;
5955 return Intrinsic::not_intrinsic;
5956 }
5957 }
5958}
5959
5960// Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
5961// to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
5962// BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
5963// Also, logical shift right -> sri, with the same structure.
5964static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
5965 EVT VT = N->getValueType(0);
5966
5967 if (!VT.isVector())
5968 return SDValue();
5969
5970 SDLoc DL(N);
5971
5972 // Is the first op an AND?
5973 const SDValue And = N->getOperand(0);
5974 if (And.getOpcode() != ISD::AND)
5975 return SDValue();
5976
5977 // Is the second op an shl or lshr?
5978 SDValue Shift = N->getOperand(1);
5979 // This will have been turned into: AArch64ISD::VSHL vector, #shift
5980 // or AArch64ISD::VLSHR vector, #shift
5981 unsigned ShiftOpc = Shift.getOpcode();
5982 if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
5983 return SDValue();
5984 bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
5985
5986 // Is the shift amount constant?
5987 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
5988 if (!C2node)
5989 return SDValue();
5990
5991 // Is the and mask vector all constant?
5992 uint64_t C1;
5993 if (!isAllConstantBuildVector(And.getOperand(1), C1))
5994 return SDValue();
5995
5996 // Is C1 == ~C2, taking into account how much one can shift elements of a
5997 // particular size?
5998 uint64_t C2 = C2node->getZExtValue();
Sanjay Patel1ed771f2016-09-14 16:37:15 +00005999 unsigned ElemSizeInBits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00006000 if (C2 > ElemSizeInBits)
6001 return SDValue();
6002 unsigned ElemMask = (1 << ElemSizeInBits) - 1;
6003 if ((C1 & ElemMask) != (~C2 & ElemMask))
6004 return SDValue();
6005
6006 SDValue X = And.getOperand(0);
6007 SDValue Y = Shift.getOperand(0);
6008
6009 unsigned Intrin =
6010 IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
6011 SDValue ResultSLI =
6012 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006013 DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
6014 Shift.getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00006015
6016 DEBUG(dbgs() << "aarch64-lower: transformed: \n");
6017 DEBUG(N->dump(&DAG));
6018 DEBUG(dbgs() << "into: \n");
6019 DEBUG(ResultSLI->dump(&DAG));
6020
6021 ++NumShiftInserts;
6022 return ResultSLI;
6023}
6024
6025SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
6026 SelectionDAG &DAG) const {
6027 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
6028 if (EnableAArch64SlrGeneration) {
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00006029 if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00006030 return Res;
6031 }
6032
6033 BuildVectorSDNode *BVN =
6034 dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
6035 SDValue LHS = Op.getOperand(1);
6036 SDLoc dl(Op);
6037 EVT VT = Op.getValueType();
6038
6039 // OR commutes, so try swapping the operands.
6040 if (!BVN) {
6041 LHS = Op.getOperand(0);
6042 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
6043 }
6044 if (!BVN)
6045 return Op;
6046
6047 APInt CnstBits(VT.getSizeInBits(), 0);
6048 APInt UndefBits(VT.getSizeInBits(), 0);
6049 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
6050 // We make use of a little bit of goto ickiness in order to avoid having to
6051 // duplicate the immediate matching logic for the undef toggled case.
6052 bool SecondTry = false;
6053 AttemptModImm:
6054
6055 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
6056 CnstBits = CnstBits.zextOrTrunc(64);
6057 uint64_t CnstVal = CnstBits.getZExtValue();
6058
6059 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6060 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6061 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6062 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006063 DAG.getConstant(CnstVal, dl, MVT::i32),
6064 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00006065 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006066 }
6067
6068 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6069 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6070 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6071 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006072 DAG.getConstant(CnstVal, dl, MVT::i32),
6073 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00006074 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006075 }
6076
6077 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6078 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6079 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6080 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006081 DAG.getConstant(CnstVal, dl, MVT::i32),
6082 DAG.getConstant(16, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00006083 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006084 }
6085
6086 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6087 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6088 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6089 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006090 DAG.getConstant(CnstVal, dl, MVT::i32),
6091 DAG.getConstant(24, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00006092 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006093 }
6094
6095 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6096 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6097 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6098 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006099 DAG.getConstant(CnstVal, dl, MVT::i32),
6100 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00006101 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006102 }
6103
6104 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6105 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6106 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6107 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006108 DAG.getConstant(CnstVal, dl, MVT::i32),
6109 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00006110 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006111 }
6112 }
6113
6114 if (SecondTry)
6115 goto FailedModImm;
6116 SecondTry = true;
6117 CnstBits = UndefBits;
6118 goto AttemptModImm;
6119 }
6120
6121// We can always fall back to a non-immediate OR.
6122FailedModImm:
6123 return Op;
6124}
6125
Kevin Qin4473c192014-07-07 02:45:40 +00006126// Normalize the operands of BUILD_VECTOR. The value of constant operands will
6127// be truncated to fit element width.
6128static SDValue NormalizeBuildVector(SDValue Op,
6129 SelectionDAG &DAG) {
6130 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
Tim Northover3b0846e2014-05-24 12:50:23 +00006131 SDLoc dl(Op);
6132 EVT VT = Op.getValueType();
Kevin Qin4473c192014-07-07 02:45:40 +00006133 EVT EltTy= VT.getVectorElementType();
6134
6135 if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
6136 return Op;
6137
6138 SmallVector<SDValue, 16> Ops;
Pete Cooper7be8f8f2015-08-03 19:04:32 +00006139 for (SDValue Lane : Op->ops()) {
6140 if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
Kevin Qin4473c192014-07-07 02:45:40 +00006141 APInt LowBits(EltTy.getSizeInBits(),
Pete Cooper7be8f8f2015-08-03 19:04:32 +00006142 CstLane->getZExtValue());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006143 Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
Kevin Qin4473c192014-07-07 02:45:40 +00006144 }
6145 Ops.push_back(Lane);
6146 }
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006147 return DAG.getBuildVector(VT, dl, Ops);
Kevin Qin4473c192014-07-07 02:45:40 +00006148}
6149
6150SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
6151 SelectionDAG &DAG) const {
6152 SDLoc dl(Op);
6153 EVT VT = Op.getValueType();
6154 Op = NormalizeBuildVector(Op, DAG);
6155 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
Tim Northover3b0846e2014-05-24 12:50:23 +00006156
6157 APInt CnstBits(VT.getSizeInBits(), 0);
6158 APInt UndefBits(VT.getSizeInBits(), 0);
6159 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
6160 // We make use of a little bit of goto ickiness in order to avoid having to
6161 // duplicate the immediate matching logic for the undef toggled case.
6162 bool SecondTry = false;
6163 AttemptModImm:
6164
6165 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
6166 CnstBits = CnstBits.zextOrTrunc(64);
6167 uint64_t CnstVal = CnstBits.getZExtValue();
6168
6169 // Certain magic vector constants (used to express things like NOT
6170 // and NEG) are passed through unmodified. This allows codegen patterns
6171 // for these operations to match. Special-purpose patterns will lower
6172 // these immediates to MOVIs if it proves necessary.
6173 if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL))
6174 return Op;
6175
6176 // The many faces of MOVI...
6177 if (AArch64_AM::isAdvSIMDModImmType10(CnstVal)) {
6178 CnstVal = AArch64_AM::encodeAdvSIMDModImmType10(CnstVal);
6179 if (VT.getSizeInBits() == 128) {
6180 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::v2i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006181 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006182 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006183 }
6184
6185 // Support the V64 version via subregister insertion.
6186 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::f64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006187 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006188 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006189 }
6190
6191 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6192 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6193 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6194 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006195 DAG.getConstant(CnstVal, dl, MVT::i32),
6196 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006197 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006198 }
6199
6200 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6201 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6202 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6203 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006204 DAG.getConstant(CnstVal, dl, MVT::i32),
6205 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006206 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006207 }
6208
6209 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6210 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6211 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6212 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006213 DAG.getConstant(CnstVal, dl, MVT::i32),
6214 DAG.getConstant(16, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006215 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006216 }
6217
6218 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6219 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6220 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6221 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006222 DAG.getConstant(CnstVal, dl, MVT::i32),
6223 DAG.getConstant(24, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006224 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006225 }
6226
6227 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6228 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6229 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6230 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006231 DAG.getConstant(CnstVal, dl, MVT::i32),
6232 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006233 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006234 }
6235
6236 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6237 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6238 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6239 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006240 DAG.getConstant(CnstVal, dl, MVT::i32),
6241 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006242 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006243 }
6244
6245 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6246 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6247 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6248 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006249 DAG.getConstant(CnstVal, dl, MVT::i32),
6250 DAG.getConstant(264, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006251 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006252 }
6253
6254 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6255 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6256 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6257 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006258 DAG.getConstant(CnstVal, dl, MVT::i32),
6259 DAG.getConstant(272, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006260 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006261 }
6262
6263 if (AArch64_AM::isAdvSIMDModImmType9(CnstVal)) {
6264 CnstVal = AArch64_AM::encodeAdvSIMDModImmType9(CnstVal);
6265 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
6266 SDValue Mov = DAG.getNode(AArch64ISD::MOVI, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006267 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006268 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006269 }
6270
6271 // The few faces of FMOV...
6272 if (AArch64_AM::isAdvSIMDModImmType11(CnstVal)) {
6273 CnstVal = AArch64_AM::encodeAdvSIMDModImmType11(CnstVal);
6274 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32;
6275 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006276 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006277 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006278 }
6279
6280 if (AArch64_AM::isAdvSIMDModImmType12(CnstVal) &&
6281 VT.getSizeInBits() == 128) {
6282 CnstVal = AArch64_AM::encodeAdvSIMDModImmType12(CnstVal);
6283 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MVT::v2f64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006284 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006285 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006286 }
6287
6288 // The many faces of MVNI...
6289 CnstVal = ~CnstVal;
6290 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6291 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6292 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6293 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006294 DAG.getConstant(CnstVal, dl, MVT::i32),
6295 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006296 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006297 }
6298
6299 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6300 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6301 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6302 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006303 DAG.getConstant(CnstVal, dl, MVT::i32),
6304 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006305 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006306 }
6307
6308 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6309 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6310 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6311 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006312 DAG.getConstant(CnstVal, dl, MVT::i32),
6313 DAG.getConstant(16, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006314 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006315 }
6316
6317 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6318 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6319 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6320 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006321 DAG.getConstant(CnstVal, dl, MVT::i32),
6322 DAG.getConstant(24, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006323 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006324 }
6325
6326 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6327 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6328 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6329 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006330 DAG.getConstant(CnstVal, dl, MVT::i32),
6331 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006332 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006333 }
6334
6335 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6336 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6337 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6338 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006339 DAG.getConstant(CnstVal, dl, MVT::i32),
6340 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006341 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006342 }
6343
6344 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6345 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6346 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6347 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006348 DAG.getConstant(CnstVal, dl, MVT::i32),
6349 DAG.getConstant(264, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006350 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006351 }
6352
6353 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6354 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6355 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6356 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006357 DAG.getConstant(CnstVal, dl, MVT::i32),
6358 DAG.getConstant(272, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006359 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006360 }
6361 }
6362
6363 if (SecondTry)
6364 goto FailedModImm;
6365 SecondTry = true;
6366 CnstBits = UndefBits;
6367 goto AttemptModImm;
6368 }
6369FailedModImm:
6370
6371 // Scan through the operands to find some interesting properties we can
6372 // exploit:
6373 // 1) If only one value is used, we can use a DUP, or
6374 // 2) if only the low element is not undef, we can just insert that, or
6375 // 3) if only one constant value is used (w/ some non-constant lanes),
6376 // we can splat the constant value into the whole vector then fill
6377 // in the non-constant lanes.
6378 // 4) FIXME: If different constant values are used, but we can intelligently
6379 // select the values we'll be overwriting for the non-constant
6380 // lanes such that we can directly materialize the vector
6381 // some other way (MOVI, e.g.), we can be sneaky.
6382 unsigned NumElts = VT.getVectorNumElements();
6383 bool isOnlyLowElement = true;
6384 bool usesOnlyOneValue = true;
6385 bool usesOnlyOneConstantValue = true;
6386 bool isConstant = true;
6387 unsigned NumConstantLanes = 0;
6388 SDValue Value;
6389 SDValue ConstantValue;
6390 for (unsigned i = 0; i < NumElts; ++i) {
6391 SDValue V = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00006392 if (V.isUndef())
Tim Northover3b0846e2014-05-24 12:50:23 +00006393 continue;
6394 if (i > 0)
6395 isOnlyLowElement = false;
6396 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6397 isConstant = false;
6398
6399 if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
6400 ++NumConstantLanes;
6401 if (!ConstantValue.getNode())
6402 ConstantValue = V;
6403 else if (ConstantValue != V)
6404 usesOnlyOneConstantValue = false;
6405 }
6406
6407 if (!Value.getNode())
6408 Value = V;
6409 else if (V != Value)
6410 usesOnlyOneValue = false;
6411 }
6412
6413 if (!Value.getNode())
6414 return DAG.getUNDEF(VT);
6415
6416 if (isOnlyLowElement)
6417 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
6418
6419 // Use DUP for non-constant splats. For f32 constant splats, reduce to
6420 // i32 and try again.
6421 if (usesOnlyOneValue) {
6422 if (!isConstant) {
6423 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6424 Value.getValueType() != VT)
6425 return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
6426
6427 // This is actually a DUPLANExx operation, which keeps everything vectory.
6428
6429 // DUPLANE works on 128-bit vectors, widen it if necessary.
6430 SDValue Lane = Value.getOperand(1);
6431 Value = Value.getOperand(0);
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00006432 if (Value.getValueSizeInBits() == 64)
Tim Northover3b0846e2014-05-24 12:50:23 +00006433 Value = WidenVector(Value, DAG);
6434
6435 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
6436 return DAG.getNode(Opcode, dl, VT, Value, Lane);
6437 }
6438
6439 if (VT.getVectorElementType().isFloatingPoint()) {
6440 SmallVector<SDValue, 8> Ops;
Pirama Arumuga Nainar12aeefc2015-03-17 23:10:29 +00006441 EVT EltTy = VT.getVectorElementType();
6442 assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
6443 "Unsupported floating-point vector type");
6444 MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00006445 for (unsigned i = 0; i < NumElts; ++i)
6446 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
6447 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006448 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
Tim Northover3b0846e2014-05-24 12:50:23 +00006449 Val = LowerBUILD_VECTOR(Val, DAG);
6450 if (Val.getNode())
6451 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6452 }
6453 }
6454
6455 // If there was only one constant value used and for more than one lane,
6456 // start by splatting that value, then replace the non-constant lanes. This
6457 // is better than the default, which will perform a separate initialization
6458 // for each lane.
6459 if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
6460 SDValue Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
6461 // Now insert the non-constant lanes.
6462 for (unsigned i = 0; i < NumElts; ++i) {
6463 SDValue V = Op.getOperand(i);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006464 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006465 if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) {
6466 // Note that type legalization likely mucked about with the VT of the
6467 // source operand, so we may have to convert it here before inserting.
6468 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
6469 }
6470 }
6471 return Val;
6472 }
6473
6474 // If all elements are constants and the case above didn't get hit, fall back
6475 // to the default expansion, which will generate a load from the constant
6476 // pool.
6477 if (isConstant)
6478 return SDValue();
6479
6480 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6481 if (NumElts >= 4) {
Ahmed Bougacha239d6352015-08-04 00:48:02 +00006482 if (SDValue shuffle = ReconstructShuffle(Op, DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00006483 return shuffle;
6484 }
6485
6486 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6487 // know the default expansion would otherwise fall back on something even
6488 // worse. For a vector with one or two non-undef values, that's
6489 // scalar_to_vector for the elements followed by a shuffle (provided the
6490 // shuffle is valid for the target) and materialization element by element
6491 // on the stack followed by a load for everything else.
6492 if (!isConstant && !usesOnlyOneValue) {
6493 SDValue Vec = DAG.getUNDEF(VT);
6494 SDValue Op0 = Op.getOperand(0);
Sanjay Patel1ed771f2016-09-14 16:37:15 +00006495 unsigned ElemSize = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00006496 unsigned i = 0;
6497 // For 32 and 64 bit types, use INSERT_SUBREG for lane zero to
6498 // a) Avoid a RMW dependency on the full vector register, and
6499 // b) Allow the register coalescer to fold away the copy if the
6500 // value is already in an S or D register.
Matthias Braun0acbd082015-08-31 18:25:15 +00006501 // Do not do this for UNDEF/LOAD nodes because we have better patterns
6502 // for those avoiding the SCALAR_TO_VECTOR/BUILD_VECTOR.
Sanjay Patel75068522016-03-14 18:09:43 +00006503 if (!Op0.isUndef() && Op0.getOpcode() != ISD::LOAD &&
Matthias Braun0acbd082015-08-31 18:25:15 +00006504 (ElemSize == 32 || ElemSize == 64)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006505 unsigned SubIdx = ElemSize == 32 ? AArch64::ssub : AArch64::dsub;
6506 MachineSDNode *N =
6507 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl, VT, Vec, Op0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006508 DAG.getTargetConstant(SubIdx, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006509 Vec = SDValue(N, 0);
6510 ++i;
6511 }
6512 for (; i < NumElts; ++i) {
6513 SDValue V = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00006514 if (V.isUndef())
Tim Northover3b0846e2014-05-24 12:50:23 +00006515 continue;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006516 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006517 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6518 }
6519 return Vec;
6520 }
6521
6522 // Just use the default expansion. We failed to find a better alternative.
6523 return SDValue();
6524}
6525
6526SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
6527 SelectionDAG &DAG) const {
6528 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
6529
Tim Northovere4b8e132014-07-15 10:00:26 +00006530 // Check for non-constant or out of range lane.
6531 EVT VT = Op.getOperand(0).getValueType();
6532 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
6533 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
Tim Northover3b0846e2014-05-24 12:50:23 +00006534 return SDValue();
6535
Tim Northover3b0846e2014-05-24 12:50:23 +00006536
6537 // Insertion/extraction are legal for V128 types.
6538 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
Oliver Stannard89d15422014-08-27 16:16:04 +00006539 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6540 VT == MVT::v8f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006541 return Op;
6542
6543 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
Oliver Stannard89d15422014-08-27 16:16:04 +00006544 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006545 return SDValue();
6546
6547 // For V64 types, we perform insertion by expanding the value
6548 // to a V128 type and perform the insertion on that.
6549 SDLoc DL(Op);
6550 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6551 EVT WideTy = WideVec.getValueType();
6552
6553 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
6554 Op.getOperand(1), Op.getOperand(2));
6555 // Re-narrow the resultant vector.
6556 return NarrowVector(Node, DAG);
6557}
6558
6559SDValue
6560AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6561 SelectionDAG &DAG) const {
6562 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
6563
Tim Northovere4b8e132014-07-15 10:00:26 +00006564 // Check for non-constant or out of range lane.
6565 EVT VT = Op.getOperand(0).getValueType();
6566 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6567 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
Tim Northover3b0846e2014-05-24 12:50:23 +00006568 return SDValue();
6569
Tim Northover3b0846e2014-05-24 12:50:23 +00006570
6571 // Insertion/extraction are legal for V128 types.
6572 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
Oliver Stannard89d15422014-08-27 16:16:04 +00006573 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6574 VT == MVT::v8f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006575 return Op;
6576
6577 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
Oliver Stannard89d15422014-08-27 16:16:04 +00006578 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006579 return SDValue();
6580
6581 // For V64 types, we perform extraction by expanding the value
6582 // to a V128 type and perform the extraction on that.
6583 SDLoc DL(Op);
6584 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6585 EVT WideTy = WideVec.getValueType();
6586
6587 EVT ExtrTy = WideTy.getVectorElementType();
6588 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
6589 ExtrTy = MVT::i32;
6590
6591 // For extractions, we just return the result directly.
6592 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
6593 Op.getOperand(1));
6594}
6595
6596SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
6597 SelectionDAG &DAG) const {
6598 EVT VT = Op.getOperand(0).getValueType();
6599 SDLoc dl(Op);
6600 // Just in case...
6601 if (!VT.isVector())
6602 return SDValue();
6603
6604 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6605 if (!Cst)
6606 return SDValue();
6607 unsigned Val = Cst->getZExtValue();
6608
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00006609 unsigned Size = Op.getValueSizeInBits();
Charlie Turner7b7b06f2015-11-09 12:45:11 +00006610
6611 // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
6612 if (Val == 0)
6613 return Op;
6614
Tim Northover3b0846e2014-05-24 12:50:23 +00006615 // If this is extracting the upper 64-bits of a 128-bit vector, we match
6616 // that directly.
Sanjay Patel1ed771f2016-09-14 16:37:15 +00006617 if (Size == 64 && Val * VT.getScalarSizeInBits() == 64)
Tim Northover3b0846e2014-05-24 12:50:23 +00006618 return Op;
6619
6620 return SDValue();
6621}
6622
6623bool AArch64TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
6624 EVT VT) const {
6625 if (VT.getVectorNumElements() == 4 &&
6626 (VT.is128BitVector() || VT.is64BitVector())) {
6627 unsigned PFIndexes[4];
6628 for (unsigned i = 0; i != 4; ++i) {
6629 if (M[i] < 0)
6630 PFIndexes[i] = 8;
6631 else
6632 PFIndexes[i] = M[i];
6633 }
6634
6635 // Compute the index in the perfect shuffle table.
6636 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6637 PFIndexes[2] * 9 + PFIndexes[3];
6638 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6639 unsigned Cost = (PFEntry >> 30);
6640
6641 if (Cost <= 4)
6642 return true;
6643 }
6644
6645 bool DummyBool;
6646 int DummyInt;
6647 unsigned DummyUnsigned;
6648
6649 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
6650 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
6651 isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
6652 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
6653 isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
6654 isZIPMask(M, VT, DummyUnsigned) ||
6655 isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
6656 isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
6657 isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
6658 isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
6659 isConcatMask(M, VT, VT.getSizeInBits() == 128));
6660}
6661
6662/// getVShiftImm - Check if this is a valid build_vector for the immediate
6663/// operand of a vector shift operation, where all the elements of the
6664/// build_vector must have the same constant integer value.
6665static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
6666 // Ignore bit_converts.
6667 while (Op.getOpcode() == ISD::BITCAST)
6668 Op = Op.getOperand(0);
6669 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6670 APInt SplatBits, SplatUndef;
6671 unsigned SplatBitSize;
6672 bool HasAnyUndefs;
6673 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
6674 HasAnyUndefs, ElementBits) ||
6675 SplatBitSize > ElementBits)
6676 return false;
6677 Cnt = SplatBits.getSExtValue();
6678 return true;
6679}
6680
6681/// isVShiftLImm - Check if this is a valid build_vector for the immediate
6682/// operand of a vector shift left operation. That value must be in the range:
6683/// 0 <= Value < ElementBits for a left shift; or
6684/// 0 <= Value <= ElementBits for a long left shift.
6685static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
6686 assert(VT.isVector() && "vector shift count is not a vector type");
Sanjay Patel1ed771f2016-09-14 16:37:15 +00006687 int64_t ElementBits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00006688 if (!getVShiftImm(Op, ElementBits, Cnt))
6689 return false;
6690 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
6691}
6692
6693/// isVShiftRImm - Check if this is a valid build_vector for the immediate
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00006694/// operand of a vector shift right operation. The value must be in the range:
6695/// 1 <= Value <= ElementBits for a right shift; or
6696static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006697 assert(VT.isVector() && "vector shift count is not a vector type");
Sanjay Patel1ed771f2016-09-14 16:37:15 +00006698 int64_t ElementBits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00006699 if (!getVShiftImm(Op, ElementBits, Cnt))
6700 return false;
Tim Northover3b0846e2014-05-24 12:50:23 +00006701 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
6702}
6703
6704SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
6705 SelectionDAG &DAG) const {
6706 EVT VT = Op.getValueType();
6707 SDLoc DL(Op);
6708 int64_t Cnt;
6709
6710 if (!Op.getOperand(1).getValueType().isVector())
6711 return Op;
Sanjay Patel1ed771f2016-09-14 16:37:15 +00006712 unsigned EltSize = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00006713
6714 switch (Op.getOpcode()) {
6715 default:
6716 llvm_unreachable("unexpected shift opcode");
6717
6718 case ISD::SHL:
6719 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006720 return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
6721 DAG.getConstant(Cnt, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006722 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006723 DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
6724 MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00006725 Op.getOperand(0), Op.getOperand(1));
6726 case ISD::SRA:
6727 case ISD::SRL:
6728 // Right shift immediate
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00006729 if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006730 unsigned Opc =
6731 (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006732 return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
6733 DAG.getConstant(Cnt, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006734 }
6735
6736 // Right shift register. Note, there is not a shift right register
6737 // instruction, but the shift left register instruction takes a signed
6738 // value, where negative numbers specify a right shift.
6739 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
6740 : Intrinsic::aarch64_neon_ushl;
6741 // negate the shift amount
6742 SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
6743 SDValue NegShiftLeft =
6744 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006745 DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
6746 NegShift);
Tim Northover3b0846e2014-05-24 12:50:23 +00006747 return NegShiftLeft;
6748 }
6749
6750 return SDValue();
6751}
6752
6753static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
6754 AArch64CC::CondCode CC, bool NoNans, EVT VT,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00006755 const SDLoc &dl, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006756 EVT SrcVT = LHS.getValueType();
Tim Northover45aa89c2015-02-08 00:50:47 +00006757 assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
6758 "function only supposed to emit natural comparisons");
Tim Northover3b0846e2014-05-24 12:50:23 +00006759
6760 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
6761 APInt CnstBits(VT.getSizeInBits(), 0);
6762 APInt UndefBits(VT.getSizeInBits(), 0);
6763 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
6764 bool IsZero = IsCnst && (CnstBits == 0);
6765
6766 if (SrcVT.getVectorElementType().isFloatingPoint()) {
6767 switch (CC) {
6768 default:
6769 return SDValue();
6770 case AArch64CC::NE: {
6771 SDValue Fcmeq;
6772 if (IsZero)
6773 Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6774 else
6775 Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6776 return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
6777 }
6778 case AArch64CC::EQ:
6779 if (IsZero)
6780 return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6781 return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6782 case AArch64CC::GE:
6783 if (IsZero)
6784 return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
6785 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
6786 case AArch64CC::GT:
6787 if (IsZero)
6788 return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
6789 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
6790 case AArch64CC::LS:
6791 if (IsZero)
6792 return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
6793 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
6794 case AArch64CC::LT:
6795 if (!NoNans)
6796 return SDValue();
Justin Bognerb03fd122016-08-17 05:10:15 +00006797 // If we ignore NaNs then we can use to the MI implementation.
6798 LLVM_FALLTHROUGH;
Tim Northover3b0846e2014-05-24 12:50:23 +00006799 case AArch64CC::MI:
6800 if (IsZero)
6801 return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
6802 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
6803 }
6804 }
6805
6806 switch (CC) {
6807 default:
6808 return SDValue();
6809 case AArch64CC::NE: {
6810 SDValue Cmeq;
6811 if (IsZero)
6812 Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6813 else
6814 Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6815 return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
6816 }
6817 case AArch64CC::EQ:
6818 if (IsZero)
6819 return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6820 return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6821 case AArch64CC::GE:
6822 if (IsZero)
6823 return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
6824 return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
6825 case AArch64CC::GT:
6826 if (IsZero)
6827 return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
6828 return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
6829 case AArch64CC::LE:
6830 if (IsZero)
6831 return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
6832 return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
6833 case AArch64CC::LS:
6834 return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
6835 case AArch64CC::LO:
6836 return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
6837 case AArch64CC::LT:
6838 if (IsZero)
6839 return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
6840 return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
6841 case AArch64CC::HI:
6842 return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
6843 case AArch64CC::HS:
6844 return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
6845 }
6846}
6847
6848SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
6849 SelectionDAG &DAG) const {
6850 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6851 SDValue LHS = Op.getOperand(0);
6852 SDValue RHS = Op.getOperand(1);
Tim Northover45aa89c2015-02-08 00:50:47 +00006853 EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
Tim Northover3b0846e2014-05-24 12:50:23 +00006854 SDLoc dl(Op);
6855
6856 if (LHS.getValueType().getVectorElementType().isInteger()) {
6857 assert(LHS.getValueType() == RHS.getValueType());
6858 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
Tim Northover45aa89c2015-02-08 00:50:47 +00006859 SDValue Cmp =
6860 EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
6861 return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00006862 }
6863
Pirama Arumuga Nainar71e9a2a2016-01-22 01:16:57 +00006864 if (LHS.getValueType().getVectorElementType() == MVT::f16)
6865 return SDValue();
6866
Tim Northover3b0846e2014-05-24 12:50:23 +00006867 assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
6868 LHS.getValueType().getVectorElementType() == MVT::f64);
6869
6870 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
6871 // clean. Some of them require two branches to implement.
6872 AArch64CC::CondCode CC1, CC2;
6873 bool ShouldInvert;
6874 changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
6875
6876 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
6877 SDValue Cmp =
Tim Northover45aa89c2015-02-08 00:50:47 +00006878 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00006879 if (!Cmp.getNode())
6880 return SDValue();
6881
6882 if (CC2 != AArch64CC::AL) {
6883 SDValue Cmp2 =
Tim Northover45aa89c2015-02-08 00:50:47 +00006884 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00006885 if (!Cmp2.getNode())
6886 return SDValue();
6887
Tim Northover45aa89c2015-02-08 00:50:47 +00006888 Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
Tim Northover3b0846e2014-05-24 12:50:23 +00006889 }
6890
Tim Northover45aa89c2015-02-08 00:50:47 +00006891 Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
6892
Tim Northover3b0846e2014-05-24 12:50:23 +00006893 if (ShouldInvert)
6894 return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
6895
6896 return Cmp;
6897}
6898
6899/// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
6900/// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
6901/// specified in the intrinsic calls.
6902bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
6903 const CallInst &I,
6904 unsigned Intrinsic) const {
Mehdi Aminia749f2a2015-07-09 02:09:52 +00006905 auto &DL = I.getModule()->getDataLayout();
Tim Northover3b0846e2014-05-24 12:50:23 +00006906 switch (Intrinsic) {
6907 case Intrinsic::aarch64_neon_ld2:
6908 case Intrinsic::aarch64_neon_ld3:
6909 case Intrinsic::aarch64_neon_ld4:
6910 case Intrinsic::aarch64_neon_ld1x2:
6911 case Intrinsic::aarch64_neon_ld1x3:
6912 case Intrinsic::aarch64_neon_ld1x4:
6913 case Intrinsic::aarch64_neon_ld2lane:
6914 case Intrinsic::aarch64_neon_ld3lane:
6915 case Intrinsic::aarch64_neon_ld4lane:
6916 case Intrinsic::aarch64_neon_ld2r:
6917 case Intrinsic::aarch64_neon_ld3r:
6918 case Intrinsic::aarch64_neon_ld4r: {
6919 Info.opc = ISD::INTRINSIC_W_CHAIN;
6920 // Conservatively set memVT to the entire set of vectors loaded.
Ahmed Bougacha97564c32015-12-09 01:19:50 +00006921 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00006922 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6923 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6924 Info.offset = 0;
6925 Info.align = 0;
6926 Info.vol = false; // volatile loads with NEON intrinsics not supported
6927 Info.readMem = true;
6928 Info.writeMem = false;
6929 return true;
6930 }
6931 case Intrinsic::aarch64_neon_st2:
6932 case Intrinsic::aarch64_neon_st3:
6933 case Intrinsic::aarch64_neon_st4:
6934 case Intrinsic::aarch64_neon_st1x2:
6935 case Intrinsic::aarch64_neon_st1x3:
6936 case Intrinsic::aarch64_neon_st1x4:
6937 case Intrinsic::aarch64_neon_st2lane:
6938 case Intrinsic::aarch64_neon_st3lane:
6939 case Intrinsic::aarch64_neon_st4lane: {
6940 Info.opc = ISD::INTRINSIC_VOID;
6941 // Conservatively set memVT to the entire set of vectors stored.
6942 unsigned NumElts = 0;
6943 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
6944 Type *ArgTy = I.getArgOperand(ArgI)->getType();
6945 if (!ArgTy->isVectorTy())
6946 break;
Ahmed Bougacha97564c32015-12-09 01:19:50 +00006947 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00006948 }
6949 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6950 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6951 Info.offset = 0;
6952 Info.align = 0;
6953 Info.vol = false; // volatile stores with NEON intrinsics not supported
6954 Info.readMem = false;
6955 Info.writeMem = true;
6956 return true;
6957 }
6958 case Intrinsic::aarch64_ldaxr:
6959 case Intrinsic::aarch64_ldxr: {
6960 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
6961 Info.opc = ISD::INTRINSIC_W_CHAIN;
6962 Info.memVT = MVT::getVT(PtrTy->getElementType());
6963 Info.ptrVal = I.getArgOperand(0);
6964 Info.offset = 0;
Mehdi Aminia749f2a2015-07-09 02:09:52 +00006965 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
Tim Northover3b0846e2014-05-24 12:50:23 +00006966 Info.vol = true;
6967 Info.readMem = true;
6968 Info.writeMem = false;
6969 return true;
6970 }
6971 case Intrinsic::aarch64_stlxr:
6972 case Intrinsic::aarch64_stxr: {
6973 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
6974 Info.opc = ISD::INTRINSIC_W_CHAIN;
6975 Info.memVT = MVT::getVT(PtrTy->getElementType());
6976 Info.ptrVal = I.getArgOperand(1);
6977 Info.offset = 0;
Mehdi Aminia749f2a2015-07-09 02:09:52 +00006978 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
Tim Northover3b0846e2014-05-24 12:50:23 +00006979 Info.vol = true;
6980 Info.readMem = false;
6981 Info.writeMem = true;
6982 return true;
6983 }
6984 case Intrinsic::aarch64_ldaxp:
6985 case Intrinsic::aarch64_ldxp: {
6986 Info.opc = ISD::INTRINSIC_W_CHAIN;
6987 Info.memVT = MVT::i128;
6988 Info.ptrVal = I.getArgOperand(0);
6989 Info.offset = 0;
6990 Info.align = 16;
6991 Info.vol = true;
6992 Info.readMem = true;
6993 Info.writeMem = false;
6994 return true;
6995 }
6996 case Intrinsic::aarch64_stlxp:
6997 case Intrinsic::aarch64_stxp: {
6998 Info.opc = ISD::INTRINSIC_W_CHAIN;
6999 Info.memVT = MVT::i128;
7000 Info.ptrVal = I.getArgOperand(2);
7001 Info.offset = 0;
7002 Info.align = 16;
7003 Info.vol = true;
7004 Info.readMem = false;
7005 Info.writeMem = true;
7006 return true;
7007 }
7008 default:
7009 break;
7010 }
7011
7012 return false;
7013}
7014
7015// Truncations from 64-bit GPR to 32-bit GPR is free.
7016bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
7017 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
7018 return false;
7019 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7020 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00007021 return NumBits1 > NumBits2;
Tim Northover3b0846e2014-05-24 12:50:23 +00007022}
7023bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
Hao Liu40914502014-05-29 09:19:07 +00007024 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00007025 return false;
7026 unsigned NumBits1 = VT1.getSizeInBits();
7027 unsigned NumBits2 = VT2.getSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00007028 return NumBits1 > NumBits2;
Tim Northover3b0846e2014-05-24 12:50:23 +00007029}
7030
Chad Rosier54390052015-02-23 19:15:16 +00007031/// Check if it is profitable to hoist instruction in then/else to if.
7032/// Not profitable if I and it's user can form a FMA instruction
7033/// because we prefer FMSUB/FMADD.
7034bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
7035 if (I->getOpcode() != Instruction::FMul)
7036 return true;
7037
7038 if (I->getNumUses() != 1)
7039 return true;
7040
7041 Instruction *User = I->user_back();
7042
7043 if (User &&
7044 !(User->getOpcode() == Instruction::FSub ||
7045 User->getOpcode() == Instruction::FAdd))
7046 return true;
7047
7048 const TargetOptions &Options = getTargetMachine().Options;
Mehdi Amini44ede332015-07-09 02:09:04 +00007049 const DataLayout &DL = I->getModule()->getDataLayout();
7050 EVT VT = getValueType(DL, User->getOperand(0)->getType());
Chad Rosier54390052015-02-23 19:15:16 +00007051
Eric Christopher114fa1c2016-02-29 22:50:49 +00007052 return !(isFMAFasterThanFMulAndFAdd(VT) &&
7053 isOperationLegalOrCustom(ISD::FMA, VT) &&
7054 (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7055 Options.UnsafeFPMath));
Chad Rosier54390052015-02-23 19:15:16 +00007056}
7057
Tim Northover3b0846e2014-05-24 12:50:23 +00007058// All 32-bit GPR operations implicitly zero the high-half of the corresponding
7059// 64-bit GPR.
7060bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
7061 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
7062 return false;
7063 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7064 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00007065 return NumBits1 == 32 && NumBits2 == 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00007066}
7067bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
Hao Liu40914502014-05-29 09:19:07 +00007068 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00007069 return false;
7070 unsigned NumBits1 = VT1.getSizeInBits();
7071 unsigned NumBits2 = VT2.getSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00007072 return NumBits1 == 32 && NumBits2 == 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00007073}
7074
7075bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
7076 EVT VT1 = Val.getValueType();
7077 if (isZExtFree(VT1, VT2)) {
7078 return true;
7079 }
7080
7081 if (Val.getOpcode() != ISD::LOAD)
7082 return false;
7083
7084 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
Hao Liu40914502014-05-29 09:19:07 +00007085 return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
7086 VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
7087 VT1.getSizeInBits() <= 32);
Tim Northover3b0846e2014-05-24 12:50:23 +00007088}
7089
Quentin Colombet6843ac42015-03-31 20:52:32 +00007090bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
7091 if (isa<FPExtInst>(Ext))
7092 return false;
7093
7094 // Vector types are next free.
7095 if (Ext->getType()->isVectorTy())
7096 return false;
7097
7098 for (const Use &U : Ext->uses()) {
7099 // The extension is free if we can fold it with a left shift in an
7100 // addressing mode or an arithmetic operation: add, sub, and cmp.
7101
7102 // Is there a shift?
7103 const Instruction *Instr = cast<Instruction>(U.getUser());
7104
7105 // Is this a constant shift?
7106 switch (Instr->getOpcode()) {
7107 case Instruction::Shl:
7108 if (!isa<ConstantInt>(Instr->getOperand(1)))
7109 return false;
7110 break;
7111 case Instruction::GetElementPtr: {
7112 gep_type_iterator GTI = gep_type_begin(Instr);
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007113 auto &DL = Ext->getModule()->getDataLayout();
Quentin Colombet6843ac42015-03-31 20:52:32 +00007114 std::advance(GTI, U.getOperandNo());
7115 Type *IdxTy = *GTI;
7116 // This extension will end up with a shift because of the scaling factor.
7117 // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
7118 // Get the shift amount based on the scaling factor:
7119 // log2(sizeof(IdxTy)) - log2(8).
7120 uint64_t ShiftAmt =
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007121 countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3;
Quentin Colombet6843ac42015-03-31 20:52:32 +00007122 // Is the constant foldable in the shift of the addressing mode?
7123 // I.e., shift amount is between 1 and 4 inclusive.
7124 if (ShiftAmt == 0 || ShiftAmt > 4)
7125 return false;
7126 break;
7127 }
7128 case Instruction::Trunc:
7129 // Check if this is a noop.
7130 // trunc(sext ty1 to ty2) to ty1.
7131 if (Instr->getType() == Ext->getOperand(0)->getType())
7132 continue;
Justin Bognercd1d5aa2016-08-17 20:30:52 +00007133 LLVM_FALLTHROUGH;
Quentin Colombet6843ac42015-03-31 20:52:32 +00007134 default:
7135 return false;
7136 }
7137
7138 // At this point we can use the bfm family, so this extension is free
7139 // for that use.
7140 }
7141 return true;
7142}
7143
Tim Northover3b0846e2014-05-24 12:50:23 +00007144bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
7145 unsigned &RequiredAligment) const {
7146 if (!LoadedType.isSimple() ||
7147 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
7148 return false;
7149 // Cyclone supports unaligned accesses.
7150 RequiredAligment = 0;
7151 unsigned NumBits = LoadedType.getSizeInBits();
7152 return NumBits == 32 || NumBits == 64;
7153}
7154
Hao Liu7ec8ee32015-06-26 02:32:07 +00007155/// \brief Lower an interleaved load into a ldN intrinsic.
7156///
7157/// E.g. Lower an interleaved load (Factor = 2):
7158/// %wide.vec = load <8 x i32>, <8 x i32>* %ptr
7159/// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
7160/// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
7161///
7162/// Into:
7163/// %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
7164/// %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
7165/// %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
7166bool AArch64TargetLowering::lowerInterleavedLoad(
7167 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
7168 ArrayRef<unsigned> Indices, unsigned Factor) const {
7169 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7170 "Invalid interleave factor");
7171 assert(!Shuffles.empty() && "Empty shufflevector input");
7172 assert(Shuffles.size() == Indices.size() &&
7173 "Unmatched number of shufflevectors and indices");
7174
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007175 const DataLayout &DL = LI->getModule()->getDataLayout();
Hao Liu7ec8ee32015-06-26 02:32:07 +00007176
7177 VectorType *VecTy = Shuffles[0]->getType();
Ahmed Bougacha97564c32015-12-09 01:19:50 +00007178 unsigned VecSize = DL.getTypeSizeInBits(VecTy);
Hao Liu7ec8ee32015-06-26 02:32:07 +00007179
Jeroen Ketemaaebca092015-10-07 14:53:29 +00007180 // Skip if we do not have NEON and skip illegal vector types.
7181 if (!Subtarget->hasNEON() || (VecSize != 64 && VecSize != 128))
Hao Liu7ec8ee32015-06-26 02:32:07 +00007182 return false;
7183
7184 // A pointer vector can not be the return type of the ldN intrinsics. Need to
7185 // load integer vectors first and then convert to pointer vectors.
7186 Type *EltTy = VecTy->getVectorElementType();
7187 if (EltTy->isPointerTy())
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007188 VecTy =
7189 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
Hao Liu7ec8ee32015-06-26 02:32:07 +00007190
7191 Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
7192 Type *Tys[2] = {VecTy, PtrTy};
7193 static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
7194 Intrinsic::aarch64_neon_ld3,
7195 Intrinsic::aarch64_neon_ld4};
7196 Function *LdNFunc =
7197 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
7198
7199 IRBuilder<> Builder(LI);
7200 Value *Ptr = Builder.CreateBitCast(LI->getPointerOperand(), PtrTy);
7201
7202 CallInst *LdN = Builder.CreateCall(LdNFunc, Ptr, "ldN");
7203
7204 // Replace uses of each shufflevector with the corresponding vector loaded
7205 // by ldN.
7206 for (unsigned i = 0; i < Shuffles.size(); i++) {
7207 ShuffleVectorInst *SVI = Shuffles[i];
7208 unsigned Index = Indices[i];
7209
7210 Value *SubVec = Builder.CreateExtractValue(LdN, Index);
7211
7212 // Convert the integer vector to pointer vector if the element is pointer.
7213 if (EltTy->isPointerTy())
7214 SubVec = Builder.CreateIntToPtr(SubVec, SVI->getType());
7215
7216 SVI->replaceAllUsesWith(SubVec);
7217 }
7218
7219 return true;
7220}
7221
7222/// \brief Get a mask consisting of sequential integers starting from \p Start.
7223///
7224/// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
7225static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
7226 unsigned NumElts) {
7227 SmallVector<Constant *, 16> Mask;
7228 for (unsigned i = 0; i < NumElts; i++)
7229 Mask.push_back(Builder.getInt32(Start + i));
7230
7231 return ConstantVector::get(Mask);
7232}
7233
7234/// \brief Lower an interleaved store into a stN intrinsic.
7235///
7236/// E.g. Lower an interleaved store (Factor = 3):
7237/// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
7238/// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
7239/// store <12 x i32> %i.vec, <12 x i32>* %ptr
7240///
7241/// Into:
7242/// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
7243/// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
7244/// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
7245/// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
7246///
7247/// Note that the new shufflevectors will be removed and we'll only generate one
7248/// st3 instruction in CodeGen.
7249bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
7250 ShuffleVectorInst *SVI,
7251 unsigned Factor) const {
7252 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7253 "Invalid interleave factor");
7254
7255 VectorType *VecTy = SVI->getType();
7256 assert(VecTy->getVectorNumElements() % Factor == 0 &&
7257 "Invalid interleaved store");
7258
7259 unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
7260 Type *EltTy = VecTy->getVectorElementType();
7261 VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
7262
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007263 const DataLayout &DL = SI->getModule()->getDataLayout();
Ahmed Bougacha97564c32015-12-09 01:19:50 +00007264 unsigned SubVecSize = DL.getTypeSizeInBits(SubVecTy);
Hao Liu7ec8ee32015-06-26 02:32:07 +00007265
Jeroen Ketemaaebca092015-10-07 14:53:29 +00007266 // Skip if we do not have NEON and skip illegal vector types.
7267 if (!Subtarget->hasNEON() || (SubVecSize != 64 && SubVecSize != 128))
Hao Liu7ec8ee32015-06-26 02:32:07 +00007268 return false;
7269
7270 Value *Op0 = SVI->getOperand(0);
7271 Value *Op1 = SVI->getOperand(1);
7272 IRBuilder<> Builder(SI);
7273
7274 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
7275 // vectors to integer vectors.
7276 if (EltTy->isPointerTy()) {
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007277 Type *IntTy = DL.getIntPtrType(EltTy);
Hao Liu7ec8ee32015-06-26 02:32:07 +00007278 unsigned NumOpElts =
7279 dyn_cast<VectorType>(Op0->getType())->getVectorNumElements();
7280
7281 // Convert to the corresponding integer vector.
7282 Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
7283 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
7284 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
7285
7286 SubVecTy = VectorType::get(IntTy, NumSubElts);
7287 }
7288
7289 Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
7290 Type *Tys[2] = {SubVecTy, PtrTy};
7291 static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
7292 Intrinsic::aarch64_neon_st3,
7293 Intrinsic::aarch64_neon_st4};
7294 Function *StNFunc =
7295 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
7296
7297 SmallVector<Value *, 5> Ops;
7298
7299 // Split the shufflevector operands into sub vectors for the new stN call.
7300 for (unsigned i = 0; i < Factor; i++)
7301 Ops.push_back(Builder.CreateShuffleVector(
7302 Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
7303
7304 Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), PtrTy));
7305 Builder.CreateCall(StNFunc, Ops);
7306 return true;
7307}
7308
Tim Northover3b0846e2014-05-24 12:50:23 +00007309static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
7310 unsigned AlignCheck) {
7311 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
7312 (DstAlign == 0 || DstAlign % AlignCheck == 0));
7313}
7314
7315EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
7316 unsigned SrcAlign, bool IsMemset,
7317 bool ZeroMemset,
7318 bool MemcpyStrSrc,
7319 MachineFunction &MF) const {
7320 // Don't use AdvSIMD to implement 16-byte memset. It would have taken one
7321 // instruction to materialize the v2i64 zero and one store (with restrictive
7322 // addressing mode). Just do two i64 store of zero-registers.
7323 bool Fast;
7324 const Function *F = MF.getFunction();
7325 if (Subtarget->hasFPARMv8() && !IsMemset && Size >= 16 &&
Duncan P. N. Exon Smith003bb7d2015-02-14 02:09:06 +00007326 !F->hasFnAttribute(Attribute::NoImplicitFloat) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00007327 (memOpAlign(SrcAlign, DstAlign, 16) ||
Matt Arsenault6f2a5262014-07-27 17:46:40 +00007328 (allowsMisalignedMemoryAccesses(MVT::f128, 0, 1, &Fast) && Fast)))
Tim Northover3b0846e2014-05-24 12:50:23 +00007329 return MVT::f128;
7330
Lang Hames90333852015-04-09 03:40:33 +00007331 if (Size >= 8 &&
7332 (memOpAlign(SrcAlign, DstAlign, 8) ||
7333 (allowsMisalignedMemoryAccesses(MVT::i64, 0, 1, &Fast) && Fast)))
7334 return MVT::i64;
7335
7336 if (Size >= 4 &&
7337 (memOpAlign(SrcAlign, DstAlign, 4) ||
7338 (allowsMisalignedMemoryAccesses(MVT::i32, 0, 1, &Fast) && Fast)))
Lang Hames522bf132015-04-09 05:34:57 +00007339 return MVT::i32;
Lang Hames90333852015-04-09 03:40:33 +00007340
7341 return MVT::Other;
Tim Northover3b0846e2014-05-24 12:50:23 +00007342}
7343
7344// 12-bit optionally shifted immediates are legal for adds.
7345bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
Geoff Berry486f49c2016-06-07 16:48:43 +00007346 // Avoid UB for INT64_MIN.
7347 if (Immed == std::numeric_limits<int64_t>::min())
7348 return false;
7349 // Same encoding for add/sub, just flip the sign.
7350 Immed = std::abs(Immed);
Eric Christopher114fa1c2016-02-29 22:50:49 +00007351 return ((Immed >> 12) == 0 || ((Immed & 0xfff) == 0 && Immed >> 24 == 0));
Tim Northover3b0846e2014-05-24 12:50:23 +00007352}
7353
7354// Integer comparisons are implemented with ADDS/SUBS, so the range of valid
7355// immediates is the same as for an add or a sub.
7356bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00007357 return isLegalAddImmediate(Immed);
7358}
7359
7360/// isLegalAddressingMode - Return true if the addressing mode represented
7361/// by AM is legal for this target, for a load/store of the specified type.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00007362bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
7363 const AddrMode &AM, Type *Ty,
Matt Arsenaultbd7d80a2015-06-01 05:31:59 +00007364 unsigned AS) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00007365 // AArch64 has five basic addressing modes:
7366 // reg
7367 // reg + 9-bit signed offset
7368 // reg + SIZE_IN_BYTES * 12-bit unsigned offset
7369 // reg1 + reg2
7370 // reg + SIZE_IN_BYTES * reg
7371
7372 // No global is ever allowed as a base.
7373 if (AM.BaseGV)
7374 return false;
7375
7376 // No reg+reg+imm addressing.
7377 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
7378 return false;
7379
7380 // check reg + imm case:
7381 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
7382 uint64_t NumBytes = 0;
7383 if (Ty->isSized()) {
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00007384 uint64_t NumBits = DL.getTypeSizeInBits(Ty);
Tim Northover3b0846e2014-05-24 12:50:23 +00007385 NumBytes = NumBits / 8;
7386 if (!isPowerOf2_64(NumBits))
7387 NumBytes = 0;
7388 }
7389
7390 if (!AM.Scale) {
7391 int64_t Offset = AM.BaseOffs;
7392
7393 // 9-bit signed offset
7394 if (Offset >= -(1LL << 9) && Offset <= (1LL << 9) - 1)
7395 return true;
7396
7397 // 12-bit unsigned offset
7398 unsigned shift = Log2_64(NumBytes);
7399 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
7400 // Must be a multiple of NumBytes (NumBytes is a power of 2)
7401 (Offset >> shift) << shift == Offset)
7402 return true;
7403 return false;
7404 }
7405
7406 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
7407
Eric Christopher114fa1c2016-02-29 22:50:49 +00007408 return !AM.Scale || AM.Scale == 1 ||
7409 (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes);
Tim Northover3b0846e2014-05-24 12:50:23 +00007410}
7411
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00007412int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
7413 const AddrMode &AM, Type *Ty,
Matt Arsenaultbd7d80a2015-06-01 05:31:59 +00007414 unsigned AS) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00007415 // Scaling factors are not free at all.
7416 // Operands | Rt Latency
7417 // -------------------------------------------
7418 // Rt, [Xn, Xm] | 4
7419 // -------------------------------------------
7420 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5
7421 // Rt, [Xn, Wm, <extend> #imm] |
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00007422 if (isLegalAddressingMode(DL, AM, Ty, AS))
Tim Northover3b0846e2014-05-24 12:50:23 +00007423 // Scale represents reg2 * scale, thus account for 1 if
7424 // it is not equal to 0 or 1.
7425 return AM.Scale != 0 && AM.Scale != 1;
7426 return -1;
7427}
7428
7429bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
7430 VT = VT.getScalarType();
7431
7432 if (!VT.isSimple())
7433 return false;
7434
7435 switch (VT.getSimpleVT().SimpleTy) {
7436 case MVT::f32:
7437 case MVT::f64:
7438 return true;
7439 default:
7440 break;
7441 }
7442
7443 return false;
7444}
7445
7446const MCPhysReg *
7447AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
7448 // LR is a callee-save register, but we must treat it as clobbered by any call
7449 // site. Hence we include LR in the scratch registers, which are in turn added
7450 // as implicit-defs for stackmaps and patchpoints.
7451 static const MCPhysReg ScratchRegs[] = {
7452 AArch64::X16, AArch64::X17, AArch64::LR, 0
7453 };
7454 return ScratchRegs;
7455}
7456
7457bool
7458AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N) const {
7459 EVT VT = N->getValueType(0);
7460 // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
7461 // it with shift to let it be lowered to UBFX.
7462 if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
7463 isa<ConstantSDNode>(N->getOperand(1))) {
7464 uint64_t TruncMask = N->getConstantOperandVal(1);
7465 if (isMask_64(TruncMask) &&
7466 N->getOperand(0).getOpcode() == ISD::SRL &&
7467 isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
7468 return false;
7469 }
7470 return true;
7471}
7472
7473bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
7474 Type *Ty) const {
7475 assert(Ty->isIntegerTy());
7476
7477 unsigned BitSize = Ty->getPrimitiveSizeInBits();
7478 if (BitSize == 0)
7479 return false;
7480
7481 int64_t Val = Imm.getSExtValue();
7482 if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
7483 return true;
7484
7485 if ((int64_t)Val < 0)
7486 Val = ~Val;
7487 if (BitSize == 32)
7488 Val &= (1LL << 32) - 1;
7489
7490 unsigned LZ = countLeadingZeros((uint64_t)Val);
7491 unsigned Shift = (63 - LZ) / 16;
7492 // MOVZ is free so return true for one or fewer MOVK.
David Blaikie186d2cb2015-03-24 16:24:01 +00007493 return Shift < 3;
Tim Northover3b0846e2014-05-24 12:50:23 +00007494}
7495
Sanjay Pateld6cb4ec2016-03-03 15:56:08 +00007496/// Turn vector tests of the signbit in the form of:
7497/// xor (sra X, elt_size(X)-1), -1
7498/// into:
7499/// cmge X, X, #0
7500static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
7501 const AArch64Subtarget *Subtarget) {
7502 EVT VT = N->getValueType(0);
7503 if (!Subtarget->hasNEON() || !VT.isVector())
7504 return SDValue();
7505
7506 // There must be a shift right algebraic before the xor, and the xor must be a
7507 // 'not' operation.
7508 SDValue Shift = N->getOperand(0);
7509 SDValue Ones = N->getOperand(1);
7510 if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() ||
7511 !ISD::isBuildVectorAllOnes(Ones.getNode()))
7512 return SDValue();
7513
7514 // The shift should be smearing the sign bit across each vector element.
7515 auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
7516 EVT ShiftEltTy = Shift.getValueType().getVectorElementType();
7517 if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1)
7518 return SDValue();
7519
7520 return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0));
7521}
7522
Tim Northover3b0846e2014-05-24 12:50:23 +00007523// Generate SUBS and CSEL for integer abs.
7524static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
7525 EVT VT = N->getValueType(0);
7526
7527 SDValue N0 = N->getOperand(0);
7528 SDValue N1 = N->getOperand(1);
7529 SDLoc DL(N);
7530
7531 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
7532 // and change it to SUB and CSEL.
7533 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
7534 N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
7535 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
7536 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
7537 if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007538 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
Tim Northover3b0846e2014-05-24 12:50:23 +00007539 N0.getOperand(0));
7540 // Generate SUBS & CSEL.
7541 SDValue Cmp =
7542 DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007543 N0.getOperand(0), DAG.getConstant(0, DL, VT));
Tim Northover3b0846e2014-05-24 12:50:23 +00007544 return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007545 DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00007546 SDValue(Cmp.getNode(), 1));
7547 }
7548 return SDValue();
7549}
7550
Tim Northover3b0846e2014-05-24 12:50:23 +00007551static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
7552 TargetLowering::DAGCombinerInfo &DCI,
7553 const AArch64Subtarget *Subtarget) {
7554 if (DCI.isBeforeLegalizeOps())
7555 return SDValue();
7556
Sanjay Pateld6cb4ec2016-03-03 15:56:08 +00007557 if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget))
7558 return Cmp;
7559
Tim Northover3b0846e2014-05-24 12:50:23 +00007560 return performIntegerAbsCombine(N, DAG);
7561}
7562
Chad Rosier17020f92014-07-23 14:57:52 +00007563SDValue
7564AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
7565 SelectionDAG &DAG,
7566 std::vector<SDNode *> *Created) const {
Haicheng Wu6a6bc752016-03-28 18:17:07 +00007567 AttributeSet Attr = DAG.getMachineFunction().getFunction()->getAttributes();
7568 if (isIntDivCheap(N->getValueType(0), Attr))
7569 return SDValue(N,0); // Lower SDIV as SDIV
7570
Chad Rosier17020f92014-07-23 14:57:52 +00007571 // fold (sdiv X, pow2)
7572 EVT VT = N->getValueType(0);
7573 if ((VT != MVT::i32 && VT != MVT::i64) ||
7574 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
7575 return SDValue();
7576
7577 SDLoc DL(N);
7578 SDValue N0 = N->getOperand(0);
7579 unsigned Lg2 = Divisor.countTrailingZeros();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007580 SDValue Zero = DAG.getConstant(0, DL, VT);
7581 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
Chad Rosier17020f92014-07-23 14:57:52 +00007582
7583 // Add (N0 < 0) ? Pow2 - 1 : 0;
7584 SDValue CCVal;
7585 SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
7586 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
7587 SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
7588
7589 if (Created) {
7590 Created->push_back(Cmp.getNode());
7591 Created->push_back(Add.getNode());
7592 Created->push_back(CSel.getNode());
7593 }
7594
7595 // Divide by pow2.
7596 SDValue SRA =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007597 DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
Chad Rosier17020f92014-07-23 14:57:52 +00007598
7599 // If we're dividing by a positive value, we're done. Otherwise, we must
7600 // negate the result.
7601 if (Divisor.isNonNegative())
7602 return SRA;
7603
7604 if (Created)
7605 Created->push_back(SRA.getNode());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007606 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
Chad Rosier17020f92014-07-23 14:57:52 +00007607}
7608
Tim Northover3b0846e2014-05-24 12:50:23 +00007609static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
7610 TargetLowering::DAGCombinerInfo &DCI,
7611 const AArch64Subtarget *Subtarget) {
7612 if (DCI.isBeforeLegalizeOps())
7613 return SDValue();
7614
7615 // Multiplication of a power of two plus/minus one can be done more
7616 // cheaply as as shift+add/sub. For now, this is true unilaterally. If
7617 // future CPUs have a cheaper MADD instruction, this may need to be
7618 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
7619 // 64-bit is 5 cycles, so this is always a win.
7620 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
Benjamin Kramer46e38f32016-06-08 10:01:20 +00007621 const APInt &Value = C->getAPIntValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00007622 EVT VT = N->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007623 SDLoc DL(N);
Chad Rosiere6b87612014-06-30 14:51:14 +00007624 if (Value.isNonNegative()) {
7625 // (mul x, 2^N + 1) => (add (shl x, N), x)
7626 APInt VM1 = Value - 1;
7627 if (VM1.isPowerOf2()) {
7628 SDValue ShiftedVal =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007629 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7630 DAG.getConstant(VM1.logBase2(), DL, MVT::i64));
7631 return DAG.getNode(ISD::ADD, DL, VT, ShiftedVal,
Chad Rosiere6b87612014-06-30 14:51:14 +00007632 N->getOperand(0));
7633 }
7634 // (mul x, 2^N - 1) => (sub (shl x, N), x)
7635 APInt VP1 = Value + 1;
7636 if (VP1.isPowerOf2()) {
7637 SDValue ShiftedVal =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007638 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7639 DAG.getConstant(VP1.logBase2(), DL, MVT::i64));
7640 return DAG.getNode(ISD::SUB, DL, VT, ShiftedVal,
Chad Rosiere6b87612014-06-30 14:51:14 +00007641 N->getOperand(0));
7642 }
7643 } else {
Chad Rosier8e38f302015-03-03 17:31:01 +00007644 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7645 APInt VNP1 = -Value + 1;
7646 if (VNP1.isPowerOf2()) {
7647 SDValue ShiftedVal =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007648 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7649 DAG.getConstant(VNP1.logBase2(), DL, MVT::i64));
7650 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0),
Chad Rosier8e38f302015-03-03 17:31:01 +00007651 ShiftedVal);
7652 }
Chad Rosiere6b87612014-06-30 14:51:14 +00007653 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7654 APInt VNM1 = -Value - 1;
7655 if (VNM1.isPowerOf2()) {
7656 SDValue ShiftedVal =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007657 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7658 DAG.getConstant(VNM1.logBase2(), DL, MVT::i64));
Chad Rosiere6b87612014-06-30 14:51:14 +00007659 SDValue Add =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007660 DAG.getNode(ISD::ADD, DL, VT, ShiftedVal, N->getOperand(0));
7661 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Add);
Chad Rosiere6b87612014-06-30 14:51:14 +00007662 }
Chad Rosierd96e9f12014-06-09 01:25:51 +00007663 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007664 }
7665 return SDValue();
7666}
7667
Jim Grosbachf7502c42014-07-18 00:40:52 +00007668static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
7669 SelectionDAG &DAG) {
7670 // Take advantage of vector comparisons producing 0 or -1 in each lane to
7671 // optimize away operation when it's from a constant.
7672 //
7673 // The general transformation is:
7674 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
7675 // AND(VECTOR_CMP(x,y), constant2)
7676 // constant2 = UNARYOP(constant)
7677
Jim Grosbach8f6f0852014-07-23 20:41:38 +00007678 // Early exit if this isn't a vector operation, the operand of the
7679 // unary operation isn't a bitwise AND, or if the sizes of the operations
7680 // aren't the same.
Jim Grosbachf7502c42014-07-18 00:40:52 +00007681 EVT VT = N->getValueType(0);
7682 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
Jim Grosbach8f6f0852014-07-23 20:41:38 +00007683 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
7684 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
Jim Grosbachf7502c42014-07-18 00:40:52 +00007685 return SDValue();
7686
Jim Grosbach724e4382014-07-23 20:41:43 +00007687 // Now check that the other operand of the AND is a constant. We could
Jim Grosbachf7502c42014-07-18 00:40:52 +00007688 // make the transformation for non-constant splats as well, but it's unclear
7689 // that would be a benefit as it would not eliminate any operations, just
7690 // perform one more step in scalar code before moving to the vector unit.
7691 if (BuildVectorSDNode *BV =
7692 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
Jim Grosbach724e4382014-07-23 20:41:43 +00007693 // Bail out if the vector isn't a constant.
7694 if (!BV->isConstant())
Jim Grosbachf7502c42014-07-18 00:40:52 +00007695 return SDValue();
7696
7697 // Everything checks out. Build up the new and improved node.
7698 SDLoc DL(N);
7699 EVT IntVT = BV->getValueType(0);
7700 // Create a new constant of the appropriate type for the transformed
7701 // DAG.
7702 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
7703 // The AND node needs bitcasts to/from an integer vector type around it.
7704 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
7705 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
7706 N->getOperand(0)->getOperand(0), MaskConst);
7707 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
7708 return Res;
7709 }
7710
7711 return SDValue();
7712}
7713
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00007714static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
7715 const AArch64Subtarget *Subtarget) {
Jim Grosbachf7502c42014-07-18 00:40:52 +00007716 // First try to optimize away the conversion when it's conditionally from
7717 // a constant. Vectors only.
Ahmed Bougacha239d6352015-08-04 00:48:02 +00007718 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
Jim Grosbachf7502c42014-07-18 00:40:52 +00007719 return Res;
7720
Tim Northover3b0846e2014-05-24 12:50:23 +00007721 EVT VT = N->getValueType(0);
7722 if (VT != MVT::f32 && VT != MVT::f64)
7723 return SDValue();
Jim Grosbachf7502c42014-07-18 00:40:52 +00007724
Tim Northover3b0846e2014-05-24 12:50:23 +00007725 // Only optimize when the source and destination types have the same width.
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00007726 if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits())
Tim Northover3b0846e2014-05-24 12:50:23 +00007727 return SDValue();
7728
7729 // If the result of an integer load is only used by an integer-to-float
7730 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
Chad Rosier1f385612015-10-02 16:42:59 +00007731 // This eliminates an "integer-to-vector-move" UOP and improves throughput.
Tim Northover3b0846e2014-05-24 12:50:23 +00007732 SDValue N0 = N->getOperand(0);
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00007733 if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Tim Northover3b0846e2014-05-24 12:50:23 +00007734 // Do not change the width of a volatile load.
7735 !cast<LoadSDNode>(N0)->isVolatile()) {
7736 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7737 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
Justin Lebar9c375812016-07-15 18:27:10 +00007738 LN0->getPointerInfo(), LN0->getAlignment(),
7739 LN0->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +00007740
7741 // Make sure successors of the original load stay after it by updating them
7742 // to use the new Chain.
7743 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
7744
7745 unsigned Opcode =
7746 (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
7747 return DAG.getNode(Opcode, SDLoc(N), VT, Load);
7748 }
7749
7750 return SDValue();
7751}
7752
Chad Rosierfa30c9b2015-10-07 17:39:18 +00007753/// Fold a floating-point multiply by power of two into floating-point to
7754/// fixed-point conversion.
7755static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
Silviu Barangafa00ba32016-08-08 13:13:57 +00007756 TargetLowering::DAGCombinerInfo &DCI,
Chad Rosierfa30c9b2015-10-07 17:39:18 +00007757 const AArch64Subtarget *Subtarget) {
7758 if (!Subtarget->hasNEON())
7759 return SDValue();
7760
7761 SDValue Op = N->getOperand(0);
Tim Northover6092de52016-03-10 23:02:21 +00007762 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
7763 Op.getOpcode() != ISD::FMUL)
Chad Rosierfa30c9b2015-10-07 17:39:18 +00007764 return SDValue();
7765
7766 SDValue ConstVec = Op->getOperand(1);
7767 if (!isa<BuildVectorSDNode>(ConstVec))
7768 return SDValue();
7769
7770 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
7771 uint32_t FloatBits = FloatTy.getSizeInBits();
7772 if (FloatBits != 32 && FloatBits != 64)
7773 return SDValue();
7774
7775 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
7776 uint32_t IntBits = IntTy.getSizeInBits();
7777 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
7778 return SDValue();
7779
7780 // Avoid conversions where iN is larger than the float (e.g., float -> i64).
7781 if (IntBits > FloatBits)
7782 return SDValue();
7783
7784 BitVector UndefElements;
7785 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
7786 int32_t Bits = IntBits == 64 ? 64 : 32;
7787 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
7788 if (C == -1 || C == 0 || C > Bits)
7789 return SDValue();
7790
7791 MVT ResTy;
7792 unsigned NumLanes = Op.getValueType().getVectorNumElements();
7793 switch (NumLanes) {
7794 default:
7795 return SDValue();
7796 case 2:
7797 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
7798 break;
7799 case 4:
Silviu Barangafa00ba32016-08-08 13:13:57 +00007800 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
Chad Rosierfa30c9b2015-10-07 17:39:18 +00007801 break;
7802 }
7803
Silviu Barangafa00ba32016-08-08 13:13:57 +00007804 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
7805 return SDValue();
7806
7807 assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) &&
7808 "Illegal vector type after legalization");
7809
Chad Rosierfa30c9b2015-10-07 17:39:18 +00007810 SDLoc DL(N);
7811 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
7812 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
7813 : Intrinsic::aarch64_neon_vcvtfp2fxu;
7814 SDValue FixConv =
7815 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
7816 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
7817 Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
7818 // We can handle smaller integers by generating an extra trunc.
7819 if (IntBits < FloatBits)
7820 FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
7821
7822 return FixConv;
7823}
7824
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00007825/// Fold a floating-point divide by power of two into fixed-point to
7826/// floating-point conversion.
7827static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
Tim Northover85cf5642016-08-26 18:52:31 +00007828 TargetLowering::DAGCombinerInfo &DCI,
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00007829 const AArch64Subtarget *Subtarget) {
7830 if (!Subtarget->hasNEON())
7831 return SDValue();
7832
7833 SDValue Op = N->getOperand(0);
7834 unsigned Opc = Op->getOpcode();
Tim Northover85cf5642016-08-26 18:52:31 +00007835 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
7836 !Op.getOperand(0).getValueType().isSimple() ||
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00007837 (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
7838 return SDValue();
7839
7840 SDValue ConstVec = N->getOperand(1);
7841 if (!isa<BuildVectorSDNode>(ConstVec))
7842 return SDValue();
7843
7844 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
7845 int32_t IntBits = IntTy.getSizeInBits();
7846 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
7847 return SDValue();
7848
7849 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
7850 int32_t FloatBits = FloatTy.getSizeInBits();
7851 if (FloatBits != 32 && FloatBits != 64)
7852 return SDValue();
7853
7854 // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
7855 if (IntBits > FloatBits)
7856 return SDValue();
7857
7858 BitVector UndefElements;
7859 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
7860 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
7861 if (C == -1 || C == 0 || C > FloatBits)
7862 return SDValue();
7863
7864 MVT ResTy;
7865 unsigned NumLanes = Op.getValueType().getVectorNumElements();
7866 switch (NumLanes) {
7867 default:
7868 return SDValue();
7869 case 2:
7870 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
7871 break;
7872 case 4:
Tim Northover85cf5642016-08-26 18:52:31 +00007873 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00007874 break;
7875 }
7876
Tim Northover85cf5642016-08-26 18:52:31 +00007877 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
7878 return SDValue();
7879
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00007880 SDLoc DL(N);
7881 SDValue ConvInput = Op.getOperand(0);
7882 bool IsSigned = Opc == ISD::SINT_TO_FP;
7883 if (IntBits < FloatBits)
7884 ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
7885 ResTy, ConvInput);
7886
7887 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
7888 : Intrinsic::aarch64_neon_vcvtfxu2fp;
7889 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
7890 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
7891 DAG.getConstant(C, DL, MVT::i32));
7892}
7893
Tim Northover3b0846e2014-05-24 12:50:23 +00007894/// An EXTR instruction is made up of two shifts, ORed together. This helper
7895/// searches for and classifies those shifts.
7896static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
7897 bool &FromHi) {
7898 if (N.getOpcode() == ISD::SHL)
7899 FromHi = false;
7900 else if (N.getOpcode() == ISD::SRL)
7901 FromHi = true;
7902 else
7903 return false;
7904
7905 if (!isa<ConstantSDNode>(N.getOperand(1)))
7906 return false;
7907
7908 ShiftAmount = N->getConstantOperandVal(1);
7909 Src = N->getOperand(0);
7910 return true;
7911}
7912
7913/// EXTR instruction extracts a contiguous chunk of bits from two existing
7914/// registers viewed as a high/low pair. This function looks for the pattern:
7915/// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an
7916/// EXTR. Can't quite be done in TableGen because the two immediates aren't
7917/// independent.
7918static SDValue tryCombineToEXTR(SDNode *N,
7919 TargetLowering::DAGCombinerInfo &DCI) {
7920 SelectionDAG &DAG = DCI.DAG;
7921 SDLoc DL(N);
7922 EVT VT = N->getValueType(0);
7923
7924 assert(N->getOpcode() == ISD::OR && "Unexpected root");
7925
7926 if (VT != MVT::i32 && VT != MVT::i64)
7927 return SDValue();
7928
7929 SDValue LHS;
7930 uint32_t ShiftLHS = 0;
7931 bool LHSFromHi = 0;
7932 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
7933 return SDValue();
7934
7935 SDValue RHS;
7936 uint32_t ShiftRHS = 0;
7937 bool RHSFromHi = 0;
7938 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
7939 return SDValue();
7940
7941 // If they're both trying to come from the high part of the register, they're
7942 // not really an EXTR.
7943 if (LHSFromHi == RHSFromHi)
7944 return SDValue();
7945
7946 if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
7947 return SDValue();
7948
7949 if (LHSFromHi) {
7950 std::swap(LHS, RHS);
7951 std::swap(ShiftLHS, ShiftRHS);
7952 }
7953
7954 return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007955 DAG.getConstant(ShiftRHS, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00007956}
7957
7958static SDValue tryCombineToBSL(SDNode *N,
7959 TargetLowering::DAGCombinerInfo &DCI) {
7960 EVT VT = N->getValueType(0);
7961 SelectionDAG &DAG = DCI.DAG;
7962 SDLoc DL(N);
7963
7964 if (!VT.isVector())
7965 return SDValue();
7966
7967 SDValue N0 = N->getOperand(0);
7968 if (N0.getOpcode() != ISD::AND)
7969 return SDValue();
7970
7971 SDValue N1 = N->getOperand(1);
7972 if (N1.getOpcode() != ISD::AND)
7973 return SDValue();
7974
7975 // We only have to look for constant vectors here since the general, variable
7976 // case can be handled in TableGen.
Sanjay Patel1ed771f2016-09-14 16:37:15 +00007977 unsigned Bits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00007978 uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
7979 for (int i = 1; i >= 0; --i)
7980 for (int j = 1; j >= 0; --j) {
7981 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
7982 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
7983 if (!BVN0 || !BVN1)
7984 continue;
7985
7986 bool FoundMatch = true;
7987 for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
7988 ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
7989 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
7990 if (!CN0 || !CN1 ||
7991 CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
7992 FoundMatch = false;
7993 break;
7994 }
7995 }
7996
7997 if (FoundMatch)
7998 return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
7999 N0->getOperand(1 - i), N1->getOperand(1 - j));
8000 }
8001
8002 return SDValue();
8003}
8004
8005static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
8006 const AArch64Subtarget *Subtarget) {
8007 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
Tim Northover3b0846e2014-05-24 12:50:23 +00008008 SelectionDAG &DAG = DCI.DAG;
8009 EVT VT = N->getValueType(0);
8010
8011 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8012 return SDValue();
8013
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00008014 if (SDValue Res = tryCombineToEXTR(N, DCI))
Tim Northover3b0846e2014-05-24 12:50:23 +00008015 return Res;
8016
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00008017 if (SDValue Res = tryCombineToBSL(N, DCI))
Tim Northover3b0846e2014-05-24 12:50:23 +00008018 return Res;
8019
8020 return SDValue();
8021}
8022
Chad Rosier14aa2ad2016-05-26 19:41:33 +00008023static SDValue performSRLCombine(SDNode *N,
8024 TargetLowering::DAGCombinerInfo &DCI) {
8025 SelectionDAG &DAG = DCI.DAG;
8026 EVT VT = N->getValueType(0);
8027 if (VT != MVT::i32 && VT != MVT::i64)
8028 return SDValue();
8029
8030 // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the
8031 // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32)
8032 // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero.
8033 SDValue N0 = N->getOperand(0);
8034 if (N0.getOpcode() == ISD::BSWAP) {
8035 SDLoc DL(N);
8036 SDValue N1 = N->getOperand(1);
8037 SDValue N00 = N0.getOperand(0);
8038 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
8039 uint64_t ShiftAmt = C->getZExtValue();
8040 if (VT == MVT::i32 && ShiftAmt == 16 &&
8041 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16)))
8042 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
8043 if (VT == MVT::i64 && ShiftAmt == 32 &&
8044 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32)))
8045 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
8046 }
8047 }
8048 return SDValue();
8049}
8050
Tim Northover3b0846e2014-05-24 12:50:23 +00008051static SDValue performBitcastCombine(SDNode *N,
8052 TargetLowering::DAGCombinerInfo &DCI,
8053 SelectionDAG &DAG) {
8054 // Wait 'til after everything is legalized to try this. That way we have
8055 // legal vector types and such.
8056 if (DCI.isBeforeLegalizeOps())
8057 return SDValue();
8058
8059 // Remove extraneous bitcasts around an extract_subvector.
8060 // For example,
8061 // (v4i16 (bitconvert
8062 // (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
8063 // becomes
8064 // (extract_subvector ((v8i16 ...), (i64 4)))
8065
8066 // Only interested in 64-bit vectors as the ultimate result.
8067 EVT VT = N->getValueType(0);
8068 if (!VT.isVector())
8069 return SDValue();
8070 if (VT.getSimpleVT().getSizeInBits() != 64)
8071 return SDValue();
8072 // Is the operand an extract_subvector starting at the beginning or halfway
8073 // point of the vector? A low half may also come through as an
8074 // EXTRACT_SUBREG, so look for that, too.
8075 SDValue Op0 = N->getOperand(0);
8076 if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
8077 !(Op0->isMachineOpcode() &&
8078 Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
8079 return SDValue();
8080 uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
8081 if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
8082 if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
8083 return SDValue();
8084 } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
8085 if (idx != AArch64::dsub)
8086 return SDValue();
8087 // The dsub reference is equivalent to a lane zero subvector reference.
8088 idx = 0;
8089 }
8090 // Look through the bitcast of the input to the extract.
8091 if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
8092 return SDValue();
8093 SDValue Source = Op0->getOperand(0)->getOperand(0);
8094 // If the source type has twice the number of elements as our destination
8095 // type, we know this is an extract of the high or low half of the vector.
8096 EVT SVT = Source->getValueType(0);
8097 if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
8098 return SDValue();
8099
8100 DEBUG(dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
8101
8102 // Create the simplified form to just extract the low or high half of the
8103 // vector directly rather than bothering with the bitcasts.
8104 SDLoc dl(N);
8105 unsigned NumElements = VT.getVectorNumElements();
8106 if (idx) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008107 SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00008108 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
8109 } else {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008110 SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00008111 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
8112 Source, SubReg),
8113 0);
8114 }
8115}
8116
8117static SDValue performConcatVectorsCombine(SDNode *N,
8118 TargetLowering::DAGCombinerInfo &DCI,
8119 SelectionDAG &DAG) {
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00008120 SDLoc dl(N);
8121 EVT VT = N->getValueType(0);
8122 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
8123
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00008124 // Optimize concat_vectors of truncated vectors, where the intermediate
8125 // type is illegal, to avoid said illegality, e.g.,
8126 // (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
8127 // (v2i16 (truncate (v2i64)))))
8128 // ->
Ahmed Bougachae6bb09a2015-03-21 01:08:39 +00008129 // (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
8130 // (v4i32 (bitcast (v2i64))),
8131 // <0, 2, 4, 6>)))
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00008132 // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
8133 // on both input and result type, so we might generate worse code.
8134 // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
8135 if (N->getNumOperands() == 2 &&
8136 N0->getOpcode() == ISD::TRUNCATE &&
8137 N1->getOpcode() == ISD::TRUNCATE) {
8138 SDValue N00 = N0->getOperand(0);
8139 SDValue N10 = N1->getOperand(0);
8140 EVT N00VT = N00.getValueType();
8141
8142 if (N00VT == N10.getValueType() &&
8143 (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
8144 N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
Ahmed Bougachae6bb09a2015-03-21 01:08:39 +00008145 MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
8146 SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
8147 for (size_t i = 0; i < Mask.size(); ++i)
8148 Mask[i] = i * 2;
8149 return DAG.getNode(ISD::TRUNCATE, dl, VT,
8150 DAG.getVectorShuffle(
8151 MidVT, dl,
8152 DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
8153 DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00008154 }
8155 }
8156
Tim Northover3b0846e2014-05-24 12:50:23 +00008157 // Wait 'til after everything is legalized to try this. That way we have
8158 // legal vector types and such.
8159 if (DCI.isBeforeLegalizeOps())
8160 return SDValue();
8161
Tim Northover3b0846e2014-05-24 12:50:23 +00008162 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
8163 // splat. The indexed instructions are going to be expecting a DUPLANE64, so
8164 // canonicalise to that.
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00008165 if (N0 == N1 && VT.getVectorNumElements() == 2) {
Sanjay Patel1ed771f2016-09-14 16:37:15 +00008166 assert(VT.getScalarSizeInBits() == 64);
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00008167 return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008168 DAG.getConstant(0, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008169 }
8170
8171 // Canonicalise concat_vectors so that the right-hand vector has as few
8172 // bit-casts as possible before its real operation. The primary matching
8173 // destination for these operations will be the narrowing "2" instructions,
8174 // which depend on the operation being performed on this right-hand vector.
8175 // For example,
8176 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS))))
8177 // becomes
8178 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
8179
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00008180 if (N1->getOpcode() != ISD::BITCAST)
Tim Northover3b0846e2014-05-24 12:50:23 +00008181 return SDValue();
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00008182 SDValue RHS = N1->getOperand(0);
Tim Northover3b0846e2014-05-24 12:50:23 +00008183 MVT RHSTy = RHS.getValueType().getSimpleVT();
8184 // If the RHS is not a vector, this is not the pattern we're looking for.
8185 if (!RHSTy.isVector())
8186 return SDValue();
8187
8188 DEBUG(dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
8189
8190 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
8191 RHSTy.getVectorNumElements() * 2);
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00008192 return DAG.getNode(ISD::BITCAST, dl, VT,
8193 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
8194 DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
8195 RHS));
Tim Northover3b0846e2014-05-24 12:50:23 +00008196}
8197
8198static SDValue tryCombineFixedPointConvert(SDNode *N,
8199 TargetLowering::DAGCombinerInfo &DCI,
8200 SelectionDAG &DAG) {
8201 // Wait 'til after everything is legalized to try this. That way we have
8202 // legal vector types and such.
8203 if (DCI.isBeforeLegalizeOps())
8204 return SDValue();
8205 // Transform a scalar conversion of a value from a lane extract into a
8206 // lane extract of a vector conversion. E.g., from foo1 to foo2:
8207 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
8208 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
8209 //
8210 // The second form interacts better with instruction selection and the
8211 // register allocator to avoid cross-class register copies that aren't
8212 // coalescable due to a lane reference.
8213
8214 // Check the operand and see if it originates from a lane extract.
8215 SDValue Op1 = N->getOperand(1);
8216 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8217 // Yep, no additional predication needed. Perform the transform.
8218 SDValue IID = N->getOperand(0);
8219 SDValue Shift = N->getOperand(2);
8220 SDValue Vec = Op1.getOperand(0);
8221 SDValue Lane = Op1.getOperand(1);
8222 EVT ResTy = N->getValueType(0);
8223 EVT VecResTy;
8224 SDLoc DL(N);
8225
8226 // The vector width should be 128 bits by the time we get here, even
8227 // if it started as 64 bits (the extract_vector handling will have
8228 // done so).
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00008229 assert(Vec.getValueSizeInBits() == 128 &&
Tim Northover3b0846e2014-05-24 12:50:23 +00008230 "unexpected vector size on extract_vector_elt!");
8231 if (Vec.getValueType() == MVT::v4i32)
8232 VecResTy = MVT::v4f32;
8233 else if (Vec.getValueType() == MVT::v2i64)
8234 VecResTy = MVT::v2f64;
8235 else
Craig Topper2a30d782014-06-18 05:05:13 +00008236 llvm_unreachable("unexpected vector type!");
Tim Northover3b0846e2014-05-24 12:50:23 +00008237
8238 SDValue Convert =
8239 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
8240 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
8241 }
8242 return SDValue();
8243}
8244
8245// AArch64 high-vector "long" operations are formed by performing the non-high
8246// version on an extract_subvector of each operand which gets the high half:
8247//
8248// (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
8249//
8250// However, there are cases which don't have an extract_high explicitly, but
8251// have another operation that can be made compatible with one for free. For
8252// example:
8253//
8254// (dupv64 scalar) --> (extract_high (dup128 scalar))
8255//
8256// This routine does the actual conversion of such DUPs, once outer routines
8257// have determined that everything else is in order.
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008258// It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
8259// similarly here.
Tim Northover3b0846e2014-05-24 12:50:23 +00008260static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00008261 switch (N.getOpcode()) {
8262 case AArch64ISD::DUP:
Tim Northover3b0846e2014-05-24 12:50:23 +00008263 case AArch64ISD::DUPLANE8:
8264 case AArch64ISD::DUPLANE16:
8265 case AArch64ISD::DUPLANE32:
8266 case AArch64ISD::DUPLANE64:
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008267 case AArch64ISD::MOVI:
8268 case AArch64ISD::MOVIshift:
8269 case AArch64ISD::MOVIedit:
8270 case AArch64ISD::MOVImsl:
8271 case AArch64ISD::MVNIshift:
8272 case AArch64ISD::MVNImsl:
Tim Northover3b0846e2014-05-24 12:50:23 +00008273 break;
8274 default:
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008275 // FMOV could be supported, but isn't very useful, as it would only occur
8276 // if you passed a bitcast' floating point immediate to an eligible long
8277 // integer op (addl, smull, ...).
Tim Northover3b0846e2014-05-24 12:50:23 +00008278 return SDValue();
8279 }
8280
8281 MVT NarrowTy = N.getSimpleValueType();
8282 if (!NarrowTy.is64BitVector())
8283 return SDValue();
8284
8285 MVT ElementTy = NarrowTy.getVectorElementType();
8286 unsigned NumElems = NarrowTy.getVectorNumElements();
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008287 MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
Tim Northover3b0846e2014-05-24 12:50:23 +00008288
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008289 SDLoc dl(N);
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008290 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
8291 DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008292 DAG.getConstant(NumElems, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008293}
8294
8295static bool isEssentiallyExtractSubvector(SDValue N) {
8296 if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
8297 return true;
8298
8299 return N.getOpcode() == ISD::BITCAST &&
8300 N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
8301}
8302
8303/// \brief Helper structure to keep track of ISD::SET_CC operands.
8304struct GenericSetCCInfo {
8305 const SDValue *Opnd0;
8306 const SDValue *Opnd1;
8307 ISD::CondCode CC;
8308};
8309
8310/// \brief Helper structure to keep track of a SET_CC lowered into AArch64 code.
8311struct AArch64SetCCInfo {
8312 const SDValue *Cmp;
8313 AArch64CC::CondCode CC;
8314};
8315
8316/// \brief Helper structure to keep track of SetCC information.
8317union SetCCInfo {
8318 GenericSetCCInfo Generic;
8319 AArch64SetCCInfo AArch64;
8320};
8321
8322/// \brief Helper structure to be able to read SetCC information. If set to
8323/// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
8324/// GenericSetCCInfo.
8325struct SetCCInfoAndKind {
8326 SetCCInfo Info;
8327 bool IsAArch64;
8328};
8329
8330/// \brief Check whether or not \p Op is a SET_CC operation, either a generic or
8331/// an
8332/// AArch64 lowered one.
8333/// \p SetCCInfo is filled accordingly.
8334/// \post SetCCInfo is meanginfull only when this function returns true.
8335/// \return True when Op is a kind of SET_CC operation.
8336static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
8337 // If this is a setcc, this is straight forward.
8338 if (Op.getOpcode() == ISD::SETCC) {
8339 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
8340 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
8341 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8342 SetCCInfo.IsAArch64 = false;
8343 return true;
8344 }
8345 // Otherwise, check if this is a matching csel instruction.
8346 // In other words:
8347 // - csel 1, 0, cc
8348 // - csel 0, 1, !cc
8349 if (Op.getOpcode() != AArch64ISD::CSEL)
8350 return false;
8351 // Set the information about the operands.
8352 // TODO: we want the operands of the Cmp not the csel
8353 SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
8354 SetCCInfo.IsAArch64 = true;
8355 SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
8356 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
8357
8358 // Check that the operands matches the constraints:
8359 // (1) Both operands must be constants.
8360 // (2) One must be 1 and the other must be 0.
8361 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
8362 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8363
8364 // Check (1).
8365 if (!TValue || !FValue)
8366 return false;
8367
8368 // Check (2).
8369 if (!TValue->isOne()) {
8370 // Update the comparison when we are interested in !cc.
8371 std::swap(TValue, FValue);
8372 SetCCInfo.Info.AArch64.CC =
8373 AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
8374 }
8375 return TValue->isOne() && FValue->isNullValue();
8376}
8377
8378// Returns true if Op is setcc or zext of setcc.
8379static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
8380 if (isSetCC(Op, Info))
8381 return true;
8382 return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
8383 isSetCC(Op->getOperand(0), Info));
8384}
8385
8386// The folding we want to perform is:
8387// (add x, [zext] (setcc cc ...) )
8388// -->
8389// (csel x, (add x, 1), !cc ...)
8390//
8391// The latter will get matched to a CSINC instruction.
8392static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
8393 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
8394 SDValue LHS = Op->getOperand(0);
8395 SDValue RHS = Op->getOperand(1);
8396 SetCCInfoAndKind InfoAndKind;
8397
8398 // If neither operand is a SET_CC, give up.
8399 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
8400 std::swap(LHS, RHS);
8401 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
8402 return SDValue();
8403 }
8404
8405 // FIXME: This could be generatized to work for FP comparisons.
8406 EVT CmpVT = InfoAndKind.IsAArch64
8407 ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
8408 : InfoAndKind.Info.Generic.Opnd0->getValueType();
8409 if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
8410 return SDValue();
8411
8412 SDValue CCVal;
8413 SDValue Cmp;
8414 SDLoc dl(Op);
8415 if (InfoAndKind.IsAArch64) {
8416 CCVal = DAG.getConstant(
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008417 AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
8418 MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00008419 Cmp = *InfoAndKind.Info.AArch64.Cmp;
8420 } else
8421 Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
8422 *InfoAndKind.Info.Generic.Opnd1,
8423 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
8424 CCVal, DAG, dl);
8425
8426 EVT VT = Op->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008427 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
Tim Northover3b0846e2014-05-24 12:50:23 +00008428 return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
8429}
8430
8431// The basic add/sub long vector instructions have variants with "2" on the end
8432// which act on the high-half of their inputs. They are normally matched by
8433// patterns like:
8434//
8435// (add (zeroext (extract_high LHS)),
8436// (zeroext (extract_high RHS)))
8437// -> uaddl2 vD, vN, vM
8438//
8439// However, if one of the extracts is something like a duplicate, this
8440// instruction can still be used profitably. This function puts the DAG into a
8441// more appropriate form for those patterns to trigger.
8442static SDValue performAddSubLongCombine(SDNode *N,
8443 TargetLowering::DAGCombinerInfo &DCI,
8444 SelectionDAG &DAG) {
8445 if (DCI.isBeforeLegalizeOps())
8446 return SDValue();
8447
8448 MVT VT = N->getSimpleValueType(0);
8449 if (!VT.is128BitVector()) {
8450 if (N->getOpcode() == ISD::ADD)
8451 return performSetccAddFolding(N, DAG);
8452 return SDValue();
8453 }
8454
8455 // Make sure both branches are extended in the same way.
8456 SDValue LHS = N->getOperand(0);
8457 SDValue RHS = N->getOperand(1);
8458 if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
8459 LHS.getOpcode() != ISD::SIGN_EXTEND) ||
8460 LHS.getOpcode() != RHS.getOpcode())
8461 return SDValue();
8462
8463 unsigned ExtType = LHS.getOpcode();
8464
8465 // It's not worth doing if at least one of the inputs isn't already an
8466 // extract, but we don't know which it'll be so we have to try both.
8467 if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
8468 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
8469 if (!RHS.getNode())
8470 return SDValue();
8471
8472 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
8473 } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
8474 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
8475 if (!LHS.getNode())
8476 return SDValue();
8477
8478 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
8479 }
8480
8481 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
8482}
8483
8484// Massage DAGs which we can use the high-half "long" operations on into
8485// something isel will recognize better. E.g.
8486//
8487// (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
8488// (aarch64_neon_umull (extract_high (v2i64 vec)))
8489// (extract_high (v2i64 (dup128 scalar)))))
8490//
Hal Finkelcd8664c2015-12-11 23:11:52 +00008491static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
Tim Northover3b0846e2014-05-24 12:50:23 +00008492 TargetLowering::DAGCombinerInfo &DCI,
8493 SelectionDAG &DAG) {
8494 if (DCI.isBeforeLegalizeOps())
8495 return SDValue();
8496
Hal Finkelcd8664c2015-12-11 23:11:52 +00008497 SDValue LHS = N->getOperand(1);
8498 SDValue RHS = N->getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00008499 assert(LHS.getValueType().is64BitVector() &&
8500 RHS.getValueType().is64BitVector() &&
8501 "unexpected shape for long operation");
8502
8503 // Either node could be a DUP, but it's not worth doing both of them (you'd
8504 // just as well use the non-high version) so look for a corresponding extract
8505 // operation on the other "wing".
8506 if (isEssentiallyExtractSubvector(LHS)) {
8507 RHS = tryExtendDUPToExtractHigh(RHS, DAG);
8508 if (!RHS.getNode())
8509 return SDValue();
8510 } else if (isEssentiallyExtractSubvector(RHS)) {
8511 LHS = tryExtendDUPToExtractHigh(LHS, DAG);
8512 if (!LHS.getNode())
8513 return SDValue();
8514 }
8515
Hal Finkelcd8664c2015-12-11 23:11:52 +00008516 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
8517 N->getOperand(0), LHS, RHS);
Tim Northover3b0846e2014-05-24 12:50:23 +00008518}
8519
8520static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
8521 MVT ElemTy = N->getSimpleValueType(0).getScalarType();
8522 unsigned ElemBits = ElemTy.getSizeInBits();
8523
8524 int64_t ShiftAmount;
8525 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
8526 APInt SplatValue, SplatUndef;
8527 unsigned SplatBitSize;
8528 bool HasAnyUndefs;
8529 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
8530 HasAnyUndefs, ElemBits) ||
8531 SplatBitSize != ElemBits)
8532 return SDValue();
8533
8534 ShiftAmount = SplatValue.getSExtValue();
8535 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
8536 ShiftAmount = CVN->getSExtValue();
8537 } else
8538 return SDValue();
8539
8540 unsigned Opcode;
8541 bool IsRightShift;
8542 switch (IID) {
8543 default:
8544 llvm_unreachable("Unknown shift intrinsic");
8545 case Intrinsic::aarch64_neon_sqshl:
8546 Opcode = AArch64ISD::SQSHL_I;
8547 IsRightShift = false;
8548 break;
8549 case Intrinsic::aarch64_neon_uqshl:
8550 Opcode = AArch64ISD::UQSHL_I;
8551 IsRightShift = false;
8552 break;
8553 case Intrinsic::aarch64_neon_srshl:
8554 Opcode = AArch64ISD::SRSHR_I;
8555 IsRightShift = true;
8556 break;
8557 case Intrinsic::aarch64_neon_urshl:
8558 Opcode = AArch64ISD::URSHR_I;
8559 IsRightShift = true;
8560 break;
8561 case Intrinsic::aarch64_neon_sqshlu:
8562 Opcode = AArch64ISD::SQSHLU_I;
8563 IsRightShift = false;
8564 break;
8565 }
8566
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008567 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
8568 SDLoc dl(N);
8569 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8570 DAG.getConstant(-ShiftAmount, dl, MVT::i32));
8571 } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
8572 SDLoc dl(N);
8573 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8574 DAG.getConstant(ShiftAmount, dl, MVT::i32));
8575 }
Tim Northover3b0846e2014-05-24 12:50:23 +00008576
8577 return SDValue();
8578}
8579
8580// The CRC32[BH] instructions ignore the high bits of their data operand. Since
8581// the intrinsics must be legal and take an i32, this means there's almost
8582// certainly going to be a zext in the DAG which we can eliminate.
8583static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
8584 SDValue AndN = N->getOperand(2);
8585 if (AndN.getOpcode() != ISD::AND)
8586 return SDValue();
8587
8588 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
8589 if (!CMask || CMask->getZExtValue() != Mask)
8590 return SDValue();
8591
8592 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
8593 N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
8594}
8595
Ahmed Bougachafab58922015-03-10 20:45:38 +00008596static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
8597 SelectionDAG &DAG) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008598 SDLoc dl(N);
8599 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
8600 DAG.getNode(Opc, dl,
Ahmed Bougachafab58922015-03-10 20:45:38 +00008601 N->getOperand(1).getSimpleValueType(),
8602 N->getOperand(1)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008603 DAG.getConstant(0, dl, MVT::i64));
Ahmed Bougachafab58922015-03-10 20:45:38 +00008604}
8605
Tim Northover3b0846e2014-05-24 12:50:23 +00008606static SDValue performIntrinsicCombine(SDNode *N,
8607 TargetLowering::DAGCombinerInfo &DCI,
8608 const AArch64Subtarget *Subtarget) {
8609 SelectionDAG &DAG = DCI.DAG;
8610 unsigned IID = getIntrinsicID(N);
8611 switch (IID) {
8612 default:
8613 break;
8614 case Intrinsic::aarch64_neon_vcvtfxs2fp:
8615 case Intrinsic::aarch64_neon_vcvtfxu2fp:
8616 return tryCombineFixedPointConvert(N, DCI, DAG);
Ahmed Bougachafab58922015-03-10 20:45:38 +00008617 case Intrinsic::aarch64_neon_saddv:
8618 return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
8619 case Intrinsic::aarch64_neon_uaddv:
8620 return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
8621 case Intrinsic::aarch64_neon_sminv:
8622 return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
8623 case Intrinsic::aarch64_neon_uminv:
8624 return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
8625 case Intrinsic::aarch64_neon_smaxv:
8626 return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
8627 case Intrinsic::aarch64_neon_umaxv:
8628 return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00008629 case Intrinsic::aarch64_neon_fmax:
James Molloyedf38f02015-08-11 12:06:33 +00008630 return DAG.getNode(ISD::FMAXNAN, SDLoc(N), N->getValueType(0),
Tim Northover3b0846e2014-05-24 12:50:23 +00008631 N->getOperand(1), N->getOperand(2));
8632 case Intrinsic::aarch64_neon_fmin:
James Molloyedf38f02015-08-11 12:06:33 +00008633 return DAG.getNode(ISD::FMINNAN, SDLoc(N), N->getValueType(0),
Tim Northover3b0846e2014-05-24 12:50:23 +00008634 N->getOperand(1), N->getOperand(2));
James Molloyb7b2a1e2015-08-11 12:06:37 +00008635 case Intrinsic::aarch64_neon_fmaxnm:
8636 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
8637 N->getOperand(1), N->getOperand(2));
8638 case Intrinsic::aarch64_neon_fminnm:
8639 return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
8640 N->getOperand(1), N->getOperand(2));
Tim Northover3b0846e2014-05-24 12:50:23 +00008641 case Intrinsic::aarch64_neon_smull:
8642 case Intrinsic::aarch64_neon_umull:
8643 case Intrinsic::aarch64_neon_pmull:
8644 case Intrinsic::aarch64_neon_sqdmull:
Hal Finkelcd8664c2015-12-11 23:11:52 +00008645 return tryCombineLongOpWithDup(IID, N, DCI, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00008646 case Intrinsic::aarch64_neon_sqshl:
8647 case Intrinsic::aarch64_neon_uqshl:
8648 case Intrinsic::aarch64_neon_sqshlu:
8649 case Intrinsic::aarch64_neon_srshl:
8650 case Intrinsic::aarch64_neon_urshl:
8651 return tryCombineShiftImm(IID, N, DAG);
8652 case Intrinsic::aarch64_crc32b:
8653 case Intrinsic::aarch64_crc32cb:
8654 return tryCombineCRC32(0xff, N, DAG);
8655 case Intrinsic::aarch64_crc32h:
8656 case Intrinsic::aarch64_crc32ch:
8657 return tryCombineCRC32(0xffff, N, DAG);
8658 }
8659 return SDValue();
8660}
8661
8662static SDValue performExtendCombine(SDNode *N,
8663 TargetLowering::DAGCombinerInfo &DCI,
8664 SelectionDAG &DAG) {
8665 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
8666 // we can convert that DUP into another extract_high (of a bigger DUP), which
8667 // helps the backend to decide that an sabdl2 would be useful, saving a real
8668 // extract_high operation.
8669 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
Hal Finkelcd8664c2015-12-11 23:11:52 +00008670 N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
Tim Northover3b0846e2014-05-24 12:50:23 +00008671 SDNode *ABDNode = N->getOperand(0).getNode();
Hal Finkelcd8664c2015-12-11 23:11:52 +00008672 unsigned IID = getIntrinsicID(ABDNode);
8673 if (IID == Intrinsic::aarch64_neon_sabd ||
8674 IID == Intrinsic::aarch64_neon_uabd) {
8675 SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
8676 if (!NewABD.getNode())
8677 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00008678
Hal Finkelcd8664c2015-12-11 23:11:52 +00008679 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
8680 NewABD);
8681 }
Tim Northover3b0846e2014-05-24 12:50:23 +00008682 }
8683
8684 // This is effectively a custom type legalization for AArch64.
8685 //
8686 // Type legalization will split an extend of a small, legal, type to a larger
8687 // illegal type by first splitting the destination type, often creating
8688 // illegal source types, which then get legalized in isel-confusing ways,
8689 // leading to really terrible codegen. E.g.,
8690 // %result = v8i32 sext v8i8 %value
8691 // becomes
8692 // %losrc = extract_subreg %value, ...
8693 // %hisrc = extract_subreg %value, ...
8694 // %lo = v4i32 sext v4i8 %losrc
8695 // %hi = v4i32 sext v4i8 %hisrc
8696 // Things go rapidly downhill from there.
8697 //
8698 // For AArch64, the [sz]ext vector instructions can only go up one element
8699 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
8700 // take two instructions.
8701 //
8702 // This implies that the most efficient way to do the extend from v8i8
8703 // to two v4i32 values is to first extend the v8i8 to v8i16, then do
8704 // the normal splitting to happen for the v8i16->v8i32.
8705
8706 // This is pre-legalization to catch some cases where the default
8707 // type legalization will create ill-tempered code.
8708 if (!DCI.isBeforeLegalizeOps())
8709 return SDValue();
8710
8711 // We're only interested in cleaning things up for non-legal vector types
8712 // here. If both the source and destination are legal, things will just
8713 // work naturally without any fiddling.
Matthew Simpson13dddb02015-12-17 21:29:47 +00008714 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00008715 EVT ResVT = N->getValueType(0);
8716 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
8717 return SDValue();
8718 // If the vector type isn't a simple VT, it's beyond the scope of what
8719 // we're worried about here. Let legalization do its thing and hope for
8720 // the best.
Jim Grosbachec2b0d02014-08-28 22:08:28 +00008721 SDValue Src = N->getOperand(0);
8722 EVT SrcVT = Src->getValueType(0);
8723 if (!ResVT.isSimple() || !SrcVT.isSimple())
Tim Northover3b0846e2014-05-24 12:50:23 +00008724 return SDValue();
8725
Tim Northover3b0846e2014-05-24 12:50:23 +00008726 // If the source VT is a 64-bit vector, we can play games and get the
8727 // better results we want.
8728 if (SrcVT.getSizeInBits() != 64)
8729 return SDValue();
8730
Sanjay Patel1ed771f2016-09-14 16:37:15 +00008731 unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00008732 unsigned ElementCount = SrcVT.getVectorNumElements();
8733 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
8734 SDLoc DL(N);
8735 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
8736
8737 // Now split the rest of the operation into two halves, each with a 64
8738 // bit source.
8739 EVT LoVT, HiVT;
8740 SDValue Lo, Hi;
8741 unsigned NumElements = ResVT.getVectorNumElements();
8742 assert(!(NumElements & 1) && "Splitting vector, but not in half!");
8743 LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
8744 ResVT.getVectorElementType(), NumElements / 2);
8745
8746 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
8747 LoVT.getVectorNumElements());
8748 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008749 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008750 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008751 DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008752 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
8753 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
8754
8755 // Now combine the parts back together so we still have a single result
8756 // like the combiner expects.
8757 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
8758}
8759
8760/// Replace a splat of a scalar to a vector store by scalar stores of the scalar
8761/// value. The load store optimizer pass will merge them to store pair stores.
8762/// This has better performance than a splat of the scalar followed by a split
8763/// vector store. Even if the stores are not merged it is four stores vs a dup,
8764/// followed by an ext.b and two stores.
8765static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode *St) {
8766 SDValue StVal = St->getValue();
8767 EVT VT = StVal.getValueType();
8768
8769 // Don't replace floating point stores, they possibly won't be transformed to
8770 // stp because of the store pair suppress pass.
8771 if (VT.isFloatingPoint())
8772 return SDValue();
8773
8774 // Check for insert vector elements.
8775 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
8776 return SDValue();
8777
8778 // We can express a splat as store pair(s) for 2 or 4 elements.
8779 unsigned NumVecElts = VT.getVectorNumElements();
8780 if (NumVecElts != 4 && NumVecElts != 2)
8781 return SDValue();
8782 SDValue SplatVal = StVal.getOperand(1);
8783 unsigned RemainInsertElts = NumVecElts - 1;
8784
8785 // Check that this is a splat.
8786 while (--RemainInsertElts) {
8787 SDValue NextInsertElt = StVal.getOperand(0);
8788 if (NextInsertElt.getOpcode() != ISD::INSERT_VECTOR_ELT)
8789 return SDValue();
8790 if (NextInsertElt.getOperand(1) != SplatVal)
8791 return SDValue();
8792 StVal = NextInsertElt;
8793 }
8794 unsigned OrigAlignment = St->getAlignment();
8795 unsigned EltOffset = NumVecElts == 4 ? 4 : 8;
8796 unsigned Alignment = std::min(OrigAlignment, EltOffset);
8797
8798 // Create scalar stores. This is at least as good as the code sequence for a
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00008799 // split unaligned store which is a dup.s, ext.b, and two stores.
Tim Northover3b0846e2014-05-24 12:50:23 +00008800 // Most of the time the three stores should be replaced by store pair
8801 // instructions (stp).
8802 SDLoc DL(St);
8803 SDValue BasePtr = St->getBasePtr();
8804 SDValue NewST1 =
8805 DAG.getStore(St->getChain(), DL, SplatVal, BasePtr, St->getPointerInfo(),
Justin Lebar9c375812016-07-15 18:27:10 +00008806 St->getAlignment(), St->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +00008807
8808 unsigned Offset = EltOffset;
8809 while (--NumVecElts) {
8810 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008811 DAG.getConstant(Offset, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008812 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
Justin Lebar9c375812016-07-15 18:27:10 +00008813 St->getPointerInfo(), Alignment,
8814 St->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +00008815 Offset += EltOffset;
8816 }
8817 return NewST1;
8818}
8819
Tim Northover339c83e2015-11-10 00:44:23 +00008820static SDValue split16BStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
8821 SelectionDAG &DAG,
8822 const AArch64Subtarget *Subtarget) {
Tim Northover3b0846e2014-05-24 12:50:23 +00008823 if (!DCI.isBeforeLegalize())
8824 return SDValue();
8825
8826 StoreSDNode *S = cast<StoreSDNode>(N);
8827 if (S->isVolatile())
8828 return SDValue();
8829
Sanjay Patelbbbf9a12015-09-25 21:49:48 +00008830 // FIXME: The logic for deciding if an unaligned store should be split should
8831 // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
8832 // a call to that function here.
8833
Matthias Braun651cff42016-06-02 18:03:53 +00008834 if (!Subtarget->isMisaligned128StoreSlow())
Tim Northover3b0846e2014-05-24 12:50:23 +00008835 return SDValue();
8836
Sanjay Patel924879a2015-08-04 15:49:57 +00008837 // Don't split at -Oz.
8838 if (DAG.getMachineFunction().getFunction()->optForMinSize())
Tim Northover3b0846e2014-05-24 12:50:23 +00008839 return SDValue();
8840
8841 SDValue StVal = S->getValue();
8842 EVT VT = StVal.getValueType();
8843
8844 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
8845 // those up regresses performance on micro-benchmarks and olden/bh.
8846 if (!VT.isVector() || VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
8847 return SDValue();
8848
8849 // Split unaligned 16B stores. They are terrible for performance.
8850 // Don't split stores with alignment of 1 or 2. Code that uses clang vector
8851 // extensions can use this to mark that it does not want splitting to happen
8852 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
8853 // eliminating alignment hazards is only 1 in 8 for alignment of 2.
8854 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
8855 S->getAlignment() <= 2)
8856 return SDValue();
8857
8858 // If we get a splat of a scalar convert this vector store to a store of
8859 // scalars. They will be merged into store pairs thereby removing two
8860 // instructions.
Ahmed Bougacha239d6352015-08-04 00:48:02 +00008861 if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, S))
Tim Northover3b0846e2014-05-24 12:50:23 +00008862 return ReplacedSplat;
8863
8864 SDLoc DL(S);
8865 unsigned NumElts = VT.getVectorNumElements() / 2;
8866 // Split VT into two.
8867 EVT HalfVT =
8868 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
8869 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008870 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008871 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008872 DAG.getConstant(NumElts, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008873 SDValue BasePtr = S->getBasePtr();
8874 SDValue NewST1 =
8875 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
Justin Lebar9c375812016-07-15 18:27:10 +00008876 S->getAlignment(), S->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +00008877 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008878 DAG.getConstant(8, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008879 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
Justin Lebar9c375812016-07-15 18:27:10 +00008880 S->getPointerInfo(), S->getAlignment(),
8881 S->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +00008882}
8883
8884/// Target-specific DAG combine function for post-increment LD1 (lane) and
8885/// post-increment LD1R.
8886static SDValue performPostLD1Combine(SDNode *N,
8887 TargetLowering::DAGCombinerInfo &DCI,
8888 bool IsLaneOp) {
8889 if (DCI.isBeforeLegalizeOps())
8890 return SDValue();
8891
8892 SelectionDAG &DAG = DCI.DAG;
8893 EVT VT = N->getValueType(0);
8894
8895 unsigned LoadIdx = IsLaneOp ? 1 : 0;
8896 SDNode *LD = N->getOperand(LoadIdx).getNode();
8897 // If it is not LOAD, can not do such combine.
8898 if (LD->getOpcode() != ISD::LOAD)
8899 return SDValue();
8900
8901 LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
8902 EVT MemVT = LoadSDN->getMemoryVT();
8903 // Check if memory operand is the same type as the vector element.
8904 if (MemVT != VT.getVectorElementType())
8905 return SDValue();
8906
8907 // Check if there are other uses. If so, do not combine as it will introduce
8908 // an extra load.
8909 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
8910 ++UI) {
8911 if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
8912 continue;
8913 if (*UI != N)
8914 return SDValue();
8915 }
8916
8917 SDValue Addr = LD->getOperand(1);
8918 SDValue Vector = N->getOperand(0);
8919 // Search for a use of the address operand that is an increment.
8920 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
8921 Addr.getNode()->use_end(); UI != UE; ++UI) {
8922 SDNode *User = *UI;
8923 if (User->getOpcode() != ISD::ADD
8924 || UI.getUse().getResNo() != Addr.getResNo())
8925 continue;
8926
8927 // Check that the add is independent of the load. Otherwise, folding it
8928 // would create a cycle.
8929 if (User->isPredecessorOf(LD) || LD->isPredecessorOf(User))
8930 continue;
8931 // Also check that add is not used in the vector operand. This would also
8932 // create a cycle.
8933 if (User->isPredecessorOf(Vector.getNode()))
8934 continue;
8935
8936 // If the increment is a constant, it must match the memory ref size.
8937 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8938 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8939 uint32_t IncVal = CInc->getZExtValue();
8940 unsigned NumBytes = VT.getScalarSizeInBits() / 8;
8941 if (IncVal != NumBytes)
8942 continue;
8943 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
8944 }
8945
Ahmed Bougacha2448ef52015-04-17 21:02:30 +00008946 // Finally, check that the vector doesn't depend on the load.
8947 // Again, this would create a cycle.
8948 // The load depending on the vector is fine, as that's the case for the
8949 // LD1*post we'll eventually generate anyway.
8950 if (LoadSDN->isPredecessorOf(Vector.getNode()))
8951 continue;
8952
Tim Northover3b0846e2014-05-24 12:50:23 +00008953 SmallVector<SDValue, 8> Ops;
8954 Ops.push_back(LD->getOperand(0)); // Chain
8955 if (IsLaneOp) {
8956 Ops.push_back(Vector); // The vector to be inserted
8957 Ops.push_back(N->getOperand(2)); // The lane to be inserted in the vector
8958 }
8959 Ops.push_back(Addr);
8960 Ops.push_back(Inc);
8961
8962 EVT Tys[3] = { VT, MVT::i64, MVT::Other };
Craig Toppere1d12942014-08-27 05:25:25 +00008963 SDVTList SDTys = DAG.getVTList(Tys);
Tim Northover3b0846e2014-05-24 12:50:23 +00008964 unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
8965 SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
8966 MemVT,
8967 LoadSDN->getMemOperand());
8968
8969 // Update the uses.
Benjamin Kramer3bc1edf2016-07-02 11:41:39 +00008970 SDValue NewResults[] = {
8971 SDValue(LD, 0), // The result of load
8972 SDValue(UpdN.getNode(), 2) // Chain
8973 };
Tim Northover3b0846e2014-05-24 12:50:23 +00008974 DCI.CombineTo(LD, NewResults);
8975 DCI.CombineTo(N, SDValue(UpdN.getNode(), 0)); // Dup/Inserted Result
8976 DCI.CombineTo(User, SDValue(UpdN.getNode(), 1)); // Write back register
8977
8978 break;
8979 }
8980 return SDValue();
8981}
8982
Tim Northover339c83e2015-11-10 00:44:23 +00008983/// Simplify \Addr given that the top byte of it is ignored by HW during
8984/// address translation.
8985static bool performTBISimplification(SDValue Addr,
8986 TargetLowering::DAGCombinerInfo &DCI,
8987 SelectionDAG &DAG) {
8988 APInt DemandedMask = APInt::getLowBitsSet(64, 56);
8989 APInt KnownZero, KnownOne;
8990 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
8991 DCI.isBeforeLegalizeOps());
8992 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8993 if (TLI.SimplifyDemandedBits(Addr, DemandedMask, KnownZero, KnownOne, TLO)) {
8994 DCI.CommitTargetLoweringOpt(TLO);
8995 return true;
8996 }
8997 return false;
8998}
8999
9000static SDValue performSTORECombine(SDNode *N,
9001 TargetLowering::DAGCombinerInfo &DCI,
9002 SelectionDAG &DAG,
9003 const AArch64Subtarget *Subtarget) {
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00009004 if (SDValue Split = split16BStores(N, DCI, DAG, Subtarget))
Tim Northover339c83e2015-11-10 00:44:23 +00009005 return Split;
9006
9007 if (Subtarget->supportsAddressTopByteIgnored() &&
9008 performTBISimplification(N->getOperand(2), DCI, DAG))
9009 return SDValue(N, 0);
9010
9011 return SDValue();
9012}
9013
9014 /// This function handles the log2-shuffle pattern produced by the
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009015/// LoopVectorizer for the across vector reduction. It consists of
9016/// log2(NumVectorElements) steps and, in each step, 2^(s) elements
9017/// are reduced, where s is an induction variable from 0 to
9018/// log2(NumVectorElements).
9019static SDValue tryMatchAcrossLaneShuffleForReduction(SDNode *N, SDValue OpV,
9020 unsigned Op,
9021 SelectionDAG &DAG) {
9022 EVT VTy = OpV->getOperand(0).getValueType();
9023 if (!VTy.isVector())
Chad Rosier6c36eff2015-09-03 18:13:57 +00009024 return SDValue();
9025
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009026 int NumVecElts = VTy.getVectorNumElements();
Jun Bum Lim0aace132015-10-09 14:11:25 +00009027 if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) {
9028 if (NumVecElts != 4)
9029 return SDValue();
9030 } else {
9031 if (NumVecElts != 4 && NumVecElts != 8 && NumVecElts != 16)
9032 return SDValue();
9033 }
Chad Rosier6c36eff2015-09-03 18:13:57 +00009034
9035 int NumExpectedSteps = APInt(8, NumVecElts).logBase2();
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009036 SDValue PreOp = OpV;
Chad Rosier6c36eff2015-09-03 18:13:57 +00009037 // Iterate over each step of the across vector reduction.
9038 for (int CurStep = 0; CurStep != NumExpectedSteps; ++CurStep) {
Chad Rosier6c36eff2015-09-03 18:13:57 +00009039 SDValue CurOp = PreOp.getOperand(0);
9040 SDValue Shuffle = PreOp.getOperand(1);
9041 if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE) {
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009042 // Try to swap the 1st and 2nd operand as add and min/max instructions
9043 // are commutative.
Chad Rosier6c36eff2015-09-03 18:13:57 +00009044 CurOp = PreOp.getOperand(1);
9045 Shuffle = PreOp.getOperand(0);
9046 if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE)
9047 return SDValue();
9048 }
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009049
9050 // Check if the input vector is fed by the operator we want to handle,
9051 // except the last step; the very first input vector is not necessarily
9052 // the same operator we are handling.
9053 if (CurOp.getOpcode() != Op && (CurStep != (NumExpectedSteps - 1)))
9054 return SDValue();
9055
Chad Rosier6c36eff2015-09-03 18:13:57 +00009056 // Check if it forms one step of the across vector reduction.
9057 // E.g.,
9058 // %cur = add %1, %0
9059 // %shuffle = vector_shuffle %cur, <2, 3, u, u>
9060 // %pre = add %cur, %shuffle
9061 if (Shuffle.getOperand(0) != CurOp)
9062 return SDValue();
9063
9064 int NumMaskElts = 1 << CurStep;
9065 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Shuffle)->getMask();
9066 // Check mask values in each step.
9067 // We expect the shuffle mask in each step follows a specific pattern
9068 // denoted here by the <M, U> form, where M is a sequence of integers
9069 // starting from NumMaskElts, increasing by 1, and the number integers
9070 // in M should be NumMaskElts. U is a sequence of UNDEFs and the number
9071 // of undef in U should be NumVecElts - NumMaskElts.
9072 // E.g., for <8 x i16>, mask values in each step should be :
9073 // step 0 : <1,u,u,u,u,u,u,u>
9074 // step 1 : <2,3,u,u,u,u,u,u>
9075 // step 2 : <4,5,6,7,u,u,u,u>
9076 for (int i = 0; i < NumVecElts; ++i)
9077 if ((i < NumMaskElts && Mask[i] != (NumMaskElts + i)) ||
9078 (i >= NumMaskElts && !(Mask[i] < 0)))
9079 return SDValue();
9080
9081 PreOp = CurOp;
9082 }
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009083 unsigned Opcode;
Jun Bum Lim0aace132015-10-09 14:11:25 +00009084 bool IsIntrinsic = false;
9085
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009086 switch (Op) {
9087 default:
9088 llvm_unreachable("Unexpected operator for across vector reduction");
9089 case ISD::ADD:
9090 Opcode = AArch64ISD::UADDV;
9091 break;
9092 case ISD::SMAX:
9093 Opcode = AArch64ISD::SMAXV;
9094 break;
9095 case ISD::UMAX:
9096 Opcode = AArch64ISD::UMAXV;
9097 break;
9098 case ISD::SMIN:
9099 Opcode = AArch64ISD::SMINV;
9100 break;
9101 case ISD::UMIN:
9102 Opcode = AArch64ISD::UMINV;
9103 break;
Jun Bum Lim0aace132015-10-09 14:11:25 +00009104 case ISD::FMAXNUM:
9105 Opcode = Intrinsic::aarch64_neon_fmaxnmv;
9106 IsIntrinsic = true;
9107 break;
9108 case ISD::FMINNUM:
9109 Opcode = Intrinsic::aarch64_neon_fminnmv;
9110 IsIntrinsic = true;
9111 break;
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009112 }
Chad Rosier6c36eff2015-09-03 18:13:57 +00009113 SDLoc DL(N);
Jun Bum Lim0aace132015-10-09 14:11:25 +00009114
9115 return IsIntrinsic
9116 ? DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, N->getValueType(0),
9117 DAG.getConstant(Opcode, DL, MVT::i32), PreOp)
9118 : DAG.getNode(
9119 ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0),
9120 DAG.getNode(Opcode, DL, PreOp.getSimpleValueType(), PreOp),
9121 DAG.getConstant(0, DL, MVT::i64));
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009122}
9123
9124/// Target-specific DAG combine for the across vector min/max reductions.
9125/// This function specifically handles the final clean-up step of the vector
9126/// min/max reductions produced by the LoopVectorizer. It is the log2-shuffle
9127/// pattern, which narrows down and finds the final min/max value from all
9128/// elements of the vector.
9129/// For example, for a <16 x i8> vector :
9130/// svn0 = vector_shuffle %0, undef<8,9,10,11,12,13,14,15,u,u,u,u,u,u,u,u>
9131/// %smax0 = smax %arr, svn0
9132/// %svn1 = vector_shuffle %smax0, undef<4,5,6,7,u,u,u,u,u,u,u,u,u,u,u,u>
9133/// %smax1 = smax %smax0, %svn1
9134/// %svn2 = vector_shuffle %smax1, undef<2,3,u,u,u,u,u,u,u,u,u,u,u,u,u,u>
9135/// %smax2 = smax %smax1, svn2
9136/// %svn3 = vector_shuffle %smax2, undef<1,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u>
9137/// %sc = setcc %smax2, %svn3, gt
9138/// %n0 = extract_vector_elt %sc, #0
9139/// %n1 = extract_vector_elt %smax2, #0
9140/// %n2 = extract_vector_elt $smax2, #1
9141/// %result = select %n0, %n1, n2
9142/// becomes :
9143/// %1 = smaxv %0
9144/// %result = extract_vector_elt %1, 0
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009145static SDValue
9146performAcrossLaneMinMaxReductionCombine(SDNode *N, SelectionDAG &DAG,
9147 const AArch64Subtarget *Subtarget) {
9148 if (!Subtarget->hasNEON())
9149 return SDValue();
9150
9151 SDValue N0 = N->getOperand(0);
9152 SDValue IfTrue = N->getOperand(1);
9153 SDValue IfFalse = N->getOperand(2);
9154
9155 // Check if the SELECT merges up the final result of the min/max
9156 // from a vector.
9157 if (N0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9158 IfTrue.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9159 IfFalse.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9160 return SDValue();
9161
9162 // Expect N0 is fed by SETCC.
9163 SDValue SetCC = N0.getOperand(0);
9164 EVT SetCCVT = SetCC.getValueType();
9165 if (SetCC.getOpcode() != ISD::SETCC || !SetCCVT.isVector() ||
9166 SetCCVT.getVectorElementType() != MVT::i1)
9167 return SDValue();
9168
9169 SDValue VectorOp = SetCC.getOperand(0);
9170 unsigned Op = VectorOp->getOpcode();
9171 // Check if the input vector is fed by the operator we want to handle.
Jun Bum Lim0aace132015-10-09 14:11:25 +00009172 if (Op != ISD::SMAX && Op != ISD::UMAX && Op != ISD::SMIN &&
9173 Op != ISD::UMIN && Op != ISD::FMAXNUM && Op != ISD::FMINNUM)
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009174 return SDValue();
9175
9176 EVT VTy = VectorOp.getValueType();
9177 if (!VTy.isVector())
9178 return SDValue();
9179
Jun Bum Lim0aace132015-10-09 14:11:25 +00009180 if (VTy.getSizeInBits() < 64)
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009181 return SDValue();
9182
Jun Bum Lim0aace132015-10-09 14:11:25 +00009183 EVT EltTy = VTy.getVectorElementType();
9184 if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) {
9185 if (EltTy != MVT::f32)
9186 return SDValue();
9187 } else {
9188 if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8)
9189 return SDValue();
9190 }
9191
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009192 // Check if extracting from the same vector.
9193 // For example,
9194 // %sc = setcc %vector, %svn1, gt
9195 // %n0 = extract_vector_elt %sc, #0
9196 // %n1 = extract_vector_elt %vector, #0
9197 // %n2 = extract_vector_elt $vector, #1
9198 if (!(VectorOp == IfTrue->getOperand(0) &&
9199 VectorOp == IfFalse->getOperand(0)))
9200 return SDValue();
9201
9202 // Check if the condition code is matched with the operator type.
9203 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get();
9204 if ((Op == ISD::SMAX && CC != ISD::SETGT && CC != ISD::SETGE) ||
9205 (Op == ISD::UMAX && CC != ISD::SETUGT && CC != ISD::SETUGE) ||
9206 (Op == ISD::SMIN && CC != ISD::SETLT && CC != ISD::SETLE) ||
Jun Bum Lim0aace132015-10-09 14:11:25 +00009207 (Op == ISD::UMIN && CC != ISD::SETULT && CC != ISD::SETULE) ||
9208 (Op == ISD::FMAXNUM && CC != ISD::SETOGT && CC != ISD::SETOGE &&
9209 CC != ISD::SETUGT && CC != ISD::SETUGE && CC != ISD::SETGT &&
9210 CC != ISD::SETGE) ||
9211 (Op == ISD::FMINNUM && CC != ISD::SETOLT && CC != ISD::SETOLE &&
9212 CC != ISD::SETULT && CC != ISD::SETULE && CC != ISD::SETLT &&
9213 CC != ISD::SETLE))
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009214 return SDValue();
9215
9216 // Expect to check only lane 0 from the vector SETCC.
Artyom Skrobov314ee042015-11-25 19:41:11 +00009217 if (!isNullConstant(N0.getOperand(1)))
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009218 return SDValue();
9219
9220 // Expect to extract the true value from lane 0.
Artyom Skrobov314ee042015-11-25 19:41:11 +00009221 if (!isNullConstant(IfTrue.getOperand(1)))
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009222 return SDValue();
9223
9224 // Expect to extract the false value from lane 1.
Artyom Skrobov314ee042015-11-25 19:41:11 +00009225 if (!isOneConstant(IfFalse.getOperand(1)))
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009226 return SDValue();
9227
9228 return tryMatchAcrossLaneShuffleForReduction(N, SetCC, Op, DAG);
9229}
9230
9231/// Target-specific DAG combine for the across vector add reduction.
9232/// This function specifically handles the final clean-up step of the vector
9233/// add reduction produced by the LoopVectorizer. It is the log2-shuffle
9234/// pattern, which adds all elements of a vector together.
9235/// For example, for a <4 x i32> vector :
9236/// %1 = vector_shuffle %0, <2,3,u,u>
9237/// %2 = add %0, %1
9238/// %3 = vector_shuffle %2, <1,u,u,u>
9239/// %4 = add %2, %3
9240/// %result = extract_vector_elt %4, 0
9241/// becomes :
9242/// %0 = uaddv %0
9243/// %result = extract_vector_elt %0, 0
9244static SDValue
9245performAcrossLaneAddReductionCombine(SDNode *N, SelectionDAG &DAG,
9246 const AArch64Subtarget *Subtarget) {
9247 if (!Subtarget->hasNEON())
9248 return SDValue();
9249 SDValue N0 = N->getOperand(0);
9250 SDValue N1 = N->getOperand(1);
9251
9252 // Check if the input vector is fed by the ADD.
9253 if (N0->getOpcode() != ISD::ADD)
9254 return SDValue();
9255
9256 // The vector extract idx must constant zero because we only expect the final
9257 // result of the reduction is placed in lane 0.
Artyom Skrobov314ee042015-11-25 19:41:11 +00009258 if (!isNullConstant(N1))
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009259 return SDValue();
9260
9261 EVT VTy = N0.getValueType();
9262 if (!VTy.isVector())
9263 return SDValue();
9264
9265 EVT EltTy = VTy.getVectorElementType();
9266 if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8)
9267 return SDValue();
9268
Jun Bum Lim0aace132015-10-09 14:11:25 +00009269 if (VTy.getSizeInBits() < 64)
9270 return SDValue();
9271
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009272 return tryMatchAcrossLaneShuffleForReduction(N, N0, ISD::ADD, DAG);
Chad Rosier6c36eff2015-09-03 18:13:57 +00009273}
9274
Tim Northover3b0846e2014-05-24 12:50:23 +00009275/// Target-specific DAG combine function for NEON load/store intrinsics
9276/// to merge base address updates.
9277static SDValue performNEONPostLDSTCombine(SDNode *N,
9278 TargetLowering::DAGCombinerInfo &DCI,
9279 SelectionDAG &DAG) {
9280 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9281 return SDValue();
9282
9283 unsigned AddrOpIdx = N->getNumOperands() - 1;
9284 SDValue Addr = N->getOperand(AddrOpIdx);
9285
9286 // Search for a use of the address operand that is an increment.
9287 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9288 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9289 SDNode *User = *UI;
9290 if (User->getOpcode() != ISD::ADD ||
9291 UI.getUse().getResNo() != Addr.getResNo())
9292 continue;
9293
9294 // Check that the add is independent of the load/store. Otherwise, folding
9295 // it would create a cycle.
9296 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9297 continue;
9298
9299 // Find the new opcode for the updating load/store.
9300 bool IsStore = false;
9301 bool IsLaneOp = false;
9302 bool IsDupOp = false;
9303 unsigned NewOpc = 0;
9304 unsigned NumVecs = 0;
9305 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9306 switch (IntNo) {
9307 default: llvm_unreachable("unexpected intrinsic for Neon base update");
9308 case Intrinsic::aarch64_neon_ld2: NewOpc = AArch64ISD::LD2post;
9309 NumVecs = 2; break;
9310 case Intrinsic::aarch64_neon_ld3: NewOpc = AArch64ISD::LD3post;
9311 NumVecs = 3; break;
9312 case Intrinsic::aarch64_neon_ld4: NewOpc = AArch64ISD::LD4post;
9313 NumVecs = 4; break;
9314 case Intrinsic::aarch64_neon_st2: NewOpc = AArch64ISD::ST2post;
9315 NumVecs = 2; IsStore = true; break;
9316 case Intrinsic::aarch64_neon_st3: NewOpc = AArch64ISD::ST3post;
9317 NumVecs = 3; IsStore = true; break;
9318 case Intrinsic::aarch64_neon_st4: NewOpc = AArch64ISD::ST4post;
9319 NumVecs = 4; IsStore = true; break;
9320 case Intrinsic::aarch64_neon_ld1x2: NewOpc = AArch64ISD::LD1x2post;
9321 NumVecs = 2; break;
9322 case Intrinsic::aarch64_neon_ld1x3: NewOpc = AArch64ISD::LD1x3post;
9323 NumVecs = 3; break;
9324 case Intrinsic::aarch64_neon_ld1x4: NewOpc = AArch64ISD::LD1x4post;
9325 NumVecs = 4; break;
9326 case Intrinsic::aarch64_neon_st1x2: NewOpc = AArch64ISD::ST1x2post;
9327 NumVecs = 2; IsStore = true; break;
9328 case Intrinsic::aarch64_neon_st1x3: NewOpc = AArch64ISD::ST1x3post;
9329 NumVecs = 3; IsStore = true; break;
9330 case Intrinsic::aarch64_neon_st1x4: NewOpc = AArch64ISD::ST1x4post;
9331 NumVecs = 4; IsStore = true; break;
9332 case Intrinsic::aarch64_neon_ld2r: NewOpc = AArch64ISD::LD2DUPpost;
9333 NumVecs = 2; IsDupOp = true; break;
9334 case Intrinsic::aarch64_neon_ld3r: NewOpc = AArch64ISD::LD3DUPpost;
9335 NumVecs = 3; IsDupOp = true; break;
9336 case Intrinsic::aarch64_neon_ld4r: NewOpc = AArch64ISD::LD4DUPpost;
9337 NumVecs = 4; IsDupOp = true; break;
9338 case Intrinsic::aarch64_neon_ld2lane: NewOpc = AArch64ISD::LD2LANEpost;
9339 NumVecs = 2; IsLaneOp = true; break;
9340 case Intrinsic::aarch64_neon_ld3lane: NewOpc = AArch64ISD::LD3LANEpost;
9341 NumVecs = 3; IsLaneOp = true; break;
9342 case Intrinsic::aarch64_neon_ld4lane: NewOpc = AArch64ISD::LD4LANEpost;
9343 NumVecs = 4; IsLaneOp = true; break;
9344 case Intrinsic::aarch64_neon_st2lane: NewOpc = AArch64ISD::ST2LANEpost;
9345 NumVecs = 2; IsStore = true; IsLaneOp = true; break;
9346 case Intrinsic::aarch64_neon_st3lane: NewOpc = AArch64ISD::ST3LANEpost;
9347 NumVecs = 3; IsStore = true; IsLaneOp = true; break;
9348 case Intrinsic::aarch64_neon_st4lane: NewOpc = AArch64ISD::ST4LANEpost;
9349 NumVecs = 4; IsStore = true; IsLaneOp = true; break;
9350 }
9351
9352 EVT VecTy;
9353 if (IsStore)
9354 VecTy = N->getOperand(2).getValueType();
9355 else
9356 VecTy = N->getValueType(0);
9357
9358 // If the increment is a constant, it must match the memory ref size.
9359 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9360 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9361 uint32_t IncVal = CInc->getZExtValue();
9362 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9363 if (IsLaneOp || IsDupOp)
9364 NumBytes /= VecTy.getVectorNumElements();
9365 if (IncVal != NumBytes)
9366 continue;
9367 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
9368 }
9369 SmallVector<SDValue, 8> Ops;
9370 Ops.push_back(N->getOperand(0)); // Incoming chain
9371 // Load lane and store have vector list as input.
9372 if (IsLaneOp || IsStore)
9373 for (unsigned i = 2; i < AddrOpIdx; ++i)
9374 Ops.push_back(N->getOperand(i));
9375 Ops.push_back(Addr); // Base register
9376 Ops.push_back(Inc);
9377
9378 // Return Types.
9379 EVT Tys[6];
9380 unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
9381 unsigned n;
9382 for (n = 0; n < NumResultVecs; ++n)
9383 Tys[n] = VecTy;
9384 Tys[n++] = MVT::i64; // Type of write back register
9385 Tys[n] = MVT::Other; // Type of the chain
Craig Toppere1d12942014-08-27 05:25:25 +00009386 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
Tim Northover3b0846e2014-05-24 12:50:23 +00009387
9388 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9389 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
9390 MemInt->getMemoryVT(),
9391 MemInt->getMemOperand());
9392
9393 // Update the uses.
9394 std::vector<SDValue> NewResults;
9395 for (unsigned i = 0; i < NumResultVecs; ++i) {
9396 NewResults.push_back(SDValue(UpdN.getNode(), i));
9397 }
9398 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
9399 DCI.CombineTo(N, NewResults);
9400 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9401
9402 break;
9403 }
9404 return SDValue();
9405}
9406
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009407// Checks to see if the value is the prescribed width and returns information
9408// about its extension mode.
9409static
9410bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
9411 ExtType = ISD::NON_EXTLOAD;
9412 switch(V.getNode()->getOpcode()) {
9413 default:
9414 return false;
9415 case ISD::LOAD: {
9416 LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
9417 if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
9418 || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
9419 ExtType = LoadNode->getExtensionType();
9420 return true;
9421 }
9422 return false;
9423 }
9424 case ISD::AssertSext: {
9425 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9426 if ((TypeNode->getVT() == MVT::i8 && width == 8)
9427 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9428 ExtType = ISD::SEXTLOAD;
9429 return true;
9430 }
9431 return false;
9432 }
9433 case ISD::AssertZext: {
9434 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9435 if ((TypeNode->getVT() == MVT::i8 && width == 8)
9436 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9437 ExtType = ISD::ZEXTLOAD;
9438 return true;
9439 }
9440 return false;
9441 }
9442 case ISD::Constant:
9443 case ISD::TargetConstant: {
Eric Christopher114fa1c2016-02-29 22:50:49 +00009444 return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
9445 1LL << (width - 1);
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009446 }
9447 }
9448
9449 return true;
9450}
9451
9452// This function does a whole lot of voodoo to determine if the tests are
9453// equivalent without and with a mask. Essentially what happens is that given a
9454// DAG resembling:
9455//
9456// +-------------+ +-------------+ +-------------+ +-------------+
9457// | Input | | AddConstant | | CompConstant| | CC |
9458// +-------------+ +-------------+ +-------------+ +-------------+
9459// | | | |
9460// V V | +----------+
9461// +-------------+ +----+ | |
9462// | ADD | |0xff| | |
9463// +-------------+ +----+ | |
9464// | | | |
9465// V V | |
9466// +-------------+ | |
9467// | AND | | |
9468// +-------------+ | |
9469// | | |
9470// +-----+ | |
9471// | | |
9472// V V V
9473// +-------------+
9474// | CMP |
9475// +-------------+
9476//
9477// The AND node may be safely removed for some combinations of inputs. In
9478// particular we need to take into account the extension type of the Input,
9479// the exact values of AddConstant, CompConstant, and CC, along with the nominal
9480// width of the input (this can work for any width inputs, the above graph is
9481// specific to 8 bits.
9482//
9483// The specific equations were worked out by generating output tables for each
9484// AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
9485// problem was simplified by working with 4 bit inputs, which means we only
9486// needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
9487// extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
9488// patterns present in both extensions (0,7). For every distinct set of
9489// AddConstant and CompConstants bit patterns we can consider the masked and
9490// unmasked versions to be equivalent if the result of this function is true for
9491// all 16 distinct bit patterns of for the current extension type of Input (w0).
9492//
9493// sub w8, w0, w1
9494// and w10, w8, #0x0f
9495// cmp w8, w2
9496// cset w9, AArch64CC
9497// cmp w10, w2
9498// cset w11, AArch64CC
9499// cmp w9, w11
9500// cset w0, eq
9501// ret
9502//
9503// Since the above function shows when the outputs are equivalent it defines
9504// when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
9505// would be expensive to run during compiles. The equations below were written
9506// in a test harness that confirmed they gave equivalent outputs to the above
9507// for all inputs function, so they can be used determine if the removal is
9508// legal instead.
9509//
9510// isEquivalentMaskless() is the code for testing if the AND can be removed
9511// factored out of the DAG recognition as the DAG can take several forms.
9512
David Majnemere61e4bf2016-06-21 05:10:24 +00009513static bool isEquivalentMaskless(unsigned CC, unsigned width,
9514 ISD::LoadExtType ExtType, int AddConstant,
9515 int CompConstant) {
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009516 // By being careful about our equations and only writing the in term
9517 // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
9518 // make them generally applicable to all bit widths.
David Majnemere61e4bf2016-06-21 05:10:24 +00009519 int MaxUInt = (1 << width);
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009520
9521 // For the purposes of these comparisons sign extending the type is
9522 // equivalent to zero extending the add and displacing it by half the integer
9523 // width. Provided we are careful and make sure our equations are valid over
9524 // the whole range we can just adjust the input and avoid writing equations
9525 // for sign extended inputs.
9526 if (ExtType == ISD::SEXTLOAD)
9527 AddConstant -= (1 << (width-1));
9528
9529 switch(CC) {
9530 case AArch64CC::LE:
9531 case AArch64CC::GT: {
9532 if ((AddConstant == 0) ||
9533 (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
9534 (AddConstant >= 0 && CompConstant < 0) ||
9535 (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
9536 return true;
9537 } break;
9538 case AArch64CC::LT:
9539 case AArch64CC::GE: {
9540 if ((AddConstant == 0) ||
9541 (AddConstant >= 0 && CompConstant <= 0) ||
9542 (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
9543 return true;
9544 } break;
9545 case AArch64CC::HI:
9546 case AArch64CC::LS: {
9547 if ((AddConstant >= 0 && CompConstant < 0) ||
9548 (AddConstant <= 0 && CompConstant >= -1 &&
9549 CompConstant < AddConstant + MaxUInt))
9550 return true;
9551 } break;
9552 case AArch64CC::PL:
9553 case AArch64CC::MI: {
9554 if ((AddConstant == 0) ||
9555 (AddConstant > 0 && CompConstant <= 0) ||
9556 (AddConstant < 0 && CompConstant <= AddConstant))
9557 return true;
9558 } break;
9559 case AArch64CC::LO:
9560 case AArch64CC::HS: {
9561 if ((AddConstant >= 0 && CompConstant <= 0) ||
9562 (AddConstant <= 0 && CompConstant >= 0 &&
9563 CompConstant <= AddConstant + MaxUInt))
9564 return true;
9565 } break;
9566 case AArch64CC::EQ:
9567 case AArch64CC::NE: {
9568 if ((AddConstant > 0 && CompConstant < 0) ||
9569 (AddConstant < 0 && CompConstant >= 0 &&
9570 CompConstant < AddConstant + MaxUInt) ||
9571 (AddConstant >= 0 && CompConstant >= 0 &&
9572 CompConstant >= AddConstant) ||
9573 (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
9574
9575 return true;
9576 } break;
9577 case AArch64CC::VS:
9578 case AArch64CC::VC:
9579 case AArch64CC::AL:
9580 case AArch64CC::NV:
9581 return true;
9582 case AArch64CC::Invalid:
9583 break;
9584 }
9585
9586 return false;
9587}
9588
9589static
9590SDValue performCONDCombine(SDNode *N,
9591 TargetLowering::DAGCombinerInfo &DCI,
9592 SelectionDAG &DAG, unsigned CCIndex,
9593 unsigned CmpIndex) {
9594 unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
9595 SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
9596 unsigned CondOpcode = SubsNode->getOpcode();
9597
9598 if (CondOpcode != AArch64ISD::SUBS)
9599 return SDValue();
9600
9601 // There is a SUBS feeding this condition. Is it fed by a mask we can
9602 // use?
9603
9604 SDNode *AndNode = SubsNode->getOperand(0).getNode();
9605 unsigned MaskBits = 0;
9606
9607 if (AndNode->getOpcode() != ISD::AND)
9608 return SDValue();
9609
9610 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
9611 uint32_t CNV = CN->getZExtValue();
9612 if (CNV == 255)
9613 MaskBits = 8;
9614 else if (CNV == 65535)
9615 MaskBits = 16;
9616 }
9617
9618 if (!MaskBits)
9619 return SDValue();
9620
9621 SDValue AddValue = AndNode->getOperand(0);
9622
9623 if (AddValue.getOpcode() != ISD::ADD)
9624 return SDValue();
9625
9626 // The basic dag structure is correct, grab the inputs and validate them.
9627
9628 SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
9629 SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
9630 SDValue SubsInputValue = SubsNode->getOperand(1);
9631
9632 // The mask is present and the provenance of all the values is a smaller type,
9633 // lets see if the mask is superfluous.
9634
9635 if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
9636 !isa<ConstantSDNode>(SubsInputValue.getNode()))
9637 return SDValue();
9638
9639 ISD::LoadExtType ExtType;
9640
9641 if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
9642 !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
9643 !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
9644 return SDValue();
9645
9646 if(!isEquivalentMaskless(CC, MaskBits, ExtType,
9647 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
9648 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
9649 return SDValue();
9650
9651 // The AND is not necessary, remove it.
9652
9653 SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
9654 SubsNode->getValueType(1));
9655 SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
9656
9657 SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
9658 DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
9659
9660 return SDValue(N, 0);
9661}
9662
Tim Northover3b0846e2014-05-24 12:50:23 +00009663// Optimize compare with zero and branch.
9664static SDValue performBRCONDCombine(SDNode *N,
9665 TargetLowering::DAGCombinerInfo &DCI,
9666 SelectionDAG &DAG) {
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00009667 if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3))
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009668 N = NV.getNode();
Tim Northover3b0846e2014-05-24 12:50:23 +00009669 SDValue Chain = N->getOperand(0);
9670 SDValue Dest = N->getOperand(1);
9671 SDValue CCVal = N->getOperand(2);
9672 SDValue Cmp = N->getOperand(3);
9673
9674 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
9675 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
9676 if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
9677 return SDValue();
9678
9679 unsigned CmpOpc = Cmp.getOpcode();
9680 if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
9681 return SDValue();
9682
9683 // Only attempt folding if there is only one use of the flag and no use of the
9684 // value.
9685 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
9686 return SDValue();
9687
9688 SDValue LHS = Cmp.getOperand(0);
9689 SDValue RHS = Cmp.getOperand(1);
9690
9691 assert(LHS.getValueType() == RHS.getValueType() &&
9692 "Expected the value type to be the same for both operands!");
9693 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
9694 return SDValue();
9695
Artyom Skrobov314ee042015-11-25 19:41:11 +00009696 if (isNullConstant(LHS))
Tim Northover3b0846e2014-05-24 12:50:23 +00009697 std::swap(LHS, RHS);
9698
Artyom Skrobov314ee042015-11-25 19:41:11 +00009699 if (!isNullConstant(RHS))
Tim Northover3b0846e2014-05-24 12:50:23 +00009700 return SDValue();
9701
9702 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
9703 LHS.getOpcode() == ISD::SRL)
9704 return SDValue();
9705
9706 // Fold the compare into the branch instruction.
9707 SDValue BR;
9708 if (CC == AArch64CC::EQ)
9709 BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9710 else
9711 BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9712
9713 // Do not add new nodes to DAG combiner worklist.
9714 DCI.CombineTo(N, BR, false);
9715
9716 return SDValue();
9717}
9718
Geoff Berry9e934b02016-01-04 18:55:47 +00009719// Optimize some simple tbz/tbnz cases. Returns the new operand and bit to test
9720// as well as whether the test should be inverted. This code is required to
9721// catch these cases (as opposed to standard dag combines) because
9722// AArch64ISD::TBZ is matched during legalization.
9723static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert,
9724 SelectionDAG &DAG) {
9725
9726 if (!Op->hasOneUse())
9727 return Op;
9728
9729 // We don't handle undef/constant-fold cases below, as they should have
9730 // already been taken care of (e.g. and of 0, test of undefined shifted bits,
9731 // etc.)
9732
9733 // (tbz (trunc x), b) -> (tbz x, b)
9734 // This case is just here to enable more of the below cases to be caught.
9735 if (Op->getOpcode() == ISD::TRUNCATE &&
9736 Bit < Op->getValueType(0).getSizeInBits()) {
9737 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9738 }
9739
9740 if (Op->getNumOperands() != 2)
9741 return Op;
9742
9743 auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
9744 if (!C)
9745 return Op;
9746
9747 switch (Op->getOpcode()) {
9748 default:
9749 return Op;
9750
9751 // (tbz (and x, m), b) -> (tbz x, b)
9752 case ISD::AND:
9753 if ((C->getZExtValue() >> Bit) & 1)
9754 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9755 return Op;
9756
9757 // (tbz (shl x, c), b) -> (tbz x, b-c)
9758 case ISD::SHL:
9759 if (C->getZExtValue() <= Bit &&
9760 (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
9761 Bit = Bit - C->getZExtValue();
9762 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9763 }
9764 return Op;
9765
9766 // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
9767 case ISD::SRA:
9768 Bit = Bit + C->getZExtValue();
9769 if (Bit >= Op->getValueType(0).getSizeInBits())
9770 Bit = Op->getValueType(0).getSizeInBits() - 1;
9771 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9772
9773 // (tbz (srl x, c), b) -> (tbz x, b+c)
9774 case ISD::SRL:
9775 if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
9776 Bit = Bit + C->getZExtValue();
9777 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9778 }
9779 return Op;
9780
9781 // (tbz (xor x, -1), b) -> (tbnz x, b)
9782 case ISD::XOR:
9783 if ((C->getZExtValue() >> Bit) & 1)
9784 Invert = !Invert;
9785 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9786 }
9787}
9788
9789// Optimize test single bit zero/non-zero and branch.
9790static SDValue performTBZCombine(SDNode *N,
9791 TargetLowering::DAGCombinerInfo &DCI,
9792 SelectionDAG &DAG) {
9793 unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
9794 bool Invert = false;
9795 SDValue TestSrc = N->getOperand(1);
9796 SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG);
9797
9798 if (TestSrc == NewTestSrc)
9799 return SDValue();
9800
9801 unsigned NewOpc = N->getOpcode();
9802 if (Invert) {
9803 if (NewOpc == AArch64ISD::TBZ)
9804 NewOpc = AArch64ISD::TBNZ;
9805 else {
9806 assert(NewOpc == AArch64ISD::TBNZ);
9807 NewOpc = AArch64ISD::TBZ;
9808 }
9809 }
9810
9811 SDLoc DL(N);
9812 return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc,
9813 DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3));
9814}
9815
Tim Northover3b0846e2014-05-24 12:50:23 +00009816// vselect (v1i1 setcc) ->
9817// vselect (v1iXX setcc) (XX is the size of the compared operand type)
9818// FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
9819// condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
9820// such VSELECT.
9821static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
9822 SDValue N0 = N->getOperand(0);
9823 EVT CCVT = N0.getValueType();
9824
9825 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
9826 CCVT.getVectorElementType() != MVT::i1)
9827 return SDValue();
9828
9829 EVT ResVT = N->getValueType(0);
9830 EVT CmpVT = N0.getOperand(0).getValueType();
9831 // Only combine when the result type is of the same size as the compared
9832 // operands.
9833 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
9834 return SDValue();
9835
9836 SDValue IfTrue = N->getOperand(1);
9837 SDValue IfFalse = N->getOperand(2);
9838 SDValue SetCC =
9839 DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
9840 N0.getOperand(0), N0.getOperand(1),
9841 cast<CondCodeSDNode>(N0.getOperand(2))->get());
9842 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
9843 IfTrue, IfFalse);
9844}
9845
9846/// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
9847/// the compare-mask instructions rather than going via NZCV, even if LHS and
9848/// RHS are really scalar. This replaces any scalar setcc in the above pattern
9849/// with a vector one followed by a DUP shuffle on the result.
Ahmed Bougachac004c602015-04-27 21:43:12 +00009850static SDValue performSelectCombine(SDNode *N,
9851 TargetLowering::DAGCombinerInfo &DCI) {
9852 SelectionDAG &DAG = DCI.DAG;
Tim Northover3b0846e2014-05-24 12:50:23 +00009853 SDValue N0 = N->getOperand(0);
9854 EVT ResVT = N->getValueType(0);
Tim Northover3c0915e2014-08-29 15:34:58 +00009855
Ahmed Bougachac004c602015-04-27 21:43:12 +00009856 if (N0.getOpcode() != ISD::SETCC)
Tim Northover3c0915e2014-08-29 15:34:58 +00009857 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00009858
Ahmed Bougachac004c602015-04-27 21:43:12 +00009859 // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
9860 // scalar SetCCResultType. We also don't expect vectors, because we assume
9861 // that selects fed by vector SETCCs are canonicalized to VSELECT.
9862 assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
9863 "Scalar-SETCC feeding SELECT has unexpected result type!");
9864
Tim Northoverc1c05ae2014-08-29 13:05:18 +00009865 // If NumMaskElts == 0, the comparison is larger than select result. The
9866 // largest real NEON comparison is 64-bits per lane, which means the result is
9867 // at most 32-bits and an illegal vector. Just bail out for now.
Tim Northover3c0915e2014-08-29 15:34:58 +00009868 EVT SrcVT = N0.getOperand(0).getValueType();
Ahmed Bougachad0ce0582014-12-01 20:59:00 +00009869
9870 // Don't try to do this optimization when the setcc itself has i1 operands.
9871 // There are no legal vectors of i1, so this would be pointless.
9872 if (SrcVT == MVT::i1)
9873 return SDValue();
9874
Tim Northover3c0915e2014-08-29 15:34:58 +00009875 int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
Tim Northoverc1c05ae2014-08-29 13:05:18 +00009876 if (!ResVT.isVector() || NumMaskElts == 0)
Tim Northover3b0846e2014-05-24 12:50:23 +00009877 return SDValue();
9878
Tim Northoverc1c05ae2014-08-29 13:05:18 +00009879 SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
Tim Northover3b0846e2014-05-24 12:50:23 +00009880 EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
9881
Ahmed Bougacha89bba612015-04-27 21:01:20 +00009882 // Also bail out if the vector CCVT isn't the same size as ResVT.
9883 // This can happen if the SETCC operand size doesn't divide the ResVT size
9884 // (e.g., f64 vs v3f32).
9885 if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
9886 return SDValue();
9887
Ahmed Bougachac004c602015-04-27 21:43:12 +00009888 // Make sure we didn't create illegal types, if we're not supposed to.
9889 assert(DCI.isBeforeLegalize() ||
9890 DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
9891
Tim Northover3b0846e2014-05-24 12:50:23 +00009892 // First perform a vector comparison, where lane 0 is the one we're interested
9893 // in.
Tim Northoverc1c05ae2014-08-29 13:05:18 +00009894 SDLoc DL(N0);
Tim Northover3b0846e2014-05-24 12:50:23 +00009895 SDValue LHS =
9896 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
9897 SDValue RHS =
9898 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
9899 SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
9900
9901 // Now duplicate the comparison mask we want across all other lanes.
9902 SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
Craig Topper2bd8b4b2016-07-01 06:54:47 +00009903 SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask);
Tim Northoverc1c05ae2014-08-29 13:05:18 +00009904 Mask = DAG.getNode(ISD::BITCAST, DL,
9905 ResVT.changeVectorElementTypeToInteger(), Mask);
Tim Northover3b0846e2014-05-24 12:50:23 +00009906
9907 return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
9908}
9909
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009910/// Get rid of unnecessary NVCASTs (that don't change the type).
9911static SDValue performNVCASTCombine(SDNode *N) {
9912 if (N->getValueType(0) == N->getOperand(0).getValueType())
9913 return N->getOperand(0);
9914
9915 return SDValue();
9916}
9917
Tim Northover3b0846e2014-05-24 12:50:23 +00009918SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
9919 DAGCombinerInfo &DCI) const {
9920 SelectionDAG &DAG = DCI.DAG;
9921 switch (N->getOpcode()) {
9922 default:
9923 break;
9924 case ISD::ADD:
9925 case ISD::SUB:
9926 return performAddSubLongCombine(N, DCI, DAG);
9927 case ISD::XOR:
9928 return performXorCombine(N, DAG, DCI, Subtarget);
9929 case ISD::MUL:
9930 return performMulCombine(N, DAG, DCI, Subtarget);
9931 case ISD::SINT_TO_FP:
9932 case ISD::UINT_TO_FP:
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00009933 return performIntToFpCombine(N, DAG, Subtarget);
Chad Rosierfa30c9b2015-10-07 17:39:18 +00009934 case ISD::FP_TO_SINT:
9935 case ISD::FP_TO_UINT:
Silviu Barangafa00ba32016-08-08 13:13:57 +00009936 return performFpToIntCombine(N, DAG, DCI, Subtarget);
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00009937 case ISD::FDIV:
Tim Northover85cf5642016-08-26 18:52:31 +00009938 return performFDivCombine(N, DAG, DCI, Subtarget);
Tim Northover3b0846e2014-05-24 12:50:23 +00009939 case ISD::OR:
9940 return performORCombine(N, DCI, Subtarget);
Chad Rosier14aa2ad2016-05-26 19:41:33 +00009941 case ISD::SRL:
9942 return performSRLCombine(N, DCI);
Tim Northover3b0846e2014-05-24 12:50:23 +00009943 case ISD::INTRINSIC_WO_CHAIN:
9944 return performIntrinsicCombine(N, DCI, Subtarget);
9945 case ISD::ANY_EXTEND:
9946 case ISD::ZERO_EXTEND:
9947 case ISD::SIGN_EXTEND:
9948 return performExtendCombine(N, DCI, DAG);
9949 case ISD::BITCAST:
9950 return performBitcastCombine(N, DCI, DAG);
9951 case ISD::CONCAT_VECTORS:
9952 return performConcatVectorsCombine(N, DCI, DAG);
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009953 case ISD::SELECT: {
9954 SDValue RV = performSelectCombine(N, DCI);
9955 if (!RV.getNode())
9956 RV = performAcrossLaneMinMaxReductionCombine(N, DAG, Subtarget);
9957 return RV;
9958 }
Tim Northover3b0846e2014-05-24 12:50:23 +00009959 case ISD::VSELECT:
9960 return performVSelectCombine(N, DCI.DAG);
Tim Northover339c83e2015-11-10 00:44:23 +00009961 case ISD::LOAD:
9962 if (performTBISimplification(N->getOperand(1), DCI, DAG))
9963 return SDValue(N, 0);
9964 break;
Tim Northover3b0846e2014-05-24 12:50:23 +00009965 case ISD::STORE:
9966 return performSTORECombine(N, DCI, DAG, Subtarget);
9967 case AArch64ISD::BRCOND:
9968 return performBRCONDCombine(N, DCI, DAG);
Geoff Berry9e934b02016-01-04 18:55:47 +00009969 case AArch64ISD::TBNZ:
9970 case AArch64ISD::TBZ:
9971 return performTBZCombine(N, DCI, DAG);
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009972 case AArch64ISD::CSEL:
9973 return performCONDCombine(N, DCI, DAG, 2, 3);
Tim Northover3b0846e2014-05-24 12:50:23 +00009974 case AArch64ISD::DUP:
9975 return performPostLD1Combine(N, DCI, false);
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009976 case AArch64ISD::NVCAST:
9977 return performNVCASTCombine(N);
Tim Northover3b0846e2014-05-24 12:50:23 +00009978 case ISD::INSERT_VECTOR_ELT:
9979 return performPostLD1Combine(N, DCI, true);
Chad Rosier6c36eff2015-09-03 18:13:57 +00009980 case ISD::EXTRACT_VECTOR_ELT:
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009981 return performAcrossLaneAddReductionCombine(N, DAG, Subtarget);
Tim Northover3b0846e2014-05-24 12:50:23 +00009982 case ISD::INTRINSIC_VOID:
9983 case ISD::INTRINSIC_W_CHAIN:
9984 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9985 case Intrinsic::aarch64_neon_ld2:
9986 case Intrinsic::aarch64_neon_ld3:
9987 case Intrinsic::aarch64_neon_ld4:
9988 case Intrinsic::aarch64_neon_ld1x2:
9989 case Intrinsic::aarch64_neon_ld1x3:
9990 case Intrinsic::aarch64_neon_ld1x4:
9991 case Intrinsic::aarch64_neon_ld2lane:
9992 case Intrinsic::aarch64_neon_ld3lane:
9993 case Intrinsic::aarch64_neon_ld4lane:
9994 case Intrinsic::aarch64_neon_ld2r:
9995 case Intrinsic::aarch64_neon_ld3r:
9996 case Intrinsic::aarch64_neon_ld4r:
9997 case Intrinsic::aarch64_neon_st2:
9998 case Intrinsic::aarch64_neon_st3:
9999 case Intrinsic::aarch64_neon_st4:
10000 case Intrinsic::aarch64_neon_st1x2:
10001 case Intrinsic::aarch64_neon_st1x3:
10002 case Intrinsic::aarch64_neon_st1x4:
10003 case Intrinsic::aarch64_neon_st2lane:
10004 case Intrinsic::aarch64_neon_st3lane:
10005 case Intrinsic::aarch64_neon_st4lane:
10006 return performNEONPostLDSTCombine(N, DCI, DAG);
10007 default:
10008 break;
10009 }
10010 }
10011 return SDValue();
10012}
10013
10014// Check if the return value is used as only a return value, as otherwise
10015// we can't perform a tail-call. In particular, we need to check for
10016// target ISD nodes that are returns and any other "odd" constructs
10017// that the generic analysis code won't necessarily catch.
10018bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
10019 SDValue &Chain) const {
10020 if (N->getNumValues() != 1)
10021 return false;
10022 if (!N->hasNUsesOfValue(1, 0))
10023 return false;
10024
10025 SDValue TCChain = Chain;
10026 SDNode *Copy = *N->use_begin();
10027 if (Copy->getOpcode() == ISD::CopyToReg) {
10028 // If the copy has a glue operand, we conservatively assume it isn't safe to
10029 // perform a tail call.
10030 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
10031 MVT::Glue)
10032 return false;
10033 TCChain = Copy->getOperand(0);
10034 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
10035 return false;
10036
10037 bool HasRet = false;
10038 for (SDNode *Node : Copy->uses()) {
10039 if (Node->getOpcode() != AArch64ISD::RET_FLAG)
10040 return false;
10041 HasRet = true;
10042 }
10043
10044 if (!HasRet)
10045 return false;
10046
10047 Chain = TCChain;
10048 return true;
10049}
10050
10051// Return whether the an instruction can potentially be optimized to a tail
10052// call. This will cause the optimizers to attempt to move, or duplicate,
10053// return instructions to help enable tail call optimizations for this
10054// instruction.
10055bool AArch64TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
Eric Christopher114fa1c2016-02-29 22:50:49 +000010056 return CI->isTailCall();
Tim Northover3b0846e2014-05-24 12:50:23 +000010057}
10058
10059bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
10060 SDValue &Offset,
10061 ISD::MemIndexedMode &AM,
10062 bool &IsInc,
10063 SelectionDAG &DAG) const {
10064 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
10065 return false;
10066
10067 Base = Op->getOperand(0);
10068 // All of the indexed addressing mode instructions take a signed
10069 // 9 bit immediate offset.
10070 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
10071 int64_t RHSC = (int64_t)RHS->getZExtValue();
10072 if (RHSC >= 256 || RHSC <= -256)
10073 return false;
10074 IsInc = (Op->getOpcode() == ISD::ADD);
10075 Offset = Op->getOperand(1);
10076 return true;
10077 }
10078 return false;
10079}
10080
10081bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10082 SDValue &Offset,
10083 ISD::MemIndexedMode &AM,
10084 SelectionDAG &DAG) const {
10085 EVT VT;
10086 SDValue Ptr;
10087 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10088 VT = LD->getMemoryVT();
10089 Ptr = LD->getBasePtr();
10090 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10091 VT = ST->getMemoryVT();
10092 Ptr = ST->getBasePtr();
10093 } else
10094 return false;
10095
10096 bool IsInc;
10097 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
10098 return false;
10099 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
10100 return true;
10101}
10102
10103bool AArch64TargetLowering::getPostIndexedAddressParts(
10104 SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
10105 ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
10106 EVT VT;
10107 SDValue Ptr;
10108 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10109 VT = LD->getMemoryVT();
10110 Ptr = LD->getBasePtr();
10111 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10112 VT = ST->getMemoryVT();
10113 Ptr = ST->getBasePtr();
10114 } else
10115 return false;
10116
10117 bool IsInc;
10118 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
10119 return false;
10120 // Post-indexing updates the base, so it's not a valid transform
10121 // if that's not the same as the load's pointer.
10122 if (Ptr != Base)
10123 return false;
10124 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
10125 return true;
10126}
10127
Tim Northoverf8bfe212014-07-18 13:07:05 +000010128static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
10129 SelectionDAG &DAG) {
Tim Northoverf8bfe212014-07-18 13:07:05 +000010130 SDLoc DL(N);
10131 SDValue Op = N->getOperand(0);
Ahmed Bougacha87946322014-12-01 20:52:32 +000010132
10133 if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
10134 return;
10135
Tim Northoverf8bfe212014-07-18 13:07:05 +000010136 Op = SDValue(
10137 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
10138 DAG.getUNDEF(MVT::i32), Op,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010139 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
Tim Northoverf8bfe212014-07-18 13:07:05 +000010140 0);
10141 Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
10142 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
10143}
10144
Charlie Turner434d4592015-10-16 15:38:25 +000010145static void ReplaceReductionResults(SDNode *N,
10146 SmallVectorImpl<SDValue> &Results,
10147 SelectionDAG &DAG, unsigned InterOp,
10148 unsigned AcrossOp) {
10149 EVT LoVT, HiVT;
10150 SDValue Lo, Hi;
10151 SDLoc dl(N);
10152 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
10153 std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
10154 SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
10155 SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
10156 Results.push_back(SplitVal);
10157}
10158
Tim Northover2f32e7f2016-08-04 19:32:28 +000010159static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) {
10160 SDLoc DL(N);
10161 SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N);
10162 SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64,
10163 DAG.getNode(ISD::SRL, DL, MVT::i128, N,
10164 DAG.getConstant(64, DL, MVT::i64)));
10165 return std::make_pair(Lo, Hi);
10166}
10167
Tim Northovercdf15292016-04-14 17:03:29 +000010168static void ReplaceCMP_SWAP_128Results(SDNode *N,
10169 SmallVectorImpl<SDValue> & Results,
10170 SelectionDAG &DAG) {
10171 assert(N->getValueType(0) == MVT::i128 &&
10172 "AtomicCmpSwap on types less than 128 should be legal");
Tim Northover2f32e7f2016-08-04 19:32:28 +000010173 auto Desired = splitInt128(N->getOperand(2), DAG);
10174 auto New = splitInt128(N->getOperand(3), DAG);
10175 SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second,
10176 New.first, New.second, N->getOperand(0)};
Tim Northovercdf15292016-04-14 17:03:29 +000010177 SDNode *CmpSwap = DAG.getMachineNode(
10178 AArch64::CMP_SWAP_128, SDLoc(N),
10179 DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops);
10180
10181 MachineFunction &MF = DAG.getMachineFunction();
10182 MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1);
10183 MemOp[0] = cast<MemSDNode>(N)->getMemOperand();
10184 cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1);
10185
10186 Results.push_back(SDValue(CmpSwap, 0));
10187 Results.push_back(SDValue(CmpSwap, 1));
10188 Results.push_back(SDValue(CmpSwap, 3));
10189}
10190
Tim Northover3b0846e2014-05-24 12:50:23 +000010191void AArch64TargetLowering::ReplaceNodeResults(
10192 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
10193 switch (N->getOpcode()) {
10194 default:
10195 llvm_unreachable("Don't know how to custom expand this");
Tim Northoverf8bfe212014-07-18 13:07:05 +000010196 case ISD::BITCAST:
10197 ReplaceBITCASTResults(N, Results, DAG);
10198 return;
Charlie Turner434d4592015-10-16 15:38:25 +000010199 case AArch64ISD::SADDV:
10200 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
10201 return;
10202 case AArch64ISD::UADDV:
10203 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
10204 return;
10205 case AArch64ISD::SMINV:
10206 ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
10207 return;
10208 case AArch64ISD::UMINV:
10209 ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
10210 return;
10211 case AArch64ISD::SMAXV:
10212 ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
10213 return;
10214 case AArch64ISD::UMAXV:
10215 ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
10216 return;
Tim Northover3b0846e2014-05-24 12:50:23 +000010217 case ISD::FP_TO_UINT:
10218 case ISD::FP_TO_SINT:
10219 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
10220 // Let normal code take care of it by not adding anything to Results.
10221 return;
Tim Northovercdf15292016-04-14 17:03:29 +000010222 case ISD::ATOMIC_CMP_SWAP:
10223 ReplaceCMP_SWAP_128Results(N, Results, DAG);
10224 return;
Tim Northover3b0846e2014-05-24 12:50:23 +000010225 }
10226}
10227
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +000010228bool AArch64TargetLowering::useLoadStackGuardNode() const {
Tim Shene885d5e2016-04-19 19:40:37 +000010229 if (!Subtarget->isTargetAndroid())
10230 return true;
10231 return TargetLowering::useLoadStackGuardNode();
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +000010232}
10233
Sanjay Patel1dd15592015-07-28 23:05:48 +000010234unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
Hao Liu44e5d7a2014-11-21 06:39:58 +000010235 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
10236 // reciprocal if there are three or more FDIVs.
Sanjay Patel1dd15592015-07-28 23:05:48 +000010237 return 3;
Hao Liu44e5d7a2014-11-21 06:39:58 +000010238}
10239
Chandler Carruth9d010ff2014-07-03 00:23:43 +000010240TargetLoweringBase::LegalizeTypeAction
10241AArch64TargetLowering::getPreferredVectorAction(EVT VT) const {
10242 MVT SVT = VT.getSimpleVT();
10243 // During type legalization, we prefer to widen v1i8, v1i16, v1i32 to v8i8,
10244 // v4i16, v2i32 instead of to promote.
10245 if (SVT == MVT::v1i8 || SVT == MVT::v1i16 || SVT == MVT::v1i32
10246 || SVT == MVT::v1f32)
10247 return TypeWidenVector;
10248
10249 return TargetLoweringBase::getPreferredVectorAction(VT);
10250}
10251
Robin Morisseted3d48f2014-09-03 21:29:59 +000010252// Loads and stores less than 128-bits are already atomic; ones above that
10253// are doomed anyway, so defer to the default libcall and blame the OS when
10254// things go wrong.
10255bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
10256 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
10257 return Size == 128;
10258}
10259
10260// Loads and stores less than 128-bits are already atomic; ones above that
10261// are doomed anyway, so defer to the default libcall and blame the OS when
10262// things go wrong.
Ahmed Bougacha52468672015-09-11 17:08:28 +000010263TargetLowering::AtomicExpansionKind
10264AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
Robin Morisseted3d48f2014-09-03 21:29:59 +000010265 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
Ahmed Bougacha52468672015-09-11 17:08:28 +000010266 return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
Robin Morisseted3d48f2014-09-03 21:29:59 +000010267}
10268
10269// For the real atomic operations, we have ldxr/stxr up to 128 bits,
Ahmed Bougacha52468672015-09-11 17:08:28 +000010270TargetLowering::AtomicExpansionKind
JF Bastienf14889e2015-03-04 15:47:57 +000010271AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
Robin Morisseted3d48f2014-09-03 21:29:59 +000010272 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
Ahmed Bougacha9d677132015-09-11 17:08:17 +000010273 return Size <= 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
Robin Morisseted3d48f2014-09-03 21:29:59 +000010274}
10275
Ahmed Bougacha52468672015-09-11 17:08:28 +000010276bool AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
10277 AtomicCmpXchgInst *AI) const {
Tim Northovercdf15292016-04-14 17:03:29 +000010278 // At -O0, fast-regalloc cannot cope with the live vregs necessary to
10279 // implement cmpxchg without spilling. If the address being exchanged is also
10280 // on the stack and close enough to the spill slot, this can lead to a
10281 // situation where the monitor always gets cleared and the atomic operation
10282 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
10283 return getTargetMachine().getOptLevel() != 0;
Robin Morisset25c8e312014-09-17 00:06:58 +000010284}
10285
Tim Northover3b0846e2014-05-24 12:50:23 +000010286Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
10287 AtomicOrdering Ord) const {
10288 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10289 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
JF Bastien800f87a2016-04-06 21:19:33 +000010290 bool IsAcquire = isAcquireOrStronger(Ord);
Tim Northover3b0846e2014-05-24 12:50:23 +000010291
10292 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
10293 // intrinsic must return {i64, i64} and we have to recombine them into a
10294 // single i128 here.
10295 if (ValTy->getPrimitiveSizeInBits() == 128) {
10296 Intrinsic::ID Int =
10297 IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
10298 Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int);
10299
10300 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10301 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
10302
10303 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
10304 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
10305 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
10306 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
10307 return Builder.CreateOr(
10308 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
10309 }
10310
10311 Type *Tys[] = { Addr->getType() };
10312 Intrinsic::ID Int =
10313 IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
10314 Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int, Tys);
10315
10316 return Builder.CreateTruncOrBitCast(
10317 Builder.CreateCall(Ldxr, Addr),
10318 cast<PointerType>(Addr->getType())->getElementType());
10319}
10320
Ahmed Bougacha07a844d2015-09-22 17:21:44 +000010321void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
10322 IRBuilder<> &Builder) const {
10323 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10324 Builder.CreateCall(
10325 llvm::Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
10326}
10327
Tim Northover3b0846e2014-05-24 12:50:23 +000010328Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
10329 Value *Val, Value *Addr,
10330 AtomicOrdering Ord) const {
10331 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
JF Bastien800f87a2016-04-06 21:19:33 +000010332 bool IsRelease = isReleaseOrStronger(Ord);
Tim Northover3b0846e2014-05-24 12:50:23 +000010333
10334 // Since the intrinsics must have legal type, the i128 intrinsics take two
10335 // parameters: "i64, i64". We must marshal Val into the appropriate form
10336 // before the call.
10337 if (Val->getType()->getPrimitiveSizeInBits() == 128) {
10338 Intrinsic::ID Int =
10339 IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
10340 Function *Stxr = Intrinsic::getDeclaration(M, Int);
10341 Type *Int64Ty = Type::getInt64Ty(M->getContext());
10342
10343 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
10344 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
10345 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
David Blaikieff6409d2015-05-18 22:13:54 +000010346 return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
Tim Northover3b0846e2014-05-24 12:50:23 +000010347 }
10348
10349 Intrinsic::ID Int =
10350 IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
10351 Type *Tys[] = { Addr->getType() };
10352 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
10353
David Blaikieff6409d2015-05-18 22:13:54 +000010354 return Builder.CreateCall(Stxr,
10355 {Builder.CreateZExtOrBitCast(
10356 Val, Stxr->getFunctionType()->getParamType(0)),
10357 Addr});
Tim Northover3b0846e2014-05-24 12:50:23 +000010358}
Tim Northover3c55cca2014-11-27 21:02:42 +000010359
10360bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
10361 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
10362 return Ty->isArrayTy();
10363}
Matthias Braunaf7d7702015-07-16 20:02:37 +000010364
10365bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
10366 EVT) const {
10367 return false;
10368}
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000010369
Tim Shen00127562016-04-08 21:26:31 +000010370Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const {
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +000010371 if (!Subtarget->isTargetAndroid())
Tim Shen00127562016-04-08 21:26:31 +000010372 return TargetLowering::getIRStackGuard(IRB);
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +000010373
10374 // Android provides a fixed TLS slot for the stack cookie. See the definition
10375 // of TLS_SLOT_STACK_GUARD in
10376 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
10377 const unsigned TlsOffset = 0x28;
10378 Module *M = IRB.GetInsertBlock()->getParent()->getParent();
10379 Function *ThreadPointerFunc =
Marcin Koscielnicki3fdc2572016-04-19 20:51:05 +000010380 Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +000010381 return IRB.CreatePointerCast(
10382 IRB.CreateConstGEP1_32(IRB.CreateCall(ThreadPointerFunc), TlsOffset),
10383 Type::getInt8PtrTy(IRB.getContext())->getPointerTo(0));
10384}
10385
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000010386Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
10387 if (!Subtarget->isTargetAndroid())
10388 return TargetLowering::getSafeStackPointerLocation(IRB);
10389
10390 // Android provides a fixed TLS slot for the SafeStack pointer. See the
10391 // definition of TLS_SLOT_SAFESTACK in
10392 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
10393 const unsigned TlsOffset = 0x48;
10394 Module *M = IRB.GetInsertBlock()->getParent()->getParent();
10395 Function *ThreadPointerFunc =
Marcin Koscielnicki3fdc2572016-04-19 20:51:05 +000010396 Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000010397 return IRB.CreatePointerCast(
10398 IRB.CreateConstGEP1_32(IRB.CreateCall(ThreadPointerFunc), TlsOffset),
10399 Type::getInt8PtrTy(IRB.getContext())->getPointerTo(0));
10400}
Manman Rencbe4f942015-12-16 21:04:19 +000010401
10402void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
10403 // Update IsSplitCSR in AArch64unctionInfo.
10404 AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>();
10405 AFI->setIsSplitCSR(true);
10406}
10407
10408void AArch64TargetLowering::insertCopiesSplitCSR(
10409 MachineBasicBlock *Entry,
10410 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
10411 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
10412 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
10413 if (!IStart)
10414 return;
10415
10416 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10417 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
Manman Ren4632e8e2016-01-15 20:13:28 +000010418 MachineBasicBlock::iterator MBBI = Entry->begin();
Manman Rencbe4f942015-12-16 21:04:19 +000010419 for (const MCPhysReg *I = IStart; *I; ++I) {
10420 const TargetRegisterClass *RC = nullptr;
10421 if (AArch64::GPR64RegClass.contains(*I))
10422 RC = &AArch64::GPR64RegClass;
10423 else if (AArch64::FPR64RegClass.contains(*I))
10424 RC = &AArch64::FPR64RegClass;
10425 else
10426 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
10427
10428 unsigned NewVR = MRI->createVirtualRegister(RC);
10429 // Create copy from CSR to a virtual register.
10430 // FIXME: this currently does not emit CFI pseudo-instructions, it works
10431 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
10432 // nounwind. If we want to generalize this later, we may need to emit
10433 // CFI pseudo-instructions.
10434 assert(Entry->getParent()->getFunction()->hasFnAttribute(
10435 Attribute::NoUnwind) &&
10436 "Function should be nounwind in insertCopiesSplitCSR!");
10437 Entry->addLiveIn(*I);
Manman Ren4632e8e2016-01-15 20:13:28 +000010438 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
Manman Rencbe4f942015-12-16 21:04:19 +000010439 .addReg(*I);
10440
Manman Ren4632e8e2016-01-15 20:13:28 +000010441 // Insert the copy-back instructions right before the terminator.
Manman Rencbe4f942015-12-16 21:04:19 +000010442 for (auto *Exit : Exits)
Manman Ren4632e8e2016-01-15 20:13:28 +000010443 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
10444 TII->get(TargetOpcode::COPY), *I)
Manman Rencbe4f942015-12-16 21:04:19 +000010445 .addReg(NewVR);
10446 }
10447}
Haicheng Wu6a6bc752016-03-28 18:17:07 +000010448
10449bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeSet Attr) const {
10450 // Integer division on AArch64 is expensive. However, when aggressively
10451 // optimizing for code size, we prefer to use a div instruction, as it is
10452 // usually smaller than the alternative sequence.
10453 // The exception to this is vector division. Since AArch64 doesn't have vector
10454 // integer division, leaving the division as-is is a loss even in terms of
10455 // size, because it will have to be scalarized, while the alternative code
10456 // sequence can be performed in vector form.
10457 bool OptSize =
10458 Attr.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
10459 return OptSize && !VT.isVector();
10460}