blob: 1b7365474b7373ef5b699c5a1fabe396fcdcffdd [file] [log] [blame]
Tim Northover3b0846e2014-05-24 12:50:23 +00001//===-- AArch64ISelLowering.cpp - AArch64 DAG Lowering Implementation ----===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the AArch64TargetLowering class.
11//
12//===----------------------------------------------------------------------===//
13
14#include "AArch64ISelLowering.h"
Tim Northover3c55cca2014-11-27 21:02:42 +000015#include "AArch64CallingConvention.h"
Benjamin Kramer1f8930e2014-07-25 11:42:14 +000016#include "AArch64MachineFunctionInfo.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000017#include "AArch64PerfectShuffle.h"
18#include "AArch64Subtarget.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000019#include "AArch64TargetMachine.h"
20#include "AArch64TargetObjectFile.h"
21#include "MCTargetDesc/AArch64AddressingModes.h"
22#include "llvm/ADT/Statistic.h"
23#include "llvm/CodeGen/CallingConvLower.h"
24#include "llvm/CodeGen/MachineFrameInfo.h"
25#include "llvm/CodeGen/MachineInstrBuilder.h"
26#include "llvm/CodeGen/MachineRegisterInfo.h"
27#include "llvm/IR/Function.h"
David Blaikie457343d2015-05-21 21:12:43 +000028#include "llvm/IR/GetElementPtrTypeIterator.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000029#include "llvm/IR/Intrinsics.h"
30#include "llvm/IR/Type.h"
31#include "llvm/Support/CommandLine.h"
32#include "llvm/Support/Debug.h"
33#include "llvm/Support/ErrorHandling.h"
34#include "llvm/Support/raw_ostream.h"
35#include "llvm/Target/TargetOptions.h"
36using namespace llvm;
37
38#define DEBUG_TYPE "aarch64-lower"
39
40STATISTIC(NumTailCalls, "Number of tail calls");
41STATISTIC(NumShiftInserts, "Number of vector shift inserts");
42
Tim Northover3b0846e2014-05-24 12:50:23 +000043// Place holder until extr generation is tested fully.
44static cl::opt<bool>
45EnableAArch64ExtrGeneration("aarch64-extr-generation", cl::Hidden,
46 cl::desc("Allow AArch64 (or (shift)(shift))->extract"),
47 cl::init(true));
48
49static cl::opt<bool>
50EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden,
Kristof Beylsaea84612015-03-04 09:12:08 +000051 cl::desc("Allow AArch64 SLI/SRI formation"),
52 cl::init(false));
53
54// FIXME: The necessary dtprel relocations don't seem to be supported
55// well in the GNU bfd and gold linkers at the moment. Therefore, by
56// default, for now, fall back to GeneralDynamic code generation.
57cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration(
58 "aarch64-elf-ldtls-generation", cl::Hidden,
59 cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
60 cl::init(false));
Tim Northover3b0846e2014-05-24 12:50:23 +000061
Matthias Braunaf7d7702015-07-16 20:02:37 +000062/// Value type used for condition codes.
63static const MVT MVT_CC = MVT::i32;
64
Eric Christopher905f12d2015-01-29 00:19:42 +000065AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
66 const AArch64Subtarget &STI)
67 : TargetLowering(TM), Subtarget(&STI) {
Tim Northover3b0846e2014-05-24 12:50:23 +000068
69 // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
70 // we have to make something up. Arbitrarily, choose ZeroOrOne.
71 setBooleanContents(ZeroOrOneBooleanContent);
72 // When comparing vectors the result sets the different elements in the
73 // vector to all-one or all-zero.
74 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
75
76 // Set up the register classes.
77 addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
78 addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
79
80 if (Subtarget->hasFPARMv8()) {
81 addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
82 addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
83 addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
84 addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
85 }
86
87 if (Subtarget->hasNEON()) {
88 addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
89 addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
90 // Someone set us up the NEON.
91 addDRTypeForNEON(MVT::v2f32);
92 addDRTypeForNEON(MVT::v8i8);
93 addDRTypeForNEON(MVT::v4i16);
94 addDRTypeForNEON(MVT::v2i32);
95 addDRTypeForNEON(MVT::v1i64);
96 addDRTypeForNEON(MVT::v1f64);
Oliver Stannard89d15422014-08-27 16:16:04 +000097 addDRTypeForNEON(MVT::v4f16);
Tim Northover3b0846e2014-05-24 12:50:23 +000098
99 addQRTypeForNEON(MVT::v4f32);
100 addQRTypeForNEON(MVT::v2f64);
101 addQRTypeForNEON(MVT::v16i8);
102 addQRTypeForNEON(MVT::v8i16);
103 addQRTypeForNEON(MVT::v4i32);
104 addQRTypeForNEON(MVT::v2i64);
Oliver Stannard89d15422014-08-27 16:16:04 +0000105 addQRTypeForNEON(MVT::v8f16);
Tim Northover3b0846e2014-05-24 12:50:23 +0000106 }
107
108 // Compute derived properties from the register classes
Eric Christopher23a3a7c2015-02-26 00:00:24 +0000109 computeRegisterProperties(Subtarget->getRegisterInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +0000110
111 // Provide all sorts of operation actions
112 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
113 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
114 setOperationAction(ISD::SETCC, MVT::i32, Custom);
115 setOperationAction(ISD::SETCC, MVT::i64, Custom);
116 setOperationAction(ISD::SETCC, MVT::f32, Custom);
117 setOperationAction(ISD::SETCC, MVT::f64, Custom);
118 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
119 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
120 setOperationAction(ISD::BR_CC, MVT::i64, Custom);
121 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
122 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
123 setOperationAction(ISD::SELECT, MVT::i32, Custom);
124 setOperationAction(ISD::SELECT, MVT::i64, Custom);
125 setOperationAction(ISD::SELECT, MVT::f32, Custom);
126 setOperationAction(ISD::SELECT, MVT::f64, Custom);
127 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
128 setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
129 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
130 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
131 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
132 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
133
134 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
135 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
136 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
137
138 setOperationAction(ISD::FREM, MVT::f32, Expand);
139 setOperationAction(ISD::FREM, MVT::f64, Expand);
140 setOperationAction(ISD::FREM, MVT::f80, Expand);
141
142 // Custom lowering hooks are needed for XOR
143 // to fold it into CSINC/CSINV.
144 setOperationAction(ISD::XOR, MVT::i32, Custom);
145 setOperationAction(ISD::XOR, MVT::i64, Custom);
146
Balaram Makam92431702016-02-01 19:13:07 +0000147 // Custom lowering hooks are needed for OR
148 // to fold it into CCMP.
149 setOperationAction(ISD::OR, MVT::i32, Custom);
150 setOperationAction(ISD::OR, MVT::i64, Custom);
151
152 // Custom lowering hooks are needed for AND
153 // to fold it into CCMP.
154 setOperationAction(ISD::AND, MVT::i32, Custom);
155 setOperationAction(ISD::AND, MVT::i64, Custom);
156
Tim Northover3b0846e2014-05-24 12:50:23 +0000157 // Virtually no operation on f128 is legal, but LLVM can't expand them when
158 // there's a valid register class, so we need custom operations in most cases.
159 setOperationAction(ISD::FABS, MVT::f128, Expand);
160 setOperationAction(ISD::FADD, MVT::f128, Custom);
161 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
162 setOperationAction(ISD::FCOS, MVT::f128, Expand);
163 setOperationAction(ISD::FDIV, MVT::f128, Custom);
164 setOperationAction(ISD::FMA, MVT::f128, Expand);
165 setOperationAction(ISD::FMUL, MVT::f128, Custom);
166 setOperationAction(ISD::FNEG, MVT::f128, Expand);
167 setOperationAction(ISD::FPOW, MVT::f128, Expand);
168 setOperationAction(ISD::FREM, MVT::f128, Expand);
169 setOperationAction(ISD::FRINT, MVT::f128, Expand);
170 setOperationAction(ISD::FSIN, MVT::f128, Expand);
171 setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
172 setOperationAction(ISD::FSQRT, MVT::f128, Expand);
173 setOperationAction(ISD::FSUB, MVT::f128, Custom);
174 setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
175 setOperationAction(ISD::SETCC, MVT::f128, Custom);
176 setOperationAction(ISD::BR_CC, MVT::f128, Custom);
177 setOperationAction(ISD::SELECT, MVT::f128, Custom);
178 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
179 setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
180
181 // Lowering for many of the conversions is actually specified by the non-f128
182 // type. The LowerXXX function will be trivial when f128 isn't involved.
183 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
184 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
185 setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
186 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
187 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
188 setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
189 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
190 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
191 setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
192 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
193 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
194 setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
195 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
196 setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
197
198 // Variable arguments.
199 setOperationAction(ISD::VASTART, MVT::Other, Custom);
200 setOperationAction(ISD::VAARG, MVT::Other, Custom);
201 setOperationAction(ISD::VACOPY, MVT::Other, Custom);
202 setOperationAction(ISD::VAEND, MVT::Other, Expand);
203
204 // Variable-sized objects.
205 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
206 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
207 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
208
Tim Northover3b0846e2014-05-24 12:50:23 +0000209 // Constant pool entries
210 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
211
212 // BlockAddress
213 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
214
215 // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
216 setOperationAction(ISD::ADDC, MVT::i32, Custom);
217 setOperationAction(ISD::ADDE, MVT::i32, Custom);
218 setOperationAction(ISD::SUBC, MVT::i32, Custom);
219 setOperationAction(ISD::SUBE, MVT::i32, Custom);
220 setOperationAction(ISD::ADDC, MVT::i64, Custom);
221 setOperationAction(ISD::ADDE, MVT::i64, Custom);
222 setOperationAction(ISD::SUBC, MVT::i64, Custom);
223 setOperationAction(ISD::SUBE, MVT::i64, Custom);
224
225 // AArch64 lacks both left-rotate and popcount instructions.
226 setOperationAction(ISD::ROTL, MVT::i32, Expand);
227 setOperationAction(ISD::ROTL, MVT::i64, Expand);
Charlie Turner458e79b2015-10-27 10:25:20 +0000228 for (MVT VT : MVT::vector_valuetypes()) {
229 setOperationAction(ISD::ROTL, VT, Expand);
230 setOperationAction(ISD::ROTR, VT, Expand);
231 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000232
233 // AArch64 doesn't have {U|S}MUL_LOHI.
234 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
235 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
236
237
238 // Expand the undefined-at-zero variants to cttz/ctlz to their defined-at-zero
239 // counterparts, which AArch64 supports directly.
240 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
241 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
242 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
243 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
244
245 setOperationAction(ISD::CTPOP, MVT::i32, Custom);
246 setOperationAction(ISD::CTPOP, MVT::i64, Custom);
247
248 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
249 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
Chad Rosierf3491492015-12-04 21:38:44 +0000250 for (MVT VT : MVT::vector_valuetypes()) {
251 setOperationAction(ISD::SDIVREM, VT, Expand);
252 setOperationAction(ISD::UDIVREM, VT, Expand);
253 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000254 setOperationAction(ISD::SREM, MVT::i32, Expand);
255 setOperationAction(ISD::SREM, MVT::i64, Expand);
256 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
257 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
258 setOperationAction(ISD::UREM, MVT::i32, Expand);
259 setOperationAction(ISD::UREM, MVT::i64, Expand);
260
261 // Custom lower Add/Sub/Mul with overflow.
262 setOperationAction(ISD::SADDO, MVT::i32, Custom);
263 setOperationAction(ISD::SADDO, MVT::i64, Custom);
264 setOperationAction(ISD::UADDO, MVT::i32, Custom);
265 setOperationAction(ISD::UADDO, MVT::i64, Custom);
266 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
267 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
268 setOperationAction(ISD::USUBO, MVT::i32, Custom);
269 setOperationAction(ISD::USUBO, MVT::i64, Custom);
270 setOperationAction(ISD::SMULO, MVT::i32, Custom);
271 setOperationAction(ISD::SMULO, MVT::i64, Custom);
272 setOperationAction(ISD::UMULO, MVT::i32, Custom);
273 setOperationAction(ISD::UMULO, MVT::i64, Custom);
274
275 setOperationAction(ISD::FSIN, MVT::f32, Expand);
276 setOperationAction(ISD::FSIN, MVT::f64, Expand);
277 setOperationAction(ISD::FCOS, MVT::f32, Expand);
278 setOperationAction(ISD::FCOS, MVT::f64, Expand);
279 setOperationAction(ISD::FPOW, MVT::f32, Expand);
280 setOperationAction(ISD::FPOW, MVT::f64, Expand);
281 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
282 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
283
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +0000284 // f16 is a storage-only type, always promote it to f32.
285 setOperationAction(ISD::SETCC, MVT::f16, Promote);
286 setOperationAction(ISD::BR_CC, MVT::f16, Promote);
287 setOperationAction(ISD::SELECT_CC, MVT::f16, Promote);
288 setOperationAction(ISD::SELECT, MVT::f16, Promote);
289 setOperationAction(ISD::FADD, MVT::f16, Promote);
290 setOperationAction(ISD::FSUB, MVT::f16, Promote);
291 setOperationAction(ISD::FMUL, MVT::f16, Promote);
292 setOperationAction(ISD::FDIV, MVT::f16, Promote);
293 setOperationAction(ISD::FREM, MVT::f16, Promote);
294 setOperationAction(ISD::FMA, MVT::f16, Promote);
295 setOperationAction(ISD::FNEG, MVT::f16, Promote);
296 setOperationAction(ISD::FABS, MVT::f16, Promote);
297 setOperationAction(ISD::FCEIL, MVT::f16, Promote);
298 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote);
299 setOperationAction(ISD::FCOS, MVT::f16, Promote);
300 setOperationAction(ISD::FFLOOR, MVT::f16, Promote);
301 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote);
302 setOperationAction(ISD::FPOW, MVT::f16, Promote);
303 setOperationAction(ISD::FPOWI, MVT::f16, Promote);
304 setOperationAction(ISD::FRINT, MVT::f16, Promote);
305 setOperationAction(ISD::FSIN, MVT::f16, Promote);
306 setOperationAction(ISD::FSINCOS, MVT::f16, Promote);
307 setOperationAction(ISD::FSQRT, MVT::f16, Promote);
308 setOperationAction(ISD::FEXP, MVT::f16, Promote);
309 setOperationAction(ISD::FEXP2, MVT::f16, Promote);
310 setOperationAction(ISD::FLOG, MVT::f16, Promote);
311 setOperationAction(ISD::FLOG2, MVT::f16, Promote);
312 setOperationAction(ISD::FLOG10, MVT::f16, Promote);
313 setOperationAction(ISD::FROUND, MVT::f16, Promote);
314 setOperationAction(ISD::FTRUNC, MVT::f16, Promote);
315 setOperationAction(ISD::FMINNUM, MVT::f16, Promote);
316 setOperationAction(ISD::FMAXNUM, MVT::f16, Promote);
James Molloy63be1982015-08-14 09:08:50 +0000317 setOperationAction(ISD::FMINNAN, MVT::f16, Promote);
318 setOperationAction(ISD::FMAXNAN, MVT::f16, Promote);
Oliver Stannardf5469be2014-08-18 14:22:39 +0000319
Oliver Stannard89d15422014-08-27 16:16:04 +0000320 // v4f16 is also a storage-only type, so promote it to v4f32 when that is
321 // known to be safe.
322 setOperationAction(ISD::FADD, MVT::v4f16, Promote);
323 setOperationAction(ISD::FSUB, MVT::v4f16, Promote);
324 setOperationAction(ISD::FMUL, MVT::v4f16, Promote);
325 setOperationAction(ISD::FDIV, MVT::v4f16, Promote);
326 setOperationAction(ISD::FP_EXTEND, MVT::v4f16, Promote);
327 setOperationAction(ISD::FP_ROUND, MVT::v4f16, Promote);
328 AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32);
329 AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32);
330 AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32);
331 AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32);
332 AddPromotedToType(ISD::FP_EXTEND, MVT::v4f16, MVT::v4f32);
333 AddPromotedToType(ISD::FP_ROUND, MVT::v4f16, MVT::v4f32);
334
335 // Expand all other v4f16 operations.
336 // FIXME: We could generate better code by promoting some operations to
337 // a pair of v4f32s
338 setOperationAction(ISD::FABS, MVT::v4f16, Expand);
339 setOperationAction(ISD::FCEIL, MVT::v4f16, Expand);
340 setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand);
341 setOperationAction(ISD::FCOS, MVT::v4f16, Expand);
342 setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand);
343 setOperationAction(ISD::FMA, MVT::v4f16, Expand);
344 setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand);
345 setOperationAction(ISD::FNEG, MVT::v4f16, Expand);
346 setOperationAction(ISD::FPOW, MVT::v4f16, Expand);
347 setOperationAction(ISD::FPOWI, MVT::v4f16, Expand);
348 setOperationAction(ISD::FREM, MVT::v4f16, Expand);
349 setOperationAction(ISD::FROUND, MVT::v4f16, Expand);
350 setOperationAction(ISD::FRINT, MVT::v4f16, Expand);
351 setOperationAction(ISD::FSIN, MVT::v4f16, Expand);
352 setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand);
353 setOperationAction(ISD::FSQRT, MVT::v4f16, Expand);
354 setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand);
355 setOperationAction(ISD::SETCC, MVT::v4f16, Expand);
356 setOperationAction(ISD::BR_CC, MVT::v4f16, Expand);
357 setOperationAction(ISD::SELECT, MVT::v4f16, Expand);
358 setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand);
359 setOperationAction(ISD::FEXP, MVT::v4f16, Expand);
360 setOperationAction(ISD::FEXP2, MVT::v4f16, Expand);
361 setOperationAction(ISD::FLOG, MVT::v4f16, Expand);
362 setOperationAction(ISD::FLOG2, MVT::v4f16, Expand);
363 setOperationAction(ISD::FLOG10, MVT::v4f16, Expand);
364
365
366 // v8f16 is also a storage-only type, so expand it.
367 setOperationAction(ISD::FABS, MVT::v8f16, Expand);
368 setOperationAction(ISD::FADD, MVT::v8f16, Expand);
369 setOperationAction(ISD::FCEIL, MVT::v8f16, Expand);
370 setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand);
371 setOperationAction(ISD::FCOS, MVT::v8f16, Expand);
372 setOperationAction(ISD::FDIV, MVT::v8f16, Expand);
373 setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand);
374 setOperationAction(ISD::FMA, MVT::v8f16, Expand);
375 setOperationAction(ISD::FMUL, MVT::v8f16, Expand);
376 setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand);
377 setOperationAction(ISD::FNEG, MVT::v8f16, Expand);
378 setOperationAction(ISD::FPOW, MVT::v8f16, Expand);
379 setOperationAction(ISD::FPOWI, MVT::v8f16, Expand);
380 setOperationAction(ISD::FREM, MVT::v8f16, Expand);
381 setOperationAction(ISD::FROUND, MVT::v8f16, Expand);
382 setOperationAction(ISD::FRINT, MVT::v8f16, Expand);
383 setOperationAction(ISD::FSIN, MVT::v8f16, Expand);
384 setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
385 setOperationAction(ISD::FSQRT, MVT::v8f16, Expand);
386 setOperationAction(ISD::FSUB, MVT::v8f16, Expand);
387 setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand);
388 setOperationAction(ISD::SETCC, MVT::v8f16, Expand);
389 setOperationAction(ISD::BR_CC, MVT::v8f16, Expand);
390 setOperationAction(ISD::SELECT, MVT::v8f16, Expand);
391 setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand);
392 setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand);
393 setOperationAction(ISD::FEXP, MVT::v8f16, Expand);
394 setOperationAction(ISD::FEXP2, MVT::v8f16, Expand);
395 setOperationAction(ISD::FLOG, MVT::v8f16, Expand);
396 setOperationAction(ISD::FLOG2, MVT::v8f16, Expand);
397 setOperationAction(ISD::FLOG10, MVT::v8f16, Expand);
398
Tim Northover3b0846e2014-05-24 12:50:23 +0000399 // AArch64 has implementations of a lot of rounding-like FP operations.
Benjamin Kramer57a3d082015-03-08 16:07:39 +0000400 for (MVT Ty : {MVT::f32, MVT::f64}) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000401 setOperationAction(ISD::FFLOOR, Ty, Legal);
402 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
403 setOperationAction(ISD::FCEIL, Ty, Legal);
404 setOperationAction(ISD::FRINT, Ty, Legal);
405 setOperationAction(ISD::FTRUNC, Ty, Legal);
406 setOperationAction(ISD::FROUND, Ty, Legal);
James Molloyb7b2a1e2015-08-11 12:06:37 +0000407 setOperationAction(ISD::FMINNUM, Ty, Legal);
408 setOperationAction(ISD::FMAXNUM, Ty, Legal);
James Molloy88edc822015-08-17 07:13:20 +0000409 setOperationAction(ISD::FMINNAN, Ty, Legal);
410 setOperationAction(ISD::FMAXNAN, Ty, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000411 }
412
413 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
414
Ahmed Bougachab0ff6432015-09-01 16:23:45 +0000415 // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
416 // This requires the Performance Monitors extension.
417 if (Subtarget->hasPerfMon())
418 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
419
Tim Northover3b0846e2014-05-24 12:50:23 +0000420 if (Subtarget->isTargetMachO()) {
421 // For iOS, we don't want to the normal expansion of a libcall to
422 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
423 // traffic.
424 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
425 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
426 } else {
427 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
428 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
429 }
430
Juergen Ributzka23266502014-12-10 19:43:32 +0000431 // Make floating-point constants legal for the large code model, so they don't
432 // become loads from the constant pool.
433 if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
434 setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
435 setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
436 }
437
Tim Northover3b0846e2014-05-24 12:50:23 +0000438 // AArch64 does not have floating-point extending loads, i1 sign-extending
439 // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000440 for (MVT VT : MVT::fp_valuetypes()) {
441 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
442 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
443 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
444 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
445 }
446 for (MVT VT : MVT::integer_valuetypes())
447 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
448
Tim Northover3b0846e2014-05-24 12:50:23 +0000449 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
450 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
451 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
452 setTruncStoreAction(MVT::f128, MVT::f80, Expand);
453 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
454 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
455 setTruncStoreAction(MVT::f128, MVT::f16, Expand);
Tim Northoverf8bfe212014-07-18 13:07:05 +0000456
457 setOperationAction(ISD::BITCAST, MVT::i16, Custom);
458 setOperationAction(ISD::BITCAST, MVT::f16, Custom);
459
Tim Northover3b0846e2014-05-24 12:50:23 +0000460 // Indexed loads and stores are supported.
461 for (unsigned im = (unsigned)ISD::PRE_INC;
462 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
463 setIndexedLoadAction(im, MVT::i8, Legal);
464 setIndexedLoadAction(im, MVT::i16, Legal);
465 setIndexedLoadAction(im, MVT::i32, Legal);
466 setIndexedLoadAction(im, MVT::i64, Legal);
467 setIndexedLoadAction(im, MVT::f64, Legal);
468 setIndexedLoadAction(im, MVT::f32, Legal);
Ahmed Bougachae0e12db2015-08-04 01:29:38 +0000469 setIndexedLoadAction(im, MVT::f16, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000470 setIndexedStoreAction(im, MVT::i8, Legal);
471 setIndexedStoreAction(im, MVT::i16, Legal);
472 setIndexedStoreAction(im, MVT::i32, Legal);
473 setIndexedStoreAction(im, MVT::i64, Legal);
474 setIndexedStoreAction(im, MVT::f64, Legal);
475 setIndexedStoreAction(im, MVT::f32, Legal);
Ahmed Bougachae0e12db2015-08-04 01:29:38 +0000476 setIndexedStoreAction(im, MVT::f16, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000477 }
478
479 // Trap.
480 setOperationAction(ISD::TRAP, MVT::Other, Legal);
481
482 // We combine OR nodes for bitfield operations.
483 setTargetDAGCombine(ISD::OR);
484
485 // Vector add and sub nodes may conceal a high-half opportunity.
486 // Also, try to fold ADD into CSINC/CSINV..
487 setTargetDAGCombine(ISD::ADD);
488 setTargetDAGCombine(ISD::SUB);
489
490 setTargetDAGCombine(ISD::XOR);
491 setTargetDAGCombine(ISD::SINT_TO_FP);
492 setTargetDAGCombine(ISD::UINT_TO_FP);
493
Chad Rosierfa30c9b2015-10-07 17:39:18 +0000494 setTargetDAGCombine(ISD::FP_TO_SINT);
495 setTargetDAGCombine(ISD::FP_TO_UINT);
Chad Rosier7c6ac2b2015-10-07 17:51:37 +0000496 setTargetDAGCombine(ISD::FDIV);
Chad Rosierfa30c9b2015-10-07 17:39:18 +0000497
Tim Northover3b0846e2014-05-24 12:50:23 +0000498 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
499
500 setTargetDAGCombine(ISD::ANY_EXTEND);
501 setTargetDAGCombine(ISD::ZERO_EXTEND);
502 setTargetDAGCombine(ISD::SIGN_EXTEND);
503 setTargetDAGCombine(ISD::BITCAST);
504 setTargetDAGCombine(ISD::CONCAT_VECTORS);
505 setTargetDAGCombine(ISD::STORE);
Tim Northover339c83e2015-11-10 00:44:23 +0000506 if (Subtarget->supportsAddressTopByteIgnored())
507 setTargetDAGCombine(ISD::LOAD);
Tim Northover3b0846e2014-05-24 12:50:23 +0000508
509 setTargetDAGCombine(ISD::MUL);
510
511 setTargetDAGCombine(ISD::SELECT);
512 setTargetDAGCombine(ISD::VSELECT);
513
514 setTargetDAGCombine(ISD::INTRINSIC_VOID);
515 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
516 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
Chad Rosier6c36eff2015-09-03 18:13:57 +0000517 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
Tim Northover3b0846e2014-05-24 12:50:23 +0000518
519 MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 8;
520 MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 4;
521 MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = 4;
522
523 setStackPointerRegisterToSaveRestore(AArch64::SP);
524
525 setSchedulingPreference(Sched::Hybrid);
526
527 // Enable TBZ/TBNZ
528 MaskAndBranchFoldingIsLegal = true;
Quentin Colombet6843ac42015-03-31 20:52:32 +0000529 EnableExtLdPromotion = true;
Tim Northover3b0846e2014-05-24 12:50:23 +0000530
531 setMinFunctionAlignment(2);
532
Tim Northover3b0846e2014-05-24 12:50:23 +0000533 setHasExtractBitsInsn(true);
534
Adhemerval Zanella7bc33192015-07-28 13:03:31 +0000535 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
536
Tim Northover3b0846e2014-05-24 12:50:23 +0000537 if (Subtarget->hasNEON()) {
538 // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
539 // silliness like this:
540 setOperationAction(ISD::FABS, MVT::v1f64, Expand);
541 setOperationAction(ISD::FADD, MVT::v1f64, Expand);
542 setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
543 setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
544 setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
545 setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
546 setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
547 setOperationAction(ISD::FMA, MVT::v1f64, Expand);
548 setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
549 setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
550 setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
551 setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
552 setOperationAction(ISD::FREM, MVT::v1f64, Expand);
553 setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
554 setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
555 setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
556 setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
557 setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
558 setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
559 setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
560 setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
561 setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
562 setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
563 setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
564 setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
565
566 setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
567 setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
568 setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
569 setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
570 setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
571
572 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
573
574 // AArch64 doesn't have a direct vector ->f32 conversion instructions for
575 // elements smaller than i32, so promote the input to i32 first.
576 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Promote);
577 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Promote);
578 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Promote);
579 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Promote);
Pirama Arumuga Nainarb1881532015-04-23 17:16:27 +0000580 // i8 and i16 vector elements also need promotion to i32 for v8i8 or v8i16
581 // -> v8f16 conversions.
582 setOperationAction(ISD::SINT_TO_FP, MVT::v8i8, Promote);
583 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Promote);
584 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
585 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Promote);
Tim Northover3b0846e2014-05-24 12:50:23 +0000586 // Similarly, there is no direct i32 -> f64 vector conversion instruction.
587 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
588 setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
589 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
590 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
Pirama Arumuga Nainarb1881532015-04-23 17:16:27 +0000591 // Or, direct i32 -> f16 vector conversion. Set it so custom, so the
592 // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
593 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
594 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000595
596 // AArch64 doesn't have MUL.2d:
597 setOperationAction(ISD::MUL, MVT::v2i64, Expand);
Chad Rosierd9d0f862014-10-08 02:31:24 +0000598 // Custom handling for some quad-vector types to detect MULL.
599 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
600 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
601 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
602
Tim Northover3b0846e2014-05-24 12:50:23 +0000603 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
604 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
605 // Likewise, narrowing and extending vector loads/stores aren't handled
606 // directly.
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000607 for (MVT VT : MVT::vector_valuetypes()) {
608 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000609
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000610 setOperationAction(ISD::MULHS, VT, Expand);
611 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
612 setOperationAction(ISD::MULHU, VT, Expand);
613 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000614
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000615 setOperationAction(ISD::BSWAP, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000616
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000617 for (MVT InnerVT : MVT::vector_valuetypes()) {
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000618 setTruncStoreAction(VT, InnerVT, Expand);
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000619 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
620 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
621 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
622 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000623 }
624
625 // AArch64 has implementations of a lot of rounding-like FP operations.
Benjamin Kramer57a3d082015-03-08 16:07:39 +0000626 for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000627 setOperationAction(ISD::FFLOOR, Ty, Legal);
628 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
629 setOperationAction(ISD::FCEIL, Ty, Legal);
630 setOperationAction(ISD::FRINT, Ty, Legal);
631 setOperationAction(ISD::FTRUNC, Ty, Legal);
632 setOperationAction(ISD::FROUND, Ty, Legal);
633 }
634 }
James Molloyf089ab72014-08-06 10:42:18 +0000635
636 // Prefer likely predicted branches to selects on out-of-order cores.
Chad Rosiercd2be7f2016-02-12 15:51:51 +0000637 if (Subtarget->isCortexA57() || Subtarget->isKryo())
James Molloyf089ab72014-08-06 10:42:18 +0000638 PredictableSelectIsExpensive = true;
Tim Northover3b0846e2014-05-24 12:50:23 +0000639}
640
641void AArch64TargetLowering::addTypeForNEON(EVT VT, EVT PromotedBitwiseVT) {
Jiangning Liu08f4cda2014-08-29 01:31:42 +0000642 if (VT == MVT::v2f32 || VT == MVT::v4f16) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000643 setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
644 AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i32);
645
646 setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
647 AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i32);
Jiangning Liu08f4cda2014-08-29 01:31:42 +0000648 } else if (VT == MVT::v2f64 || VT == MVT::v4f32 || VT == MVT::v8f16) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000649 setOperationAction(ISD::LOAD, VT.getSimpleVT(), Promote);
650 AddPromotedToType(ISD::LOAD, VT.getSimpleVT(), MVT::v2i64);
651
652 setOperationAction(ISD::STORE, VT.getSimpleVT(), Promote);
653 AddPromotedToType(ISD::STORE, VT.getSimpleVT(), MVT::v2i64);
654 }
655
656 // Mark vector float intrinsics as expand.
657 if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
658 setOperationAction(ISD::FSIN, VT.getSimpleVT(), Expand);
659 setOperationAction(ISD::FCOS, VT.getSimpleVT(), Expand);
660 setOperationAction(ISD::FPOWI, VT.getSimpleVT(), Expand);
661 setOperationAction(ISD::FPOW, VT.getSimpleVT(), Expand);
662 setOperationAction(ISD::FLOG, VT.getSimpleVT(), Expand);
663 setOperationAction(ISD::FLOG2, VT.getSimpleVT(), Expand);
664 setOperationAction(ISD::FLOG10, VT.getSimpleVT(), Expand);
665 setOperationAction(ISD::FEXP, VT.getSimpleVT(), Expand);
666 setOperationAction(ISD::FEXP2, VT.getSimpleVT(), Expand);
Ahmed Bougachab0ae36f2015-08-04 00:42:34 +0000667
668 // But we do support custom-lowering for FCOPYSIGN.
669 setOperationAction(ISD::FCOPYSIGN, VT.getSimpleVT(), Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000670 }
671
672 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT.getSimpleVT(), Custom);
673 setOperationAction(ISD::INSERT_VECTOR_ELT, VT.getSimpleVT(), Custom);
674 setOperationAction(ISD::BUILD_VECTOR, VT.getSimpleVT(), Custom);
675 setOperationAction(ISD::VECTOR_SHUFFLE, VT.getSimpleVT(), Custom);
676 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT.getSimpleVT(), Custom);
677 setOperationAction(ISD::SRA, VT.getSimpleVT(), Custom);
678 setOperationAction(ISD::SRL, VT.getSimpleVT(), Custom);
679 setOperationAction(ISD::SHL, VT.getSimpleVT(), Custom);
680 setOperationAction(ISD::AND, VT.getSimpleVT(), Custom);
681 setOperationAction(ISD::OR, VT.getSimpleVT(), Custom);
682 setOperationAction(ISD::SETCC, VT.getSimpleVT(), Custom);
683 setOperationAction(ISD::CONCAT_VECTORS, VT.getSimpleVT(), Legal);
684
685 setOperationAction(ISD::SELECT, VT.getSimpleVT(), Expand);
686 setOperationAction(ISD::SELECT_CC, VT.getSimpleVT(), Expand);
687 setOperationAction(ISD::VSELECT, VT.getSimpleVT(), Expand);
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000688 for (MVT InnerVT : MVT::all_valuetypes())
689 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT.getSimpleVT(), Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000690
691 // CNT supports only B element sizes.
692 if (VT != MVT::v8i8 && VT != MVT::v16i8)
693 setOperationAction(ISD::CTPOP, VT.getSimpleVT(), Expand);
694
695 setOperationAction(ISD::UDIV, VT.getSimpleVT(), Expand);
696 setOperationAction(ISD::SDIV, VT.getSimpleVT(), Expand);
697 setOperationAction(ISD::UREM, VT.getSimpleVT(), Expand);
698 setOperationAction(ISD::SREM, VT.getSimpleVT(), Expand);
699 setOperationAction(ISD::FREM, VT.getSimpleVT(), Expand);
700
701 setOperationAction(ISD::FP_TO_SINT, VT.getSimpleVT(), Custom);
702 setOperationAction(ISD::FP_TO_UINT, VT.getSimpleVT(), Custom);
703
Hal Finkelcd8664c2015-12-11 23:11:52 +0000704 // [SU][MIN|MAX] are available for all NEON types apart from i64.
James Molloycfb04432015-05-15 16:15:57 +0000705 if (!VT.isFloatingPoint() &&
706 VT.getSimpleVT() != MVT::v2i64 && VT.getSimpleVT() != MVT::v1i64)
Hal Finkelcd8664c2015-12-11 23:11:52 +0000707 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
James Molloycfb04432015-05-15 16:15:57 +0000708 setOperationAction(Opcode, VT.getSimpleVT(), Legal);
709
James Molloy63be1982015-08-14 09:08:50 +0000710 // F[MIN|MAX][NUM|NAN] are available for all FP NEON types (not f16 though!).
711 if (VT.isFloatingPoint() && VT.getVectorElementType() != MVT::f16)
James Molloyb7b2a1e2015-08-11 12:06:37 +0000712 for (unsigned Opcode : {ISD::FMINNAN, ISD::FMAXNAN,
713 ISD::FMINNUM, ISD::FMAXNUM})
James Molloyedf38f02015-08-11 12:06:33 +0000714 setOperationAction(Opcode, VT.getSimpleVT(), Legal);
715
Tim Northover3b0846e2014-05-24 12:50:23 +0000716 if (Subtarget->isLittleEndian()) {
717 for (unsigned im = (unsigned)ISD::PRE_INC;
718 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
719 setIndexedLoadAction(im, VT.getSimpleVT(), Legal);
720 setIndexedStoreAction(im, VT.getSimpleVT(), Legal);
721 }
722 }
723}
724
725void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
726 addRegisterClass(VT, &AArch64::FPR64RegClass);
727 addTypeForNEON(VT, MVT::v2i32);
728}
729
730void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
731 addRegisterClass(VT, &AArch64::FPR128RegClass);
732 addTypeForNEON(VT, MVT::v4i32);
733}
734
Mehdi Amini44ede332015-07-09 02:09:04 +0000735EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
736 EVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +0000737 if (!VT.isVector())
738 return MVT::i32;
739 return VT.changeVectorElementTypeToInteger();
740}
741
742/// computeKnownBitsForTargetNode - Determine which of the bits specified in
743/// Mask are known to be either zero or one and return them in the
744/// KnownZero/KnownOne bitsets.
745void AArch64TargetLowering::computeKnownBitsForTargetNode(
746 const SDValue Op, APInt &KnownZero, APInt &KnownOne,
747 const SelectionDAG &DAG, unsigned Depth) const {
748 switch (Op.getOpcode()) {
749 default:
750 break;
751 case AArch64ISD::CSEL: {
752 APInt KnownZero2, KnownOne2;
753 DAG.computeKnownBits(Op->getOperand(0), KnownZero, KnownOne, Depth + 1);
754 DAG.computeKnownBits(Op->getOperand(1), KnownZero2, KnownOne2, Depth + 1);
755 KnownZero &= KnownZero2;
756 KnownOne &= KnownOne2;
757 break;
758 }
759 case ISD::INTRINSIC_W_CHAIN: {
Jun Bum Lim4d3c5982015-09-08 16:11:22 +0000760 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +0000761 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
762 switch (IntID) {
763 default: return;
764 case Intrinsic::aarch64_ldaxr:
765 case Intrinsic::aarch64_ldxr: {
766 unsigned BitWidth = KnownOne.getBitWidth();
767 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
768 unsigned MemBits = VT.getScalarType().getSizeInBits();
769 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
770 return;
771 }
772 }
773 break;
774 }
775 case ISD::INTRINSIC_WO_CHAIN:
776 case ISD::INTRINSIC_VOID: {
777 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
778 switch (IntNo) {
779 default:
780 break;
781 case Intrinsic::aarch64_neon_umaxv:
782 case Intrinsic::aarch64_neon_uminv: {
783 // Figure out the datatype of the vector operand. The UMINV instruction
784 // will zero extend the result, so we can mark as known zero all the
785 // bits larger than the element datatype. 32-bit or larget doesn't need
786 // this as those are legal types and will be handled by isel directly.
787 MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
788 unsigned BitWidth = KnownZero.getBitWidth();
789 if (VT == MVT::v8i8 || VT == MVT::v16i8) {
790 assert(BitWidth >= 8 && "Unexpected width!");
791 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
792 KnownZero |= Mask;
793 } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
794 assert(BitWidth >= 16 && "Unexpected width!");
795 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
796 KnownZero |= Mask;
797 }
798 break;
799 } break;
800 }
801 }
802 }
803}
804
Mehdi Aminieaabc512015-07-09 15:12:23 +0000805MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
806 EVT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +0000807 return MVT::i64;
808}
809
Akira Hatanakaf53b0402015-07-29 14:17:26 +0000810bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
811 unsigned AddrSpace,
812 unsigned Align,
813 bool *Fast) const {
814 if (Subtarget->requiresStrictAlign())
815 return false;
Sanjay Patelbbbf9a12015-09-25 21:49:48 +0000816
817 // FIXME: This is mostly true for Cyclone, but not necessarily others.
818 if (Fast) {
819 // FIXME: Define an attribute for slow unaligned accesses instead of
820 // relying on the CPU type as a proxy.
821 // On Cyclone, unaligned 128-bit stores are slow.
822 *Fast = !Subtarget->isCyclone() || VT.getStoreSize() != 16 ||
823 // See comments in performSTORECombine() for more details about
824 // these conditions.
825
826 // Code that uses clang vector extensions can mark that it
827 // wants unaligned accesses to be treated as fast by
828 // underspecifying alignment to be 1 or 2.
829 Align <= 2 ||
830
831 // Disregard v2i64. Memcpy lowering produces those and splitting
832 // them regresses performance on micro-benchmarks and olden/bh.
833 VT == MVT::v2i64;
834 }
Akira Hatanakaf53b0402015-07-29 14:17:26 +0000835 return true;
836}
837
Tim Northover3b0846e2014-05-24 12:50:23 +0000838FastISel *
839AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
840 const TargetLibraryInfo *libInfo) const {
841 return AArch64::createFastISel(funcInfo, libInfo);
842}
843
844const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
Matthias Braund04893f2015-05-07 21:33:59 +0000845 switch ((AArch64ISD::NodeType)Opcode) {
846 case AArch64ISD::FIRST_NUMBER: break;
Tim Northover3b0846e2014-05-24 12:50:23 +0000847 case AArch64ISD::CALL: return "AArch64ISD::CALL";
848 case AArch64ISD::ADRP: return "AArch64ISD::ADRP";
849 case AArch64ISD::ADDlow: return "AArch64ISD::ADDlow";
850 case AArch64ISD::LOADgot: return "AArch64ISD::LOADgot";
851 case AArch64ISD::RET_FLAG: return "AArch64ISD::RET_FLAG";
852 case AArch64ISD::BRCOND: return "AArch64ISD::BRCOND";
853 case AArch64ISD::CSEL: return "AArch64ISD::CSEL";
854 case AArch64ISD::FCSEL: return "AArch64ISD::FCSEL";
855 case AArch64ISD::CSINV: return "AArch64ISD::CSINV";
856 case AArch64ISD::CSNEG: return "AArch64ISD::CSNEG";
857 case AArch64ISD::CSINC: return "AArch64ISD::CSINC";
858 case AArch64ISD::THREAD_POINTER: return "AArch64ISD::THREAD_POINTER";
Kristof Beylsaea84612015-03-04 09:12:08 +0000859 case AArch64ISD::TLSDESC_CALLSEQ: return "AArch64ISD::TLSDESC_CALLSEQ";
Tim Northover3b0846e2014-05-24 12:50:23 +0000860 case AArch64ISD::ADC: return "AArch64ISD::ADC";
861 case AArch64ISD::SBC: return "AArch64ISD::SBC";
862 case AArch64ISD::ADDS: return "AArch64ISD::ADDS";
863 case AArch64ISD::SUBS: return "AArch64ISD::SUBS";
864 case AArch64ISD::ADCS: return "AArch64ISD::ADCS";
865 case AArch64ISD::SBCS: return "AArch64ISD::SBCS";
866 case AArch64ISD::ANDS: return "AArch64ISD::ANDS";
Matthias Braunaf7d7702015-07-16 20:02:37 +0000867 case AArch64ISD::CCMP: return "AArch64ISD::CCMP";
868 case AArch64ISD::CCMN: return "AArch64ISD::CCMN";
869 case AArch64ISD::FCCMP: return "AArch64ISD::FCCMP";
Tim Northover3b0846e2014-05-24 12:50:23 +0000870 case AArch64ISD::FCMP: return "AArch64ISD::FCMP";
Tim Northover3b0846e2014-05-24 12:50:23 +0000871 case AArch64ISD::DUP: return "AArch64ISD::DUP";
872 case AArch64ISD::DUPLANE8: return "AArch64ISD::DUPLANE8";
873 case AArch64ISD::DUPLANE16: return "AArch64ISD::DUPLANE16";
874 case AArch64ISD::DUPLANE32: return "AArch64ISD::DUPLANE32";
875 case AArch64ISD::DUPLANE64: return "AArch64ISD::DUPLANE64";
876 case AArch64ISD::MOVI: return "AArch64ISD::MOVI";
877 case AArch64ISD::MOVIshift: return "AArch64ISD::MOVIshift";
878 case AArch64ISD::MOVIedit: return "AArch64ISD::MOVIedit";
879 case AArch64ISD::MOVImsl: return "AArch64ISD::MOVImsl";
880 case AArch64ISD::FMOV: return "AArch64ISD::FMOV";
881 case AArch64ISD::MVNIshift: return "AArch64ISD::MVNIshift";
882 case AArch64ISD::MVNImsl: return "AArch64ISD::MVNImsl";
883 case AArch64ISD::BICi: return "AArch64ISD::BICi";
884 case AArch64ISD::ORRi: return "AArch64ISD::ORRi";
885 case AArch64ISD::BSL: return "AArch64ISD::BSL";
886 case AArch64ISD::NEG: return "AArch64ISD::NEG";
887 case AArch64ISD::EXTR: return "AArch64ISD::EXTR";
888 case AArch64ISD::ZIP1: return "AArch64ISD::ZIP1";
889 case AArch64ISD::ZIP2: return "AArch64ISD::ZIP2";
890 case AArch64ISD::UZP1: return "AArch64ISD::UZP1";
891 case AArch64ISD::UZP2: return "AArch64ISD::UZP2";
892 case AArch64ISD::TRN1: return "AArch64ISD::TRN1";
893 case AArch64ISD::TRN2: return "AArch64ISD::TRN2";
894 case AArch64ISD::REV16: return "AArch64ISD::REV16";
895 case AArch64ISD::REV32: return "AArch64ISD::REV32";
896 case AArch64ISD::REV64: return "AArch64ISD::REV64";
897 case AArch64ISD::EXT: return "AArch64ISD::EXT";
898 case AArch64ISD::VSHL: return "AArch64ISD::VSHL";
899 case AArch64ISD::VLSHR: return "AArch64ISD::VLSHR";
900 case AArch64ISD::VASHR: return "AArch64ISD::VASHR";
901 case AArch64ISD::CMEQ: return "AArch64ISD::CMEQ";
902 case AArch64ISD::CMGE: return "AArch64ISD::CMGE";
903 case AArch64ISD::CMGT: return "AArch64ISD::CMGT";
904 case AArch64ISD::CMHI: return "AArch64ISD::CMHI";
905 case AArch64ISD::CMHS: return "AArch64ISD::CMHS";
906 case AArch64ISD::FCMEQ: return "AArch64ISD::FCMEQ";
907 case AArch64ISD::FCMGE: return "AArch64ISD::FCMGE";
908 case AArch64ISD::FCMGT: return "AArch64ISD::FCMGT";
909 case AArch64ISD::CMEQz: return "AArch64ISD::CMEQz";
910 case AArch64ISD::CMGEz: return "AArch64ISD::CMGEz";
911 case AArch64ISD::CMGTz: return "AArch64ISD::CMGTz";
912 case AArch64ISD::CMLEz: return "AArch64ISD::CMLEz";
913 case AArch64ISD::CMLTz: return "AArch64ISD::CMLTz";
914 case AArch64ISD::FCMEQz: return "AArch64ISD::FCMEQz";
915 case AArch64ISD::FCMGEz: return "AArch64ISD::FCMGEz";
916 case AArch64ISD::FCMGTz: return "AArch64ISD::FCMGTz";
917 case AArch64ISD::FCMLEz: return "AArch64ISD::FCMLEz";
918 case AArch64ISD::FCMLTz: return "AArch64ISD::FCMLTz";
Ahmed Bougachafab58922015-03-10 20:45:38 +0000919 case AArch64ISD::SADDV: return "AArch64ISD::SADDV";
920 case AArch64ISD::UADDV: return "AArch64ISD::UADDV";
921 case AArch64ISD::SMINV: return "AArch64ISD::SMINV";
922 case AArch64ISD::UMINV: return "AArch64ISD::UMINV";
923 case AArch64ISD::SMAXV: return "AArch64ISD::SMAXV";
924 case AArch64ISD::UMAXV: return "AArch64ISD::UMAXV";
Tim Northover3b0846e2014-05-24 12:50:23 +0000925 case AArch64ISD::NOT: return "AArch64ISD::NOT";
926 case AArch64ISD::BIT: return "AArch64ISD::BIT";
927 case AArch64ISD::CBZ: return "AArch64ISD::CBZ";
928 case AArch64ISD::CBNZ: return "AArch64ISD::CBNZ";
929 case AArch64ISD::TBZ: return "AArch64ISD::TBZ";
930 case AArch64ISD::TBNZ: return "AArch64ISD::TBNZ";
931 case AArch64ISD::TC_RETURN: return "AArch64ISD::TC_RETURN";
Matthias Braund04893f2015-05-07 21:33:59 +0000932 case AArch64ISD::PREFETCH: return "AArch64ISD::PREFETCH";
Tim Northover3b0846e2014-05-24 12:50:23 +0000933 case AArch64ISD::SITOF: return "AArch64ISD::SITOF";
934 case AArch64ISD::UITOF: return "AArch64ISD::UITOF";
Asiri Rathnayake530b3ed2014-10-01 09:59:45 +0000935 case AArch64ISD::NVCAST: return "AArch64ISD::NVCAST";
Tim Northover3b0846e2014-05-24 12:50:23 +0000936 case AArch64ISD::SQSHL_I: return "AArch64ISD::SQSHL_I";
937 case AArch64ISD::UQSHL_I: return "AArch64ISD::UQSHL_I";
938 case AArch64ISD::SRSHR_I: return "AArch64ISD::SRSHR_I";
939 case AArch64ISD::URSHR_I: return "AArch64ISD::URSHR_I";
940 case AArch64ISD::SQSHLU_I: return "AArch64ISD::SQSHLU_I";
941 case AArch64ISD::WrapperLarge: return "AArch64ISD::WrapperLarge";
942 case AArch64ISD::LD2post: return "AArch64ISD::LD2post";
943 case AArch64ISD::LD3post: return "AArch64ISD::LD3post";
944 case AArch64ISD::LD4post: return "AArch64ISD::LD4post";
945 case AArch64ISD::ST2post: return "AArch64ISD::ST2post";
946 case AArch64ISD::ST3post: return "AArch64ISD::ST3post";
947 case AArch64ISD::ST4post: return "AArch64ISD::ST4post";
948 case AArch64ISD::LD1x2post: return "AArch64ISD::LD1x2post";
949 case AArch64ISD::LD1x3post: return "AArch64ISD::LD1x3post";
950 case AArch64ISD::LD1x4post: return "AArch64ISD::LD1x4post";
951 case AArch64ISD::ST1x2post: return "AArch64ISD::ST1x2post";
952 case AArch64ISD::ST1x3post: return "AArch64ISD::ST1x3post";
953 case AArch64ISD::ST1x4post: return "AArch64ISD::ST1x4post";
954 case AArch64ISD::LD1DUPpost: return "AArch64ISD::LD1DUPpost";
955 case AArch64ISD::LD2DUPpost: return "AArch64ISD::LD2DUPpost";
956 case AArch64ISD::LD3DUPpost: return "AArch64ISD::LD3DUPpost";
957 case AArch64ISD::LD4DUPpost: return "AArch64ISD::LD4DUPpost";
958 case AArch64ISD::LD1LANEpost: return "AArch64ISD::LD1LANEpost";
959 case AArch64ISD::LD2LANEpost: return "AArch64ISD::LD2LANEpost";
960 case AArch64ISD::LD3LANEpost: return "AArch64ISD::LD3LANEpost";
961 case AArch64ISD::LD4LANEpost: return "AArch64ISD::LD4LANEpost";
962 case AArch64ISD::ST2LANEpost: return "AArch64ISD::ST2LANEpost";
963 case AArch64ISD::ST3LANEpost: return "AArch64ISD::ST3LANEpost";
964 case AArch64ISD::ST4LANEpost: return "AArch64ISD::ST4LANEpost";
Chad Rosierd9d0f862014-10-08 02:31:24 +0000965 case AArch64ISD::SMULL: return "AArch64ISD::SMULL";
966 case AArch64ISD::UMULL: return "AArch64ISD::UMULL";
Tim Northover3b0846e2014-05-24 12:50:23 +0000967 }
Matthias Braund04893f2015-05-07 21:33:59 +0000968 return nullptr;
Tim Northover3b0846e2014-05-24 12:50:23 +0000969}
970
971MachineBasicBlock *
972AArch64TargetLowering::EmitF128CSEL(MachineInstr *MI,
973 MachineBasicBlock *MBB) const {
974 // We materialise the F128CSEL pseudo-instruction as some control flow and a
975 // phi node:
976
977 // OrigBB:
978 // [... previous instrs leading to comparison ...]
979 // b.ne TrueBB
980 // b EndBB
981 // TrueBB:
982 // ; Fallthrough
983 // EndBB:
984 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
985
Tim Northover3b0846e2014-05-24 12:50:23 +0000986 MachineFunction *MF = MBB->getParent();
Eric Christopher905f12d2015-01-29 00:19:42 +0000987 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +0000988 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
989 DebugLoc DL = MI->getDebugLoc();
Duncan P. N. Exon Smithd3b9df02015-10-13 20:02:15 +0000990 MachineFunction::iterator It = ++MBB->getIterator();
Tim Northover3b0846e2014-05-24 12:50:23 +0000991
992 unsigned DestReg = MI->getOperand(0).getReg();
993 unsigned IfTrueReg = MI->getOperand(1).getReg();
994 unsigned IfFalseReg = MI->getOperand(2).getReg();
995 unsigned CondCode = MI->getOperand(3).getImm();
996 bool NZCVKilled = MI->getOperand(4).isKill();
997
998 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
999 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
1000 MF->insert(It, TrueBB);
1001 MF->insert(It, EndBB);
1002
1003 // Transfer rest of current basic-block to EndBB
1004 EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
1005 MBB->end());
1006 EndBB->transferSuccessorsAndUpdatePHIs(MBB);
1007
1008 BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
1009 BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
1010 MBB->addSuccessor(TrueBB);
1011 MBB->addSuccessor(EndBB);
1012
1013 // TrueBB falls through to the end.
1014 TrueBB->addSuccessor(EndBB);
1015
1016 if (!NZCVKilled) {
1017 TrueBB->addLiveIn(AArch64::NZCV);
1018 EndBB->addLiveIn(AArch64::NZCV);
1019 }
1020
1021 BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
1022 .addReg(IfTrueReg)
1023 .addMBB(TrueBB)
1024 .addReg(IfFalseReg)
1025 .addMBB(MBB);
1026
1027 MI->eraseFromParent();
1028 return EndBB;
1029}
1030
1031MachineBasicBlock *
1032AArch64TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1033 MachineBasicBlock *BB) const {
1034 switch (MI->getOpcode()) {
1035 default:
1036#ifndef NDEBUG
1037 MI->dump();
1038#endif
Craig Topper35b2f752014-06-19 06:10:58 +00001039 llvm_unreachable("Unexpected instruction for custom inserter!");
Tim Northover3b0846e2014-05-24 12:50:23 +00001040
1041 case AArch64::F128CSEL:
1042 return EmitF128CSEL(MI, BB);
1043
1044 case TargetOpcode::STACKMAP:
1045 case TargetOpcode::PATCHPOINT:
1046 return emitPatchPoint(MI, BB);
1047 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001048}
1049
1050//===----------------------------------------------------------------------===//
1051// AArch64 Lowering private implementation.
1052//===----------------------------------------------------------------------===//
1053
1054//===----------------------------------------------------------------------===//
1055// Lowering Code
1056//===----------------------------------------------------------------------===//
1057
1058/// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1059/// CC
1060static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1061 switch (CC) {
1062 default:
1063 llvm_unreachable("Unknown condition code!");
1064 case ISD::SETNE:
1065 return AArch64CC::NE;
1066 case ISD::SETEQ:
1067 return AArch64CC::EQ;
1068 case ISD::SETGT:
1069 return AArch64CC::GT;
1070 case ISD::SETGE:
1071 return AArch64CC::GE;
1072 case ISD::SETLT:
1073 return AArch64CC::LT;
1074 case ISD::SETLE:
1075 return AArch64CC::LE;
1076 case ISD::SETUGT:
1077 return AArch64CC::HI;
1078 case ISD::SETUGE:
1079 return AArch64CC::HS;
1080 case ISD::SETULT:
1081 return AArch64CC::LO;
1082 case ISD::SETULE:
1083 return AArch64CC::LS;
1084 }
1085}
1086
1087/// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1088static void changeFPCCToAArch64CC(ISD::CondCode CC,
1089 AArch64CC::CondCode &CondCode,
1090 AArch64CC::CondCode &CondCode2) {
1091 CondCode2 = AArch64CC::AL;
1092 switch (CC) {
1093 default:
1094 llvm_unreachable("Unknown FP condition!");
1095 case ISD::SETEQ:
1096 case ISD::SETOEQ:
1097 CondCode = AArch64CC::EQ;
1098 break;
1099 case ISD::SETGT:
1100 case ISD::SETOGT:
1101 CondCode = AArch64CC::GT;
1102 break;
1103 case ISD::SETGE:
1104 case ISD::SETOGE:
1105 CondCode = AArch64CC::GE;
1106 break;
1107 case ISD::SETOLT:
1108 CondCode = AArch64CC::MI;
1109 break;
1110 case ISD::SETOLE:
1111 CondCode = AArch64CC::LS;
1112 break;
1113 case ISD::SETONE:
1114 CondCode = AArch64CC::MI;
1115 CondCode2 = AArch64CC::GT;
1116 break;
1117 case ISD::SETO:
1118 CondCode = AArch64CC::VC;
1119 break;
1120 case ISD::SETUO:
1121 CondCode = AArch64CC::VS;
1122 break;
1123 case ISD::SETUEQ:
1124 CondCode = AArch64CC::EQ;
1125 CondCode2 = AArch64CC::VS;
1126 break;
1127 case ISD::SETUGT:
1128 CondCode = AArch64CC::HI;
1129 break;
1130 case ISD::SETUGE:
1131 CondCode = AArch64CC::PL;
1132 break;
1133 case ISD::SETLT:
1134 case ISD::SETULT:
1135 CondCode = AArch64CC::LT;
1136 break;
1137 case ISD::SETLE:
1138 case ISD::SETULE:
1139 CondCode = AArch64CC::LE;
1140 break;
1141 case ISD::SETNE:
1142 case ISD::SETUNE:
1143 CondCode = AArch64CC::NE;
1144 break;
1145 }
1146}
1147
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001148/// Convert a DAG fp condition code to an AArch64 CC.
1149/// This differs from changeFPCCToAArch64CC in that it returns cond codes that
1150/// should be AND'ed instead of OR'ed.
1151static void changeFPCCToANDAArch64CC(ISD::CondCode CC,
1152 AArch64CC::CondCode &CondCode,
1153 AArch64CC::CondCode &CondCode2) {
1154 CondCode2 = AArch64CC::AL;
1155 switch (CC) {
1156 default:
1157 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1158 assert(CondCode2 == AArch64CC::AL);
1159 break;
1160 case ISD::SETONE:
1161 // (a one b)
1162 // == ((a olt b) || (a ogt b))
1163 // == ((a ord b) && (a une b))
1164 CondCode = AArch64CC::VC;
1165 CondCode2 = AArch64CC::NE;
1166 break;
1167 case ISD::SETUEQ:
1168 // (a ueq b)
1169 // == ((a uno b) || (a oeq b))
1170 // == ((a ule b) && (a uge b))
1171 CondCode = AArch64CC::PL;
1172 CondCode2 = AArch64CC::LE;
1173 break;
1174 }
1175}
1176
Tim Northover3b0846e2014-05-24 12:50:23 +00001177/// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1178/// CC usable with the vector instructions. Fewer operations are available
1179/// without a real NZCV register, so we have to use less efficient combinations
1180/// to get the same effect.
1181static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1182 AArch64CC::CondCode &CondCode,
1183 AArch64CC::CondCode &CondCode2,
1184 bool &Invert) {
1185 Invert = false;
1186 switch (CC) {
1187 default:
1188 // Mostly the scalar mappings work fine.
1189 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1190 break;
1191 case ISD::SETUO:
1192 Invert = true; // Fallthrough
1193 case ISD::SETO:
1194 CondCode = AArch64CC::MI;
1195 CondCode2 = AArch64CC::GE;
1196 break;
1197 case ISD::SETUEQ:
1198 case ISD::SETULT:
1199 case ISD::SETULE:
1200 case ISD::SETUGT:
1201 case ISD::SETUGE:
1202 // All of the compare-mask comparisons are ordered, but we can switch
1203 // between the two by a double inversion. E.g. ULE == !OGT.
1204 Invert = true;
1205 changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1206 break;
1207 }
1208}
1209
1210static bool isLegalArithImmed(uint64_t C) {
1211 // Matches AArch64DAGToDAGISel::SelectArithImmed().
1212 return (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1213}
1214
1215static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1216 SDLoc dl, SelectionDAG &DAG) {
1217 EVT VT = LHS.getValueType();
1218
1219 if (VT.isFloatingPoint())
1220 return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
1221
1222 // The CMP instruction is just an alias for SUBS, and representing it as
1223 // SUBS means that it's possible to get CSE with subtract operations.
1224 // A later phase can perform the optimization of setting the destination
1225 // register to WZR/XZR if it ends up being unused.
1226 unsigned Opcode = AArch64ISD::SUBS;
1227
Artyom Skrobov314ee042015-11-25 19:41:11 +00001228 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001229 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1230 // We'd like to combine a (CMP op1, (sub 0, op2) into a CMN instruction on
1231 // the grounds that "op1 - (-op2) == op1 + op2". However, the C and V flags
1232 // can be set differently by this operation. It comes down to whether
1233 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1234 // everything is fine. If not then the optimization is wrong. Thus general
1235 // comparisons are only valid if op2 != 0.
1236
1237 // So, finally, the only LLVM-native comparisons that don't mention C and V
1238 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1239 // the absence of information about op2.
1240 Opcode = AArch64ISD::ADDS;
1241 RHS = RHS.getOperand(1);
Artyom Skrobov314ee042015-11-25 19:41:11 +00001242 } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001243 !isUnsignedIntSetCC(CC)) {
1244 // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1245 // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1246 // of the signed comparisons.
1247 Opcode = AArch64ISD::ANDS;
1248 RHS = LHS.getOperand(1);
1249 LHS = LHS.getOperand(0);
1250 }
1251
Matthias Braunaf7d7702015-07-16 20:02:37 +00001252 return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
Tim Northover3b0846e2014-05-24 12:50:23 +00001253 .getValue(1);
1254}
1255
Matthias Braunaf7d7702015-07-16 20:02:37 +00001256/// \defgroup AArch64CCMP CMP;CCMP matching
1257///
1258/// These functions deal with the formation of CMP;CCMP;... sequences.
1259/// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1260/// a comparison. They set the NZCV flags to a predefined value if their
1261/// predicate is false. This allows to express arbitrary conjunctions, for
1262/// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B))))"
1263/// expressed as:
1264/// cmp A
1265/// ccmp B, inv(CB), CA
1266/// check for CB flags
1267///
1268/// In general we can create code for arbitrary "... (and (and A B) C)"
1269/// sequences. We can also implement some "or" expressions, because "(or A B)"
1270/// is equivalent to "not (and (not A) (not B))" and we can implement some
1271/// negation operations:
1272/// We can negate the results of a single comparison by inverting the flags
1273/// used when the predicate fails and inverting the flags tested in the next
1274/// instruction; We can also negate the results of the whole previous
1275/// conditional compare sequence by inverting the flags tested in the next
1276/// instruction. However there is no way to negate the result of a partial
1277/// sequence.
1278///
1279/// Therefore on encountering an "or" expression we can negate the subtree on
1280/// one side and have to be able to push the negate to the leafs of the subtree
1281/// on the other side (see also the comments in code). As complete example:
1282/// "or (or (setCA (cmp A)) (setCB (cmp B)))
1283/// (and (setCC (cmp C)) (setCD (cmp D)))"
1284/// is transformed to
1285/// "not (and (not (and (setCC (cmp C)) (setCC (cmp D))))
1286/// (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1287/// and implemented as:
1288/// cmp C
1289/// ccmp D, inv(CD), CC
1290/// ccmp A, CA, inv(CD)
1291/// ccmp B, CB, inv(CA)
1292/// check for CB flags
1293/// A counterexample is "or (and A B) (and C D)" which cannot be implemented
1294/// by conditional compare sequences.
1295/// @{
1296
Geoff Berrye41c2df2015-07-20 22:03:52 +00001297/// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001298static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1299 ISD::CondCode CC, SDValue CCOp,
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001300 AArch64CC::CondCode Predicate,
1301 AArch64CC::CondCode OutCC,
Matthias Braunaf7d7702015-07-16 20:02:37 +00001302 SDLoc DL, SelectionDAG &DAG) {
1303 unsigned Opcode = 0;
1304 if (LHS.getValueType().isFloatingPoint())
1305 Opcode = AArch64ISD::FCCMP;
1306 else if (RHS.getOpcode() == ISD::SUB) {
1307 SDValue SubOp0 = RHS.getOperand(0);
Artyom Skrobov314ee042015-11-25 19:41:11 +00001308 if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
Matthias Braunfd13c142016-01-23 04:05:16 +00001309 // See emitComparison() on why we can only do this for SETEQ and SETNE.
1310 Opcode = AArch64ISD::CCMN;
1311 RHS = RHS.getOperand(1);
1312 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001313 }
1314 if (Opcode == 0)
1315 Opcode = AArch64ISD::CCMP;
1316
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001317 SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC);
1318 AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1319 unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001320 SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1321 return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1322}
1323
1324/// Returns true if @p Val is a tree of AND/OR/SETCC operations.
1325/// CanPushNegate is set to true if we can push a negate operation through
1326/// the tree in a was that we are left with AND operations and negate operations
1327/// at the leafs only. i.e. "not (or (or x y) z)" can be changed to
1328/// "and (and (not x) (not y)) (not z)"; "not (or (and x y) z)" cannot be
1329/// brought into such a form.
Matthias Braunfdef49b2016-01-23 04:05:22 +00001330static bool isConjunctionDisjunctionTree(const SDValue Val, bool &CanNegate,
Matthias Braunaf7d7702015-07-16 20:02:37 +00001331 unsigned Depth = 0) {
1332 if (!Val.hasOneUse())
1333 return false;
1334 unsigned Opcode = Val->getOpcode();
1335 if (Opcode == ISD::SETCC) {
Matthias Braunfdef49b2016-01-23 04:05:22 +00001336 CanNegate = true;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001337 return true;
1338 }
Matthias Braun985bdf92016-01-23 04:05:18 +00001339 // Protect against exponential runtime and stack overflow.
1340 if (Depth > 6)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001341 return false;
1342 if (Opcode == ISD::AND || Opcode == ISD::OR) {
1343 SDValue O0 = Val->getOperand(0);
1344 SDValue O1 = Val->getOperand(1);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001345 bool CanNegateL;
1346 if (!isConjunctionDisjunctionTree(O0, CanNegateL, Depth+1))
Matthias Braunaf7d7702015-07-16 20:02:37 +00001347 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001348 bool CanNegateR;
1349 if (!isConjunctionDisjunctionTree(O1, CanNegateR, Depth+1))
Matthias Braunaf7d7702015-07-16 20:02:37 +00001350 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001351
1352 if (Opcode == ISD::OR) {
1353 // For an OR expression we need to be able to negate at least one side or
1354 // we cannot do the transformation at all.
1355 if (!CanNegateL && !CanNegateR)
1356 return false;
1357 // We can however change a (not (or x y)) to (and (not x) (not y)) if we
1358 // can negate the x and y subtrees.
1359 CanNegate = CanNegateL && CanNegateR;
1360 } else {
1361 // If the operands are OR expressions then we finally need to negate their
1362 // outputs, we can only do that for the operand with emitted last by
1363 // negating OutCC, not for both operands.
1364 bool NeedsNegOutL = O0->getOpcode() == ISD::OR;
1365 bool NeedsNegOutR = O1->getOpcode() == ISD::OR;
1366 if (NeedsNegOutL && NeedsNegOutR)
1367 return false;
1368 // We cannot negate an AND operation (it would become an OR),
1369 CanNegate = false;
1370 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001371 return true;
1372 }
1373 return false;
1374}
1375
1376/// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1377/// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1378/// Tries to transform the given i1 producing node @p Val to a series compare
1379/// and conditional compare operations. @returns an NZCV flags producing node
1380/// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1381/// transformation was not possible.
1382/// On recursive invocations @p PushNegate may be set to true to have negation
1383/// effects pushed to the tree leafs; @p Predicate is an NZCV flag predicate
1384/// for the comparisons in the current subtree; @p Depth limits the search
1385/// depth to avoid stack overflow.
Matthias Braunfdef49b2016-01-23 04:05:22 +00001386static SDValue emitConjunctionDisjunctionTreeRec(SelectionDAG &DAG, SDValue Val,
1387 AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp,
1388 AArch64CC::CondCode Predicate) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001389 // We're at a tree leaf, produce a conditional comparison operation.
1390 unsigned Opcode = Val->getOpcode();
1391 if (Opcode == ISD::SETCC) {
1392 SDValue LHS = Val->getOperand(0);
1393 SDValue RHS = Val->getOperand(1);
1394 ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1395 bool isInteger = LHS.getValueType().isInteger();
Matthias Braunfdef49b2016-01-23 04:05:22 +00001396 if (Negate)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001397 CC = getSetCCInverse(CC, isInteger);
1398 SDLoc DL(Val);
1399 // Determine OutCC and handle FP special case.
1400 if (isInteger) {
1401 OutCC = changeIntCCToAArch64CC(CC);
1402 } else {
1403 assert(LHS.getValueType().isFloatingPoint());
1404 AArch64CC::CondCode ExtraCC;
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001405 changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
1406 // Some floating point conditions can't be tested with a single condition
1407 // code. Construct an additional comparison in this case.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001408 if (ExtraCC != AArch64CC::AL) {
1409 SDValue ExtraCmp;
1410 if (!CCOp.getNode())
1411 ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001412 else
1413 ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate,
1414 ExtraCC, DL, DAG);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001415 CCOp = ExtraCmp;
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001416 Predicate = ExtraCC;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001417 }
1418 }
1419
1420 // Produce a normal comparison if we are first in the chain
Matthias Braunfdef49b2016-01-23 04:05:22 +00001421 if (!CCOp)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001422 return emitComparison(LHS, RHS, CC, DL, DAG);
1423 // Otherwise produce a ccmp.
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001424 return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL,
Matthias Braunaf7d7702015-07-16 20:02:37 +00001425 DAG);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001426 }
Junmo Park3ca3e192016-01-25 10:17:17 +00001427 assert((Opcode == ISD::AND || (Opcode == ISD::OR && Val->hasOneUse())) &&
1428 "Valid conjunction/disjunction tree");
Matthias Braunaf7d7702015-07-16 20:02:37 +00001429
1430 // Check if both sides can be transformed.
1431 SDValue LHS = Val->getOperand(0);
1432 SDValue RHS = Val->getOperand(1);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001433
Matthias Braunfdef49b2016-01-23 04:05:22 +00001434 // In case of an OR we need to negate our operands and the result.
1435 // (A v B) <=> not(not(A) ^ not(B))
1436 bool NegateOpsAndResult = Opcode == ISD::OR;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001437 // We can negate the results of all previous operations by inverting the
Matthias Braunfdef49b2016-01-23 04:05:22 +00001438 // predicate flags giving us a free negation for one side. The other side
1439 // must be negatable by itself.
1440 if (NegateOpsAndResult) {
1441 // See which side we can negate.
1442 bool CanNegateL;
1443 bool isValidL = isConjunctionDisjunctionTree(LHS, CanNegateL);
1444 assert(isValidL && "Valid conjunction/disjunction tree");
1445 (void)isValidL;
1446
1447#ifndef NDEBUG
1448 bool CanNegateR;
1449 bool isValidR = isConjunctionDisjunctionTree(RHS, CanNegateR);
1450 assert(isValidR && "Valid conjunction/disjunction tree");
1451 assert((CanNegateL || CanNegateR) && "Valid conjunction/disjunction tree");
1452#endif
1453
1454 // Order the side which we cannot negate to RHS so we can emit it first.
1455 if (!CanNegateL)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001456 std::swap(LHS, RHS);
Matthias Braun46e56392015-08-20 23:33:34 +00001457 } else {
1458 bool NeedsNegOutL = LHS->getOpcode() == ISD::OR;
Matthias Braun327bca72016-01-23 06:49:29 +00001459 assert((!NeedsNegOutL || RHS->getOpcode() != ISD::OR) &&
Matthias Braunfdef49b2016-01-23 04:05:22 +00001460 "Valid conjunction/disjunction tree");
Matthias Braun46e56392015-08-20 23:33:34 +00001461 // Order the side where we need to negate the output flags to RHS so it
1462 // gets emitted first.
1463 if (NeedsNegOutL)
1464 std::swap(LHS, RHS);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001465 }
1466
1467 // Emit RHS. If we want to negate the tree we only need to push a negate
1468 // through if we are already in a PushNegate case, otherwise we can negate
1469 // the "flags to test" afterwards.
1470 AArch64CC::CondCode RHSCC;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001471 SDValue CmpR = emitConjunctionDisjunctionTreeRec(DAG, RHS, RHSCC, Negate,
1472 CCOp, Predicate);
1473 if (NegateOpsAndResult && !Negate)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001474 RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001475 // Emit LHS. We may need to negate it.
1476 SDValue CmpL = emitConjunctionDisjunctionTreeRec(DAG, LHS, OutCC,
1477 NegateOpsAndResult, CmpR,
1478 RHSCC);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001479 // If we transformed an OR to and AND then we have to negate the result
Matthias Braunfdef49b2016-01-23 04:05:22 +00001480 // (or absorb the Negate parameter).
1481 if (NegateOpsAndResult && !Negate)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001482 OutCC = AArch64CC::getInvertedCondCode(OutCC);
1483 return CmpL;
1484}
1485
Matthias Braunfdef49b2016-01-23 04:05:22 +00001486/// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1487/// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1488/// \see emitConjunctionDisjunctionTreeRec().
1489static SDValue emitConjunctionDisjunctionTree(SelectionDAG &DAG, SDValue Val,
1490 AArch64CC::CondCode &OutCC) {
1491 bool CanNegate;
1492 if (!isConjunctionDisjunctionTree(Val, CanNegate))
1493 return SDValue();
1494
1495 return emitConjunctionDisjunctionTreeRec(DAG, Val, OutCC, false, SDValue(),
1496 AArch64CC::AL);
1497}
1498
Matthias Braunaf7d7702015-07-16 20:02:37 +00001499/// @}
1500
Tim Northover3b0846e2014-05-24 12:50:23 +00001501static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
1502 SDValue &AArch64cc, SelectionDAG &DAG, SDLoc dl) {
1503 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1504 EVT VT = RHS.getValueType();
1505 uint64_t C = RHSC->getZExtValue();
1506 if (!isLegalArithImmed(C)) {
1507 // Constant does not fit, try adjusting it by one?
1508 switch (CC) {
1509 default:
1510 break;
1511 case ISD::SETLT:
1512 case ISD::SETGE:
1513 if ((VT == MVT::i32 && C != 0x80000000 &&
1514 isLegalArithImmed((uint32_t)(C - 1))) ||
1515 (VT == MVT::i64 && C != 0x80000000ULL &&
1516 isLegalArithImmed(C - 1ULL))) {
1517 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1518 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001519 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001520 }
1521 break;
1522 case ISD::SETULT:
1523 case ISD::SETUGE:
1524 if ((VT == MVT::i32 && C != 0 &&
1525 isLegalArithImmed((uint32_t)(C - 1))) ||
1526 (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1527 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1528 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001529 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001530 }
1531 break;
1532 case ISD::SETLE:
1533 case ISD::SETGT:
Oliver Stannard269a275c2014-11-03 15:28:40 +00001534 if ((VT == MVT::i32 && C != INT32_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001535 isLegalArithImmed((uint32_t)(C + 1))) ||
Oliver Stannard269a275c2014-11-03 15:28:40 +00001536 (VT == MVT::i64 && C != INT64_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001537 isLegalArithImmed(C + 1ULL))) {
1538 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1539 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001540 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001541 }
1542 break;
1543 case ISD::SETULE:
1544 case ISD::SETUGT:
Oliver Stannard269a275c2014-11-03 15:28:40 +00001545 if ((VT == MVT::i32 && C != UINT32_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001546 isLegalArithImmed((uint32_t)(C + 1))) ||
Oliver Stannard269a275c2014-11-03 15:28:40 +00001547 (VT == MVT::i64 && C != UINT64_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001548 isLegalArithImmed(C + 1ULL))) {
1549 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1550 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001551 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001552 }
1553 break;
1554 }
1555 }
1556 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001557 SDValue Cmp;
1558 AArch64CC::CondCode AArch64CC;
David Xuee978202014-08-28 04:59:53 +00001559 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001560 const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
1561
1562 // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
1563 // For the i8 operand, the largest immediate is 255, so this can be easily
1564 // encoded in the compare instruction. For the i16 operand, however, the
1565 // largest immediate cannot be encoded in the compare.
1566 // Therefore, use a sign extending load and cmn to avoid materializing the
1567 // -1 constant. For example,
1568 // movz w1, #65535
1569 // ldrh w0, [x0, #0]
1570 // cmp w0, w1
1571 // >
1572 // ldrsh w0, [x0, #0]
1573 // cmn w0, #1
1574 // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
1575 // if and only if (sext LHS) == (sext RHS). The checks are in place to
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001576 // ensure both the LHS and RHS are truly zero extended and to make sure the
Matthias Braunaf7d7702015-07-16 20:02:37 +00001577 // transformation is profitable.
1578 if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
1579 cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
1580 cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
1581 LHS.getNode()->hasNUsesOfValue(1, 0)) {
1582 int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
1583 if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
1584 SDValue SExt =
1585 DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
1586 DAG.getValueType(MVT::i16));
1587 Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
1588 RHS.getValueType()),
1589 CC, dl, DAG);
1590 AArch64CC = changeIntCCToAArch64CC(CC);
1591 }
1592 }
1593
1594 if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
1595 if ((Cmp = emitConjunctionDisjunctionTree(DAG, LHS, AArch64CC))) {
1596 if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
1597 AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
David Xuee978202014-08-28 04:59:53 +00001598 }
1599 }
1600 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001601
1602 if (!Cmp) {
1603 Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
1604 AArch64CC = changeIntCCToAArch64CC(CC);
1605 }
1606 AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
Tim Northover3b0846e2014-05-24 12:50:23 +00001607 return Cmp;
1608}
1609
Balaram Makam92431702016-02-01 19:13:07 +00001610// Attempt to form conditional compare sequences for and/or trees
1611// with setcc leafs.
1612static SDValue tryLowerToAArch64Cmp(SDValue Op, SelectionDAG &DAG) {
1613 SDValue LHS = Op.getOperand(0);
1614 SDValue RHS = Op.getOperand(1);
1615 if ((LHS.getOpcode() != ISD::SETCC) || (RHS.getOpcode() != ISD::SETCC))
1616 return Op;
1617
1618 bool CanNegate;
1619 if (!isConjunctionDisjunctionTree(Op, CanNegate))
1620 return SDValue();
1621
1622 EVT VT = Op.getValueType();
1623 SDLoc DL(Op);
1624 SDValue TVal = DAG.getConstant(1, DL, VT);
1625 SDValue FVal = DAG.getConstant(0, DL, VT);
1626 SDValue CCVal;
1627 SDValue Cmp = getAArch64Cmp(Op, FVal, ISD::SETEQ, CCVal, DAG, DL);
1628 return DAG.getNode(AArch64ISD::CSEL, DL, VT, FVal, TVal, CCVal, Cmp);
1629}
1630
Tim Northover3b0846e2014-05-24 12:50:23 +00001631static std::pair<SDValue, SDValue>
1632getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
1633 assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
1634 "Unsupported value type");
1635 SDValue Value, Overflow;
1636 SDLoc DL(Op);
1637 SDValue LHS = Op.getOperand(0);
1638 SDValue RHS = Op.getOperand(1);
1639 unsigned Opc = 0;
1640 switch (Op.getOpcode()) {
1641 default:
1642 llvm_unreachable("Unknown overflow instruction!");
1643 case ISD::SADDO:
1644 Opc = AArch64ISD::ADDS;
1645 CC = AArch64CC::VS;
1646 break;
1647 case ISD::UADDO:
1648 Opc = AArch64ISD::ADDS;
1649 CC = AArch64CC::HS;
1650 break;
1651 case ISD::SSUBO:
1652 Opc = AArch64ISD::SUBS;
1653 CC = AArch64CC::VS;
1654 break;
1655 case ISD::USUBO:
1656 Opc = AArch64ISD::SUBS;
1657 CC = AArch64CC::LO;
1658 break;
1659 // Multiply needs a little bit extra work.
1660 case ISD::SMULO:
1661 case ISD::UMULO: {
1662 CC = AArch64CC::NE;
David Blaikie186d2cb2015-03-24 16:24:01 +00001663 bool IsSigned = Op.getOpcode() == ISD::SMULO;
Tim Northover3b0846e2014-05-24 12:50:23 +00001664 if (Op.getValueType() == MVT::i32) {
1665 unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1666 // For a 32 bit multiply with overflow check we want the instruction
1667 // selector to generate a widening multiply (SMADDL/UMADDL). For that we
1668 // need to generate the following pattern:
1669 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
1670 LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
1671 RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
1672 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1673 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001674 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001675 // On AArch64 the upper 32 bits are always zero extended for a 32 bit
1676 // operation. We need to clear out the upper 32 bits, because we used a
1677 // widening multiply that wrote all 64 bits. In the end this should be a
1678 // noop.
1679 Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
1680 if (IsSigned) {
1681 // The signed overflow check requires more than just a simple check for
1682 // any bit set in the upper 32 bits of the result. These bits could be
1683 // just the sign bits of a negative number. To perform the overflow
1684 // check we have to arithmetic shift right the 32nd bit of the result by
1685 // 31 bits. Then we compare the result to the upper 32 bits.
1686 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001687 DAG.getConstant(32, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001688 UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
1689 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001690 DAG.getConstant(31, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001691 // It is important that LowerBits is last, otherwise the arithmetic
1692 // shift will not be folded into the compare (SUBS).
1693 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
1694 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1695 .getValue(1);
1696 } else {
1697 // The overflow check for unsigned multiply is easy. We only need to
1698 // check if any of the upper 32 bits are set. This can be done with a
1699 // CMP (shifted register). For that we need to generate the following
1700 // pattern:
1701 // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
1702 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001703 DAG.getConstant(32, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001704 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1705 Overflow =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001706 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1707 DAG.getConstant(0, DL, MVT::i64),
Tim Northover3b0846e2014-05-24 12:50:23 +00001708 UpperBits).getValue(1);
1709 }
1710 break;
1711 }
1712 assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
1713 // For the 64 bit multiply
1714 Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1715 if (IsSigned) {
1716 SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
1717 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001718 DAG.getConstant(63, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001719 // It is important that LowerBits is last, otherwise the arithmetic
1720 // shift will not be folded into the compare (SUBS).
1721 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1722 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1723 .getValue(1);
1724 } else {
1725 SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
1726 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1727 Overflow =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001728 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1729 DAG.getConstant(0, DL, MVT::i64),
Tim Northover3b0846e2014-05-24 12:50:23 +00001730 UpperBits).getValue(1);
1731 }
1732 break;
1733 }
1734 } // switch (...)
1735
1736 if (Opc) {
1737 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
1738
1739 // Emit the AArch64 operation with overflow check.
1740 Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
1741 Overflow = Value.getValue(1);
1742 }
1743 return std::make_pair(Value, Overflow);
1744}
1745
1746SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
1747 RTLIB::Libcall Call) const {
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00001748 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
Craig Topper8fe40e02015-10-22 17:05:00 +00001749 return makeLibCall(DAG, Call, MVT::f128, Ops, false, SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00001750}
1751
Balaram Makam92431702016-02-01 19:13:07 +00001752SDValue AArch64TargetLowering::LowerAND(SDValue Op, SelectionDAG &DAG) const {
1753 if (Op.getValueType().isVector())
1754 return LowerVectorAND(Op, DAG);
1755 return tryLowerToAArch64Cmp(Op, DAG);
1756}
1757
1758SDValue AArch64TargetLowering::LowerOR(SDValue Op, SelectionDAG &DAG) const {
1759 if (Op.getValueType().isVector())
1760 return LowerVectorOR(Op, DAG);
1761 return tryLowerToAArch64Cmp(Op, DAG);
1762}
1763
Tim Northover3b0846e2014-05-24 12:50:23 +00001764static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
1765 SDValue Sel = Op.getOperand(0);
1766 SDValue Other = Op.getOperand(1);
1767
1768 // If neither operand is a SELECT_CC, give up.
1769 if (Sel.getOpcode() != ISD::SELECT_CC)
1770 std::swap(Sel, Other);
1771 if (Sel.getOpcode() != ISD::SELECT_CC)
1772 return Op;
1773
1774 // The folding we want to perform is:
1775 // (xor x, (select_cc a, b, cc, 0, -1) )
1776 // -->
1777 // (csel x, (xor x, -1), cc ...)
1778 //
1779 // The latter will get matched to a CSINV instruction.
1780
1781 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
1782 SDValue LHS = Sel.getOperand(0);
1783 SDValue RHS = Sel.getOperand(1);
1784 SDValue TVal = Sel.getOperand(2);
1785 SDValue FVal = Sel.getOperand(3);
1786 SDLoc dl(Sel);
1787
1788 // FIXME: This could be generalized to non-integer comparisons.
1789 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
1790 return Op;
1791
1792 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
1793 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
1794
Eric Christopher572e03a2015-06-19 01:53:21 +00001795 // The values aren't constants, this isn't the pattern we're looking for.
Tim Northover3b0846e2014-05-24 12:50:23 +00001796 if (!CFVal || !CTVal)
1797 return Op;
1798
1799 // We can commute the SELECT_CC by inverting the condition. This
1800 // might be needed to make this fit into a CSINV pattern.
1801 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
1802 std::swap(TVal, FVal);
1803 std::swap(CTVal, CFVal);
1804 CC = ISD::getSetCCInverse(CC, true);
1805 }
1806
1807 // If the constants line up, perform the transform!
1808 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
1809 SDValue CCVal;
1810 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
1811
1812 FVal = Other;
1813 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001814 DAG.getConstant(-1ULL, dl, Other.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00001815
1816 return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
1817 CCVal, Cmp);
1818 }
1819
1820 return Op;
1821}
1822
1823static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
1824 EVT VT = Op.getValueType();
1825
1826 // Let legalize expand this if it isn't a legal type yet.
1827 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
1828 return SDValue();
1829
1830 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
1831
1832 unsigned Opc;
1833 bool ExtraOp = false;
1834 switch (Op.getOpcode()) {
1835 default:
Craig Topper2a30d782014-06-18 05:05:13 +00001836 llvm_unreachable("Invalid code");
Tim Northover3b0846e2014-05-24 12:50:23 +00001837 case ISD::ADDC:
1838 Opc = AArch64ISD::ADDS;
1839 break;
1840 case ISD::SUBC:
1841 Opc = AArch64ISD::SUBS;
1842 break;
1843 case ISD::ADDE:
1844 Opc = AArch64ISD::ADCS;
1845 ExtraOp = true;
1846 break;
1847 case ISD::SUBE:
1848 Opc = AArch64ISD::SBCS;
1849 ExtraOp = true;
1850 break;
1851 }
1852
1853 if (!ExtraOp)
1854 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
1855 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
1856 Op.getOperand(2));
1857}
1858
1859static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
1860 // Let legalize expand this if it isn't a legal type yet.
1861 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
1862 return SDValue();
1863
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001864 SDLoc dl(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00001865 AArch64CC::CondCode CC;
1866 // The actual operation that sets the overflow or carry flag.
1867 SDValue Value, Overflow;
1868 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
1869
1870 // We use 0 and 1 as false and true values.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001871 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
1872 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00001873
1874 // We use an inverted condition, because the conditional select is inverted
1875 // too. This will allow it to be selected to a single instruction:
1876 // CSINC Wd, WZR, WZR, invert(cond).
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001877 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
1878 Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
Tim Northover3b0846e2014-05-24 12:50:23 +00001879 CCVal, Overflow);
1880
1881 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001882 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
Tim Northover3b0846e2014-05-24 12:50:23 +00001883}
1884
1885// Prefetch operands are:
1886// 1: Address to prefetch
1887// 2: bool isWrite
1888// 3: int locality (0 = no locality ... 3 = extreme locality)
1889// 4: bool isDataCache
1890static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
1891 SDLoc DL(Op);
1892 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
1893 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
Yi Konge56de692014-08-05 12:46:47 +00001894 unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00001895
1896 bool IsStream = !Locality;
1897 // When the locality number is set
1898 if (Locality) {
1899 // The front-end should have filtered out the out-of-range values
1900 assert(Locality <= 3 && "Prefetch locality out-of-range");
1901 // The locality degree is the opposite of the cache speed.
1902 // Put the number the other way around.
1903 // The encoding starts at 0 for level 1
1904 Locality = 3 - Locality;
1905 }
1906
1907 // built the mask value encoding the expected behavior.
1908 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit
Yi Konge56de692014-08-05 12:46:47 +00001909 (!IsData << 3) | // IsDataCache bit
Tim Northover3b0846e2014-05-24 12:50:23 +00001910 (Locality << 1) | // Cache level bits
1911 (unsigned)IsStream; // Stream bit
1912 return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001913 DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00001914}
1915
1916SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
1917 SelectionDAG &DAG) const {
1918 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
1919
1920 RTLIB::Libcall LC;
1921 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
1922
1923 return LowerF128Call(Op, DAG, LC);
1924}
1925
1926SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
1927 SelectionDAG &DAG) const {
1928 if (Op.getOperand(0).getValueType() != MVT::f128) {
1929 // It's legal except when f128 is involved
1930 return Op;
1931 }
1932
1933 RTLIB::Libcall LC;
1934 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
1935
1936 // FP_ROUND node has a second operand indicating whether it is known to be
1937 // precise. That doesn't take part in the LibCall so we can't directly use
1938 // LowerF128Call.
1939 SDValue SrcVal = Op.getOperand(0);
Craig Topper8fe40e02015-10-22 17:05:00 +00001940 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
1941 SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00001942}
1943
1944static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
1945 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1946 // Any additional optimization in this function should be recorded
1947 // in the cost tables.
1948 EVT InVT = Op.getOperand(0).getValueType();
1949 EVT VT = Op.getValueType();
Pirama Arumuga Nainar1317d5f2015-12-10 17:16:49 +00001950 unsigned NumElts = InVT.getVectorNumElements();
1951
1952 // f16 vectors are promoted to f32 before a conversion.
1953 if (InVT.getVectorElementType() == MVT::f16) {
1954 MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
1955 SDLoc dl(Op);
1956 return DAG.getNode(
1957 Op.getOpcode(), dl, Op.getValueType(),
1958 DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
1959 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001960
Tim Northoverdbecc3b2014-06-15 09:27:15 +00001961 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001962 SDLoc dl(Op);
1963 SDValue Cv =
1964 DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
1965 Op.getOperand(0));
1966 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
Tim Northoverdbecc3b2014-06-15 09:27:15 +00001967 }
1968
1969 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001970 SDLoc dl(Op);
Oliver Stannard89d15422014-08-27 16:16:04 +00001971 MVT ExtVT =
1972 MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
1973 VT.getVectorNumElements());
1974 SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
Tim Northover3b0846e2014-05-24 12:50:23 +00001975 return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
1976 }
1977
1978 // Type changing conversions are illegal.
Tim Northoverdbecc3b2014-06-15 09:27:15 +00001979 return Op;
Tim Northover3b0846e2014-05-24 12:50:23 +00001980}
1981
1982SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
1983 SelectionDAG &DAG) const {
1984 if (Op.getOperand(0).getValueType().isVector())
1985 return LowerVectorFP_TO_INT(Op, DAG);
1986
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00001987 // f16 conversions are promoted to f32.
1988 if (Op.getOperand(0).getValueType() == MVT::f16) {
1989 SDLoc dl(Op);
1990 return DAG.getNode(
1991 Op.getOpcode(), dl, Op.getValueType(),
1992 DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
1993 }
1994
Tim Northover3b0846e2014-05-24 12:50:23 +00001995 if (Op.getOperand(0).getValueType() != MVT::f128) {
1996 // It's legal except when f128 is involved
1997 return Op;
1998 }
1999
2000 RTLIB::Libcall LC;
2001 if (Op.getOpcode() == ISD::FP_TO_SINT)
2002 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
2003 else
2004 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
2005
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002006 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
Craig Topper8fe40e02015-10-22 17:05:00 +00002007 return makeLibCall(DAG, LC, Op.getValueType(), Ops, false, SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00002008}
2009
2010static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
2011 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2012 // Any additional optimization in this function should be recorded
2013 // in the cost tables.
2014 EVT VT = Op.getValueType();
2015 SDLoc dl(Op);
2016 SDValue In = Op.getOperand(0);
2017 EVT InVT = In.getValueType();
2018
Tim Northoveref0d7602014-06-15 09:27:06 +00002019 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2020 MVT CastVT =
2021 MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
2022 InVT.getVectorNumElements());
2023 In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002024 return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
Tim Northover3b0846e2014-05-24 12:50:23 +00002025 }
2026
Tim Northoveref0d7602014-06-15 09:27:06 +00002027 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2028 unsigned CastOpc =
2029 Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2030 EVT CastVT = VT.changeVectorElementTypeToInteger();
2031 In = DAG.getNode(CastOpc, dl, CastVT, In);
2032 return DAG.getNode(Op.getOpcode(), dl, VT, In);
Tim Northover3b0846e2014-05-24 12:50:23 +00002033 }
2034
Tim Northoveref0d7602014-06-15 09:27:06 +00002035 return Op;
Tim Northover3b0846e2014-05-24 12:50:23 +00002036}
2037
2038SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
2039 SelectionDAG &DAG) const {
2040 if (Op.getValueType().isVector())
2041 return LowerVectorINT_TO_FP(Op, DAG);
2042
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00002043 // f16 conversions are promoted to f32.
2044 if (Op.getValueType() == MVT::f16) {
2045 SDLoc dl(Op);
2046 return DAG.getNode(
2047 ISD::FP_ROUND, dl, MVT::f16,
2048 DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002049 DAG.getIntPtrConstant(0, dl));
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00002050 }
2051
Tim Northover3b0846e2014-05-24 12:50:23 +00002052 // i128 conversions are libcalls.
2053 if (Op.getOperand(0).getValueType() == MVT::i128)
2054 return SDValue();
2055
2056 // Other conversions are legal, unless it's to the completely software-based
2057 // fp128.
2058 if (Op.getValueType() != MVT::f128)
2059 return Op;
2060
2061 RTLIB::Libcall LC;
2062 if (Op.getOpcode() == ISD::SINT_TO_FP)
2063 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2064 else
2065 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2066
2067 return LowerF128Call(Op, DAG, LC);
2068}
2069
2070SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
2071 SelectionDAG &DAG) const {
2072 // For iOS, we want to call an alternative entry point: __sincos_stret,
2073 // which returns the values in two S / D registers.
2074 SDLoc dl(Op);
2075 SDValue Arg = Op.getOperand(0);
2076 EVT ArgVT = Arg.getValueType();
2077 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2078
2079 ArgListTy Args;
2080 ArgListEntry Entry;
2081
2082 Entry.Node = Arg;
2083 Entry.Ty = ArgTy;
2084 Entry.isSExt = false;
2085 Entry.isZExt = false;
2086 Args.push_back(Entry);
2087
2088 const char *LibcallName =
2089 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
Mehdi Amini44ede332015-07-09 02:09:04 +00002090 SDValue Callee =
2091 DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00002092
Reid Kleckner343c3952014-11-20 23:51:47 +00002093 StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
Tim Northover3b0846e2014-05-24 12:50:23 +00002094 TargetLowering::CallLoweringInfo CLI(DAG);
2095 CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
Juergen Ributzka3bd03c72014-07-01 22:01:54 +00002096 .setCallee(CallingConv::Fast, RetTy, Callee, std::move(Args), 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00002097
2098 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2099 return CallResult.first;
2100}
2101
Tim Northoverf8bfe212014-07-18 13:07:05 +00002102static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
2103 if (Op.getValueType() != MVT::f16)
2104 return SDValue();
2105
2106 assert(Op.getOperand(0).getValueType() == MVT::i16);
2107 SDLoc DL(Op);
2108
2109 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
2110 Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
2111 return SDValue(
2112 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002113 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
Tim Northoverf8bfe212014-07-18 13:07:05 +00002114 0);
2115}
2116
Chad Rosierd9d0f862014-10-08 02:31:24 +00002117static EVT getExtensionTo64Bits(const EVT &OrigVT) {
2118 if (OrigVT.getSizeInBits() >= 64)
2119 return OrigVT;
2120
2121 assert(OrigVT.isSimple() && "Expecting a simple value type");
2122
2123 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
2124 switch (OrigSimpleTy) {
2125 default: llvm_unreachable("Unexpected Vector Type");
2126 case MVT::v2i8:
2127 case MVT::v2i16:
2128 return MVT::v2i32;
2129 case MVT::v4i8:
2130 return MVT::v4i16;
2131 }
2132}
2133
2134static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2135 const EVT &OrigTy,
2136 const EVT &ExtTy,
2137 unsigned ExtOpcode) {
2138 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2139 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2140 // 64-bits we need to insert a new extension so that it will be 64-bits.
2141 assert(ExtTy.is128BitVector() && "Unexpected extension size");
2142 if (OrigTy.getSizeInBits() >= 64)
2143 return N;
2144
2145 // Must extend size to at least 64 bits to be used as an operand for VMULL.
2146 EVT NewVT = getExtensionTo64Bits(OrigTy);
2147
2148 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2149}
2150
2151static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2152 bool isSigned) {
2153 EVT VT = N->getValueType(0);
2154
2155 if (N->getOpcode() != ISD::BUILD_VECTOR)
2156 return false;
2157
Pete Cooper3af9a252015-06-26 18:17:36 +00002158 for (const SDValue &Elt : N->op_values()) {
Chad Rosierd9d0f862014-10-08 02:31:24 +00002159 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
2160 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
2161 unsigned HalfSize = EltSize / 2;
2162 if (isSigned) {
2163 if (!isIntN(HalfSize, C->getSExtValue()))
2164 return false;
2165 } else {
2166 if (!isUIntN(HalfSize, C->getZExtValue()))
2167 return false;
2168 }
2169 continue;
2170 }
2171 return false;
2172 }
2173
2174 return true;
2175}
2176
2177static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2178 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2179 return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2180 N->getOperand(0)->getValueType(0),
2181 N->getValueType(0),
2182 N->getOpcode());
2183
2184 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2185 EVT VT = N->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002186 SDLoc dl(N);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002187 unsigned EltSize = VT.getVectorElementType().getSizeInBits() / 2;
2188 unsigned NumElts = VT.getVectorNumElements();
2189 MVT TruncVT = MVT::getIntegerVT(EltSize);
2190 SmallVector<SDValue, 8> Ops;
2191 for (unsigned i = 0; i != NumElts; ++i) {
2192 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2193 const APInt &CInt = C->getAPIntValue();
2194 // Element types smaller than 32 bits are not legal, so use i32 elements.
2195 // The values are implicitly truncated so sext vs. zext doesn't matter.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002196 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
Chad Rosierd9d0f862014-10-08 02:31:24 +00002197 }
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002198 return DAG.getNode(ISD::BUILD_VECTOR, dl,
Chad Rosierd9d0f862014-10-08 02:31:24 +00002199 MVT::getVectorVT(TruncVT, NumElts), Ops);
2200}
2201
2202static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
2203 if (N->getOpcode() == ISD::SIGN_EXTEND)
2204 return true;
2205 if (isExtendedBUILD_VECTOR(N, DAG, true))
2206 return true;
2207 return false;
2208}
2209
2210static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
2211 if (N->getOpcode() == ISD::ZERO_EXTEND)
2212 return true;
2213 if (isExtendedBUILD_VECTOR(N, DAG, false))
2214 return true;
2215 return false;
2216}
2217
2218static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2219 unsigned Opcode = N->getOpcode();
2220 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2221 SDNode *N0 = N->getOperand(0).getNode();
2222 SDNode *N1 = N->getOperand(1).getNode();
2223 return N0->hasOneUse() && N1->hasOneUse() &&
2224 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2225 }
2226 return false;
2227}
2228
2229static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2230 unsigned Opcode = N->getOpcode();
2231 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2232 SDNode *N0 = N->getOperand(0).getNode();
2233 SDNode *N1 = N->getOperand(1).getNode();
2234 return N0->hasOneUse() && N1->hasOneUse() &&
2235 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2236 }
2237 return false;
2238}
2239
2240static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2241 // Multiplications are only custom-lowered for 128-bit vectors so that
2242 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
2243 EVT VT = Op.getValueType();
2244 assert(VT.is128BitVector() && VT.isInteger() &&
2245 "unexpected type for custom-lowering ISD::MUL");
2246 SDNode *N0 = Op.getOperand(0).getNode();
2247 SDNode *N1 = Op.getOperand(1).getNode();
2248 unsigned NewOpc = 0;
2249 bool isMLA = false;
2250 bool isN0SExt = isSignExtended(N0, DAG);
2251 bool isN1SExt = isSignExtended(N1, DAG);
2252 if (isN0SExt && isN1SExt)
2253 NewOpc = AArch64ISD::SMULL;
2254 else {
2255 bool isN0ZExt = isZeroExtended(N0, DAG);
2256 bool isN1ZExt = isZeroExtended(N1, DAG);
2257 if (isN0ZExt && isN1ZExt)
2258 NewOpc = AArch64ISD::UMULL;
2259 else if (isN1SExt || isN1ZExt) {
2260 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2261 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2262 if (isN1SExt && isAddSubSExt(N0, DAG)) {
2263 NewOpc = AArch64ISD::SMULL;
2264 isMLA = true;
2265 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2266 NewOpc = AArch64ISD::UMULL;
2267 isMLA = true;
2268 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2269 std::swap(N0, N1);
2270 NewOpc = AArch64ISD::UMULL;
2271 isMLA = true;
2272 }
2273 }
2274
2275 if (!NewOpc) {
2276 if (VT == MVT::v2i64)
2277 // Fall through to expand this. It is not legal.
2278 return SDValue();
2279 else
2280 // Other vector multiplications are legal.
2281 return Op;
2282 }
2283 }
2284
2285 // Legalize to a S/UMULL instruction
2286 SDLoc DL(Op);
2287 SDValue Op0;
2288 SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2289 if (!isMLA) {
2290 Op0 = skipExtensionForVectorMULL(N0, DAG);
2291 assert(Op0.getValueType().is64BitVector() &&
2292 Op1.getValueType().is64BitVector() &&
2293 "unexpected types for extended operands to VMULL");
2294 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2295 }
2296 // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2297 // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2298 // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2299 SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2300 SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2301 EVT Op1VT = Op1.getValueType();
2302 return DAG.getNode(N0->getOpcode(), DL, VT,
2303 DAG.getNode(NewOpc, DL, VT,
2304 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2305 DAG.getNode(NewOpc, DL, VT,
2306 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2307}
Tim Northoverf8bfe212014-07-18 13:07:05 +00002308
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002309SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2310 SelectionDAG &DAG) const {
2311 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2312 SDLoc dl(Op);
2313 switch (IntNo) {
2314 default: return SDValue(); // Don't custom lower most intrinsics.
2315 case Intrinsic::aarch64_thread_pointer: {
2316 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2317 return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
2318 }
Silviu Barangadb1ddb32015-08-26 11:11:14 +00002319 case Intrinsic::aarch64_neon_smax:
2320 return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
2321 Op.getOperand(1), Op.getOperand(2));
2322 case Intrinsic::aarch64_neon_umax:
2323 return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
2324 Op.getOperand(1), Op.getOperand(2));
2325 case Intrinsic::aarch64_neon_smin:
2326 return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
2327 Op.getOperand(1), Op.getOperand(2));
2328 case Intrinsic::aarch64_neon_umin:
2329 return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
2330 Op.getOperand(1), Op.getOperand(2));
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002331 }
2332}
2333
Tim Northover3b0846e2014-05-24 12:50:23 +00002334SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
2335 SelectionDAG &DAG) const {
2336 switch (Op.getOpcode()) {
2337 default:
2338 llvm_unreachable("unimplemented operand");
2339 return SDValue();
Tim Northoverf8bfe212014-07-18 13:07:05 +00002340 case ISD::BITCAST:
2341 return LowerBITCAST(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002342 case ISD::GlobalAddress:
2343 return LowerGlobalAddress(Op, DAG);
2344 case ISD::GlobalTLSAddress:
2345 return LowerGlobalTLSAddress(Op, DAG);
2346 case ISD::SETCC:
2347 return LowerSETCC(Op, DAG);
2348 case ISD::BR_CC:
2349 return LowerBR_CC(Op, DAG);
2350 case ISD::SELECT:
2351 return LowerSELECT(Op, DAG);
2352 case ISD::SELECT_CC:
2353 return LowerSELECT_CC(Op, DAG);
2354 case ISD::JumpTable:
2355 return LowerJumpTable(Op, DAG);
2356 case ISD::ConstantPool:
2357 return LowerConstantPool(Op, DAG);
2358 case ISD::BlockAddress:
2359 return LowerBlockAddress(Op, DAG);
2360 case ISD::VASTART:
2361 return LowerVASTART(Op, DAG);
2362 case ISD::VACOPY:
2363 return LowerVACOPY(Op, DAG);
2364 case ISD::VAARG:
2365 return LowerVAARG(Op, DAG);
2366 case ISD::ADDC:
2367 case ISD::ADDE:
2368 case ISD::SUBC:
2369 case ISD::SUBE:
2370 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
2371 case ISD::SADDO:
2372 case ISD::UADDO:
2373 case ISD::SSUBO:
2374 case ISD::USUBO:
2375 case ISD::SMULO:
2376 case ISD::UMULO:
2377 return LowerXALUO(Op, DAG);
2378 case ISD::FADD:
2379 return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
2380 case ISD::FSUB:
2381 return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
2382 case ISD::FMUL:
2383 return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
2384 case ISD::FDIV:
2385 return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
2386 case ISD::FP_ROUND:
2387 return LowerFP_ROUND(Op, DAG);
2388 case ISD::FP_EXTEND:
2389 return LowerFP_EXTEND(Op, DAG);
2390 case ISD::FRAMEADDR:
2391 return LowerFRAMEADDR(Op, DAG);
2392 case ISD::RETURNADDR:
2393 return LowerRETURNADDR(Op, DAG);
2394 case ISD::INSERT_VECTOR_ELT:
2395 return LowerINSERT_VECTOR_ELT(Op, DAG);
2396 case ISD::EXTRACT_VECTOR_ELT:
2397 return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2398 case ISD::BUILD_VECTOR:
2399 return LowerBUILD_VECTOR(Op, DAG);
2400 case ISD::VECTOR_SHUFFLE:
2401 return LowerVECTOR_SHUFFLE(Op, DAG);
2402 case ISD::EXTRACT_SUBVECTOR:
2403 return LowerEXTRACT_SUBVECTOR(Op, DAG);
2404 case ISD::SRA:
2405 case ISD::SRL:
2406 case ISD::SHL:
2407 return LowerVectorSRA_SRL_SHL(Op, DAG);
2408 case ISD::SHL_PARTS:
2409 return LowerShiftLeftParts(Op, DAG);
2410 case ISD::SRL_PARTS:
2411 case ISD::SRA_PARTS:
2412 return LowerShiftRightParts(Op, DAG);
2413 case ISD::CTPOP:
2414 return LowerCTPOP(Op, DAG);
2415 case ISD::FCOPYSIGN:
2416 return LowerFCOPYSIGN(Op, DAG);
2417 case ISD::AND:
Balaram Makam92431702016-02-01 19:13:07 +00002418 return LowerAND(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002419 case ISD::OR:
Balaram Makam92431702016-02-01 19:13:07 +00002420 return LowerOR(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002421 case ISD::XOR:
2422 return LowerXOR(Op, DAG);
2423 case ISD::PREFETCH:
2424 return LowerPREFETCH(Op, DAG);
2425 case ISD::SINT_TO_FP:
2426 case ISD::UINT_TO_FP:
2427 return LowerINT_TO_FP(Op, DAG);
2428 case ISD::FP_TO_SINT:
2429 case ISD::FP_TO_UINT:
2430 return LowerFP_TO_INT(Op, DAG);
2431 case ISD::FSINCOS:
2432 return LowerFSINCOS(Op, DAG);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002433 case ISD::MUL:
2434 return LowerMUL(Op, DAG);
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002435 case ISD::INTRINSIC_WO_CHAIN:
2436 return LowerINTRINSIC_WO_CHAIN(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002437 }
2438}
2439
Tim Northover3b0846e2014-05-24 12:50:23 +00002440//===----------------------------------------------------------------------===//
2441// Calling Convention Implementation
2442//===----------------------------------------------------------------------===//
2443
2444#include "AArch64GenCallingConv.inc"
2445
Robin Morisset039781e2014-08-29 21:53:01 +00002446/// Selects the correct CCAssignFn for a given CallingConvention value.
Tim Northover3b0846e2014-05-24 12:50:23 +00002447CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2448 bool IsVarArg) const {
2449 switch (CC) {
2450 default:
2451 llvm_unreachable("Unsupported calling convention.");
2452 case CallingConv::WebKit_JS:
2453 return CC_AArch64_WebKit_JS;
Greg Fitzgeraldfa78d082015-01-19 17:40:05 +00002454 case CallingConv::GHC:
2455 return CC_AArch64_GHC;
Tim Northover3b0846e2014-05-24 12:50:23 +00002456 case CallingConv::C:
2457 case CallingConv::Fast:
2458 if (!Subtarget->isTargetDarwin())
2459 return CC_AArch64_AAPCS;
2460 return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
2461 }
2462}
2463
2464SDValue AArch64TargetLowering::LowerFormalArguments(
2465 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2466 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2467 SmallVectorImpl<SDValue> &InVals) const {
2468 MachineFunction &MF = DAG.getMachineFunction();
2469 MachineFrameInfo *MFI = MF.getFrameInfo();
2470
2471 // Assign locations to all of the incoming arguments.
2472 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002473 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2474 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002475
2476 // At this point, Ins[].VT may already be promoted to i32. To correctly
2477 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2478 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2479 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
2480 // we use a special version of AnalyzeFormalArguments to pass in ValVT and
2481 // LocVT.
2482 unsigned NumArgs = Ins.size();
2483 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2484 unsigned CurArgIdx = 0;
2485 for (unsigned i = 0; i != NumArgs; ++i) {
2486 MVT ValVT = Ins[i].VT;
Andrew Trick05938a52015-02-16 18:10:47 +00002487 if (Ins[i].isOrigArg()) {
2488 std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
2489 CurArgIdx = Ins[i].getOrigArgIndex();
Tim Northover3b0846e2014-05-24 12:50:23 +00002490
Andrew Trick05938a52015-02-16 18:10:47 +00002491 // Get type of the original argument.
Mehdi Amini44ede332015-07-09 02:09:04 +00002492 EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
2493 /*AllowUnknown*/ true);
Andrew Trick05938a52015-02-16 18:10:47 +00002494 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
2495 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2496 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2497 ValVT = MVT::i8;
2498 else if (ActualMVT == MVT::i16)
2499 ValVT = MVT::i16;
2500 }
Tim Northover3b0846e2014-05-24 12:50:23 +00002501 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2502 bool Res =
Tim Northover47e003c2014-05-26 17:21:53 +00002503 AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00002504 assert(!Res && "Call operand has unhandled type");
2505 (void)Res;
2506 }
2507 assert(ArgLocs.size() == Ins.size());
2508 SmallVector<SDValue, 16> ArgValues;
2509 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2510 CCValAssign &VA = ArgLocs[i];
2511
2512 if (Ins[i].Flags.isByVal()) {
2513 // Byval is used for HFAs in the PCS, but the system should work in a
2514 // non-compliant manner for larger structs.
Mehdi Amini44ede332015-07-09 02:09:04 +00002515 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00002516 int Size = Ins[i].Flags.getByValSize();
2517 unsigned NumRegs = (Size + 7) / 8;
2518
2519 // FIXME: This works on big-endian for composite byvals, which are the common
2520 // case. It should also work for fundamental types too.
2521 unsigned FrameIdx =
2522 MFI->CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
Mehdi Amini44ede332015-07-09 02:09:04 +00002523 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00002524 InVals.push_back(FrameIdxN);
2525
2526 continue;
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002527 }
Junmo Park3b8c7152016-01-05 09:36:47 +00002528
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002529 if (VA.isRegLoc()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00002530 // Arguments stored in registers.
2531 EVT RegVT = VA.getLocVT();
2532
2533 SDValue ArgValue;
2534 const TargetRegisterClass *RC;
2535
2536 if (RegVT == MVT::i32)
2537 RC = &AArch64::GPR32RegClass;
2538 else if (RegVT == MVT::i64)
2539 RC = &AArch64::GPR64RegClass;
Oliver Stannard6eda6ff2014-07-11 13:33:46 +00002540 else if (RegVT == MVT::f16)
2541 RC = &AArch64::FPR16RegClass;
Tim Northover3b0846e2014-05-24 12:50:23 +00002542 else if (RegVT == MVT::f32)
2543 RC = &AArch64::FPR32RegClass;
2544 else if (RegVT == MVT::f64 || RegVT.is64BitVector())
2545 RC = &AArch64::FPR64RegClass;
2546 else if (RegVT == MVT::f128 || RegVT.is128BitVector())
2547 RC = &AArch64::FPR128RegClass;
2548 else
2549 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2550
2551 // Transform the arguments in physical registers into virtual ones.
2552 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2553 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2554
2555 // If this is an 8, 16 or 32-bit value, it is really passed promoted
2556 // to 64 bits. Insert an assert[sz]ext to capture this, then
2557 // truncate to the right size.
2558 switch (VA.getLocInfo()) {
2559 default:
2560 llvm_unreachable("Unknown loc info!");
2561 case CCValAssign::Full:
2562 break;
2563 case CCValAssign::BCvt:
2564 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
2565 break;
Tim Northover47e003c2014-05-26 17:21:53 +00002566 case CCValAssign::AExt:
Tim Northover3b0846e2014-05-24 12:50:23 +00002567 case CCValAssign::SExt:
Tim Northover3b0846e2014-05-24 12:50:23 +00002568 case CCValAssign::ZExt:
Tim Northover47e003c2014-05-26 17:21:53 +00002569 // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
2570 // nodes after our lowering.
2571 assert(RegVT == Ins[i].VT && "incorrect register location selected");
Tim Northover3b0846e2014-05-24 12:50:23 +00002572 break;
2573 }
2574
2575 InVals.push_back(ArgValue);
2576
2577 } else { // VA.isRegLoc()
2578 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
2579 unsigned ArgOffset = VA.getLocMemOffset();
Amara Emerson82da7d02014-08-15 14:29:57 +00002580 unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
Tim Northover3b0846e2014-05-24 12:50:23 +00002581
2582 uint32_t BEAlign = 0;
Tim Northover293d4142014-12-03 17:49:26 +00002583 if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
2584 !Ins[i].Flags.isInConsecutiveRegs())
Tim Northover3b0846e2014-05-24 12:50:23 +00002585 BEAlign = 8 - ArgSize;
2586
2587 int FI = MFI->CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
2588
2589 // Create load nodes to retrieve arguments from the stack.
Mehdi Amini44ede332015-07-09 02:09:04 +00002590 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00002591 SDValue ArgValue;
2592
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002593 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
Tim Northover47e003c2014-05-26 17:21:53 +00002594 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002595 MVT MemVT = VA.getValVT();
2596
Tim Northover47e003c2014-05-26 17:21:53 +00002597 switch (VA.getLocInfo()) {
2598 default:
2599 break;
Tim Northover6890add2014-06-03 13:54:53 +00002600 case CCValAssign::BCvt:
2601 MemVT = VA.getLocVT();
2602 break;
Tim Northover47e003c2014-05-26 17:21:53 +00002603 case CCValAssign::SExt:
2604 ExtType = ISD::SEXTLOAD;
2605 break;
2606 case CCValAssign::ZExt:
2607 ExtType = ISD::ZEXTLOAD;
2608 break;
2609 case CCValAssign::AExt:
2610 ExtType = ISD::EXTLOAD;
2611 break;
Tim Northover3b0846e2014-05-24 12:50:23 +00002612 }
2613
Alex Lorenze40c8a22015-08-11 23:09:45 +00002614 ArgValue = DAG.getExtLoad(
2615 ExtType, DL, VA.getLocVT(), Chain, FIN,
2616 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
2617 MemVT, false, false, false, 0);
Tim Northover47e003c2014-05-26 17:21:53 +00002618
Tim Northover3b0846e2014-05-24 12:50:23 +00002619 InVals.push_back(ArgValue);
2620 }
2621 }
2622
2623 // varargs
2624 if (isVarArg) {
2625 if (!Subtarget->isTargetDarwin()) {
2626 // The AAPCS variadic function ABI is identical to the non-variadic
2627 // one. As a result there may be more arguments in registers and we should
2628 // save them for future reference.
2629 saveVarArgRegisters(CCInfo, DAG, DL, Chain);
2630 }
2631
2632 AArch64FunctionInfo *AFI = MF.getInfo<AArch64FunctionInfo>();
2633 // This will point to the next argument passed via stack.
2634 unsigned StackOffset = CCInfo.getNextStackOffset();
2635 // We currently pass all varargs at 8-byte alignment.
2636 StackOffset = ((StackOffset + 7) & ~7);
2637 AFI->setVarArgsStackIndex(MFI->CreateFixedObject(4, StackOffset, true));
2638 }
2639
2640 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2641 unsigned StackArgSize = CCInfo.getNextStackOffset();
2642 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2643 if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
2644 // This is a non-standard ABI so by fiat I say we're allowed to make full
2645 // use of the stack area to be popped, which must be aligned to 16 bytes in
2646 // any case:
Rui Ueyamada00f2f2016-01-14 21:06:47 +00002647 StackArgSize = alignTo(StackArgSize, 16);
Tim Northover3b0846e2014-05-24 12:50:23 +00002648
2649 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
2650 // a multiple of 16.
2651 FuncInfo->setArgumentStackToRestore(StackArgSize);
2652
2653 // This realignment carries over to the available bytes below. Our own
2654 // callers will guarantee the space is free by giving an aligned value to
2655 // CALLSEQ_START.
2656 }
2657 // Even if we're not expected to free up the space, it's useful to know how
2658 // much is there while considering tail calls (because we can reuse it).
2659 FuncInfo->setBytesInStackArgArea(StackArgSize);
2660
2661 return Chain;
2662}
2663
2664void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
2665 SelectionDAG &DAG, SDLoc DL,
2666 SDValue &Chain) const {
2667 MachineFunction &MF = DAG.getMachineFunction();
2668 MachineFrameInfo *MFI = MF.getFrameInfo();
2669 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Mehdi Amini44ede332015-07-09 02:09:04 +00002670 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00002671
2672 SmallVector<SDValue, 8> MemOps;
2673
2674 static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
2675 AArch64::X3, AArch64::X4, AArch64::X5,
2676 AArch64::X6, AArch64::X7 };
2677 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
Tim Northover3b6b7ca2015-02-21 02:11:17 +00002678 unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
Tim Northover3b0846e2014-05-24 12:50:23 +00002679
2680 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
2681 int GPRIdx = 0;
2682 if (GPRSaveSize != 0) {
2683 GPRIdx = MFI->CreateStackObject(GPRSaveSize, 8, false);
2684
Mehdi Amini44ede332015-07-09 02:09:04 +00002685 SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00002686
2687 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
2688 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
2689 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
Alex Lorenze40c8a22015-08-11 23:09:45 +00002690 SDValue Store = DAG.getStore(
2691 Val.getValue(1), DL, Val, FIN,
2692 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8), false,
2693 false, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00002694 MemOps.push_back(Store);
Mehdi Amini44ede332015-07-09 02:09:04 +00002695 FIN =
2696 DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00002697 }
2698 }
2699 FuncInfo->setVarArgsGPRIndex(GPRIdx);
2700 FuncInfo->setVarArgsGPRSize(GPRSaveSize);
2701
2702 if (Subtarget->hasFPARMv8()) {
2703 static const MCPhysReg FPRArgRegs[] = {
2704 AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
2705 AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
2706 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
Tim Northover3b6b7ca2015-02-21 02:11:17 +00002707 unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
Tim Northover3b0846e2014-05-24 12:50:23 +00002708
2709 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
2710 int FPRIdx = 0;
2711 if (FPRSaveSize != 0) {
2712 FPRIdx = MFI->CreateStackObject(FPRSaveSize, 16, false);
2713
Mehdi Amini44ede332015-07-09 02:09:04 +00002714 SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00002715
2716 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
2717 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
2718 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
2719
Alex Lorenze40c8a22015-08-11 23:09:45 +00002720 SDValue Store = DAG.getStore(
2721 Val.getValue(1), DL, Val, FIN,
2722 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16),
2723 false, false, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00002724 MemOps.push_back(Store);
Mehdi Amini44ede332015-07-09 02:09:04 +00002725 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
2726 DAG.getConstant(16, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00002727 }
2728 }
2729 FuncInfo->setVarArgsFPRIndex(FPRIdx);
2730 FuncInfo->setVarArgsFPRSize(FPRSaveSize);
2731 }
2732
2733 if (!MemOps.empty()) {
2734 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
2735 }
2736}
2737
2738/// LowerCallResult - Lower the result values of a call into the
2739/// appropriate copies out of appropriate physical registers.
2740SDValue AArch64TargetLowering::LowerCallResult(
2741 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
2742 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2743 SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
2744 SDValue ThisVal) const {
2745 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
2746 ? RetCC_AArch64_WebKit_JS
2747 : RetCC_AArch64_AAPCS;
2748 // Assign locations to each value returned by this call.
2749 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002750 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2751 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002752 CCInfo.AnalyzeCallResult(Ins, RetCC);
2753
2754 // Copy all of the result registers out of their specified physreg.
2755 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2756 CCValAssign VA = RVLocs[i];
2757
2758 // Pass 'this' value directly from the argument to return value, to avoid
2759 // reg unit interference
2760 if (i == 0 && isThisReturn) {
2761 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
2762 "unexpected return calling convention register assignment");
2763 InVals.push_back(ThisVal);
2764 continue;
2765 }
2766
2767 SDValue Val =
2768 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2769 Chain = Val.getValue(1);
2770 InFlag = Val.getValue(2);
2771
2772 switch (VA.getLocInfo()) {
2773 default:
2774 llvm_unreachable("Unknown loc info!");
2775 case CCValAssign::Full:
2776 break;
2777 case CCValAssign::BCvt:
2778 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2779 break;
2780 }
2781
2782 InVals.push_back(Val);
2783 }
2784
2785 return Chain;
2786}
2787
2788bool AArch64TargetLowering::isEligibleForTailCallOptimization(
2789 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
2790 bool isCalleeStructRet, bool isCallerStructRet,
2791 const SmallVectorImpl<ISD::OutputArg> &Outs,
2792 const SmallVectorImpl<SDValue> &OutVals,
2793 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2794 // For CallingConv::C this function knows whether the ABI needs
2795 // changing. That's not true for other conventions so they will have to opt in
2796 // manually.
2797 if (!IsTailCallConvention(CalleeCC) && CalleeCC != CallingConv::C)
2798 return false;
2799
2800 const MachineFunction &MF = DAG.getMachineFunction();
2801 const Function *CallerF = MF.getFunction();
2802 CallingConv::ID CallerCC = CallerF->getCallingConv();
2803 bool CCMatch = CallerCC == CalleeCC;
2804
2805 // Byval parameters hand the function a pointer directly into the stack area
2806 // we want to reuse during a tail call. Working around this *is* possible (see
2807 // X86) but less efficient and uglier in LowerCall.
2808 for (Function::const_arg_iterator i = CallerF->arg_begin(),
2809 e = CallerF->arg_end();
2810 i != e; ++i)
2811 if (i->hasByValAttr())
2812 return false;
2813
2814 if (getTargetMachine().Options.GuaranteedTailCallOpt) {
Eric Christopher114fa1c2016-02-29 22:50:49 +00002815 return IsTailCallConvention(CalleeCC) && CCMatch;
Tim Northover3b0846e2014-05-24 12:50:23 +00002816 }
2817
Oliver Stannard12993dd2014-08-18 12:42:15 +00002818 // Externally-defined functions with weak linkage should not be
2819 // tail-called on AArch64 when the OS does not support dynamic
2820 // pre-emption of symbols, as the AAELF spec requires normal calls
2821 // to undefined weak functions to be replaced with a NOP or jump to the
2822 // next instruction. The behaviour of branch instructions in this
2823 // situation (as used for tail calls) is implementation-defined, so we
2824 // cannot rely on the linker replacing the tail call with a return.
2825 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2826 const GlobalValue *GV = G->getGlobal();
Daniel Sandersc81f4502015-06-16 15:44:21 +00002827 const Triple &TT = getTargetMachine().getTargetTriple();
Saleem Abdulrasool67f72992015-01-03 21:35:00 +00002828 if (GV->hasExternalWeakLinkage() &&
2829 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
Oliver Stannard12993dd2014-08-18 12:42:15 +00002830 return false;
2831 }
2832
Tim Northover3b0846e2014-05-24 12:50:23 +00002833 // Now we search for cases where we can use a tail call without changing the
2834 // ABI. Sibcall is used in some places (particularly gcc) to refer to this
2835 // concept.
2836
2837 // I want anyone implementing a new calling convention to think long and hard
2838 // about this assert.
2839 assert((!isVarArg || CalleeCC == CallingConv::C) &&
2840 "Unexpected variadic calling convention");
2841
2842 if (isVarArg && !Outs.empty()) {
2843 // At least two cases here: if caller is fastcc then we can't have any
2844 // memory arguments (we'd be expected to clean up the stack afterwards). If
2845 // caller is C then we could potentially use its argument area.
2846
2847 // FIXME: for now we take the most conservative of these in both cases:
2848 // disallow all variadic memory operands.
2849 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002850 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2851 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002852
2853 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
Pete Cooper7be8f8f2015-08-03 19:04:32 +00002854 for (const CCValAssign &ArgLoc : ArgLocs)
2855 if (!ArgLoc.isRegLoc())
Tim Northover3b0846e2014-05-24 12:50:23 +00002856 return false;
2857 }
2858
2859 // If the calling conventions do not match, then we'd better make sure the
2860 // results are returned in the same way as what the caller expects.
2861 if (!CCMatch) {
2862 SmallVector<CCValAssign, 16> RVLocs1;
Eric Christopherb5217502014-08-06 18:45:26 +00002863 CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
2864 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002865 CCInfo1.AnalyzeCallResult(Ins, CCAssignFnForCall(CalleeCC, isVarArg));
2866
2867 SmallVector<CCValAssign, 16> RVLocs2;
Eric Christopherb5217502014-08-06 18:45:26 +00002868 CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
2869 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002870 CCInfo2.AnalyzeCallResult(Ins, CCAssignFnForCall(CallerCC, isVarArg));
2871
2872 if (RVLocs1.size() != RVLocs2.size())
2873 return false;
2874 for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
2875 if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
2876 return false;
2877 if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
2878 return false;
2879 if (RVLocs1[i].isRegLoc()) {
2880 if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
2881 return false;
2882 } else {
2883 if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
2884 return false;
2885 }
2886 }
2887 }
2888
2889 // Nothing more to check if the callee is taking no arguments
2890 if (Outs.empty())
2891 return true;
2892
2893 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002894 CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
2895 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002896
2897 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2898
2899 const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2900
2901 // If the stack arguments for this call would fit into our own save area then
2902 // the call can be made tail.
2903 return CCInfo.getNextStackOffset() <= FuncInfo->getBytesInStackArgArea();
2904}
2905
2906SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
2907 SelectionDAG &DAG,
2908 MachineFrameInfo *MFI,
2909 int ClobberedFI) const {
2910 SmallVector<SDValue, 8> ArgChains;
2911 int64_t FirstByte = MFI->getObjectOffset(ClobberedFI);
2912 int64_t LastByte = FirstByte + MFI->getObjectSize(ClobberedFI) - 1;
2913
2914 // Include the original chain at the beginning of the list. When this is
2915 // used by target LowerCall hooks, this helps legalize find the
2916 // CALLSEQ_BEGIN node.
2917 ArgChains.push_back(Chain);
2918
2919 // Add a chain value for each stack argument corresponding
2920 for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
2921 UE = DAG.getEntryNode().getNode()->use_end();
2922 U != UE; ++U)
2923 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
2924 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
2925 if (FI->getIndex() < 0) {
2926 int64_t InFirstByte = MFI->getObjectOffset(FI->getIndex());
2927 int64_t InLastByte = InFirstByte;
2928 InLastByte += MFI->getObjectSize(FI->getIndex()) - 1;
2929
2930 if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
2931 (FirstByte <= InFirstByte && InFirstByte <= LastByte))
2932 ArgChains.push_back(SDValue(L, 1));
2933 }
2934
2935 // Build a tokenfactor for all the chains.
2936 return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
2937}
2938
2939bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
2940 bool TailCallOpt) const {
2941 return CallCC == CallingConv::Fast && TailCallOpt;
2942}
2943
2944bool AArch64TargetLowering::IsTailCallConvention(CallingConv::ID CallCC) const {
2945 return CallCC == CallingConv::Fast;
2946}
2947
2948/// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
2949/// and add input and output parameter nodes.
2950SDValue
2951AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
2952 SmallVectorImpl<SDValue> &InVals) const {
2953 SelectionDAG &DAG = CLI.DAG;
2954 SDLoc &DL = CLI.DL;
2955 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2956 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2957 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2958 SDValue Chain = CLI.Chain;
2959 SDValue Callee = CLI.Callee;
2960 bool &IsTailCall = CLI.IsTailCall;
2961 CallingConv::ID CallConv = CLI.CallConv;
2962 bool IsVarArg = CLI.IsVarArg;
2963
2964 MachineFunction &MF = DAG.getMachineFunction();
2965 bool IsStructRet = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
2966 bool IsThisReturn = false;
2967
2968 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2969 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2970 bool IsSibCall = false;
2971
2972 if (IsTailCall) {
2973 // Check if it's really possible to do a tail call.
2974 IsTailCall = isEligibleForTailCallOptimization(
2975 Callee, CallConv, IsVarArg, IsStructRet,
2976 MF.getFunction()->hasStructRetAttr(), Outs, OutVals, Ins, DAG);
2977 if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
2978 report_fatal_error("failed to perform tail call elimination on a call "
2979 "site marked musttail");
2980
2981 // A sibling call is one where we're under the usual C ABI and not planning
2982 // to change that but can still do a tail call:
2983 if (!TailCallOpt && IsTailCall)
2984 IsSibCall = true;
2985
2986 if (IsTailCall)
2987 ++NumTailCalls;
2988 }
2989
2990 // Analyze operands of the call, assigning locations to each operand.
2991 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002992 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
2993 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002994
2995 if (IsVarArg) {
2996 // Handle fixed and variable vector arguments differently.
2997 // Variable vector arguments always go into memory.
2998 unsigned NumArgs = Outs.size();
2999
3000 for (unsigned i = 0; i != NumArgs; ++i) {
3001 MVT ArgVT = Outs[i].VT;
3002 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3003 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
3004 /*IsVarArg=*/ !Outs[i].IsFixed);
3005 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3006 assert(!Res && "Call operand has unhandled type");
3007 (void)Res;
3008 }
3009 } else {
3010 // At this point, Outs[].VT may already be promoted to i32. To correctly
3011 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
3012 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
3013 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
3014 // we use a special version of AnalyzeCallOperands to pass in ValVT and
3015 // LocVT.
3016 unsigned NumArgs = Outs.size();
3017 for (unsigned i = 0; i != NumArgs; ++i) {
3018 MVT ValVT = Outs[i].VT;
3019 // Get type of the original argument.
Mehdi Amini44ede332015-07-09 02:09:04 +00003020 EVT ActualVT = getValueType(DAG.getDataLayout(),
3021 CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
Tim Northover3b0846e2014-05-24 12:50:23 +00003022 /*AllowUnknown*/ true);
3023 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
3024 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3025 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
Tim Northover3b0846e2014-05-24 12:50:23 +00003026 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
Tim Northover47e003c2014-05-26 17:21:53 +00003027 ValVT = MVT::i8;
Tim Northover3b0846e2014-05-24 12:50:23 +00003028 else if (ActualMVT == MVT::i16)
Tim Northover47e003c2014-05-26 17:21:53 +00003029 ValVT = MVT::i16;
Tim Northover3b0846e2014-05-24 12:50:23 +00003030
3031 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
Tim Northover47e003c2014-05-26 17:21:53 +00003032 bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00003033 assert(!Res && "Call operand has unhandled type");
3034 (void)Res;
3035 }
3036 }
3037
3038 // Get a count of how many bytes are to be pushed on the stack.
3039 unsigned NumBytes = CCInfo.getNextStackOffset();
3040
3041 if (IsSibCall) {
3042 // Since we're not changing the ABI to make this a tail call, the memory
3043 // operands are already available in the caller's incoming argument space.
3044 NumBytes = 0;
3045 }
3046
3047 // FPDiff is the byte offset of the call's argument area from the callee's.
3048 // Stores to callee stack arguments will be placed in FixedStackSlots offset
3049 // by this amount for a tail call. In a sibling call it must be 0 because the
3050 // caller will deallocate the entire stack and the callee still expects its
3051 // arguments to begin at SP+0. Completely unused for non-tail calls.
3052 int FPDiff = 0;
3053
3054 if (IsTailCall && !IsSibCall) {
3055 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
3056
3057 // Since callee will pop argument stack as a tail call, we must keep the
3058 // popped size 16-byte aligned.
Rui Ueyamada00f2f2016-01-14 21:06:47 +00003059 NumBytes = alignTo(NumBytes, 16);
Tim Northover3b0846e2014-05-24 12:50:23 +00003060
3061 // FPDiff will be negative if this tail call requires more space than we
3062 // would automatically have in our incoming argument space. Positive if we
3063 // can actually shrink the stack.
3064 FPDiff = NumReusableBytes - NumBytes;
3065
3066 // The stack pointer must be 16-byte aligned at all times it's used for a
3067 // memory operation, which in practice means at *all* times and in
3068 // particular across call boundaries. Therefore our own arguments started at
3069 // a 16-byte aligned SP and the delta applied for the tail call should
3070 // satisfy the same constraint.
3071 assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
3072 }
3073
3074 // Adjust the stack pointer for the new arguments...
3075 // These operations are automatically eliminated by the prolog/epilog pass
3076 if (!IsSibCall)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003077 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, DL,
3078 true),
3079 DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003080
Mehdi Amini44ede332015-07-09 02:09:04 +00003081 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
3082 getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00003083
3084 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3085 SmallVector<SDValue, 8> MemOpChains;
Mehdi Amini44ede332015-07-09 02:09:04 +00003086 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003087
3088 // Walk the register/memloc assignments, inserting copies/loads.
3089 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
3090 ++i, ++realArgIdx) {
3091 CCValAssign &VA = ArgLocs[i];
3092 SDValue Arg = OutVals[realArgIdx];
3093 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
3094
3095 // Promote the value if needed.
3096 switch (VA.getLocInfo()) {
3097 default:
3098 llvm_unreachable("Unknown loc info!");
3099 case CCValAssign::Full:
3100 break;
3101 case CCValAssign::SExt:
3102 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3103 break;
3104 case CCValAssign::ZExt:
3105 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3106 break;
3107 case CCValAssign::AExt:
Tim Northover68ae5032014-05-26 17:22:07 +00003108 if (Outs[realArgIdx].ArgVT == MVT::i1) {
3109 // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
3110 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3111 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
3112 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003113 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3114 break;
3115 case CCValAssign::BCvt:
3116 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3117 break;
3118 case CCValAssign::FPExt:
3119 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3120 break;
3121 }
3122
3123 if (VA.isRegLoc()) {
3124 if (realArgIdx == 0 && Flags.isReturned() && Outs[0].VT == MVT::i64) {
3125 assert(VA.getLocVT() == MVT::i64 &&
3126 "unexpected calling convention register assignment");
3127 assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
3128 "unexpected use of 'returned'");
3129 IsThisReturn = true;
3130 }
3131 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3132 } else {
3133 assert(VA.isMemLoc());
3134
3135 SDValue DstAddr;
3136 MachinePointerInfo DstInfo;
3137
3138 // FIXME: This works on big-endian for composite byvals, which are the
3139 // common case. It should also work for fundamental types too.
3140 uint32_t BEAlign = 0;
3141 unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
Amara Emerson82da7d02014-08-15 14:29:57 +00003142 : VA.getValVT().getSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00003143 OpSize = (OpSize + 7) / 8;
Tim Northover293d4142014-12-03 17:49:26 +00003144 if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
3145 !Flags.isInConsecutiveRegs()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003146 if (OpSize < 8)
3147 BEAlign = 8 - OpSize;
3148 }
3149 unsigned LocMemOffset = VA.getLocMemOffset();
3150 int32_t Offset = LocMemOffset + BEAlign;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003151 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
Mehdi Amini44ede332015-07-09 02:09:04 +00003152 PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
Tim Northover3b0846e2014-05-24 12:50:23 +00003153
3154 if (IsTailCall) {
3155 Offset = Offset + FPDiff;
3156 int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3157
Mehdi Amini44ede332015-07-09 02:09:04 +00003158 DstAddr = DAG.getFrameIndex(FI, PtrVT);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003159 DstInfo =
3160 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
Tim Northover3b0846e2014-05-24 12:50:23 +00003161
3162 // Make sure any stack arguments overlapping with where we're storing
3163 // are loaded before this eventual operation. Otherwise they'll be
3164 // clobbered.
3165 Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
3166 } else {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003167 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003168
Mehdi Amini44ede332015-07-09 02:09:04 +00003169 DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003170 DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
3171 LocMemOffset);
Tim Northover3b0846e2014-05-24 12:50:23 +00003172 }
3173
3174 if (Outs[i].Flags.isByVal()) {
3175 SDValue SizeNode =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003176 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00003177 SDValue Cpy = DAG.getMemcpy(
3178 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
Krzysztof Parzyszeka46c36b2015-04-13 17:16:45 +00003179 /*isVol = */ false, /*AlwaysInline = */ false,
3180 /*isTailCall = */ false,
3181 DstInfo, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00003182
3183 MemOpChains.push_back(Cpy);
3184 } else {
3185 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
3186 // promoted to a legal register type i32, we should truncate Arg back to
3187 // i1/i8/i16.
Tim Northover6890add2014-06-03 13:54:53 +00003188 if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
3189 VA.getValVT() == MVT::i16)
3190 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
Tim Northover3b0846e2014-05-24 12:50:23 +00003191
3192 SDValue Store =
3193 DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, false, false, 0);
3194 MemOpChains.push_back(Store);
3195 }
3196 }
3197 }
3198
3199 if (!MemOpChains.empty())
3200 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3201
3202 // Build a sequence of copy-to-reg nodes chained together with token chain
3203 // and flag operands which copy the outgoing args into the appropriate regs.
3204 SDValue InFlag;
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003205 for (auto &RegToPass : RegsToPass) {
3206 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3207 RegToPass.second, InFlag);
Tim Northover3b0846e2014-05-24 12:50:23 +00003208 InFlag = Chain.getValue(1);
3209 }
3210
3211 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3212 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3213 // node so that legalize doesn't hack it.
3214 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3215 Subtarget->isTargetMachO()) {
3216 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3217 const GlobalValue *GV = G->getGlobal();
3218 bool InternalLinkage = GV->hasInternalLinkage();
3219 if (InternalLinkage)
Mehdi Amini44ede332015-07-09 02:09:04 +00003220 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00003221 else {
Mehdi Amini44ede332015-07-09 02:09:04 +00003222 Callee =
3223 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT);
3224 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
Tim Northover3b0846e2014-05-24 12:50:23 +00003225 }
3226 } else if (ExternalSymbolSDNode *S =
3227 dyn_cast<ExternalSymbolSDNode>(Callee)) {
3228 const char *Sym = S->getSymbol();
Mehdi Amini44ede332015-07-09 02:09:04 +00003229 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
3230 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
Tim Northover3b0846e2014-05-24 12:50:23 +00003231 }
3232 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3233 const GlobalValue *GV = G->getGlobal();
Mehdi Amini44ede332015-07-09 02:09:04 +00003234 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00003235 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3236 const char *Sym = S->getSymbol();
Mehdi Amini44ede332015-07-09 02:09:04 +00003237 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00003238 }
3239
3240 // We don't usually want to end the call-sequence here because we would tidy
3241 // the frame up *after* the call, however in the ABI-changing tail-call case
3242 // we've carefully laid out the parameters so that when sp is reset they'll be
3243 // in the correct location.
3244 if (IsTailCall && !IsSibCall) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003245 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3246 DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003247 InFlag = Chain.getValue(1);
3248 }
3249
3250 std::vector<SDValue> Ops;
3251 Ops.push_back(Chain);
3252 Ops.push_back(Callee);
3253
3254 if (IsTailCall) {
3255 // Each tail call may have to adjust the stack by a different amount, so
3256 // this information must travel along with the operation for eventual
3257 // consumption by emitEpilogue.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003258 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00003259 }
3260
3261 // Add argument registers to the end of the list so that they are known live
3262 // into the call.
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003263 for (auto &RegToPass : RegsToPass)
3264 Ops.push_back(DAG.getRegister(RegToPass.first,
3265 RegToPass.second.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00003266
3267 // Add a register mask operand representing the call-preserved registers.
3268 const uint32_t *Mask;
Eric Christopher905f12d2015-01-29 00:19:42 +00003269 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00003270 if (IsThisReturn) {
3271 // For 'this' returns, use the X0-preserving mask if applicable
Eric Christopher9deb75d2015-03-11 22:42:13 +00003272 Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003273 if (!Mask) {
3274 IsThisReturn = false;
Eric Christopher9deb75d2015-03-11 22:42:13 +00003275 Mask = TRI->getCallPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003276 }
3277 } else
Eric Christopher9deb75d2015-03-11 22:42:13 +00003278 Mask = TRI->getCallPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003279
3280 assert(Mask && "Missing call preserved mask for calling convention");
3281 Ops.push_back(DAG.getRegisterMask(Mask));
3282
3283 if (InFlag.getNode())
3284 Ops.push_back(InFlag);
3285
3286 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3287
3288 // If we're doing a tall call, use a TC_RETURN here rather than an
3289 // actual call instruction.
Arnold Schwaighoferf54b73d2015-05-08 23:52:00 +00003290 if (IsTailCall) {
3291 MF.getFrameInfo()->setHasTailCall();
Tim Northover3b0846e2014-05-24 12:50:23 +00003292 return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
Arnold Schwaighoferf54b73d2015-05-08 23:52:00 +00003293 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003294
3295 // Returns a chain and a flag for retval copy to use.
3296 Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
3297 InFlag = Chain.getValue(1);
3298
Rui Ueyamada00f2f2016-01-14 21:06:47 +00003299 uint64_t CalleePopBytes =
3300 DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00003301
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003302 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3303 DAG.getIntPtrConstant(CalleePopBytes, DL, true),
Tim Northover3b0846e2014-05-24 12:50:23 +00003304 InFlag, DL);
3305 if (!Ins.empty())
3306 InFlag = Chain.getValue(1);
3307
3308 // Handle result values, copying them out of physregs into vregs that we
3309 // return.
3310 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3311 InVals, IsThisReturn,
3312 IsThisReturn ? OutVals[0] : SDValue());
3313}
3314
3315bool AArch64TargetLowering::CanLowerReturn(
3316 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
3317 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
3318 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3319 ? RetCC_AArch64_WebKit_JS
3320 : RetCC_AArch64_AAPCS;
3321 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003322 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
Tim Northover3b0846e2014-05-24 12:50:23 +00003323 return CCInfo.CheckReturn(Outs, RetCC);
3324}
3325
3326SDValue
3327AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3328 bool isVarArg,
3329 const SmallVectorImpl<ISD::OutputArg> &Outs,
3330 const SmallVectorImpl<SDValue> &OutVals,
3331 SDLoc DL, SelectionDAG &DAG) const {
3332 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3333 ? RetCC_AArch64_WebKit_JS
3334 : RetCC_AArch64_AAPCS;
3335 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003336 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3337 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00003338 CCInfo.AnalyzeReturn(Outs, RetCC);
3339
3340 // Copy the result values into the output registers.
3341 SDValue Flag;
3342 SmallVector<SDValue, 4> RetOps(1, Chain);
3343 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
3344 ++i, ++realRVLocIdx) {
3345 CCValAssign &VA = RVLocs[i];
3346 assert(VA.isRegLoc() && "Can only return in registers!");
3347 SDValue Arg = OutVals[realRVLocIdx];
3348
3349 switch (VA.getLocInfo()) {
3350 default:
3351 llvm_unreachable("Unknown loc info!");
3352 case CCValAssign::Full:
Tim Northover68ae5032014-05-26 17:22:07 +00003353 if (Outs[i].ArgVT == MVT::i1) {
3354 // AAPCS requires i1 to be zero-extended to i8 by the producer of the
3355 // value. This is strictly redundant on Darwin (which uses "zeroext
3356 // i1"), but will be optimised out before ISel.
3357 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3358 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3359 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003360 break;
3361 case CCValAssign::BCvt:
3362 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3363 break;
3364 }
3365
3366 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
3367 Flag = Chain.getValue(1);
3368 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3369 }
Manman Rencbe4f942015-12-16 21:04:19 +00003370 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3371 const MCPhysReg *I =
3372 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
3373 if (I) {
3374 for (; *I; ++I) {
3375 if (AArch64::GPR64RegClass.contains(*I))
3376 RetOps.push_back(DAG.getRegister(*I, MVT::i64));
3377 else if (AArch64::FPR64RegClass.contains(*I))
3378 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
3379 else
3380 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
3381 }
3382 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003383
3384 RetOps[0] = Chain; // Update chain.
3385
3386 // Add the flag if we have it.
3387 if (Flag.getNode())
3388 RetOps.push_back(Flag);
3389
3390 return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
3391}
3392
3393//===----------------------------------------------------------------------===//
3394// Other Lowering Code
3395//===----------------------------------------------------------------------===//
3396
3397SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
3398 SelectionDAG &DAG) const {
Mehdi Amini44ede332015-07-09 02:09:04 +00003399 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003400 SDLoc DL(Op);
Asiri Rathnayake369c0302014-09-10 13:54:38 +00003401 const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
3402 const GlobalValue *GV = GN->getGlobal();
Tim Northover3b0846e2014-05-24 12:50:23 +00003403 unsigned char OpFlags =
3404 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
3405
3406 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
3407 "unexpected offset in global node");
3408
3409 // This also catched the large code model case for Darwin.
3410 if ((OpFlags & AArch64II::MO_GOT) != 0) {
3411 SDValue GotAddr = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
3412 // FIXME: Once remat is capable of dealing with instructions with register
3413 // operands, expand this into two nodes instead of using a wrapper node.
3414 return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
3415 }
3416
Asiri Rathnayake369c0302014-09-10 13:54:38 +00003417 if ((OpFlags & AArch64II::MO_CONSTPOOL) != 0) {
3418 assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
3419 "use of MO_CONSTPOOL only supported on small model");
3420 SDValue Hi = DAG.getTargetConstantPool(GV, PtrVT, 0, 0, AArch64II::MO_PAGE);
3421 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3422 unsigned char LoFlags = AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
3423 SDValue Lo = DAG.getTargetConstantPool(GV, PtrVT, 0, 0, LoFlags);
3424 SDValue PoolAddr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003425 SDValue GlobalAddr = DAG.getLoad(
3426 PtrVT, DL, DAG.getEntryNode(), PoolAddr,
3427 MachinePointerInfo::getConstantPool(DAG.getMachineFunction()),
3428 /*isVolatile=*/false,
3429 /*isNonTemporal=*/true,
3430 /*isInvariant=*/true, 8);
Asiri Rathnayake369c0302014-09-10 13:54:38 +00003431 if (GN->getOffset() != 0)
3432 return DAG.getNode(ISD::ADD, DL, PtrVT, GlobalAddr,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003433 DAG.getConstant(GN->getOffset(), DL, PtrVT));
Asiri Rathnayake369c0302014-09-10 13:54:38 +00003434 return GlobalAddr;
3435 }
3436
Tim Northover3b0846e2014-05-24 12:50:23 +00003437 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
3438 const unsigned char MO_NC = AArch64II::MO_NC;
3439 return DAG.getNode(
3440 AArch64ISD::WrapperLarge, DL, PtrVT,
3441 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G3),
3442 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
3443 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
3444 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
3445 } else {
3446 // Use ADRP/ADD or ADRP/LDR for everything else: the small model on ELF and
3447 // the only correct model on Darwin.
3448 SDValue Hi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
3449 OpFlags | AArch64II::MO_PAGE);
3450 unsigned char LoFlags = OpFlags | AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
3451 SDValue Lo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, LoFlags);
3452
3453 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3454 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3455 }
3456}
3457
3458/// \brief Convert a TLS address reference into the correct sequence of loads
3459/// and calls to compute the variable's address (for Darwin, currently) and
3460/// return an SDValue containing the final node.
3461
3462/// Darwin only has one TLS scheme which must be capable of dealing with the
3463/// fully general situation, in the worst case. This means:
3464/// + "extern __thread" declaration.
3465/// + Defined in a possibly unknown dynamic library.
3466///
3467/// The general system is that each __thread variable has a [3 x i64] descriptor
3468/// which contains information used by the runtime to calculate the address. The
3469/// only part of this the compiler needs to know about is the first xword, which
3470/// contains a function pointer that must be called with the address of the
3471/// entire descriptor in "x0".
3472///
3473/// Since this descriptor may be in a different unit, in general even the
3474/// descriptor must be accessed via an indirect load. The "ideal" code sequence
3475/// is:
3476/// adrp x0, _var@TLVPPAGE
3477/// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor
3478/// ldr x1, [x0] ; x1 contains 1st entry of descriptor,
3479/// ; the function pointer
3480/// blr x1 ; Uses descriptor address in x0
3481/// ; Address of _var is now in x0.
3482///
3483/// If the address of _var's descriptor *is* known to the linker, then it can
3484/// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
3485/// a slight efficiency gain.
3486SDValue
3487AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
3488 SelectionDAG &DAG) const {
3489 assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
3490
3491 SDLoc DL(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00003492 MVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003493 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3494
3495 SDValue TLVPAddr =
3496 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3497 SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
3498
3499 // The first entry in the descriptor is a function pointer that we must call
3500 // to obtain the address of the variable.
3501 SDValue Chain = DAG.getEntryNode();
3502 SDValue FuncTLVGet =
Alex Lorenze40c8a22015-08-11 23:09:45 +00003503 DAG.getLoad(MVT::i64, DL, Chain, DescAddr,
3504 MachinePointerInfo::getGOT(DAG.getMachineFunction()), false,
3505 true, true, 8);
Tim Northover3b0846e2014-05-24 12:50:23 +00003506 Chain = FuncTLVGet.getValue(1);
3507
3508 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3509 MFI->setAdjustsStack(true);
3510
3511 // TLS calls preserve all registers except those that absolutely must be
3512 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
3513 // silly).
Eric Christopher6c901622015-01-28 03:51:33 +00003514 const uint32_t *Mask =
Eric Christopher905f12d2015-01-29 00:19:42 +00003515 Subtarget->getRegisterInfo()->getTLSCallPreservedMask();
Tim Northover3b0846e2014-05-24 12:50:23 +00003516
3517 // Finally, we can make the call. This is just a degenerate version of a
3518 // normal AArch64 call node: x0 takes the address of the descriptor, and
3519 // returns the address of the variable in this thread.
3520 Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
3521 Chain =
3522 DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3523 Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
3524 DAG.getRegisterMask(Mask), Chain.getValue(1));
3525 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
3526}
3527
3528/// When accessing thread-local variables under either the general-dynamic or
3529/// local-dynamic system, we make a "TLS-descriptor" call. The variable will
3530/// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
Kristof Beylsaea84612015-03-04 09:12:08 +00003531/// is a function pointer to carry out the resolution.
Tim Northover3b0846e2014-05-24 12:50:23 +00003532///
Kristof Beylsaea84612015-03-04 09:12:08 +00003533/// The sequence is:
3534/// adrp x0, :tlsdesc:var
3535/// ldr x1, [x0, #:tlsdesc_lo12:var]
3536/// add x0, x0, #:tlsdesc_lo12:var
3537/// .tlsdesccall var
3538/// blr x1
3539/// (TPIDR_EL0 offset now in x0)
Tim Northover3b0846e2014-05-24 12:50:23 +00003540///
Kristof Beylsaea84612015-03-04 09:12:08 +00003541/// The above sequence must be produced unscheduled, to enable the linker to
3542/// optimize/relax this sequence.
3543/// Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
3544/// above sequence, and expanded really late in the compilation flow, to ensure
3545/// the sequence is produced as per above.
3546SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr, SDLoc DL,
3547 SelectionDAG &DAG) const {
Mehdi Amini44ede332015-07-09 02:09:04 +00003548 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003549
Kristof Beylsaea84612015-03-04 09:12:08 +00003550 SDValue Chain = DAG.getEntryNode();
Tim Northover3b0846e2014-05-24 12:50:23 +00003551 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
Kristof Beylsaea84612015-03-04 09:12:08 +00003552
3553 SmallVector<SDValue, 2> Ops;
3554 Ops.push_back(Chain);
3555 Ops.push_back(SymAddr);
3556
3557 Chain = DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, Ops);
3558 SDValue Glue = Chain.getValue(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00003559
3560 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
3561}
3562
3563SDValue
3564AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
3565 SelectionDAG &DAG) const {
3566 assert(Subtarget->isTargetELF() && "This function expects an ELF target");
3567 assert(getTargetMachine().getCodeModel() == CodeModel::Small &&
3568 "ELF TLS only supported in small memory model");
Kristof Beylsaea84612015-03-04 09:12:08 +00003569 // Different choices can be made for the maximum size of the TLS area for a
3570 // module. For the small address model, the default TLS size is 16MiB and the
3571 // maximum TLS size is 4GiB.
3572 // FIXME: add -mtls-size command line option and make it control the 16MiB
3573 // vs. 4GiB code sequence generation.
Tim Northover3b0846e2014-05-24 12:50:23 +00003574 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3575
3576 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
Chih-Hung Hsieh1e859582015-07-28 16:24:05 +00003577
3578 if (DAG.getTarget().Options.EmulatedTLS)
3579 return LowerToTLSEmulatedModel(GA, DAG);
3580
Kristof Beylsaea84612015-03-04 09:12:08 +00003581 if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
3582 if (Model == TLSModel::LocalDynamic)
3583 Model = TLSModel::GeneralDynamic;
3584 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003585
3586 SDValue TPOff;
Mehdi Amini44ede332015-07-09 02:09:04 +00003587 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003588 SDLoc DL(Op);
3589 const GlobalValue *GV = GA->getGlobal();
3590
3591 SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
3592
3593 if (Model == TLSModel::LocalExec) {
3594 SDValue HiVar = DAG.getTargetGlobalAddress(
Kristof Beylsaea84612015-03-04 09:12:08 +00003595 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
Tim Northover3b0846e2014-05-24 12:50:23 +00003596 SDValue LoVar = DAG.getTargetGlobalAddress(
3597 GV, DL, PtrVT, 0,
Kristof Beylsaea84612015-03-04 09:12:08 +00003598 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
Tim Northover3b0846e2014-05-24 12:50:23 +00003599
Kristof Beylsaea84612015-03-04 09:12:08 +00003600 SDValue TPWithOff_lo =
3601 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003602 HiVar,
3603 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003604 0);
3605 SDValue TPWithOff =
3606 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003607 LoVar,
3608 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003609 0);
3610 return TPWithOff;
Tim Northover3b0846e2014-05-24 12:50:23 +00003611 } else if (Model == TLSModel::InitialExec) {
3612 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3613 TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
3614 } else if (Model == TLSModel::LocalDynamic) {
3615 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
3616 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
3617 // the beginning of the module's TLS region, followed by a DTPREL offset
3618 // calculation.
3619
3620 // These accesses will need deduplicating if there's more than one.
3621 AArch64FunctionInfo *MFI =
3622 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
3623 MFI->incNumLocalDynamicTLSAccesses();
3624
Tim Northover3b0846e2014-05-24 12:50:23 +00003625 // The call needs a relocation too for linker relaxation. It doesn't make
3626 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3627 // the address.
3628 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
3629 AArch64II::MO_TLS);
3630
3631 // Now we can calculate the offset from TPIDR_EL0 to this module's
3632 // thread-local area.
Kristof Beylsaea84612015-03-04 09:12:08 +00003633 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00003634
3635 // Now use :dtprel_whatever: operations to calculate this variable's offset
3636 // in its thread-storage area.
3637 SDValue HiVar = DAG.getTargetGlobalAddress(
Kristof Beylsaea84612015-03-04 09:12:08 +00003638 GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
Tim Northover3b0846e2014-05-24 12:50:23 +00003639 SDValue LoVar = DAG.getTargetGlobalAddress(
3640 GV, DL, MVT::i64, 0,
Tim Northover3b0846e2014-05-24 12:50:23 +00003641 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3642
Kristof Beylsaea84612015-03-04 09:12:08 +00003643 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003644 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003645 0);
3646 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003647 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003648 0);
3649 } else if (Model == TLSModel::GeneralDynamic) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003650 // The call needs a relocation too for linker relaxation. It doesn't make
3651 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3652 // the address.
3653 SDValue SymAddr =
3654 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3655
3656 // Finally we can make a call to calculate the offset from tpidr_el0.
Kristof Beylsaea84612015-03-04 09:12:08 +00003657 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00003658 } else
3659 llvm_unreachable("Unsupported ELF TLS access model");
3660
3661 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
3662}
3663
3664SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
3665 SelectionDAG &DAG) const {
3666 if (Subtarget->isTargetDarwin())
3667 return LowerDarwinGlobalTLSAddress(Op, DAG);
3668 else if (Subtarget->isTargetELF())
3669 return LowerELFGlobalTLSAddress(Op, DAG);
3670
3671 llvm_unreachable("Unexpected platform trying to use TLS");
3672}
3673SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3674 SDValue Chain = Op.getOperand(0);
3675 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3676 SDValue LHS = Op.getOperand(2);
3677 SDValue RHS = Op.getOperand(3);
3678 SDValue Dest = Op.getOperand(4);
3679 SDLoc dl(Op);
3680
3681 // Handle f128 first, since lowering it will result in comparing the return
3682 // value of a libcall against zero, which is just what the rest of LowerBR_CC
3683 // is expecting to deal with.
3684 if (LHS.getValueType() == MVT::f128) {
3685 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3686
3687 // If softenSetCCOperands returned a scalar, we need to compare the result
3688 // against zero to select between true and false values.
3689 if (!RHS.getNode()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003690 RHS = DAG.getConstant(0, dl, LHS.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00003691 CC = ISD::SETNE;
3692 }
3693 }
3694
3695 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
3696 // instruction.
3697 unsigned Opc = LHS.getOpcode();
Artyom Skrobov314ee042015-11-25 19:41:11 +00003698 if (LHS.getResNo() == 1 && isOneConstant(RHS) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00003699 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3700 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
3701 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
3702 "Unexpected condition code.");
3703 // Only lower legal XALUO ops.
3704 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
3705 return SDValue();
3706
3707 // The actual operation with overflow check.
3708 AArch64CC::CondCode OFCC;
3709 SDValue Value, Overflow;
3710 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
3711
3712 if (CC == ISD::SETNE)
3713 OFCC = getInvertedCondCode(OFCC);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003714 SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003715
Ahmed Bougachadf956a22015-02-06 23:15:39 +00003716 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3717 Overflow);
Tim Northover3b0846e2014-05-24 12:50:23 +00003718 }
3719
3720 if (LHS.getValueType().isInteger()) {
3721 assert((LHS.getValueType() == RHS.getValueType()) &&
3722 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3723
3724 // If the RHS of the comparison is zero, we can potentially fold this
3725 // to a specialized branch.
3726 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
3727 if (RHSC && RHSC->getZExtValue() == 0) {
3728 if (CC == ISD::SETEQ) {
3729 // See if we can use a TBZ to fold in an AND as well.
3730 // TBZ has a smaller branch displacement than CBZ. If the offset is
3731 // out of bounds, a late MI-layer pass rewrites branches.
3732 // 403.gcc is an example that hits this case.
3733 if (LHS.getOpcode() == ISD::AND &&
3734 isa<ConstantSDNode>(LHS.getOperand(1)) &&
3735 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3736 SDValue Test = LHS.getOperand(0);
3737 uint64_t Mask = LHS.getConstantOperandVal(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00003738 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003739 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3740 Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00003741 }
3742
3743 return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
3744 } else if (CC == ISD::SETNE) {
3745 // See if we can use a TBZ to fold in an AND as well.
3746 // TBZ has a smaller branch displacement than CBZ. If the offset is
3747 // out of bounds, a late MI-layer pass rewrites branches.
3748 // 403.gcc is an example that hits this case.
3749 if (LHS.getOpcode() == ISD::AND &&
3750 isa<ConstantSDNode>(LHS.getOperand(1)) &&
3751 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3752 SDValue Test = LHS.getOperand(0);
3753 uint64_t Mask = LHS.getConstantOperandVal(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00003754 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003755 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3756 Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00003757 }
3758
3759 return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
Chad Rosier579c02c2014-08-01 14:48:56 +00003760 } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
3761 // Don't combine AND since emitComparison converts the AND to an ANDS
3762 // (a.k.a. TST) and the test in the test bit and branch instruction
3763 // becomes redundant. This would also increase register pressure.
3764 uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
3765 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003766 DAG.getConstant(Mask, dl, MVT::i64), Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00003767 }
3768 }
Chad Rosier579c02c2014-08-01 14:48:56 +00003769 if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
3770 LHS.getOpcode() != ISD::AND) {
3771 // Don't combine AND since emitComparison converts the AND to an ANDS
3772 // (a.k.a. TST) and the test in the test bit and branch instruction
3773 // becomes redundant. This would also increase register pressure.
3774 uint64_t Mask = LHS.getValueType().getSizeInBits() - 1;
3775 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003776 DAG.getConstant(Mask, dl, MVT::i64), Dest);
Chad Rosier579c02c2014-08-01 14:48:56 +00003777 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003778
3779 SDValue CCVal;
3780 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3781 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3782 Cmp);
3783 }
3784
3785 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3786
3787 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
3788 // clean. Some of them require two branches to implement.
3789 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3790 AArch64CC::CondCode CC1, CC2;
3791 changeFPCCToAArch64CC(CC, CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003792 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003793 SDValue BR1 =
3794 DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
3795 if (CC2 != AArch64CC::AL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003796 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003797 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
3798 Cmp);
3799 }
3800
3801 return BR1;
3802}
3803
3804SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
3805 SelectionDAG &DAG) const {
3806 EVT VT = Op.getValueType();
3807 SDLoc DL(Op);
3808
3809 SDValue In1 = Op.getOperand(0);
3810 SDValue In2 = Op.getOperand(1);
3811 EVT SrcVT = In2.getValueType();
Ahmed Bougacha2a97b1b2015-08-13 01:13:56 +00003812
3813 if (SrcVT.bitsLT(VT))
3814 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
3815 else if (SrcVT.bitsGT(VT))
3816 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
Tim Northover3b0846e2014-05-24 12:50:23 +00003817
3818 EVT VecVT;
3819 EVT EltVT;
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00003820 uint64_t EltMask;
3821 SDValue VecVal1, VecVal2;
Tim Northover3b0846e2014-05-24 12:50:23 +00003822 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
3823 EltVT = MVT::i32;
Ahmed Bougachab0ae36f2015-08-04 00:42:34 +00003824 VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00003825 EltMask = 0x80000000ULL;
Tim Northover3b0846e2014-05-24 12:50:23 +00003826
3827 if (!VT.isVector()) {
3828 VecVal1 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3829 DAG.getUNDEF(VecVT), In1);
3830 VecVal2 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3831 DAG.getUNDEF(VecVT), In2);
3832 } else {
3833 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3834 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3835 }
3836 } else if (VT == MVT::f64 || VT == MVT::v2f64) {
3837 EltVT = MVT::i64;
3838 VecVT = MVT::v2i64;
3839
Eric Christopher572e03a2015-06-19 01:53:21 +00003840 // We want to materialize a mask with the high bit set, but the AdvSIMD
Tim Northover3b0846e2014-05-24 12:50:23 +00003841 // immediate moves cannot materialize that in a single instruction for
3842 // 64-bit elements. Instead, materialize zero and then negate it.
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00003843 EltMask = 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00003844
3845 if (!VT.isVector()) {
3846 VecVal1 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3847 DAG.getUNDEF(VecVT), In1);
3848 VecVal2 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3849 DAG.getUNDEF(VecVT), In2);
3850 } else {
3851 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3852 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3853 }
3854 } else {
3855 llvm_unreachable("Invalid type for copysign!");
3856 }
3857
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003858 SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00003859
3860 // If we couldn't materialize the mask above, then the mask vector will be
3861 // the zero vector, and we need to negate it here.
3862 if (VT == MVT::f64 || VT == MVT::v2f64) {
3863 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
3864 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
3865 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
3866 }
3867
3868 SDValue Sel =
3869 DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
3870
3871 if (VT == MVT::f32)
3872 return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
3873 else if (VT == MVT::f64)
3874 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
3875 else
3876 return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
3877}
3878
3879SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
Duncan P. N. Exon Smith003bb7d2015-02-14 02:09:06 +00003880 if (DAG.getMachineFunction().getFunction()->hasFnAttribute(
3881 Attribute::NoImplicitFloat))
Tim Northover3b0846e2014-05-24 12:50:23 +00003882 return SDValue();
3883
Weiming Zhao7a2d1562014-11-19 00:29:14 +00003884 if (!Subtarget->hasNEON())
3885 return SDValue();
3886
Tim Northover3b0846e2014-05-24 12:50:23 +00003887 // While there is no integer popcount instruction, it can
3888 // be more efficiently lowered to the following sequence that uses
3889 // AdvSIMD registers/instructions as long as the copies to/from
3890 // the AdvSIMD registers are cheap.
3891 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd
3892 // CNT V0.8B, V0.8B // 8xbyte pop-counts
3893 // ADDV B0, V0.8B // sum 8xbyte pop-counts
3894 // UMOV X0, V0.B[0] // copy byte result back to integer reg
3895 SDValue Val = Op.getOperand(0);
3896 SDLoc DL(Op);
3897 EVT VT = Op.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00003898
Hao Liue0335d72015-01-30 02:13:53 +00003899 if (VT == MVT::i32)
3900 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
3901 Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
Tim Northover3b0846e2014-05-24 12:50:23 +00003902
Hao Liue0335d72015-01-30 02:13:53 +00003903 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
Tim Northover3b0846e2014-05-24 12:50:23 +00003904 SDValue UaddLV = DAG.getNode(
3905 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003906 DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
Tim Northover3b0846e2014-05-24 12:50:23 +00003907
3908 if (VT == MVT::i64)
3909 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
3910 return UaddLV;
3911}
3912
3913SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3914
3915 if (Op.getValueType().isVector())
3916 return LowerVSETCC(Op, DAG);
3917
3918 SDValue LHS = Op.getOperand(0);
3919 SDValue RHS = Op.getOperand(1);
3920 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3921 SDLoc dl(Op);
3922
3923 // We chose ZeroOrOneBooleanContents, so use zero and one.
3924 EVT VT = Op.getValueType();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003925 SDValue TVal = DAG.getConstant(1, dl, VT);
3926 SDValue FVal = DAG.getConstant(0, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00003927
3928 // Handle f128 first, since one possible outcome is a normal integer
3929 // comparison which gets picked up by the next if statement.
3930 if (LHS.getValueType() == MVT::f128) {
3931 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3932
3933 // If softenSetCCOperands returned a scalar, use it.
3934 if (!RHS.getNode()) {
3935 assert(LHS.getValueType() == Op.getValueType() &&
3936 "Unexpected setcc expansion!");
3937 return LHS;
3938 }
3939 }
3940
3941 if (LHS.getValueType().isInteger()) {
3942 SDValue CCVal;
3943 SDValue Cmp =
3944 getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
3945
3946 // Note that we inverted the condition above, so we reverse the order of
3947 // the true and false operands here. This will allow the setcc to be
3948 // matched to a single CSINC instruction.
3949 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
3950 }
3951
3952 // Now we know we're dealing with FP values.
3953 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3954
3955 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
3956 // and do the comparison.
3957 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3958
3959 AArch64CC::CondCode CC1, CC2;
3960 changeFPCCToAArch64CC(CC, CC1, CC2);
3961 if (CC2 == AArch64CC::AL) {
3962 changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003963 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003964
3965 // Note that we inverted the condition above, so we reverse the order of
3966 // the true and false operands here. This will allow the setcc to be
3967 // matched to a single CSINC instruction.
3968 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
3969 } else {
3970 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
3971 // totally clean. Some of them require two CSELs to implement. As is in
3972 // this case, we emit the first CSEL and then emit a second using the output
3973 // of the first as the RHS. We're effectively OR'ing the two CC's together.
3974
3975 // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003976 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003977 SDValue CS1 =
3978 DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3979
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003980 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003981 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3982 }
3983}
3984
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00003985SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
3986 SDValue RHS, SDValue TVal,
3987 SDValue FVal, SDLoc dl,
Tim Northover3b0846e2014-05-24 12:50:23 +00003988 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00003989 // Handle f128 first, because it will result in a comparison of some RTLIB
3990 // call result against zero.
3991 if (LHS.getValueType() == MVT::f128) {
3992 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3993
3994 // If softenSetCCOperands returned a scalar, we need to compare the result
3995 // against zero to select between true and false values.
3996 if (!RHS.getNode()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003997 RHS = DAG.getConstant(0, dl, LHS.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00003998 CC = ISD::SETNE;
3999 }
4000 }
4001
Ahmed Bougacha88ddeae2015-11-17 16:45:40 +00004002 // Also handle f16, for which we need to do a f32 comparison.
4003 if (LHS.getValueType() == MVT::f16) {
4004 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
4005 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
4006 }
4007
4008 // Next, handle integers.
Tim Northover3b0846e2014-05-24 12:50:23 +00004009 if (LHS.getValueType().isInteger()) {
4010 assert((LHS.getValueType() == RHS.getValueType()) &&
4011 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
4012
4013 unsigned Opcode = AArch64ISD::CSEL;
4014
4015 // If both the TVal and the FVal are constants, see if we can swap them in
4016 // order to for a CSINV or CSINC out of them.
4017 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
4018 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
4019
4020 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
4021 std::swap(TVal, FVal);
4022 std::swap(CTVal, CFVal);
4023 CC = ISD::getSetCCInverse(CC, true);
4024 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
4025 std::swap(TVal, FVal);
4026 std::swap(CTVal, CFVal);
4027 CC = ISD::getSetCCInverse(CC, true);
4028 } else if (TVal.getOpcode() == ISD::XOR) {
4029 // If TVal is a NOT we want to swap TVal and FVal so that we can match
4030 // with a CSINV rather than a CSEL.
Artyom Skrobov314ee042015-11-25 19:41:11 +00004031 if (isAllOnesConstant(TVal.getOperand(1))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004032 std::swap(TVal, FVal);
4033 std::swap(CTVal, CFVal);
4034 CC = ISD::getSetCCInverse(CC, true);
4035 }
4036 } else if (TVal.getOpcode() == ISD::SUB) {
4037 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
4038 // that we can match with a CSNEG rather than a CSEL.
Artyom Skrobov314ee042015-11-25 19:41:11 +00004039 if (isNullConstant(TVal.getOperand(0))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004040 std::swap(TVal, FVal);
4041 std::swap(CTVal, CFVal);
4042 CC = ISD::getSetCCInverse(CC, true);
4043 }
4044 } else if (CTVal && CFVal) {
4045 const int64_t TrueVal = CTVal->getSExtValue();
4046 const int64_t FalseVal = CFVal->getSExtValue();
4047 bool Swap = false;
4048
4049 // If both TVal and FVal are constants, see if FVal is the
4050 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
4051 // instead of a CSEL in that case.
4052 if (TrueVal == ~FalseVal) {
4053 Opcode = AArch64ISD::CSINV;
4054 } else if (TrueVal == -FalseVal) {
4055 Opcode = AArch64ISD::CSNEG;
4056 } else if (TVal.getValueType() == MVT::i32) {
4057 // If our operands are only 32-bit wide, make sure we use 32-bit
4058 // arithmetic for the check whether we can use CSINC. This ensures that
4059 // the addition in the check will wrap around properly in case there is
4060 // an overflow (which would not be the case if we do the check with
4061 // 64-bit arithmetic).
4062 const uint32_t TrueVal32 = CTVal->getZExtValue();
4063 const uint32_t FalseVal32 = CFVal->getZExtValue();
4064
4065 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
4066 Opcode = AArch64ISD::CSINC;
4067
4068 if (TrueVal32 > FalseVal32) {
4069 Swap = true;
4070 }
4071 }
4072 // 64-bit check whether we can use CSINC.
4073 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
4074 Opcode = AArch64ISD::CSINC;
4075
4076 if (TrueVal > FalseVal) {
4077 Swap = true;
4078 }
4079 }
4080
4081 // Swap TVal and FVal if necessary.
4082 if (Swap) {
4083 std::swap(TVal, FVal);
4084 std::swap(CTVal, CFVal);
4085 CC = ISD::getSetCCInverse(CC, true);
4086 }
4087
4088 if (Opcode != AArch64ISD::CSEL) {
4089 // Drop FVal since we can get its value by simply inverting/negating
4090 // TVal.
4091 FVal = TVal;
4092 }
4093 }
4094
4095 SDValue CCVal;
4096 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
4097
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004098 EVT VT = TVal.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00004099 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
4100 }
4101
4102 // Now we know we're dealing with FP values.
4103 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
4104 assert(LHS.getValueType() == RHS.getValueType());
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004105 EVT VT = TVal.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00004106 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
4107
4108 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4109 // clean. Some of them require two CSELs to implement.
4110 AArch64CC::CondCode CC1, CC2;
4111 changeFPCCToAArch64CC(CC, CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004112 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004113 SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4114
4115 // If we need a second CSEL, emit it, using the output of the first as the
4116 // RHS. We're effectively OR'ing the two CC's together.
4117 if (CC2 != AArch64CC::AL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004118 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004119 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4120 }
4121
4122 // Otherwise, return the output of the first CSEL.
4123 return CS1;
4124}
4125
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004126SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
4127 SelectionDAG &DAG) const {
4128 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4129 SDValue LHS = Op.getOperand(0);
4130 SDValue RHS = Op.getOperand(1);
4131 SDValue TVal = Op.getOperand(2);
4132 SDValue FVal = Op.getOperand(3);
4133 SDLoc DL(Op);
4134 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4135}
4136
4137SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
4138 SelectionDAG &DAG) const {
4139 SDValue CCVal = Op->getOperand(0);
4140 SDValue TVal = Op->getOperand(1);
4141 SDValue FVal = Op->getOperand(2);
4142 SDLoc DL(Op);
4143
4144 unsigned Opc = CCVal.getOpcode();
4145 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
4146 // instruction.
4147 if (CCVal.getResNo() == 1 &&
4148 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4149 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
4150 // Only lower legal XALUO ops.
4151 if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
4152 return SDValue();
4153
4154 AArch64CC::CondCode OFCC;
4155 SDValue Value, Overflow;
4156 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004157 SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004158
4159 return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
4160 CCVal, Overflow);
4161 }
4162
4163 // Lower it the same way as we would lower a SELECT_CC node.
4164 ISD::CondCode CC;
4165 SDValue LHS, RHS;
4166 if (CCVal.getOpcode() == ISD::SETCC) {
4167 LHS = CCVal.getOperand(0);
4168 RHS = CCVal.getOperand(1);
4169 CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
4170 } else {
4171 LHS = CCVal;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004172 RHS = DAG.getConstant(0, DL, CCVal.getValueType());
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004173 CC = ISD::SETNE;
4174 }
4175 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4176}
4177
Tim Northover3b0846e2014-05-24 12:50:23 +00004178SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
4179 SelectionDAG &DAG) const {
4180 // Jump table entries as PC relative offsets. No additional tweaking
4181 // is necessary here. Just get the address of the jump table.
4182 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00004183 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004184 SDLoc DL(Op);
4185
4186 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4187 !Subtarget->isTargetMachO()) {
4188 const unsigned char MO_NC = AArch64II::MO_NC;
4189 return DAG.getNode(
4190 AArch64ISD::WrapperLarge, DL, PtrVT,
4191 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G3),
4192 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G2 | MO_NC),
4193 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G1 | MO_NC),
4194 DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4195 AArch64II::MO_G0 | MO_NC));
4196 }
4197
4198 SDValue Hi =
4199 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_PAGE);
4200 SDValue Lo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4201 AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4202 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4203 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4204}
4205
4206SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
4207 SelectionDAG &DAG) const {
4208 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00004209 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004210 SDLoc DL(Op);
4211
4212 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4213 // Use the GOT for the large code model on iOS.
4214 if (Subtarget->isTargetMachO()) {
4215 SDValue GotAddr = DAG.getTargetConstantPool(
4216 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4217 AArch64II::MO_GOT);
4218 return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
4219 }
4220
4221 const unsigned char MO_NC = AArch64II::MO_NC;
4222 return DAG.getNode(
4223 AArch64ISD::WrapperLarge, DL, PtrVT,
4224 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4225 CP->getOffset(), AArch64II::MO_G3),
4226 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4227 CP->getOffset(), AArch64II::MO_G2 | MO_NC),
4228 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4229 CP->getOffset(), AArch64II::MO_G1 | MO_NC),
4230 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4231 CP->getOffset(), AArch64II::MO_G0 | MO_NC));
4232 } else {
4233 // Use ADRP/ADD or ADRP/LDR for everything else: the small memory model on
4234 // ELF, the only valid one on Darwin.
4235 SDValue Hi =
4236 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4237 CP->getOffset(), AArch64II::MO_PAGE);
4238 SDValue Lo = DAG.getTargetConstantPool(
4239 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4240 AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4241
4242 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4243 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4244 }
4245}
4246
4247SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
4248 SelectionDAG &DAG) const {
4249 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
Mehdi Amini44ede332015-07-09 02:09:04 +00004250 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004251 SDLoc DL(Op);
4252 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4253 !Subtarget->isTargetMachO()) {
4254 const unsigned char MO_NC = AArch64II::MO_NC;
4255 return DAG.getNode(
4256 AArch64ISD::WrapperLarge, DL, PtrVT,
4257 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G3),
4258 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
4259 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
4260 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
4261 } else {
4262 SDValue Hi = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGE);
4263 SDValue Lo = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGEOFF |
4264 AArch64II::MO_NC);
4265 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4266 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4267 }
4268}
4269
4270SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
4271 SelectionDAG &DAG) const {
4272 AArch64FunctionInfo *FuncInfo =
4273 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4274
4275 SDLoc DL(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00004276 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
4277 getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00004278 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4279 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
4280 MachinePointerInfo(SV), false, false, 0);
4281}
4282
4283SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
4284 SelectionDAG &DAG) const {
4285 // The layout of the va_list struct is specified in the AArch64 Procedure Call
4286 // Standard, section B.3.
4287 MachineFunction &MF = DAG.getMachineFunction();
4288 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Mehdi Amini44ede332015-07-09 02:09:04 +00004289 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004290 SDLoc DL(Op);
4291
4292 SDValue Chain = Op.getOperand(0);
4293 SDValue VAList = Op.getOperand(1);
4294 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4295 SmallVector<SDValue, 4> MemOps;
4296
4297 // void *__stack at offset 0
Mehdi Amini44ede332015-07-09 02:09:04 +00004298 SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004299 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
4300 MachinePointerInfo(SV), false, false, 8));
4301
4302 // void *__gr_top at offset 8
4303 int GPRSize = FuncInfo->getVarArgsGPRSize();
4304 if (GPRSize > 0) {
4305 SDValue GRTop, GRTopAddr;
4306
Mehdi Amini44ede332015-07-09 02:09:04 +00004307 GRTopAddr =
4308 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004309
Mehdi Amini44ede332015-07-09 02:09:04 +00004310 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
4311 GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
4312 DAG.getConstant(GPRSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004313
4314 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
4315 MachinePointerInfo(SV, 8), false, false, 8));
4316 }
4317
4318 // void *__vr_top at offset 16
4319 int FPRSize = FuncInfo->getVarArgsFPRSize();
4320 if (FPRSize > 0) {
4321 SDValue VRTop, VRTopAddr;
Mehdi Amini44ede332015-07-09 02:09:04 +00004322 VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4323 DAG.getConstant(16, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004324
Mehdi Amini44ede332015-07-09 02:09:04 +00004325 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
4326 VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
4327 DAG.getConstant(FPRSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004328
4329 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
4330 MachinePointerInfo(SV, 16), false, false, 8));
4331 }
4332
4333 // int __gr_offs at offset 24
Mehdi Amini44ede332015-07-09 02:09:04 +00004334 SDValue GROffsAddr =
4335 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004336 MemOps.push_back(DAG.getStore(Chain, DL,
4337 DAG.getConstant(-GPRSize, DL, MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00004338 GROffsAddr, MachinePointerInfo(SV, 24), false,
4339 false, 4));
4340
4341 // int __vr_offs at offset 28
Mehdi Amini44ede332015-07-09 02:09:04 +00004342 SDValue VROffsAddr =
4343 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004344 MemOps.push_back(DAG.getStore(Chain, DL,
4345 DAG.getConstant(-FPRSize, DL, MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00004346 VROffsAddr, MachinePointerInfo(SV, 28), false,
4347 false, 4));
4348
4349 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
4350}
4351
4352SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
4353 SelectionDAG &DAG) const {
4354 return Subtarget->isTargetDarwin() ? LowerDarwin_VASTART(Op, DAG)
4355 : LowerAAPCS_VASTART(Op, DAG);
4356}
4357
4358SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
4359 SelectionDAG &DAG) const {
4360 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
4361 // pointer.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004362 SDLoc DL(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00004363 unsigned VaListSize = Subtarget->isTargetDarwin() ? 8 : 32;
4364 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4365 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4366
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004367 return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1),
4368 Op.getOperand(2),
4369 DAG.getConstant(VaListSize, DL, MVT::i32),
Krzysztof Parzyszeka46c36b2015-04-13 17:16:45 +00004370 8, false, false, false, MachinePointerInfo(DestSV),
Tim Northover3b0846e2014-05-24 12:50:23 +00004371 MachinePointerInfo(SrcSV));
4372}
4373
4374SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
4375 assert(Subtarget->isTargetDarwin() &&
4376 "automatic va_arg instruction only works on Darwin");
4377
4378 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4379 EVT VT = Op.getValueType();
4380 SDLoc DL(Op);
4381 SDValue Chain = Op.getOperand(0);
4382 SDValue Addr = Op.getOperand(1);
4383 unsigned Align = Op.getConstantOperandVal(3);
Mehdi Amini44ede332015-07-09 02:09:04 +00004384 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004385
Mehdi Amini44ede332015-07-09 02:09:04 +00004386 SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V),
4387 false, false, false, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00004388 Chain = VAList.getValue(1);
4389
4390 if (Align > 8) {
4391 assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
Mehdi Amini44ede332015-07-09 02:09:04 +00004392 VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4393 DAG.getConstant(Align - 1, DL, PtrVT));
4394 VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
4395 DAG.getConstant(-(int64_t)Align, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004396 }
4397
4398 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
Mehdi Amini44ede332015-07-09 02:09:04 +00004399 uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
Tim Northover3b0846e2014-05-24 12:50:23 +00004400
4401 // Scalar integer and FP values smaller than 64 bits are implicitly extended
4402 // up to 64 bits. At the very least, we have to increase the striding of the
4403 // vaargs list to match this, and for FP values we need to introduce
4404 // FP_ROUND nodes as well.
4405 if (VT.isInteger() && !VT.isVector())
4406 ArgSize = 8;
4407 bool NeedFPTrunc = false;
4408 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
4409 ArgSize = 8;
4410 NeedFPTrunc = true;
4411 }
4412
4413 // Increment the pointer, VAList, to the next vaarg
Mehdi Amini44ede332015-07-09 02:09:04 +00004414 SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4415 DAG.getConstant(ArgSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004416 // Store the incremented VAList to the legalized pointer
4417 SDValue APStore = DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V),
4418 false, false, 0);
4419
4420 // Load the actual argument out of the pointer VAList
4421 if (NeedFPTrunc) {
4422 // Load the value as an f64.
4423 SDValue WideFP = DAG.getLoad(MVT::f64, DL, APStore, VAList,
4424 MachinePointerInfo(), false, false, false, 0);
4425 // Round the value down to an f32.
4426 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004427 DAG.getIntPtrConstant(1, DL));
Tim Northover3b0846e2014-05-24 12:50:23 +00004428 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
4429 // Merge the rounded value with the chain output of the load.
4430 return DAG.getMergeValues(Ops, DL);
4431 }
4432
4433 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo(), false,
4434 false, false, 0);
4435}
4436
4437SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
4438 SelectionDAG &DAG) const {
4439 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4440 MFI->setFrameAddressIsTaken(true);
4441
4442 EVT VT = Op.getValueType();
4443 SDLoc DL(Op);
4444 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4445 SDValue FrameAddr =
4446 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
4447 while (Depth--)
4448 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
4449 MachinePointerInfo(), false, false, false, 0);
4450 return FrameAddr;
4451}
4452
4453// FIXME? Maybe this could be a TableGen attribute on some registers and
4454// this table could be generated automatically from RegInfo.
Pat Gavlina717f252015-07-09 17:40:29 +00004455unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT,
4456 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004457 unsigned Reg = StringSwitch<unsigned>(RegName)
4458 .Case("sp", AArch64::SP)
4459 .Default(0);
4460 if (Reg)
4461 return Reg;
Luke Cheeseman85fd06d2015-06-01 12:02:47 +00004462 report_fatal_error(Twine("Invalid register name \""
4463 + StringRef(RegName) + "\"."));
Tim Northover3b0846e2014-05-24 12:50:23 +00004464}
4465
4466SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
4467 SelectionDAG &DAG) const {
4468 MachineFunction &MF = DAG.getMachineFunction();
4469 MachineFrameInfo *MFI = MF.getFrameInfo();
4470 MFI->setReturnAddressIsTaken(true);
4471
4472 EVT VT = Op.getValueType();
4473 SDLoc DL(Op);
4474 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4475 if (Depth) {
4476 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
Mehdi Amini44ede332015-07-09 02:09:04 +00004477 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00004478 return DAG.getLoad(VT, DL, DAG.getEntryNode(),
4479 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
4480 MachinePointerInfo(), false, false, false, 0);
4481 }
4482
4483 // Return LR, which contains the return address. Mark it an implicit live-in.
4484 unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
4485 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4486}
4487
4488/// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4489/// i64 values and take a 2 x i64 value to shift plus a shift amount.
4490SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
4491 SelectionDAG &DAG) const {
4492 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4493 EVT VT = Op.getValueType();
4494 unsigned VTBits = VT.getSizeInBits();
4495 SDLoc dl(Op);
4496 SDValue ShOpLo = Op.getOperand(0);
4497 SDValue ShOpHi = Op.getOperand(1);
4498 SDValue ShAmt = Op.getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00004499 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4500
4501 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4502
4503 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004504 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
Tim Northoverf3be9d52015-12-02 00:33:54 +00004505 SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4506
4507 // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
4508 // is "undef". We wanted 0, so CSEL it directly.
4509 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
4510 ISD::SETEQ, dl, DAG);
4511 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
4512 HiBitsForLo =
4513 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
4514 HiBitsForLo, CCVal, Cmp);
4515
Tim Northover3b0846e2014-05-24 12:50:23 +00004516 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004517 DAG.getConstant(VTBits, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00004518
Tim Northoverf3be9d52015-12-02 00:33:54 +00004519 SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4520 SDValue LoForNormalShift =
4521 DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
Tim Northover3b0846e2014-05-24 12:50:23 +00004522
Tim Northoverf3be9d52015-12-02 00:33:54 +00004523 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
4524 dl, DAG);
4525 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4526 SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4527 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
4528 LoForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00004529
4530 // AArch64 shifts larger than the register width are wrapped rather than
4531 // clamped, so we can't just emit "hi >> x".
Tim Northoverf3be9d52015-12-02 00:33:54 +00004532 SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4533 SDValue HiForBigShift =
4534 Opc == ISD::SRA
4535 ? DAG.getNode(Opc, dl, VT, ShOpHi,
4536 DAG.getConstant(VTBits - 1, dl, MVT::i64))
4537 : DAG.getConstant(0, dl, VT);
4538 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
4539 HiForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00004540
4541 SDValue Ops[2] = { Lo, Hi };
4542 return DAG.getMergeValues(Ops, dl);
4543}
4544
Tim Northoverf3be9d52015-12-02 00:33:54 +00004545
Tim Northover3b0846e2014-05-24 12:50:23 +00004546/// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4547/// i64 values and take a 2 x i64 value to shift plus a shift amount.
4548SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
Tim Northoverf3be9d52015-12-02 00:33:54 +00004549 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004550 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4551 EVT VT = Op.getValueType();
4552 unsigned VTBits = VT.getSizeInBits();
4553 SDLoc dl(Op);
4554 SDValue ShOpLo = Op.getOperand(0);
4555 SDValue ShOpHi = Op.getOperand(1);
4556 SDValue ShAmt = Op.getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00004557
4558 assert(Op.getOpcode() == ISD::SHL_PARTS);
4559 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004560 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
Tim Northoverf3be9d52015-12-02 00:33:54 +00004561 SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4562
4563 // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
4564 // is "undef". We wanted 0, so CSEL it directly.
4565 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
4566 ISD::SETEQ, dl, DAG);
4567 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
4568 LoBitsForHi =
4569 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
4570 LoBitsForHi, CCVal, Cmp);
4571
Tim Northover3b0846e2014-05-24 12:50:23 +00004572 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004573 DAG.getConstant(VTBits, dl, MVT::i64));
Tim Northoverf3be9d52015-12-02 00:33:54 +00004574 SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4575 SDValue HiForNormalShift =
4576 DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
Tim Northover3b0846e2014-05-24 12:50:23 +00004577
Tim Northoverf3be9d52015-12-02 00:33:54 +00004578 SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
Tim Northover3b0846e2014-05-24 12:50:23 +00004579
Tim Northoverf3be9d52015-12-02 00:33:54 +00004580 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
4581 dl, DAG);
4582 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4583 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
4584 HiForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00004585
4586 // AArch64 shifts of larger than register sizes are wrapped rather than
4587 // clamped, so we can't just emit "lo << a" if a is too big.
Tim Northoverf3be9d52015-12-02 00:33:54 +00004588 SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
4589 SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4590 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
4591 LoForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00004592
4593 SDValue Ops[2] = { Lo, Hi };
4594 return DAG.getMergeValues(Ops, dl);
4595}
4596
4597bool AArch64TargetLowering::isOffsetFoldingLegal(
4598 const GlobalAddressSDNode *GA) const {
4599 // The AArch64 target doesn't support folding offsets into global addresses.
4600 return false;
4601}
4602
4603bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4604 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
4605 // FIXME: We should be able to handle f128 as well with a clever lowering.
4606 if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32))
4607 return true;
4608
4609 if (VT == MVT::f64)
4610 return AArch64_AM::getFP64Imm(Imm) != -1;
4611 else if (VT == MVT::f32)
4612 return AArch64_AM::getFP32Imm(Imm) != -1;
4613 return false;
4614}
4615
4616//===----------------------------------------------------------------------===//
4617// AArch64 Optimization Hooks
4618//===----------------------------------------------------------------------===//
4619
4620//===----------------------------------------------------------------------===//
4621// AArch64 Inline Assembly Support
4622//===----------------------------------------------------------------------===//
4623
4624// Table of Constraints
4625// TODO: This is the current set of constraints supported by ARM for the
4626// compiler, not all of them may make sense, e.g. S may be difficult to support.
4627//
4628// r - A general register
4629// w - An FP/SIMD register of some size in the range v0-v31
4630// x - An FP/SIMD register of some size in the range v0-v15
4631// I - Constant that can be used with an ADD instruction
4632// J - Constant that can be used with a SUB instruction
4633// K - Constant that can be used with a 32-bit logical instruction
4634// L - Constant that can be used with a 64-bit logical instruction
4635// M - Constant that can be used as a 32-bit MOV immediate
4636// N - Constant that can be used as a 64-bit MOV immediate
4637// Q - A memory reference with base register and no offset
4638// S - A symbolic address
4639// Y - Floating point constant zero
4640// Z - Integer constant zero
4641//
4642// Note that general register operands will be output using their 64-bit x
4643// register name, whatever the size of the variable, unless the asm operand
4644// is prefixed by the %w modifier. Floating-point and SIMD register operands
4645// will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
4646// %q modifier.
4647
4648/// getConstraintType - Given a constraint letter, return the type of
4649/// constraint it is for this target.
4650AArch64TargetLowering::ConstraintType
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00004651AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004652 if (Constraint.size() == 1) {
4653 switch (Constraint[0]) {
4654 default:
4655 break;
4656 case 'z':
4657 return C_Other;
4658 case 'x':
4659 case 'w':
4660 return C_RegisterClass;
4661 // An address with a single base register. Due to the way we
4662 // currently handle addresses it is the same as 'r'.
4663 case 'Q':
4664 return C_Memory;
4665 }
4666 }
4667 return TargetLowering::getConstraintType(Constraint);
4668}
4669
4670/// Examine constraint type and operand type and determine a weight value.
4671/// This object must already have been set up with the operand type
4672/// and the current alternative constraint selected.
4673TargetLowering::ConstraintWeight
4674AArch64TargetLowering::getSingleConstraintMatchWeight(
4675 AsmOperandInfo &info, const char *constraint) const {
4676 ConstraintWeight weight = CW_Invalid;
4677 Value *CallOperandVal = info.CallOperandVal;
4678 // If we don't have a value, we can't do a match,
4679 // but allow it at the lowest weight.
4680 if (!CallOperandVal)
4681 return CW_Default;
4682 Type *type = CallOperandVal->getType();
4683 // Look at the constraint type.
4684 switch (*constraint) {
4685 default:
4686 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
4687 break;
4688 case 'x':
4689 case 'w':
4690 if (type->isFloatingPointTy() || type->isVectorTy())
4691 weight = CW_Register;
4692 break;
4693 case 'z':
4694 weight = CW_Constant;
4695 break;
4696 }
4697 return weight;
4698}
4699
4700std::pair<unsigned, const TargetRegisterClass *>
4701AArch64TargetLowering::getRegForInlineAsmConstraint(
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00004702 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004703 if (Constraint.size() == 1) {
4704 switch (Constraint[0]) {
4705 case 'r':
4706 if (VT.getSizeInBits() == 64)
4707 return std::make_pair(0U, &AArch64::GPR64commonRegClass);
4708 return std::make_pair(0U, &AArch64::GPR32commonRegClass);
4709 case 'w':
4710 if (VT == MVT::f32)
4711 return std::make_pair(0U, &AArch64::FPR32RegClass);
4712 if (VT.getSizeInBits() == 64)
4713 return std::make_pair(0U, &AArch64::FPR64RegClass);
4714 if (VT.getSizeInBits() == 128)
4715 return std::make_pair(0U, &AArch64::FPR128RegClass);
4716 break;
4717 // The instructions that this constraint is designed for can
4718 // only take 128-bit registers so just use that regclass.
4719 case 'x':
4720 if (VT.getSizeInBits() == 128)
4721 return std::make_pair(0U, &AArch64::FPR128_loRegClass);
4722 break;
4723 }
4724 }
4725 if (StringRef("{cc}").equals_lower(Constraint))
4726 return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
4727
4728 // Use the default implementation in TargetLowering to convert the register
4729 // constraint into a member of a register class.
4730 std::pair<unsigned, const TargetRegisterClass *> Res;
Eric Christopher11e4df72015-02-26 22:38:43 +00004731 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004732
4733 // Not found as a standard register?
4734 if (!Res.second) {
4735 unsigned Size = Constraint.size();
4736 if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
4737 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00004738 int RegNo;
4739 bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
4740 if (!Failed && RegNo >= 0 && RegNo <= 31) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004741 // v0 - v31 are aliases of q0 - q31.
4742 // By default we'll emit v0-v31 for this unless there's a modifier where
4743 // we'll emit the correct register as well.
4744 Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
4745 Res.second = &AArch64::FPR128RegClass;
4746 }
4747 }
4748 }
4749
4750 return Res;
4751}
4752
4753/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
4754/// vector. If it is invalid, don't add anything to Ops.
4755void AArch64TargetLowering::LowerAsmOperandForConstraint(
4756 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
4757 SelectionDAG &DAG) const {
4758 SDValue Result;
4759
4760 // Currently only support length 1 constraints.
4761 if (Constraint.length() != 1)
4762 return;
4763
4764 char ConstraintLetter = Constraint[0];
4765 switch (ConstraintLetter) {
4766 default:
4767 break;
4768
4769 // This set of constraints deal with valid constants for various instructions.
4770 // Validate and return a target constant for them if we can.
4771 case 'z': {
4772 // 'z' maps to xzr or wzr so it needs an input of 0.
Artyom Skrobov314ee042015-11-25 19:41:11 +00004773 if (!isNullConstant(Op))
Tim Northover3b0846e2014-05-24 12:50:23 +00004774 return;
4775
4776 if (Op.getValueType() == MVT::i64)
4777 Result = DAG.getRegister(AArch64::XZR, MVT::i64);
4778 else
4779 Result = DAG.getRegister(AArch64::WZR, MVT::i32);
4780 break;
4781 }
4782
4783 case 'I':
4784 case 'J':
4785 case 'K':
4786 case 'L':
4787 case 'M':
4788 case 'N':
4789 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4790 if (!C)
4791 return;
4792
4793 // Grab the value and do some validation.
4794 uint64_t CVal = C->getZExtValue();
4795 switch (ConstraintLetter) {
4796 // The I constraint applies only to simple ADD or SUB immediate operands:
4797 // i.e. 0 to 4095 with optional shift by 12
4798 // The J constraint applies only to ADD or SUB immediates that would be
4799 // valid when negated, i.e. if [an add pattern] were to be output as a SUB
4800 // instruction [or vice versa], in other words -1 to -4095 with optional
4801 // left shift by 12.
4802 case 'I':
4803 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
4804 break;
4805 return;
4806 case 'J': {
4807 uint64_t NVal = -C->getSExtValue();
Tim Northover2c46beb2014-07-27 07:10:29 +00004808 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
4809 CVal = C->getSExtValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00004810 break;
Tim Northover2c46beb2014-07-27 07:10:29 +00004811 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004812 return;
4813 }
4814 // The K and L constraints apply *only* to logical immediates, including
4815 // what used to be the MOVI alias for ORR (though the MOVI alias has now
4816 // been removed and MOV should be used). So these constraints have to
4817 // distinguish between bit patterns that are valid 32-bit or 64-bit
4818 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
4819 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
4820 // versa.
4821 case 'K':
4822 if (AArch64_AM::isLogicalImmediate(CVal, 32))
4823 break;
4824 return;
4825 case 'L':
4826 if (AArch64_AM::isLogicalImmediate(CVal, 64))
4827 break;
4828 return;
4829 // The M and N constraints are a superset of K and L respectively, for use
4830 // with the MOV (immediate) alias. As well as the logical immediates they
4831 // also match 32 or 64-bit immediates that can be loaded either using a
4832 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
4833 // (M) or 64-bit 0x1234000000000000 (N) etc.
4834 // As a note some of this code is liberally stolen from the asm parser.
4835 case 'M': {
4836 if (!isUInt<32>(CVal))
4837 return;
4838 if (AArch64_AM::isLogicalImmediate(CVal, 32))
4839 break;
4840 if ((CVal & 0xFFFF) == CVal)
4841 break;
4842 if ((CVal & 0xFFFF0000ULL) == CVal)
4843 break;
4844 uint64_t NCVal = ~(uint32_t)CVal;
4845 if ((NCVal & 0xFFFFULL) == NCVal)
4846 break;
4847 if ((NCVal & 0xFFFF0000ULL) == NCVal)
4848 break;
4849 return;
4850 }
4851 case 'N': {
4852 if (AArch64_AM::isLogicalImmediate(CVal, 64))
4853 break;
4854 if ((CVal & 0xFFFFULL) == CVal)
4855 break;
4856 if ((CVal & 0xFFFF0000ULL) == CVal)
4857 break;
4858 if ((CVal & 0xFFFF00000000ULL) == CVal)
4859 break;
4860 if ((CVal & 0xFFFF000000000000ULL) == CVal)
4861 break;
4862 uint64_t NCVal = ~CVal;
4863 if ((NCVal & 0xFFFFULL) == NCVal)
4864 break;
4865 if ((NCVal & 0xFFFF0000ULL) == NCVal)
4866 break;
4867 if ((NCVal & 0xFFFF00000000ULL) == NCVal)
4868 break;
4869 if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
4870 break;
4871 return;
4872 }
4873 default:
4874 return;
4875 }
4876
4877 // All assembler immediates are 64-bit integers.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004878 Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00004879 break;
4880 }
4881
4882 if (Result.getNode()) {
4883 Ops.push_back(Result);
4884 return;
4885 }
4886
4887 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
4888}
4889
4890//===----------------------------------------------------------------------===//
4891// AArch64 Advanced SIMD Support
4892//===----------------------------------------------------------------------===//
4893
4894/// WidenVector - Given a value in the V64 register class, produce the
4895/// equivalent value in the V128 register class.
4896static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
4897 EVT VT = V64Reg.getValueType();
4898 unsigned NarrowSize = VT.getVectorNumElements();
4899 MVT EltTy = VT.getVectorElementType().getSimpleVT();
4900 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
4901 SDLoc DL(V64Reg);
4902
4903 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004904 V64Reg, DAG.getConstant(0, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00004905}
4906
4907/// getExtFactor - Determine the adjustment factor for the position when
4908/// generating an "extract from vector registers" instruction.
4909static unsigned getExtFactor(SDValue &V) {
4910 EVT EltType = V.getValueType().getVectorElementType();
4911 return EltType.getSizeInBits() / 8;
4912}
4913
4914/// NarrowVector - Given a value in the V128 register class, produce the
4915/// equivalent value in the V64 register class.
4916static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
4917 EVT VT = V128Reg.getValueType();
4918 unsigned WideSize = VT.getVectorNumElements();
4919 MVT EltTy = VT.getVectorElementType().getSimpleVT();
4920 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
4921 SDLoc DL(V128Reg);
4922
4923 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
4924}
4925
4926// Gather data to see if the operation can be modelled as a
4927// shuffle in combination with VEXTs.
4928SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
4929 SelectionDAG &DAG) const {
Kevin Qinf0ec9af2014-06-18 05:54:42 +00004930 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
Tim Northover3b0846e2014-05-24 12:50:23 +00004931 SDLoc dl(Op);
4932 EVT VT = Op.getValueType();
4933 unsigned NumElts = VT.getVectorNumElements();
4934
Tim Northover7324e842014-07-24 15:39:55 +00004935 struct ShuffleSourceInfo {
4936 SDValue Vec;
4937 unsigned MinElt;
4938 unsigned MaxElt;
Tim Northover3b0846e2014-05-24 12:50:23 +00004939
Tim Northover7324e842014-07-24 15:39:55 +00004940 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
4941 // be compatible with the shuffle we intend to construct. As a result
4942 // ShuffleVec will be some sliding window into the original Vec.
4943 SDValue ShuffleVec;
4944
4945 // Code should guarantee that element i in Vec starts at element "WindowBase
4946 // + i * WindowScale in ShuffleVec".
4947 int WindowBase;
4948 int WindowScale;
4949
4950 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
4951 ShuffleSourceInfo(SDValue Vec)
4952 : Vec(Vec), MinElt(UINT_MAX), MaxElt(0), ShuffleVec(Vec), WindowBase(0),
4953 WindowScale(1) {}
4954 };
4955
4956 // First gather all vectors used as an immediate source for this BUILD_VECTOR
4957 // node.
4958 SmallVector<ShuffleSourceInfo, 2> Sources;
Tim Northover3b0846e2014-05-24 12:50:23 +00004959 for (unsigned i = 0; i < NumElts; ++i) {
4960 SDValue V = Op.getOperand(i);
4961 if (V.getOpcode() == ISD::UNDEF)
4962 continue;
Ahmed Bougachadfc77352016-01-14 02:12:30 +00004963 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4964 !isa<ConstantSDNode>(V.getOperand(1))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004965 // A shuffle can only come from building a vector from various
Ahmed Bougachadfc77352016-01-14 02:12:30 +00004966 // elements of other vectors, provided their indices are constant.
Tim Northover3b0846e2014-05-24 12:50:23 +00004967 return SDValue();
4968 }
4969
Tim Northover7324e842014-07-24 15:39:55 +00004970 // Add this element source to the list if it's not already there.
Tim Northover3b0846e2014-05-24 12:50:23 +00004971 SDValue SourceVec = V.getOperand(0);
Tim Northover7324e842014-07-24 15:39:55 +00004972 auto Source = std::find(Sources.begin(), Sources.end(), SourceVec);
4973 if (Source == Sources.end())
James Molloyf497d552014-10-17 17:06:31 +00004974 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
Tim Northover3b0846e2014-05-24 12:50:23 +00004975
Tim Northover7324e842014-07-24 15:39:55 +00004976 // Update the minimum and maximum lane number seen.
4977 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
4978 Source->MinElt = std::min(Source->MinElt, EltNo);
4979 Source->MaxElt = std::max(Source->MaxElt, EltNo);
Tim Northover3b0846e2014-05-24 12:50:23 +00004980 }
4981
4982 // Currently only do something sane when at most two source vectors
Tim Northover7324e842014-07-24 15:39:55 +00004983 // are involved.
4984 if (Sources.size() > 2)
Tim Northover3b0846e2014-05-24 12:50:23 +00004985 return SDValue();
4986
Kevin Qin9a2a2c52014-07-24 02:05:42 +00004987 // Find out the smallest element size among result and two sources, and use
4988 // it as element size to build the shuffle_vector.
4989 EVT SmallestEltTy = VT.getVectorElementType();
Tim Northover7324e842014-07-24 15:39:55 +00004990 for (auto &Source : Sources) {
4991 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00004992 if (SrcEltTy.bitsLT(SmallestEltTy)) {
4993 SmallestEltTy = SrcEltTy;
4994 }
4995 }
4996 unsigned ResMultiplier =
4997 VT.getVectorElementType().getSizeInBits() / SmallestEltTy.getSizeInBits();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00004998 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
4999 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
Tim Northover3b0846e2014-05-24 12:50:23 +00005000
Tim Northover7324e842014-07-24 15:39:55 +00005001 // If the source vector is too wide or too narrow, we may nevertheless be able
5002 // to construct a compatible shuffle either by concatenating it with UNDEF or
5003 // extracting a suitable range of elements.
5004 for (auto &Src : Sources) {
5005 EVT SrcVT = Src.ShuffleVec.getValueType();
Kevin Qinf0ec9af2014-06-18 05:54:42 +00005006
Tim Northover7324e842014-07-24 15:39:55 +00005007 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
Tim Northover3b0846e2014-05-24 12:50:23 +00005008 continue;
Tim Northover7324e842014-07-24 15:39:55 +00005009
5010 // This stage of the search produces a source with the same element type as
5011 // the original, but with a total width matching the BUILD_VECTOR output.
5012 EVT EltVT = SrcVT.getVectorElementType();
James Molloyf497d552014-10-17 17:06:31 +00005013 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
5014 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
Tim Northover7324e842014-07-24 15:39:55 +00005015
5016 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
5017 assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00005018 // We can pad out the smaller vector for free, so if it's part of a
5019 // shuffle...
Tim Northover7324e842014-07-24 15:39:55 +00005020 Src.ShuffleVec =
5021 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
5022 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00005023 continue;
5024 }
5025
Tim Northover7324e842014-07-24 15:39:55 +00005026 assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00005027
James Molloyf497d552014-10-17 17:06:31 +00005028 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005029 // Span too large for a VEXT to cope
5030 return SDValue();
5031 }
5032
James Molloyf497d552014-10-17 17:06:31 +00005033 if (Src.MinElt >= NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005034 // The extraction can just take the second half
Tim Northover7324e842014-07-24 15:39:55 +00005035 Src.ShuffleVec =
5036 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005037 DAG.getConstant(NumSrcElts, dl, MVT::i64));
James Molloyf497d552014-10-17 17:06:31 +00005038 Src.WindowBase = -NumSrcElts;
5039 } else if (Src.MaxElt < NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005040 // The extraction can just take the first half
Tim Northover5e84fe32014-12-06 00:33:37 +00005041 Src.ShuffleVec =
5042 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005043 DAG.getConstant(0, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005044 } else {
5045 // An actual VEXT is needed
Tim Northover5e84fe32014-12-06 00:33:37 +00005046 SDValue VEXTSrc1 =
5047 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005048 DAG.getConstant(0, dl, MVT::i64));
Tim Northover7324e842014-07-24 15:39:55 +00005049 SDValue VEXTSrc2 =
5050 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005051 DAG.getConstant(NumSrcElts, dl, MVT::i64));
Tim Northover7324e842014-07-24 15:39:55 +00005052 unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
5053
5054 Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005055 VEXTSrc2,
5056 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover7324e842014-07-24 15:39:55 +00005057 Src.WindowBase = -Src.MinElt;
Tim Northover3b0846e2014-05-24 12:50:23 +00005058 }
5059 }
5060
Tim Northover7324e842014-07-24 15:39:55 +00005061 // Another possible incompatibility occurs from the vector element types. We
5062 // can fix this by bitcasting the source vectors to the same type we intend
5063 // for the shuffle.
5064 for (auto &Src : Sources) {
5065 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
5066 if (SrcEltTy == SmallestEltTy)
5067 continue;
5068 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
5069 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
5070 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
5071 Src.WindowBase *= Src.WindowScale;
5072 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005073
Tim Northover7324e842014-07-24 15:39:55 +00005074 // Final sanity check before we try to actually produce a shuffle.
5075 DEBUG(
5076 for (auto Src : Sources)
5077 assert(Src.ShuffleVec.getValueType() == ShuffleVT);
5078 );
5079
5080 // The stars all align, our next step is to produce the mask for the shuffle.
5081 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
5082 int BitsPerShuffleLane = ShuffleVT.getVectorElementType().getSizeInBits();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00005083 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005084 SDValue Entry = Op.getOperand(i);
Tim Northover7324e842014-07-24 15:39:55 +00005085 if (Entry.getOpcode() == ISD::UNDEF)
5086 continue;
Tim Northover3b0846e2014-05-24 12:50:23 +00005087
Tim Northover7324e842014-07-24 15:39:55 +00005088 auto Src = std::find(Sources.begin(), Sources.end(), Entry.getOperand(0));
5089 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
5090
5091 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
5092 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
5093 // segment.
5094 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
5095 int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
5096 VT.getVectorElementType().getSizeInBits());
5097 int LanesDefined = BitsDefined / BitsPerShuffleLane;
5098
5099 // This source is expected to fill ResMultiplier lanes of the final shuffle,
5100 // starting at the appropriate offset.
5101 int *LaneMask = &Mask[i * ResMultiplier];
5102
5103 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
5104 ExtractBase += NumElts * (Src - Sources.begin());
5105 for (int j = 0; j < LanesDefined; ++j)
5106 LaneMask[j] = ExtractBase + j;
Tim Northover3b0846e2014-05-24 12:50:23 +00005107 }
5108
5109 // Final check before we try to produce nonsense...
Tim Northover7324e842014-07-24 15:39:55 +00005110 if (!isShuffleMaskLegal(Mask, ShuffleVT))
5111 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00005112
Tim Northover7324e842014-07-24 15:39:55 +00005113 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
5114 for (unsigned i = 0; i < Sources.size(); ++i)
5115 ShuffleOps[i] = Sources[i].ShuffleVec;
5116
5117 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
5118 ShuffleOps[1], &Mask[0]);
5119 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
Tim Northover3b0846e2014-05-24 12:50:23 +00005120}
5121
5122// check if an EXT instruction can handle the shuffle mask when the
5123// vector sources of the shuffle are the same.
5124static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
5125 unsigned NumElts = VT.getVectorNumElements();
5126
5127 // Assume that the first shuffle index is not UNDEF. Fail if it is.
5128 if (M[0] < 0)
5129 return false;
5130
5131 Imm = M[0];
5132
5133 // If this is a VEXT shuffle, the immediate value is the index of the first
5134 // element. The other shuffle indices must be the successive elements after
5135 // the first one.
5136 unsigned ExpectedElt = Imm;
5137 for (unsigned i = 1; i < NumElts; ++i) {
5138 // Increment the expected index. If it wraps around, just follow it
5139 // back to index zero and keep going.
5140 ++ExpectedElt;
5141 if (ExpectedElt == NumElts)
5142 ExpectedElt = 0;
5143
5144 if (M[i] < 0)
5145 continue; // ignore UNDEF indices
5146 if (ExpectedElt != static_cast<unsigned>(M[i]))
5147 return false;
5148 }
5149
5150 return true;
5151}
5152
5153// check if an EXT instruction can handle the shuffle mask when the
5154// vector sources of the shuffle are different.
5155static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
5156 unsigned &Imm) {
5157 // Look for the first non-undef element.
5158 const int *FirstRealElt = std::find_if(M.begin(), M.end(),
5159 [](int Elt) {return Elt >= 0;});
5160
5161 // Benefit form APInt to handle overflow when calculating expected element.
5162 unsigned NumElts = VT.getVectorNumElements();
5163 unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
5164 APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
5165 // The following shuffle indices must be the successive elements after the
5166 // first real element.
5167 const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
5168 [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
5169 if (FirstWrongElt != M.end())
5170 return false;
5171
5172 // The index of an EXT is the first element if it is not UNDEF.
5173 // Watch out for the beginning UNDEFs. The EXT index should be the expected
Junmo Park3b8c7152016-01-05 09:36:47 +00005174 // value of the first element. E.g.
Tim Northover3b0846e2014-05-24 12:50:23 +00005175 // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
5176 // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
5177 // ExpectedElt is the last mask index plus 1.
5178 Imm = ExpectedElt.getZExtValue();
5179
5180 // There are two difference cases requiring to reverse input vectors.
5181 // For example, for vector <4 x i32> we have the following cases,
5182 // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
5183 // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
5184 // For both cases, we finally use mask <5, 6, 7, 0>, which requires
5185 // to reverse two input vectors.
5186 if (Imm < NumElts)
5187 ReverseEXT = true;
5188 else
5189 Imm -= NumElts;
5190
5191 return true;
5192}
5193
5194/// isREVMask - Check if a vector shuffle corresponds to a REV
5195/// instruction with the specified blocksize. (The order of the elements
5196/// within each block of the vector is reversed.)
5197static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5198 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
5199 "Only possible block sizes for REV are: 16, 32, 64");
5200
5201 unsigned EltSz = VT.getVectorElementType().getSizeInBits();
5202 if (EltSz == 64)
5203 return false;
5204
5205 unsigned NumElts = VT.getVectorNumElements();
5206 unsigned BlockElts = M[0] + 1;
5207 // If the first shuffle index is UNDEF, be optimistic.
5208 if (M[0] < 0)
5209 BlockElts = BlockSize / EltSz;
5210
5211 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5212 return false;
5213
5214 for (unsigned i = 0; i < NumElts; ++i) {
5215 if (M[i] < 0)
5216 continue; // ignore UNDEF indices
5217 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
5218 return false;
5219 }
5220
5221 return true;
5222}
5223
5224static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5225 unsigned NumElts = VT.getVectorNumElements();
5226 WhichResult = (M[0] == 0 ? 0 : 1);
5227 unsigned Idx = WhichResult * NumElts / 2;
5228 for (unsigned i = 0; i != NumElts; i += 2) {
5229 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5230 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
5231 return false;
5232 Idx += 1;
5233 }
5234
5235 return true;
5236}
5237
5238static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5239 unsigned NumElts = VT.getVectorNumElements();
5240 WhichResult = (M[0] == 0 ? 0 : 1);
5241 for (unsigned i = 0; i != NumElts; ++i) {
5242 if (M[i] < 0)
5243 continue; // ignore UNDEF indices
5244 if ((unsigned)M[i] != 2 * i + WhichResult)
5245 return false;
5246 }
5247
5248 return true;
5249}
5250
5251static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5252 unsigned NumElts = VT.getVectorNumElements();
5253 WhichResult = (M[0] == 0 ? 0 : 1);
5254 for (unsigned i = 0; i < NumElts; i += 2) {
5255 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5256 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
5257 return false;
5258 }
5259 return true;
5260}
5261
5262/// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
5263/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5264/// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5265static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5266 unsigned NumElts = VT.getVectorNumElements();
5267 WhichResult = (M[0] == 0 ? 0 : 1);
5268 unsigned Idx = WhichResult * NumElts / 2;
5269 for (unsigned i = 0; i != NumElts; i += 2) {
5270 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5271 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
5272 return false;
5273 Idx += 1;
5274 }
5275
5276 return true;
5277}
5278
5279/// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
5280/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5281/// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5282static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5283 unsigned Half = VT.getVectorNumElements() / 2;
5284 WhichResult = (M[0] == 0 ? 0 : 1);
5285 for (unsigned j = 0; j != 2; ++j) {
5286 unsigned Idx = WhichResult;
5287 for (unsigned i = 0; i != Half; ++i) {
5288 int MIdx = M[i + j * Half];
5289 if (MIdx >= 0 && (unsigned)MIdx != Idx)
5290 return false;
5291 Idx += 2;
5292 }
5293 }
5294
5295 return true;
5296}
5297
5298/// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
5299/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5300/// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5301static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5302 unsigned NumElts = VT.getVectorNumElements();
5303 WhichResult = (M[0] == 0 ? 0 : 1);
5304 for (unsigned i = 0; i < NumElts; i += 2) {
5305 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5306 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
5307 return false;
5308 }
5309 return true;
5310}
5311
5312static bool isINSMask(ArrayRef<int> M, int NumInputElements,
5313 bool &DstIsLeft, int &Anomaly) {
5314 if (M.size() != static_cast<size_t>(NumInputElements))
5315 return false;
5316
5317 int NumLHSMatch = 0, NumRHSMatch = 0;
5318 int LastLHSMismatch = -1, LastRHSMismatch = -1;
5319
5320 for (int i = 0; i < NumInputElements; ++i) {
5321 if (M[i] == -1) {
5322 ++NumLHSMatch;
5323 ++NumRHSMatch;
5324 continue;
5325 }
5326
5327 if (M[i] == i)
5328 ++NumLHSMatch;
5329 else
5330 LastLHSMismatch = i;
5331
5332 if (M[i] == i + NumInputElements)
5333 ++NumRHSMatch;
5334 else
5335 LastRHSMismatch = i;
5336 }
5337
5338 if (NumLHSMatch == NumInputElements - 1) {
5339 DstIsLeft = true;
5340 Anomaly = LastLHSMismatch;
5341 return true;
5342 } else if (NumRHSMatch == NumInputElements - 1) {
5343 DstIsLeft = false;
5344 Anomaly = LastRHSMismatch;
5345 return true;
5346 }
5347
5348 return false;
5349}
5350
5351static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
5352 if (VT.getSizeInBits() != 128)
5353 return false;
5354
5355 unsigned NumElts = VT.getVectorNumElements();
5356
5357 for (int I = 0, E = NumElts / 2; I != E; I++) {
5358 if (Mask[I] != I)
5359 return false;
5360 }
5361
5362 int Offset = NumElts / 2;
5363 for (int I = NumElts / 2, E = NumElts; I != E; I++) {
5364 if (Mask[I] != I + SplitLHS * Offset)
5365 return false;
5366 }
5367
5368 return true;
5369}
5370
5371static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
5372 SDLoc DL(Op);
5373 EVT VT = Op.getValueType();
5374 SDValue V0 = Op.getOperand(0);
5375 SDValue V1 = Op.getOperand(1);
5376 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
5377
5378 if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
5379 VT.getVectorElementType() != V1.getValueType().getVectorElementType())
5380 return SDValue();
5381
5382 bool SplitV0 = V0.getValueType().getSizeInBits() == 128;
5383
5384 if (!isConcatMask(Mask, VT, SplitV0))
5385 return SDValue();
5386
5387 EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
5388 VT.getVectorNumElements() / 2);
5389 if (SplitV0) {
5390 V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005391 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005392 }
5393 if (V1.getValueType().getSizeInBits() == 128) {
5394 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005395 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005396 }
5397 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
5398}
5399
5400/// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5401/// the specified operations to build the shuffle.
5402static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5403 SDValue RHS, SelectionDAG &DAG,
5404 SDLoc dl) {
5405 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5406 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
5407 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
5408
5409 enum {
5410 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5411 OP_VREV,
5412 OP_VDUP0,
5413 OP_VDUP1,
5414 OP_VDUP2,
5415 OP_VDUP3,
5416 OP_VEXT1,
5417 OP_VEXT2,
5418 OP_VEXT3,
5419 OP_VUZPL, // VUZP, left result
5420 OP_VUZPR, // VUZP, right result
5421 OP_VZIPL, // VZIP, left result
5422 OP_VZIPR, // VZIP, right result
5423 OP_VTRNL, // VTRN, left result
5424 OP_VTRNR // VTRN, right result
5425 };
5426
5427 if (OpNum == OP_COPY) {
5428 if (LHSID == (1 * 9 + 2) * 9 + 3)
5429 return LHS;
5430 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
5431 return RHS;
5432 }
5433
5434 SDValue OpLHS, OpRHS;
5435 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5436 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5437 EVT VT = OpLHS.getValueType();
5438
5439 switch (OpNum) {
5440 default:
5441 llvm_unreachable("Unknown shuffle opcode!");
5442 case OP_VREV:
5443 // VREV divides the vector in half and swaps within the half.
5444 if (VT.getVectorElementType() == MVT::i32 ||
5445 VT.getVectorElementType() == MVT::f32)
5446 return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
5447 // vrev <4 x i16> -> REV32
Oliver Stannard89d15422014-08-27 16:16:04 +00005448 if (VT.getVectorElementType() == MVT::i16 ||
5449 VT.getVectorElementType() == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00005450 return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
5451 // vrev <4 x i8> -> REV16
5452 assert(VT.getVectorElementType() == MVT::i8);
5453 return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
5454 case OP_VDUP0:
5455 case OP_VDUP1:
5456 case OP_VDUP2:
5457 case OP_VDUP3: {
5458 EVT EltTy = VT.getVectorElementType();
5459 unsigned Opcode;
5460 if (EltTy == MVT::i8)
5461 Opcode = AArch64ISD::DUPLANE8;
Ahmed Bougacha941420d2015-04-16 23:57:07 +00005462 else if (EltTy == MVT::i16 || EltTy == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00005463 Opcode = AArch64ISD::DUPLANE16;
5464 else if (EltTy == MVT::i32 || EltTy == MVT::f32)
5465 Opcode = AArch64ISD::DUPLANE32;
5466 else if (EltTy == MVT::i64 || EltTy == MVT::f64)
5467 Opcode = AArch64ISD::DUPLANE64;
5468 else
5469 llvm_unreachable("Invalid vector element type?");
5470
5471 if (VT.getSizeInBits() == 64)
5472 OpLHS = WidenVector(OpLHS, DAG);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005473 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00005474 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
5475 }
5476 case OP_VEXT1:
5477 case OP_VEXT2:
5478 case OP_VEXT3: {
5479 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
5480 return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005481 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005482 }
5483 case OP_VUZPL:
5484 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
5485 OpRHS);
5486 case OP_VUZPR:
5487 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
5488 OpRHS);
5489 case OP_VZIPL:
5490 return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
5491 OpRHS);
5492 case OP_VZIPR:
5493 return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
5494 OpRHS);
5495 case OP_VTRNL:
5496 return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
5497 OpRHS);
5498 case OP_VTRNR:
5499 return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
5500 OpRHS);
5501 }
5502}
5503
5504static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
5505 SelectionDAG &DAG) {
5506 // Check to see if we can use the TBL instruction.
5507 SDValue V1 = Op.getOperand(0);
5508 SDValue V2 = Op.getOperand(1);
5509 SDLoc DL(Op);
5510
5511 EVT EltVT = Op.getValueType().getVectorElementType();
5512 unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
5513
5514 SmallVector<SDValue, 8> TBLMask;
5515 for (int Val : ShuffleMask) {
5516 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
5517 unsigned Offset = Byte + Val * BytesPerElt;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005518 TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005519 }
5520 }
5521
5522 MVT IndexVT = MVT::v8i8;
5523 unsigned IndexLen = 8;
5524 if (Op.getValueType().getSizeInBits() == 128) {
5525 IndexVT = MVT::v16i8;
5526 IndexLen = 16;
5527 }
5528
5529 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
5530 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
5531
5532 SDValue Shuffle;
5533 if (V2.getNode()->getOpcode() == ISD::UNDEF) {
5534 if (IndexLen == 8)
5535 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
5536 Shuffle = DAG.getNode(
5537 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005538 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
Tim Northover3b0846e2014-05-24 12:50:23 +00005539 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5540 makeArrayRef(TBLMask.data(), IndexLen)));
5541 } else {
5542 if (IndexLen == 8) {
5543 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
5544 Shuffle = DAG.getNode(
5545 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005546 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
Tim Northover3b0846e2014-05-24 12:50:23 +00005547 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5548 makeArrayRef(TBLMask.data(), IndexLen)));
5549 } else {
5550 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
5551 // cannot currently represent the register constraints on the input
5552 // table registers.
5553 // Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
5554 // DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5555 // &TBLMask[0], IndexLen));
5556 Shuffle = DAG.getNode(
5557 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005558 DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32),
5559 V1Cst, V2Cst,
Tim Northover3b0846e2014-05-24 12:50:23 +00005560 DAG.getNode(ISD::BUILD_VECTOR, DL, IndexVT,
5561 makeArrayRef(TBLMask.data(), IndexLen)));
5562 }
5563 }
5564 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
5565}
5566
5567static unsigned getDUPLANEOp(EVT EltType) {
5568 if (EltType == MVT::i8)
5569 return AArch64ISD::DUPLANE8;
Oliver Stannard89d15422014-08-27 16:16:04 +00005570 if (EltType == MVT::i16 || EltType == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00005571 return AArch64ISD::DUPLANE16;
5572 if (EltType == MVT::i32 || EltType == MVT::f32)
5573 return AArch64ISD::DUPLANE32;
5574 if (EltType == MVT::i64 || EltType == MVT::f64)
5575 return AArch64ISD::DUPLANE64;
5576
5577 llvm_unreachable("Invalid vector element type?");
5578}
5579
5580SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5581 SelectionDAG &DAG) const {
5582 SDLoc dl(Op);
5583 EVT VT = Op.getValueType();
5584
5585 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5586
5587 // Convert shuffles that are directly supported on NEON to target-specific
5588 // DAG nodes, instead of keeping them as shuffles and matching them again
5589 // during code selection. This is more efficient and avoids the possibility
5590 // of inconsistencies between legalization and selection.
5591 ArrayRef<int> ShuffleMask = SVN->getMask();
5592
5593 SDValue V1 = Op.getOperand(0);
5594 SDValue V2 = Op.getOperand(1);
5595
5596 if (ShuffleVectorSDNode::isSplatMask(&ShuffleMask[0],
5597 V1.getValueType().getSimpleVT())) {
5598 int Lane = SVN->getSplatIndex();
5599 // If this is undef splat, generate it via "just" vdup, if possible.
5600 if (Lane == -1)
5601 Lane = 0;
5602
5603 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
5604 return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
5605 V1.getOperand(0));
5606 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
5607 // constant. If so, we can just reference the lane's definition directly.
5608 if (V1.getOpcode() == ISD::BUILD_VECTOR &&
5609 !isa<ConstantSDNode>(V1.getOperand(Lane)))
5610 return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
5611
5612 // Otherwise, duplicate from the lane of the input vector.
5613 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
5614
5615 // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
5616 // to make a vector of the same size as this SHUFFLE. We can ignore the
5617 // extract entirely, and canonicalise the concat using WidenVector.
5618 if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
5619 Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
5620 V1 = V1.getOperand(0);
5621 } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
5622 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
5623 Lane -= Idx * VT.getVectorNumElements() / 2;
5624 V1 = WidenVector(V1.getOperand(Idx), DAG);
5625 } else if (VT.getSizeInBits() == 64)
5626 V1 = WidenVector(V1, DAG);
5627
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005628 return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005629 }
5630
5631 if (isREVMask(ShuffleMask, VT, 64))
5632 return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
5633 if (isREVMask(ShuffleMask, VT, 32))
5634 return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
5635 if (isREVMask(ShuffleMask, VT, 16))
5636 return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
5637
5638 bool ReverseEXT = false;
5639 unsigned Imm;
5640 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
5641 if (ReverseEXT)
5642 std::swap(V1, V2);
5643 Imm *= getExtFactor(V1);
5644 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005645 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005646 } else if (V2->getOpcode() == ISD::UNDEF &&
5647 isSingletonEXTMask(ShuffleMask, VT, Imm)) {
5648 Imm *= getExtFactor(V1);
5649 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005650 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005651 }
5652
5653 unsigned WhichResult;
5654 if (isZIPMask(ShuffleMask, VT, WhichResult)) {
5655 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5656 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5657 }
5658 if (isUZPMask(ShuffleMask, VT, WhichResult)) {
5659 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5660 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5661 }
5662 if (isTRNMask(ShuffleMask, VT, WhichResult)) {
5663 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5664 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5665 }
5666
5667 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5668 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5669 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5670 }
5671 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5672 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5673 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5674 }
5675 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5676 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5677 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5678 }
5679
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00005680 if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00005681 return Concat;
5682
5683 bool DstIsLeft;
5684 int Anomaly;
5685 int NumInputElements = V1.getValueType().getVectorNumElements();
5686 if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
5687 SDValue DstVec = DstIsLeft ? V1 : V2;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005688 SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00005689
5690 SDValue SrcVec = V1;
5691 int SrcLane = ShuffleMask[Anomaly];
5692 if (SrcLane >= NumInputElements) {
5693 SrcVec = V2;
5694 SrcLane -= VT.getVectorNumElements();
5695 }
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005696 SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00005697
5698 EVT ScalarVT = VT.getVectorElementType();
Oliver Stannard89d15422014-08-27 16:16:04 +00005699
5700 if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00005701 ScalarVT = MVT::i32;
5702
5703 return DAG.getNode(
5704 ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5705 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
5706 DstLaneV);
5707 }
5708
5709 // If the shuffle is not directly supported and it has 4 elements, use
5710 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5711 unsigned NumElts = VT.getVectorNumElements();
5712 if (NumElts == 4) {
5713 unsigned PFIndexes[4];
5714 for (unsigned i = 0; i != 4; ++i) {
5715 if (ShuffleMask[i] < 0)
5716 PFIndexes[i] = 8;
5717 else
5718 PFIndexes[i] = ShuffleMask[i];
5719 }
5720
5721 // Compute the index in the perfect shuffle table.
5722 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
5723 PFIndexes[2] * 9 + PFIndexes[3];
5724 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5725 unsigned Cost = (PFEntry >> 30);
5726
5727 if (Cost <= 4)
5728 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5729 }
5730
5731 return GenerateTBL(Op, ShuffleMask, DAG);
5732}
5733
5734static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
5735 APInt &UndefBits) {
5736 EVT VT = BVN->getValueType(0);
5737 APInt SplatBits, SplatUndef;
5738 unsigned SplatBitSize;
5739 bool HasAnyUndefs;
5740 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5741 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
5742
5743 for (unsigned i = 0; i < NumSplats; ++i) {
5744 CnstBits <<= SplatBitSize;
5745 UndefBits <<= SplatBitSize;
5746 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
5747 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
5748 }
5749
5750 return true;
5751 }
5752
5753 return false;
5754}
5755
5756SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op,
5757 SelectionDAG &DAG) const {
5758 BuildVectorSDNode *BVN =
5759 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5760 SDValue LHS = Op.getOperand(0);
5761 SDLoc dl(Op);
5762 EVT VT = Op.getValueType();
5763
5764 if (!BVN)
5765 return Op;
5766
5767 APInt CnstBits(VT.getSizeInBits(), 0);
5768 APInt UndefBits(VT.getSizeInBits(), 0);
5769 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5770 // We only have BIC vector immediate instruction, which is and-not.
5771 CnstBits = ~CnstBits;
5772
5773 // We make use of a little bit of goto ickiness in order to avoid having to
5774 // duplicate the immediate matching logic for the undef toggled case.
5775 bool SecondTry = false;
5776 AttemptModImm:
5777
5778 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5779 CnstBits = CnstBits.zextOrTrunc(64);
5780 uint64_t CnstVal = CnstBits.getZExtValue();
5781
5782 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5783 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5784 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5785 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005786 DAG.getConstant(CnstVal, dl, MVT::i32),
5787 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005788 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005789 }
5790
5791 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5792 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5793 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5794 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005795 DAG.getConstant(CnstVal, dl, MVT::i32),
5796 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005797 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005798 }
5799
5800 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5801 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5802 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5803 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005804 DAG.getConstant(CnstVal, dl, MVT::i32),
5805 DAG.getConstant(16, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005806 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005807 }
5808
5809 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5810 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5811 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5812 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005813 DAG.getConstant(CnstVal, dl, MVT::i32),
5814 DAG.getConstant(24, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005815 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005816 }
5817
5818 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5819 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5820 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5821 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005822 DAG.getConstant(CnstVal, dl, MVT::i32),
5823 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005824 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005825 }
5826
5827 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
5828 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
5829 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5830 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005831 DAG.getConstant(CnstVal, dl, MVT::i32),
5832 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005833 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005834 }
5835 }
5836
5837 if (SecondTry)
5838 goto FailedModImm;
5839 SecondTry = true;
5840 CnstBits = ~UndefBits;
5841 goto AttemptModImm;
5842 }
5843
5844// We can always fall back to a non-immediate AND.
5845FailedModImm:
5846 return Op;
5847}
5848
5849// Specialized code to quickly find if PotentialBVec is a BuildVector that
5850// consists of only the same constant int value, returned in reference arg
5851// ConstVal
5852static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
5853 uint64_t &ConstVal) {
5854 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
5855 if (!Bvec)
5856 return false;
5857 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
5858 if (!FirstElt)
5859 return false;
5860 EVT VT = Bvec->getValueType(0);
5861 unsigned NumElts = VT.getVectorNumElements();
5862 for (unsigned i = 1; i < NumElts; ++i)
5863 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
5864 return false;
5865 ConstVal = FirstElt->getZExtValue();
5866 return true;
5867}
5868
5869static unsigned getIntrinsicID(const SDNode *N) {
5870 unsigned Opcode = N->getOpcode();
5871 switch (Opcode) {
5872 default:
5873 return Intrinsic::not_intrinsic;
5874 case ISD::INTRINSIC_WO_CHAIN: {
5875 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
5876 if (IID < Intrinsic::num_intrinsics)
5877 return IID;
5878 return Intrinsic::not_intrinsic;
5879 }
5880 }
5881}
5882
5883// Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
5884// to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
5885// BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
5886// Also, logical shift right -> sri, with the same structure.
5887static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
5888 EVT VT = N->getValueType(0);
5889
5890 if (!VT.isVector())
5891 return SDValue();
5892
5893 SDLoc DL(N);
5894
5895 // Is the first op an AND?
5896 const SDValue And = N->getOperand(0);
5897 if (And.getOpcode() != ISD::AND)
5898 return SDValue();
5899
5900 // Is the second op an shl or lshr?
5901 SDValue Shift = N->getOperand(1);
5902 // This will have been turned into: AArch64ISD::VSHL vector, #shift
5903 // or AArch64ISD::VLSHR vector, #shift
5904 unsigned ShiftOpc = Shift.getOpcode();
5905 if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
5906 return SDValue();
5907 bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
5908
5909 // Is the shift amount constant?
5910 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
5911 if (!C2node)
5912 return SDValue();
5913
5914 // Is the and mask vector all constant?
5915 uint64_t C1;
5916 if (!isAllConstantBuildVector(And.getOperand(1), C1))
5917 return SDValue();
5918
5919 // Is C1 == ~C2, taking into account how much one can shift elements of a
5920 // particular size?
5921 uint64_t C2 = C2node->getZExtValue();
5922 unsigned ElemSizeInBits = VT.getVectorElementType().getSizeInBits();
5923 if (C2 > ElemSizeInBits)
5924 return SDValue();
5925 unsigned ElemMask = (1 << ElemSizeInBits) - 1;
5926 if ((C1 & ElemMask) != (~C2 & ElemMask))
5927 return SDValue();
5928
5929 SDValue X = And.getOperand(0);
5930 SDValue Y = Shift.getOperand(0);
5931
5932 unsigned Intrin =
5933 IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
5934 SDValue ResultSLI =
5935 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005936 DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
5937 Shift.getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00005938
5939 DEBUG(dbgs() << "aarch64-lower: transformed: \n");
5940 DEBUG(N->dump(&DAG));
5941 DEBUG(dbgs() << "into: \n");
5942 DEBUG(ResultSLI->dump(&DAG));
5943
5944 ++NumShiftInserts;
5945 return ResultSLI;
5946}
5947
5948SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
5949 SelectionDAG &DAG) const {
5950 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
5951 if (EnableAArch64SlrGeneration) {
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00005952 if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00005953 return Res;
5954 }
5955
5956 BuildVectorSDNode *BVN =
5957 dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
5958 SDValue LHS = Op.getOperand(1);
5959 SDLoc dl(Op);
5960 EVT VT = Op.getValueType();
5961
5962 // OR commutes, so try swapping the operands.
5963 if (!BVN) {
5964 LHS = Op.getOperand(0);
5965 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5966 }
5967 if (!BVN)
5968 return Op;
5969
5970 APInt CnstBits(VT.getSizeInBits(), 0);
5971 APInt UndefBits(VT.getSizeInBits(), 0);
5972 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5973 // We make use of a little bit of goto ickiness in order to avoid having to
5974 // duplicate the immediate matching logic for the undef toggled case.
5975 bool SecondTry = false;
5976 AttemptModImm:
5977
5978 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5979 CnstBits = CnstBits.zextOrTrunc(64);
5980 uint64_t CnstVal = CnstBits.getZExtValue();
5981
5982 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5983 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5984 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5985 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005986 DAG.getConstant(CnstVal, dl, MVT::i32),
5987 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005988 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005989 }
5990
5991 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5992 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5993 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5994 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005995 DAG.getConstant(CnstVal, dl, MVT::i32),
5996 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005997 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005998 }
5999
6000 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6001 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6002 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6003 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006004 DAG.getConstant(CnstVal, dl, MVT::i32),
6005 DAG.getConstant(16, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00006006 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006007 }
6008
6009 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6010 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6011 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6012 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006013 DAG.getConstant(CnstVal, dl, MVT::i32),
6014 DAG.getConstant(24, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00006015 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006016 }
6017
6018 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6019 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6020 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6021 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006022 DAG.getConstant(CnstVal, dl, MVT::i32),
6023 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00006024 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006025 }
6026
6027 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6028 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6029 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6030 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006031 DAG.getConstant(CnstVal, dl, MVT::i32),
6032 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00006033 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006034 }
6035 }
6036
6037 if (SecondTry)
6038 goto FailedModImm;
6039 SecondTry = true;
6040 CnstBits = UndefBits;
6041 goto AttemptModImm;
6042 }
6043
6044// We can always fall back to a non-immediate OR.
6045FailedModImm:
6046 return Op;
6047}
6048
Kevin Qin4473c192014-07-07 02:45:40 +00006049// Normalize the operands of BUILD_VECTOR. The value of constant operands will
6050// be truncated to fit element width.
6051static SDValue NormalizeBuildVector(SDValue Op,
6052 SelectionDAG &DAG) {
6053 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
Tim Northover3b0846e2014-05-24 12:50:23 +00006054 SDLoc dl(Op);
6055 EVT VT = Op.getValueType();
Kevin Qin4473c192014-07-07 02:45:40 +00006056 EVT EltTy= VT.getVectorElementType();
6057
6058 if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
6059 return Op;
6060
6061 SmallVector<SDValue, 16> Ops;
Pete Cooper7be8f8f2015-08-03 19:04:32 +00006062 for (SDValue Lane : Op->ops()) {
6063 if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
Kevin Qin4473c192014-07-07 02:45:40 +00006064 APInt LowBits(EltTy.getSizeInBits(),
Pete Cooper7be8f8f2015-08-03 19:04:32 +00006065 CstLane->getZExtValue());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006066 Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
Kevin Qin4473c192014-07-07 02:45:40 +00006067 }
6068 Ops.push_back(Lane);
6069 }
6070 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6071}
6072
6073SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
6074 SelectionDAG &DAG) const {
6075 SDLoc dl(Op);
6076 EVT VT = Op.getValueType();
6077 Op = NormalizeBuildVector(Op, DAG);
6078 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
Tim Northover3b0846e2014-05-24 12:50:23 +00006079
6080 APInt CnstBits(VT.getSizeInBits(), 0);
6081 APInt UndefBits(VT.getSizeInBits(), 0);
6082 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
6083 // We make use of a little bit of goto ickiness in order to avoid having to
6084 // duplicate the immediate matching logic for the undef toggled case.
6085 bool SecondTry = false;
6086 AttemptModImm:
6087
6088 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
6089 CnstBits = CnstBits.zextOrTrunc(64);
6090 uint64_t CnstVal = CnstBits.getZExtValue();
6091
6092 // Certain magic vector constants (used to express things like NOT
6093 // and NEG) are passed through unmodified. This allows codegen patterns
6094 // for these operations to match. Special-purpose patterns will lower
6095 // these immediates to MOVIs if it proves necessary.
6096 if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL))
6097 return Op;
6098
6099 // The many faces of MOVI...
6100 if (AArch64_AM::isAdvSIMDModImmType10(CnstVal)) {
6101 CnstVal = AArch64_AM::encodeAdvSIMDModImmType10(CnstVal);
6102 if (VT.getSizeInBits() == 128) {
6103 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::v2i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006104 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006105 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006106 }
6107
6108 // Support the V64 version via subregister insertion.
6109 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::f64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006110 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006111 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006112 }
6113
6114 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6115 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6116 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6117 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006118 DAG.getConstant(CnstVal, dl, MVT::i32),
6119 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006120 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006121 }
6122
6123 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6124 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6125 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6126 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006127 DAG.getConstant(CnstVal, dl, MVT::i32),
6128 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006129 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006130 }
6131
6132 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6133 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6134 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6135 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006136 DAG.getConstant(CnstVal, dl, MVT::i32),
6137 DAG.getConstant(16, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006138 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006139 }
6140
6141 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6142 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6143 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6144 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006145 DAG.getConstant(CnstVal, dl, MVT::i32),
6146 DAG.getConstant(24, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006147 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006148 }
6149
6150 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6151 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6152 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6153 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006154 DAG.getConstant(CnstVal, dl, MVT::i32),
6155 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006156 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006157 }
6158
6159 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6160 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6161 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6162 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006163 DAG.getConstant(CnstVal, dl, MVT::i32),
6164 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006165 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006166 }
6167
6168 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6169 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6170 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6171 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006172 DAG.getConstant(CnstVal, dl, MVT::i32),
6173 DAG.getConstant(264, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006174 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006175 }
6176
6177 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6178 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6179 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6180 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006181 DAG.getConstant(CnstVal, dl, MVT::i32),
6182 DAG.getConstant(272, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006183 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006184 }
6185
6186 if (AArch64_AM::isAdvSIMDModImmType9(CnstVal)) {
6187 CnstVal = AArch64_AM::encodeAdvSIMDModImmType9(CnstVal);
6188 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
6189 SDValue Mov = DAG.getNode(AArch64ISD::MOVI, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006190 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006191 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006192 }
6193
6194 // The few faces of FMOV...
6195 if (AArch64_AM::isAdvSIMDModImmType11(CnstVal)) {
6196 CnstVal = AArch64_AM::encodeAdvSIMDModImmType11(CnstVal);
6197 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32;
6198 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006199 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006200 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006201 }
6202
6203 if (AArch64_AM::isAdvSIMDModImmType12(CnstVal) &&
6204 VT.getSizeInBits() == 128) {
6205 CnstVal = AArch64_AM::encodeAdvSIMDModImmType12(CnstVal);
6206 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MVT::v2f64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006207 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006208 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006209 }
6210
6211 // The many faces of MVNI...
6212 CnstVal = ~CnstVal;
6213 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6214 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6215 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6216 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006217 DAG.getConstant(CnstVal, dl, MVT::i32),
6218 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006219 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006220 }
6221
6222 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6223 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6224 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6225 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006226 DAG.getConstant(CnstVal, dl, MVT::i32),
6227 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006228 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006229 }
6230
6231 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6232 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6233 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6234 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006235 DAG.getConstant(CnstVal, dl, MVT::i32),
6236 DAG.getConstant(16, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006237 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006238 }
6239
6240 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6241 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6242 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6243 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006244 DAG.getConstant(CnstVal, dl, MVT::i32),
6245 DAG.getConstant(24, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006246 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006247 }
6248
6249 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6250 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6251 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6252 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006253 DAG.getConstant(CnstVal, dl, MVT::i32),
6254 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006255 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006256 }
6257
6258 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6259 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6260 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6261 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006262 DAG.getConstant(CnstVal, dl, MVT::i32),
6263 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006264 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006265 }
6266
6267 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6268 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6269 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6270 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006271 DAG.getConstant(CnstVal, dl, MVT::i32),
6272 DAG.getConstant(264, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006273 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006274 }
6275
6276 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6277 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6278 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6279 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006280 DAG.getConstant(CnstVal, dl, MVT::i32),
6281 DAG.getConstant(272, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006282 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006283 }
6284 }
6285
6286 if (SecondTry)
6287 goto FailedModImm;
6288 SecondTry = true;
6289 CnstBits = UndefBits;
6290 goto AttemptModImm;
6291 }
6292FailedModImm:
6293
6294 // Scan through the operands to find some interesting properties we can
6295 // exploit:
6296 // 1) If only one value is used, we can use a DUP, or
6297 // 2) if only the low element is not undef, we can just insert that, or
6298 // 3) if only one constant value is used (w/ some non-constant lanes),
6299 // we can splat the constant value into the whole vector then fill
6300 // in the non-constant lanes.
6301 // 4) FIXME: If different constant values are used, but we can intelligently
6302 // select the values we'll be overwriting for the non-constant
6303 // lanes such that we can directly materialize the vector
6304 // some other way (MOVI, e.g.), we can be sneaky.
6305 unsigned NumElts = VT.getVectorNumElements();
6306 bool isOnlyLowElement = true;
6307 bool usesOnlyOneValue = true;
6308 bool usesOnlyOneConstantValue = true;
6309 bool isConstant = true;
6310 unsigned NumConstantLanes = 0;
6311 SDValue Value;
6312 SDValue ConstantValue;
6313 for (unsigned i = 0; i < NumElts; ++i) {
6314 SDValue V = Op.getOperand(i);
6315 if (V.getOpcode() == ISD::UNDEF)
6316 continue;
6317 if (i > 0)
6318 isOnlyLowElement = false;
6319 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6320 isConstant = false;
6321
6322 if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
6323 ++NumConstantLanes;
6324 if (!ConstantValue.getNode())
6325 ConstantValue = V;
6326 else if (ConstantValue != V)
6327 usesOnlyOneConstantValue = false;
6328 }
6329
6330 if (!Value.getNode())
6331 Value = V;
6332 else if (V != Value)
6333 usesOnlyOneValue = false;
6334 }
6335
6336 if (!Value.getNode())
6337 return DAG.getUNDEF(VT);
6338
6339 if (isOnlyLowElement)
6340 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
6341
6342 // Use DUP for non-constant splats. For f32 constant splats, reduce to
6343 // i32 and try again.
6344 if (usesOnlyOneValue) {
6345 if (!isConstant) {
6346 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6347 Value.getValueType() != VT)
6348 return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
6349
6350 // This is actually a DUPLANExx operation, which keeps everything vectory.
6351
6352 // DUPLANE works on 128-bit vectors, widen it if necessary.
6353 SDValue Lane = Value.getOperand(1);
6354 Value = Value.getOperand(0);
6355 if (Value.getValueType().getSizeInBits() == 64)
6356 Value = WidenVector(Value, DAG);
6357
6358 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
6359 return DAG.getNode(Opcode, dl, VT, Value, Lane);
6360 }
6361
6362 if (VT.getVectorElementType().isFloatingPoint()) {
6363 SmallVector<SDValue, 8> Ops;
Pirama Arumuga Nainar12aeefc2015-03-17 23:10:29 +00006364 EVT EltTy = VT.getVectorElementType();
6365 assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
6366 "Unsupported floating-point vector type");
6367 MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00006368 for (unsigned i = 0; i < NumElts; ++i)
6369 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
6370 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
6371 SDValue Val = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
6372 Val = LowerBUILD_VECTOR(Val, DAG);
6373 if (Val.getNode())
6374 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6375 }
6376 }
6377
6378 // If there was only one constant value used and for more than one lane,
6379 // start by splatting that value, then replace the non-constant lanes. This
6380 // is better than the default, which will perform a separate initialization
6381 // for each lane.
6382 if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
6383 SDValue Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
6384 // Now insert the non-constant lanes.
6385 for (unsigned i = 0; i < NumElts; ++i) {
6386 SDValue V = Op.getOperand(i);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006387 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006388 if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) {
6389 // Note that type legalization likely mucked about with the VT of the
6390 // source operand, so we may have to convert it here before inserting.
6391 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
6392 }
6393 }
6394 return Val;
6395 }
6396
6397 // If all elements are constants and the case above didn't get hit, fall back
6398 // to the default expansion, which will generate a load from the constant
6399 // pool.
6400 if (isConstant)
6401 return SDValue();
6402
6403 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6404 if (NumElts >= 4) {
Ahmed Bougacha239d6352015-08-04 00:48:02 +00006405 if (SDValue shuffle = ReconstructShuffle(Op, DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00006406 return shuffle;
6407 }
6408
6409 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6410 // know the default expansion would otherwise fall back on something even
6411 // worse. For a vector with one or two non-undef values, that's
6412 // scalar_to_vector for the elements followed by a shuffle (provided the
6413 // shuffle is valid for the target) and materialization element by element
6414 // on the stack followed by a load for everything else.
6415 if (!isConstant && !usesOnlyOneValue) {
6416 SDValue Vec = DAG.getUNDEF(VT);
6417 SDValue Op0 = Op.getOperand(0);
6418 unsigned ElemSize = VT.getVectorElementType().getSizeInBits();
6419 unsigned i = 0;
6420 // For 32 and 64 bit types, use INSERT_SUBREG for lane zero to
6421 // a) Avoid a RMW dependency on the full vector register, and
6422 // b) Allow the register coalescer to fold away the copy if the
6423 // value is already in an S or D register.
Matthias Braun0acbd082015-08-31 18:25:15 +00006424 // Do not do this for UNDEF/LOAD nodes because we have better patterns
6425 // for those avoiding the SCALAR_TO_VECTOR/BUILD_VECTOR.
6426 if (Op0.getOpcode() != ISD::UNDEF && Op0.getOpcode() != ISD::LOAD &&
6427 (ElemSize == 32 || ElemSize == 64)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006428 unsigned SubIdx = ElemSize == 32 ? AArch64::ssub : AArch64::dsub;
6429 MachineSDNode *N =
6430 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, dl, VT, Vec, Op0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006431 DAG.getTargetConstant(SubIdx, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006432 Vec = SDValue(N, 0);
6433 ++i;
6434 }
6435 for (; i < NumElts; ++i) {
6436 SDValue V = Op.getOperand(i);
6437 if (V.getOpcode() == ISD::UNDEF)
6438 continue;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006439 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006440 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6441 }
6442 return Vec;
6443 }
6444
6445 // Just use the default expansion. We failed to find a better alternative.
6446 return SDValue();
6447}
6448
6449SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
6450 SelectionDAG &DAG) const {
6451 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
6452
Tim Northovere4b8e132014-07-15 10:00:26 +00006453 // Check for non-constant or out of range lane.
6454 EVT VT = Op.getOperand(0).getValueType();
6455 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
6456 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
Tim Northover3b0846e2014-05-24 12:50:23 +00006457 return SDValue();
6458
Tim Northover3b0846e2014-05-24 12:50:23 +00006459
6460 // Insertion/extraction are legal for V128 types.
6461 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
Oliver Stannard89d15422014-08-27 16:16:04 +00006462 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6463 VT == MVT::v8f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006464 return Op;
6465
6466 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
Oliver Stannard89d15422014-08-27 16:16:04 +00006467 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006468 return SDValue();
6469
6470 // For V64 types, we perform insertion by expanding the value
6471 // to a V128 type and perform the insertion on that.
6472 SDLoc DL(Op);
6473 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6474 EVT WideTy = WideVec.getValueType();
6475
6476 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
6477 Op.getOperand(1), Op.getOperand(2));
6478 // Re-narrow the resultant vector.
6479 return NarrowVector(Node, DAG);
6480}
6481
6482SDValue
6483AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6484 SelectionDAG &DAG) const {
6485 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
6486
Tim Northovere4b8e132014-07-15 10:00:26 +00006487 // Check for non-constant or out of range lane.
6488 EVT VT = Op.getOperand(0).getValueType();
6489 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6490 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
Tim Northover3b0846e2014-05-24 12:50:23 +00006491 return SDValue();
6492
Tim Northover3b0846e2014-05-24 12:50:23 +00006493
6494 // Insertion/extraction are legal for V128 types.
6495 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
Oliver Stannard89d15422014-08-27 16:16:04 +00006496 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6497 VT == MVT::v8f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006498 return Op;
6499
6500 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
Oliver Stannard89d15422014-08-27 16:16:04 +00006501 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006502 return SDValue();
6503
6504 // For V64 types, we perform extraction by expanding the value
6505 // to a V128 type and perform the extraction on that.
6506 SDLoc DL(Op);
6507 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6508 EVT WideTy = WideVec.getValueType();
6509
6510 EVT ExtrTy = WideTy.getVectorElementType();
6511 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
6512 ExtrTy = MVT::i32;
6513
6514 // For extractions, we just return the result directly.
6515 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
6516 Op.getOperand(1));
6517}
6518
6519SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
6520 SelectionDAG &DAG) const {
6521 EVT VT = Op.getOperand(0).getValueType();
6522 SDLoc dl(Op);
6523 // Just in case...
6524 if (!VT.isVector())
6525 return SDValue();
6526
6527 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6528 if (!Cst)
6529 return SDValue();
6530 unsigned Val = Cst->getZExtValue();
6531
6532 unsigned Size = Op.getValueType().getSizeInBits();
Charlie Turner7b7b06f2015-11-09 12:45:11 +00006533
6534 // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
6535 if (Val == 0)
6536 return Op;
6537
Tim Northover3b0846e2014-05-24 12:50:23 +00006538 // If this is extracting the upper 64-bits of a 128-bit vector, we match
6539 // that directly.
6540 if (Size == 64 && Val * VT.getVectorElementType().getSizeInBits() == 64)
6541 return Op;
6542
6543 return SDValue();
6544}
6545
6546bool AArch64TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
6547 EVT VT) const {
6548 if (VT.getVectorNumElements() == 4 &&
6549 (VT.is128BitVector() || VT.is64BitVector())) {
6550 unsigned PFIndexes[4];
6551 for (unsigned i = 0; i != 4; ++i) {
6552 if (M[i] < 0)
6553 PFIndexes[i] = 8;
6554 else
6555 PFIndexes[i] = M[i];
6556 }
6557
6558 // Compute the index in the perfect shuffle table.
6559 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6560 PFIndexes[2] * 9 + PFIndexes[3];
6561 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6562 unsigned Cost = (PFEntry >> 30);
6563
6564 if (Cost <= 4)
6565 return true;
6566 }
6567
6568 bool DummyBool;
6569 int DummyInt;
6570 unsigned DummyUnsigned;
6571
6572 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
6573 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
6574 isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
6575 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
6576 isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
6577 isZIPMask(M, VT, DummyUnsigned) ||
6578 isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
6579 isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
6580 isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
6581 isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
6582 isConcatMask(M, VT, VT.getSizeInBits() == 128));
6583}
6584
6585/// getVShiftImm - Check if this is a valid build_vector for the immediate
6586/// operand of a vector shift operation, where all the elements of the
6587/// build_vector must have the same constant integer value.
6588static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
6589 // Ignore bit_converts.
6590 while (Op.getOpcode() == ISD::BITCAST)
6591 Op = Op.getOperand(0);
6592 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6593 APInt SplatBits, SplatUndef;
6594 unsigned SplatBitSize;
6595 bool HasAnyUndefs;
6596 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
6597 HasAnyUndefs, ElementBits) ||
6598 SplatBitSize > ElementBits)
6599 return false;
6600 Cnt = SplatBits.getSExtValue();
6601 return true;
6602}
6603
6604/// isVShiftLImm - Check if this is a valid build_vector for the immediate
6605/// operand of a vector shift left operation. That value must be in the range:
6606/// 0 <= Value < ElementBits for a left shift; or
6607/// 0 <= Value <= ElementBits for a long left shift.
6608static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
6609 assert(VT.isVector() && "vector shift count is not a vector type");
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00006610 int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00006611 if (!getVShiftImm(Op, ElementBits, Cnt))
6612 return false;
6613 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
6614}
6615
6616/// isVShiftRImm - Check if this is a valid build_vector for the immediate
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00006617/// operand of a vector shift right operation. The value must be in the range:
6618/// 1 <= Value <= ElementBits for a right shift; or
6619static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006620 assert(VT.isVector() && "vector shift count is not a vector type");
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00006621 int64_t ElementBits = VT.getVectorElementType().getSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00006622 if (!getVShiftImm(Op, ElementBits, Cnt))
6623 return false;
Tim Northover3b0846e2014-05-24 12:50:23 +00006624 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
6625}
6626
6627SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
6628 SelectionDAG &DAG) const {
6629 EVT VT = Op.getValueType();
6630 SDLoc DL(Op);
6631 int64_t Cnt;
6632
6633 if (!Op.getOperand(1).getValueType().isVector())
6634 return Op;
6635 unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6636
6637 switch (Op.getOpcode()) {
6638 default:
6639 llvm_unreachable("unexpected shift opcode");
6640
6641 case ISD::SHL:
6642 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006643 return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
6644 DAG.getConstant(Cnt, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006645 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006646 DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
6647 MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00006648 Op.getOperand(0), Op.getOperand(1));
6649 case ISD::SRA:
6650 case ISD::SRL:
6651 // Right shift immediate
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00006652 if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006653 unsigned Opc =
6654 (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006655 return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
6656 DAG.getConstant(Cnt, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006657 }
6658
6659 // Right shift register. Note, there is not a shift right register
6660 // instruction, but the shift left register instruction takes a signed
6661 // value, where negative numbers specify a right shift.
6662 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
6663 : Intrinsic::aarch64_neon_ushl;
6664 // negate the shift amount
6665 SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
6666 SDValue NegShiftLeft =
6667 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006668 DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
6669 NegShift);
Tim Northover3b0846e2014-05-24 12:50:23 +00006670 return NegShiftLeft;
6671 }
6672
6673 return SDValue();
6674}
6675
6676static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
6677 AArch64CC::CondCode CC, bool NoNans, EVT VT,
6678 SDLoc dl, SelectionDAG &DAG) {
6679 EVT SrcVT = LHS.getValueType();
Tim Northover45aa89c2015-02-08 00:50:47 +00006680 assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
6681 "function only supposed to emit natural comparisons");
Tim Northover3b0846e2014-05-24 12:50:23 +00006682
6683 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
6684 APInt CnstBits(VT.getSizeInBits(), 0);
6685 APInt UndefBits(VT.getSizeInBits(), 0);
6686 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
6687 bool IsZero = IsCnst && (CnstBits == 0);
6688
6689 if (SrcVT.getVectorElementType().isFloatingPoint()) {
6690 switch (CC) {
6691 default:
6692 return SDValue();
6693 case AArch64CC::NE: {
6694 SDValue Fcmeq;
6695 if (IsZero)
6696 Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6697 else
6698 Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6699 return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
6700 }
6701 case AArch64CC::EQ:
6702 if (IsZero)
6703 return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6704 return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6705 case AArch64CC::GE:
6706 if (IsZero)
6707 return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
6708 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
6709 case AArch64CC::GT:
6710 if (IsZero)
6711 return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
6712 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
6713 case AArch64CC::LS:
6714 if (IsZero)
6715 return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
6716 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
6717 case AArch64CC::LT:
6718 if (!NoNans)
6719 return SDValue();
6720 // If we ignore NaNs then we can use to the MI implementation.
6721 // Fallthrough.
6722 case AArch64CC::MI:
6723 if (IsZero)
6724 return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
6725 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
6726 }
6727 }
6728
6729 switch (CC) {
6730 default:
6731 return SDValue();
6732 case AArch64CC::NE: {
6733 SDValue Cmeq;
6734 if (IsZero)
6735 Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6736 else
6737 Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6738 return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
6739 }
6740 case AArch64CC::EQ:
6741 if (IsZero)
6742 return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6743 return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6744 case AArch64CC::GE:
6745 if (IsZero)
6746 return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
6747 return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
6748 case AArch64CC::GT:
6749 if (IsZero)
6750 return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
6751 return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
6752 case AArch64CC::LE:
6753 if (IsZero)
6754 return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
6755 return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
6756 case AArch64CC::LS:
6757 return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
6758 case AArch64CC::LO:
6759 return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
6760 case AArch64CC::LT:
6761 if (IsZero)
6762 return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
6763 return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
6764 case AArch64CC::HI:
6765 return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
6766 case AArch64CC::HS:
6767 return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
6768 }
6769}
6770
6771SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
6772 SelectionDAG &DAG) const {
6773 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6774 SDValue LHS = Op.getOperand(0);
6775 SDValue RHS = Op.getOperand(1);
Tim Northover45aa89c2015-02-08 00:50:47 +00006776 EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
Tim Northover3b0846e2014-05-24 12:50:23 +00006777 SDLoc dl(Op);
6778
6779 if (LHS.getValueType().getVectorElementType().isInteger()) {
6780 assert(LHS.getValueType() == RHS.getValueType());
6781 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
Tim Northover45aa89c2015-02-08 00:50:47 +00006782 SDValue Cmp =
6783 EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
6784 return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00006785 }
6786
Pirama Arumuga Nainar71e9a2a2016-01-22 01:16:57 +00006787 if (LHS.getValueType().getVectorElementType() == MVT::f16)
6788 return SDValue();
6789
Tim Northover3b0846e2014-05-24 12:50:23 +00006790 assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
6791 LHS.getValueType().getVectorElementType() == MVT::f64);
6792
6793 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
6794 // clean. Some of them require two branches to implement.
6795 AArch64CC::CondCode CC1, CC2;
6796 bool ShouldInvert;
6797 changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
6798
6799 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
6800 SDValue Cmp =
Tim Northover45aa89c2015-02-08 00:50:47 +00006801 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00006802 if (!Cmp.getNode())
6803 return SDValue();
6804
6805 if (CC2 != AArch64CC::AL) {
6806 SDValue Cmp2 =
Tim Northover45aa89c2015-02-08 00:50:47 +00006807 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00006808 if (!Cmp2.getNode())
6809 return SDValue();
6810
Tim Northover45aa89c2015-02-08 00:50:47 +00006811 Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
Tim Northover3b0846e2014-05-24 12:50:23 +00006812 }
6813
Tim Northover45aa89c2015-02-08 00:50:47 +00006814 Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
6815
Tim Northover3b0846e2014-05-24 12:50:23 +00006816 if (ShouldInvert)
6817 return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
6818
6819 return Cmp;
6820}
6821
6822/// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
6823/// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
6824/// specified in the intrinsic calls.
6825bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
6826 const CallInst &I,
6827 unsigned Intrinsic) const {
Mehdi Aminia749f2a2015-07-09 02:09:52 +00006828 auto &DL = I.getModule()->getDataLayout();
Tim Northover3b0846e2014-05-24 12:50:23 +00006829 switch (Intrinsic) {
6830 case Intrinsic::aarch64_neon_ld2:
6831 case Intrinsic::aarch64_neon_ld3:
6832 case Intrinsic::aarch64_neon_ld4:
6833 case Intrinsic::aarch64_neon_ld1x2:
6834 case Intrinsic::aarch64_neon_ld1x3:
6835 case Intrinsic::aarch64_neon_ld1x4:
6836 case Intrinsic::aarch64_neon_ld2lane:
6837 case Intrinsic::aarch64_neon_ld3lane:
6838 case Intrinsic::aarch64_neon_ld4lane:
6839 case Intrinsic::aarch64_neon_ld2r:
6840 case Intrinsic::aarch64_neon_ld3r:
6841 case Intrinsic::aarch64_neon_ld4r: {
6842 Info.opc = ISD::INTRINSIC_W_CHAIN;
6843 // Conservatively set memVT to the entire set of vectors loaded.
Ahmed Bougacha97564c32015-12-09 01:19:50 +00006844 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00006845 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6846 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6847 Info.offset = 0;
6848 Info.align = 0;
6849 Info.vol = false; // volatile loads with NEON intrinsics not supported
6850 Info.readMem = true;
6851 Info.writeMem = false;
6852 return true;
6853 }
6854 case Intrinsic::aarch64_neon_st2:
6855 case Intrinsic::aarch64_neon_st3:
6856 case Intrinsic::aarch64_neon_st4:
6857 case Intrinsic::aarch64_neon_st1x2:
6858 case Intrinsic::aarch64_neon_st1x3:
6859 case Intrinsic::aarch64_neon_st1x4:
6860 case Intrinsic::aarch64_neon_st2lane:
6861 case Intrinsic::aarch64_neon_st3lane:
6862 case Intrinsic::aarch64_neon_st4lane: {
6863 Info.opc = ISD::INTRINSIC_VOID;
6864 // Conservatively set memVT to the entire set of vectors stored.
6865 unsigned NumElts = 0;
6866 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
6867 Type *ArgTy = I.getArgOperand(ArgI)->getType();
6868 if (!ArgTy->isVectorTy())
6869 break;
Ahmed Bougacha97564c32015-12-09 01:19:50 +00006870 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00006871 }
6872 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
6873 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
6874 Info.offset = 0;
6875 Info.align = 0;
6876 Info.vol = false; // volatile stores with NEON intrinsics not supported
6877 Info.readMem = false;
6878 Info.writeMem = true;
6879 return true;
6880 }
6881 case Intrinsic::aarch64_ldaxr:
6882 case Intrinsic::aarch64_ldxr: {
6883 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
6884 Info.opc = ISD::INTRINSIC_W_CHAIN;
6885 Info.memVT = MVT::getVT(PtrTy->getElementType());
6886 Info.ptrVal = I.getArgOperand(0);
6887 Info.offset = 0;
Mehdi Aminia749f2a2015-07-09 02:09:52 +00006888 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
Tim Northover3b0846e2014-05-24 12:50:23 +00006889 Info.vol = true;
6890 Info.readMem = true;
6891 Info.writeMem = false;
6892 return true;
6893 }
6894 case Intrinsic::aarch64_stlxr:
6895 case Intrinsic::aarch64_stxr: {
6896 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
6897 Info.opc = ISD::INTRINSIC_W_CHAIN;
6898 Info.memVT = MVT::getVT(PtrTy->getElementType());
6899 Info.ptrVal = I.getArgOperand(1);
6900 Info.offset = 0;
Mehdi Aminia749f2a2015-07-09 02:09:52 +00006901 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
Tim Northover3b0846e2014-05-24 12:50:23 +00006902 Info.vol = true;
6903 Info.readMem = false;
6904 Info.writeMem = true;
6905 return true;
6906 }
6907 case Intrinsic::aarch64_ldaxp:
6908 case Intrinsic::aarch64_ldxp: {
6909 Info.opc = ISD::INTRINSIC_W_CHAIN;
6910 Info.memVT = MVT::i128;
6911 Info.ptrVal = I.getArgOperand(0);
6912 Info.offset = 0;
6913 Info.align = 16;
6914 Info.vol = true;
6915 Info.readMem = true;
6916 Info.writeMem = false;
6917 return true;
6918 }
6919 case Intrinsic::aarch64_stlxp:
6920 case Intrinsic::aarch64_stxp: {
6921 Info.opc = ISD::INTRINSIC_W_CHAIN;
6922 Info.memVT = MVT::i128;
6923 Info.ptrVal = I.getArgOperand(2);
6924 Info.offset = 0;
6925 Info.align = 16;
6926 Info.vol = true;
6927 Info.readMem = false;
6928 Info.writeMem = true;
6929 return true;
6930 }
6931 default:
6932 break;
6933 }
6934
6935 return false;
6936}
6937
6938// Truncations from 64-bit GPR to 32-bit GPR is free.
6939bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
6940 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6941 return false;
6942 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6943 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00006944 return NumBits1 > NumBits2;
Tim Northover3b0846e2014-05-24 12:50:23 +00006945}
6946bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
Hao Liu40914502014-05-29 09:19:07 +00006947 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00006948 return false;
6949 unsigned NumBits1 = VT1.getSizeInBits();
6950 unsigned NumBits2 = VT2.getSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00006951 return NumBits1 > NumBits2;
Tim Northover3b0846e2014-05-24 12:50:23 +00006952}
6953
Chad Rosier54390052015-02-23 19:15:16 +00006954/// Check if it is profitable to hoist instruction in then/else to if.
6955/// Not profitable if I and it's user can form a FMA instruction
6956/// because we prefer FMSUB/FMADD.
6957bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
6958 if (I->getOpcode() != Instruction::FMul)
6959 return true;
6960
6961 if (I->getNumUses() != 1)
6962 return true;
6963
6964 Instruction *User = I->user_back();
6965
6966 if (User &&
6967 !(User->getOpcode() == Instruction::FSub ||
6968 User->getOpcode() == Instruction::FAdd))
6969 return true;
6970
6971 const TargetOptions &Options = getTargetMachine().Options;
Mehdi Amini44ede332015-07-09 02:09:04 +00006972 const DataLayout &DL = I->getModule()->getDataLayout();
6973 EVT VT = getValueType(DL, User->getOperand(0)->getType());
Chad Rosier54390052015-02-23 19:15:16 +00006974
Eric Christopher114fa1c2016-02-29 22:50:49 +00006975 return !(isFMAFasterThanFMulAndFAdd(VT) &&
6976 isOperationLegalOrCustom(ISD::FMA, VT) &&
6977 (Options.AllowFPOpFusion == FPOpFusion::Fast ||
6978 Options.UnsafeFPMath));
Chad Rosier54390052015-02-23 19:15:16 +00006979}
6980
Tim Northover3b0846e2014-05-24 12:50:23 +00006981// All 32-bit GPR operations implicitly zero the high-half of the corresponding
6982// 64-bit GPR.
6983bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
6984 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
6985 return false;
6986 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
6987 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00006988 return NumBits1 == 32 && NumBits2 == 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00006989}
6990bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
Hao Liu40914502014-05-29 09:19:07 +00006991 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00006992 return false;
6993 unsigned NumBits1 = VT1.getSizeInBits();
6994 unsigned NumBits2 = VT2.getSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00006995 return NumBits1 == 32 && NumBits2 == 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00006996}
6997
6998bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
6999 EVT VT1 = Val.getValueType();
7000 if (isZExtFree(VT1, VT2)) {
7001 return true;
7002 }
7003
7004 if (Val.getOpcode() != ISD::LOAD)
7005 return false;
7006
7007 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
Hao Liu40914502014-05-29 09:19:07 +00007008 return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
7009 VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
7010 VT1.getSizeInBits() <= 32);
Tim Northover3b0846e2014-05-24 12:50:23 +00007011}
7012
Quentin Colombet6843ac42015-03-31 20:52:32 +00007013bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
7014 if (isa<FPExtInst>(Ext))
7015 return false;
7016
7017 // Vector types are next free.
7018 if (Ext->getType()->isVectorTy())
7019 return false;
7020
7021 for (const Use &U : Ext->uses()) {
7022 // The extension is free if we can fold it with a left shift in an
7023 // addressing mode or an arithmetic operation: add, sub, and cmp.
7024
7025 // Is there a shift?
7026 const Instruction *Instr = cast<Instruction>(U.getUser());
7027
7028 // Is this a constant shift?
7029 switch (Instr->getOpcode()) {
7030 case Instruction::Shl:
7031 if (!isa<ConstantInt>(Instr->getOperand(1)))
7032 return false;
7033 break;
7034 case Instruction::GetElementPtr: {
7035 gep_type_iterator GTI = gep_type_begin(Instr);
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007036 auto &DL = Ext->getModule()->getDataLayout();
Quentin Colombet6843ac42015-03-31 20:52:32 +00007037 std::advance(GTI, U.getOperandNo());
7038 Type *IdxTy = *GTI;
7039 // This extension will end up with a shift because of the scaling factor.
7040 // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
7041 // Get the shift amount based on the scaling factor:
7042 // log2(sizeof(IdxTy)) - log2(8).
7043 uint64_t ShiftAmt =
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007044 countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3;
Quentin Colombet6843ac42015-03-31 20:52:32 +00007045 // Is the constant foldable in the shift of the addressing mode?
7046 // I.e., shift amount is between 1 and 4 inclusive.
7047 if (ShiftAmt == 0 || ShiftAmt > 4)
7048 return false;
7049 break;
7050 }
7051 case Instruction::Trunc:
7052 // Check if this is a noop.
7053 // trunc(sext ty1 to ty2) to ty1.
7054 if (Instr->getType() == Ext->getOperand(0)->getType())
7055 continue;
7056 // FALL THROUGH.
7057 default:
7058 return false;
7059 }
7060
7061 // At this point we can use the bfm family, so this extension is free
7062 // for that use.
7063 }
7064 return true;
7065}
7066
Tim Northover3b0846e2014-05-24 12:50:23 +00007067bool AArch64TargetLowering::hasPairedLoad(Type *LoadedType,
7068 unsigned &RequiredAligment) const {
7069 if (!LoadedType->isIntegerTy() && !LoadedType->isFloatTy())
7070 return false;
7071 // Cyclone supports unaligned accesses.
7072 RequiredAligment = 0;
7073 unsigned NumBits = LoadedType->getPrimitiveSizeInBits();
7074 return NumBits == 32 || NumBits == 64;
7075}
7076
7077bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
7078 unsigned &RequiredAligment) const {
7079 if (!LoadedType.isSimple() ||
7080 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
7081 return false;
7082 // Cyclone supports unaligned accesses.
7083 RequiredAligment = 0;
7084 unsigned NumBits = LoadedType.getSizeInBits();
7085 return NumBits == 32 || NumBits == 64;
7086}
7087
Hao Liu7ec8ee32015-06-26 02:32:07 +00007088/// \brief Lower an interleaved load into a ldN intrinsic.
7089///
7090/// E.g. Lower an interleaved load (Factor = 2):
7091/// %wide.vec = load <8 x i32>, <8 x i32>* %ptr
7092/// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
7093/// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
7094///
7095/// Into:
7096/// %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
7097/// %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
7098/// %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
7099bool AArch64TargetLowering::lowerInterleavedLoad(
7100 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
7101 ArrayRef<unsigned> Indices, unsigned Factor) const {
7102 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7103 "Invalid interleave factor");
7104 assert(!Shuffles.empty() && "Empty shufflevector input");
7105 assert(Shuffles.size() == Indices.size() &&
7106 "Unmatched number of shufflevectors and indices");
7107
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007108 const DataLayout &DL = LI->getModule()->getDataLayout();
Hao Liu7ec8ee32015-06-26 02:32:07 +00007109
7110 VectorType *VecTy = Shuffles[0]->getType();
Ahmed Bougacha97564c32015-12-09 01:19:50 +00007111 unsigned VecSize = DL.getTypeSizeInBits(VecTy);
Hao Liu7ec8ee32015-06-26 02:32:07 +00007112
Jeroen Ketemaaebca092015-10-07 14:53:29 +00007113 // Skip if we do not have NEON and skip illegal vector types.
7114 if (!Subtarget->hasNEON() || (VecSize != 64 && VecSize != 128))
Hao Liu7ec8ee32015-06-26 02:32:07 +00007115 return false;
7116
7117 // A pointer vector can not be the return type of the ldN intrinsics. Need to
7118 // load integer vectors first and then convert to pointer vectors.
7119 Type *EltTy = VecTy->getVectorElementType();
7120 if (EltTy->isPointerTy())
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007121 VecTy =
7122 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
Hao Liu7ec8ee32015-06-26 02:32:07 +00007123
7124 Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
7125 Type *Tys[2] = {VecTy, PtrTy};
7126 static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
7127 Intrinsic::aarch64_neon_ld3,
7128 Intrinsic::aarch64_neon_ld4};
7129 Function *LdNFunc =
7130 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
7131
7132 IRBuilder<> Builder(LI);
7133 Value *Ptr = Builder.CreateBitCast(LI->getPointerOperand(), PtrTy);
7134
7135 CallInst *LdN = Builder.CreateCall(LdNFunc, Ptr, "ldN");
7136
7137 // Replace uses of each shufflevector with the corresponding vector loaded
7138 // by ldN.
7139 for (unsigned i = 0; i < Shuffles.size(); i++) {
7140 ShuffleVectorInst *SVI = Shuffles[i];
7141 unsigned Index = Indices[i];
7142
7143 Value *SubVec = Builder.CreateExtractValue(LdN, Index);
7144
7145 // Convert the integer vector to pointer vector if the element is pointer.
7146 if (EltTy->isPointerTy())
7147 SubVec = Builder.CreateIntToPtr(SubVec, SVI->getType());
7148
7149 SVI->replaceAllUsesWith(SubVec);
7150 }
7151
7152 return true;
7153}
7154
7155/// \brief Get a mask consisting of sequential integers starting from \p Start.
7156///
7157/// I.e. <Start, Start + 1, ..., Start + NumElts - 1>
7158static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned Start,
7159 unsigned NumElts) {
7160 SmallVector<Constant *, 16> Mask;
7161 for (unsigned i = 0; i < NumElts; i++)
7162 Mask.push_back(Builder.getInt32(Start + i));
7163
7164 return ConstantVector::get(Mask);
7165}
7166
7167/// \brief Lower an interleaved store into a stN intrinsic.
7168///
7169/// E.g. Lower an interleaved store (Factor = 3):
7170/// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
7171/// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
7172/// store <12 x i32> %i.vec, <12 x i32>* %ptr
7173///
7174/// Into:
7175/// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
7176/// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
7177/// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
7178/// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
7179///
7180/// Note that the new shufflevectors will be removed and we'll only generate one
7181/// st3 instruction in CodeGen.
7182bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
7183 ShuffleVectorInst *SVI,
7184 unsigned Factor) const {
7185 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7186 "Invalid interleave factor");
7187
7188 VectorType *VecTy = SVI->getType();
7189 assert(VecTy->getVectorNumElements() % Factor == 0 &&
7190 "Invalid interleaved store");
7191
7192 unsigned NumSubElts = VecTy->getVectorNumElements() / Factor;
7193 Type *EltTy = VecTy->getVectorElementType();
7194 VectorType *SubVecTy = VectorType::get(EltTy, NumSubElts);
7195
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007196 const DataLayout &DL = SI->getModule()->getDataLayout();
Ahmed Bougacha97564c32015-12-09 01:19:50 +00007197 unsigned SubVecSize = DL.getTypeSizeInBits(SubVecTy);
Hao Liu7ec8ee32015-06-26 02:32:07 +00007198
Jeroen Ketemaaebca092015-10-07 14:53:29 +00007199 // Skip if we do not have NEON and skip illegal vector types.
7200 if (!Subtarget->hasNEON() || (SubVecSize != 64 && SubVecSize != 128))
Hao Liu7ec8ee32015-06-26 02:32:07 +00007201 return false;
7202
7203 Value *Op0 = SVI->getOperand(0);
7204 Value *Op1 = SVI->getOperand(1);
7205 IRBuilder<> Builder(SI);
7206
7207 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
7208 // vectors to integer vectors.
7209 if (EltTy->isPointerTy()) {
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007210 Type *IntTy = DL.getIntPtrType(EltTy);
Hao Liu7ec8ee32015-06-26 02:32:07 +00007211 unsigned NumOpElts =
7212 dyn_cast<VectorType>(Op0->getType())->getVectorNumElements();
7213
7214 // Convert to the corresponding integer vector.
7215 Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
7216 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
7217 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
7218
7219 SubVecTy = VectorType::get(IntTy, NumSubElts);
7220 }
7221
7222 Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
7223 Type *Tys[2] = {SubVecTy, PtrTy};
7224 static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
7225 Intrinsic::aarch64_neon_st3,
7226 Intrinsic::aarch64_neon_st4};
7227 Function *StNFunc =
7228 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
7229
7230 SmallVector<Value *, 5> Ops;
7231
7232 // Split the shufflevector operands into sub vectors for the new stN call.
7233 for (unsigned i = 0; i < Factor; i++)
7234 Ops.push_back(Builder.CreateShuffleVector(
7235 Op0, Op1, getSequentialMask(Builder, NumSubElts * i, NumSubElts)));
7236
7237 Ops.push_back(Builder.CreateBitCast(SI->getPointerOperand(), PtrTy));
7238 Builder.CreateCall(StNFunc, Ops);
7239 return true;
7240}
7241
Tim Northover3b0846e2014-05-24 12:50:23 +00007242static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
7243 unsigned AlignCheck) {
7244 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
7245 (DstAlign == 0 || DstAlign % AlignCheck == 0));
7246}
7247
7248EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
7249 unsigned SrcAlign, bool IsMemset,
7250 bool ZeroMemset,
7251 bool MemcpyStrSrc,
7252 MachineFunction &MF) const {
7253 // Don't use AdvSIMD to implement 16-byte memset. It would have taken one
7254 // instruction to materialize the v2i64 zero and one store (with restrictive
7255 // addressing mode). Just do two i64 store of zero-registers.
7256 bool Fast;
7257 const Function *F = MF.getFunction();
7258 if (Subtarget->hasFPARMv8() && !IsMemset && Size >= 16 &&
Duncan P. N. Exon Smith003bb7d2015-02-14 02:09:06 +00007259 !F->hasFnAttribute(Attribute::NoImplicitFloat) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00007260 (memOpAlign(SrcAlign, DstAlign, 16) ||
Matt Arsenault6f2a5262014-07-27 17:46:40 +00007261 (allowsMisalignedMemoryAccesses(MVT::f128, 0, 1, &Fast) && Fast)))
Tim Northover3b0846e2014-05-24 12:50:23 +00007262 return MVT::f128;
7263
Lang Hames90333852015-04-09 03:40:33 +00007264 if (Size >= 8 &&
7265 (memOpAlign(SrcAlign, DstAlign, 8) ||
7266 (allowsMisalignedMemoryAccesses(MVT::i64, 0, 1, &Fast) && Fast)))
7267 return MVT::i64;
7268
7269 if (Size >= 4 &&
7270 (memOpAlign(SrcAlign, DstAlign, 4) ||
7271 (allowsMisalignedMemoryAccesses(MVT::i32, 0, 1, &Fast) && Fast)))
Lang Hames522bf132015-04-09 05:34:57 +00007272 return MVT::i32;
Lang Hames90333852015-04-09 03:40:33 +00007273
7274 return MVT::Other;
Tim Northover3b0846e2014-05-24 12:50:23 +00007275}
7276
7277// 12-bit optionally shifted immediates are legal for adds.
7278bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
Geoff Berryf5ba61d2016-02-29 19:53:22 +00007279 // Same encoding for add/sub, just flip the sign.
7280 Immed = std::abs(Immed);
Eric Christopher114fa1c2016-02-29 22:50:49 +00007281 return ((Immed >> 12) == 0 || ((Immed & 0xfff) == 0 && Immed >> 24 == 0));
Tim Northover3b0846e2014-05-24 12:50:23 +00007282}
7283
7284// Integer comparisons are implemented with ADDS/SUBS, so the range of valid
7285// immediates is the same as for an add or a sub.
7286bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00007287 return isLegalAddImmediate(Immed);
7288}
7289
7290/// isLegalAddressingMode - Return true if the addressing mode represented
7291/// by AM is legal for this target, for a load/store of the specified type.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00007292bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
7293 const AddrMode &AM, Type *Ty,
Matt Arsenaultbd7d80a2015-06-01 05:31:59 +00007294 unsigned AS) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00007295 // AArch64 has five basic addressing modes:
7296 // reg
7297 // reg + 9-bit signed offset
7298 // reg + SIZE_IN_BYTES * 12-bit unsigned offset
7299 // reg1 + reg2
7300 // reg + SIZE_IN_BYTES * reg
7301
7302 // No global is ever allowed as a base.
7303 if (AM.BaseGV)
7304 return false;
7305
7306 // No reg+reg+imm addressing.
7307 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
7308 return false;
7309
7310 // check reg + imm case:
7311 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
7312 uint64_t NumBytes = 0;
7313 if (Ty->isSized()) {
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00007314 uint64_t NumBits = DL.getTypeSizeInBits(Ty);
Tim Northover3b0846e2014-05-24 12:50:23 +00007315 NumBytes = NumBits / 8;
7316 if (!isPowerOf2_64(NumBits))
7317 NumBytes = 0;
7318 }
7319
7320 if (!AM.Scale) {
7321 int64_t Offset = AM.BaseOffs;
7322
7323 // 9-bit signed offset
7324 if (Offset >= -(1LL << 9) && Offset <= (1LL << 9) - 1)
7325 return true;
7326
7327 // 12-bit unsigned offset
7328 unsigned shift = Log2_64(NumBytes);
7329 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
7330 // Must be a multiple of NumBytes (NumBytes is a power of 2)
7331 (Offset >> shift) << shift == Offset)
7332 return true;
7333 return false;
7334 }
7335
7336 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
7337
Eric Christopher114fa1c2016-02-29 22:50:49 +00007338 return !AM.Scale || AM.Scale == 1 ||
7339 (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes);
Tim Northover3b0846e2014-05-24 12:50:23 +00007340}
7341
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00007342int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
7343 const AddrMode &AM, Type *Ty,
Matt Arsenaultbd7d80a2015-06-01 05:31:59 +00007344 unsigned AS) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00007345 // Scaling factors are not free at all.
7346 // Operands | Rt Latency
7347 // -------------------------------------------
7348 // Rt, [Xn, Xm] | 4
7349 // -------------------------------------------
7350 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5
7351 // Rt, [Xn, Wm, <extend> #imm] |
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00007352 if (isLegalAddressingMode(DL, AM, Ty, AS))
Tim Northover3b0846e2014-05-24 12:50:23 +00007353 // Scale represents reg2 * scale, thus account for 1 if
7354 // it is not equal to 0 or 1.
7355 return AM.Scale != 0 && AM.Scale != 1;
7356 return -1;
7357}
7358
7359bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
7360 VT = VT.getScalarType();
7361
7362 if (!VT.isSimple())
7363 return false;
7364
7365 switch (VT.getSimpleVT().SimpleTy) {
7366 case MVT::f32:
7367 case MVT::f64:
7368 return true;
7369 default:
7370 break;
7371 }
7372
7373 return false;
7374}
7375
7376const MCPhysReg *
7377AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
7378 // LR is a callee-save register, but we must treat it as clobbered by any call
7379 // site. Hence we include LR in the scratch registers, which are in turn added
7380 // as implicit-defs for stackmaps and patchpoints.
7381 static const MCPhysReg ScratchRegs[] = {
7382 AArch64::X16, AArch64::X17, AArch64::LR, 0
7383 };
7384 return ScratchRegs;
7385}
7386
7387bool
7388AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N) const {
7389 EVT VT = N->getValueType(0);
7390 // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
7391 // it with shift to let it be lowered to UBFX.
7392 if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
7393 isa<ConstantSDNode>(N->getOperand(1))) {
7394 uint64_t TruncMask = N->getConstantOperandVal(1);
7395 if (isMask_64(TruncMask) &&
7396 N->getOperand(0).getOpcode() == ISD::SRL &&
7397 isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
7398 return false;
7399 }
7400 return true;
7401}
7402
7403bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
7404 Type *Ty) const {
7405 assert(Ty->isIntegerTy());
7406
7407 unsigned BitSize = Ty->getPrimitiveSizeInBits();
7408 if (BitSize == 0)
7409 return false;
7410
7411 int64_t Val = Imm.getSExtValue();
7412 if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
7413 return true;
7414
7415 if ((int64_t)Val < 0)
7416 Val = ~Val;
7417 if (BitSize == 32)
7418 Val &= (1LL << 32) - 1;
7419
7420 unsigned LZ = countLeadingZeros((uint64_t)Val);
7421 unsigned Shift = (63 - LZ) / 16;
7422 // MOVZ is free so return true for one or fewer MOVK.
David Blaikie186d2cb2015-03-24 16:24:01 +00007423 return Shift < 3;
Tim Northover3b0846e2014-05-24 12:50:23 +00007424}
7425
7426// Generate SUBS and CSEL for integer abs.
7427static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
7428 EVT VT = N->getValueType(0);
7429
7430 SDValue N0 = N->getOperand(0);
7431 SDValue N1 = N->getOperand(1);
7432 SDLoc DL(N);
7433
7434 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
7435 // and change it to SUB and CSEL.
7436 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
7437 N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
7438 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
7439 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
7440 if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007441 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
Tim Northover3b0846e2014-05-24 12:50:23 +00007442 N0.getOperand(0));
7443 // Generate SUBS & CSEL.
7444 SDValue Cmp =
7445 DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007446 N0.getOperand(0), DAG.getConstant(0, DL, VT));
Tim Northover3b0846e2014-05-24 12:50:23 +00007447 return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007448 DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00007449 SDValue(Cmp.getNode(), 1));
7450 }
7451 return SDValue();
7452}
7453
7454// performXorCombine - Attempts to handle integer ABS.
7455static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
7456 TargetLowering::DAGCombinerInfo &DCI,
7457 const AArch64Subtarget *Subtarget) {
7458 if (DCI.isBeforeLegalizeOps())
7459 return SDValue();
7460
7461 return performIntegerAbsCombine(N, DAG);
7462}
7463
Chad Rosier17020f92014-07-23 14:57:52 +00007464SDValue
7465AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
7466 SelectionDAG &DAG,
7467 std::vector<SDNode *> *Created) const {
7468 // fold (sdiv X, pow2)
7469 EVT VT = N->getValueType(0);
7470 if ((VT != MVT::i32 && VT != MVT::i64) ||
7471 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
7472 return SDValue();
7473
7474 SDLoc DL(N);
7475 SDValue N0 = N->getOperand(0);
7476 unsigned Lg2 = Divisor.countTrailingZeros();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007477 SDValue Zero = DAG.getConstant(0, DL, VT);
7478 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
Chad Rosier17020f92014-07-23 14:57:52 +00007479
7480 // Add (N0 < 0) ? Pow2 - 1 : 0;
7481 SDValue CCVal;
7482 SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
7483 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
7484 SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
7485
7486 if (Created) {
7487 Created->push_back(Cmp.getNode());
7488 Created->push_back(Add.getNode());
7489 Created->push_back(CSel.getNode());
7490 }
7491
7492 // Divide by pow2.
7493 SDValue SRA =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007494 DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
Chad Rosier17020f92014-07-23 14:57:52 +00007495
7496 // If we're dividing by a positive value, we're done. Otherwise, we must
7497 // negate the result.
7498 if (Divisor.isNonNegative())
7499 return SRA;
7500
7501 if (Created)
7502 Created->push_back(SRA.getNode());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007503 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
Chad Rosier17020f92014-07-23 14:57:52 +00007504}
7505
Tim Northover3b0846e2014-05-24 12:50:23 +00007506static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
7507 TargetLowering::DAGCombinerInfo &DCI,
7508 const AArch64Subtarget *Subtarget) {
7509 if (DCI.isBeforeLegalizeOps())
7510 return SDValue();
7511
7512 // Multiplication of a power of two plus/minus one can be done more
7513 // cheaply as as shift+add/sub. For now, this is true unilaterally. If
7514 // future CPUs have a cheaper MADD instruction, this may need to be
7515 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
7516 // 64-bit is 5 cycles, so this is always a win.
7517 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1))) {
7518 APInt Value = C->getAPIntValue();
7519 EVT VT = N->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007520 SDLoc DL(N);
Chad Rosiere6b87612014-06-30 14:51:14 +00007521 if (Value.isNonNegative()) {
7522 // (mul x, 2^N + 1) => (add (shl x, N), x)
7523 APInt VM1 = Value - 1;
7524 if (VM1.isPowerOf2()) {
7525 SDValue ShiftedVal =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007526 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7527 DAG.getConstant(VM1.logBase2(), DL, MVT::i64));
7528 return DAG.getNode(ISD::ADD, DL, VT, ShiftedVal,
Chad Rosiere6b87612014-06-30 14:51:14 +00007529 N->getOperand(0));
7530 }
7531 // (mul x, 2^N - 1) => (sub (shl x, N), x)
7532 APInt VP1 = Value + 1;
7533 if (VP1.isPowerOf2()) {
7534 SDValue ShiftedVal =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007535 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7536 DAG.getConstant(VP1.logBase2(), DL, MVT::i64));
7537 return DAG.getNode(ISD::SUB, DL, VT, ShiftedVal,
Chad Rosiere6b87612014-06-30 14:51:14 +00007538 N->getOperand(0));
7539 }
7540 } else {
Chad Rosier8e38f302015-03-03 17:31:01 +00007541 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
7542 APInt VNP1 = -Value + 1;
7543 if (VNP1.isPowerOf2()) {
7544 SDValue ShiftedVal =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007545 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7546 DAG.getConstant(VNP1.logBase2(), DL, MVT::i64));
7547 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0),
Chad Rosier8e38f302015-03-03 17:31:01 +00007548 ShiftedVal);
7549 }
Chad Rosiere6b87612014-06-30 14:51:14 +00007550 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
7551 APInt VNM1 = -Value - 1;
7552 if (VNM1.isPowerOf2()) {
7553 SDValue ShiftedVal =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007554 DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
7555 DAG.getConstant(VNM1.logBase2(), DL, MVT::i64));
Chad Rosiere6b87612014-06-30 14:51:14 +00007556 SDValue Add =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007557 DAG.getNode(ISD::ADD, DL, VT, ShiftedVal, N->getOperand(0));
7558 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Add);
Chad Rosiere6b87612014-06-30 14:51:14 +00007559 }
Chad Rosierd96e9f12014-06-09 01:25:51 +00007560 }
Tim Northover3b0846e2014-05-24 12:50:23 +00007561 }
7562 return SDValue();
7563}
7564
Jim Grosbachf7502c42014-07-18 00:40:52 +00007565static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
7566 SelectionDAG &DAG) {
7567 // Take advantage of vector comparisons producing 0 or -1 in each lane to
7568 // optimize away operation when it's from a constant.
7569 //
7570 // The general transformation is:
7571 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
7572 // AND(VECTOR_CMP(x,y), constant2)
7573 // constant2 = UNARYOP(constant)
7574
Jim Grosbach8f6f0852014-07-23 20:41:38 +00007575 // Early exit if this isn't a vector operation, the operand of the
7576 // unary operation isn't a bitwise AND, or if the sizes of the operations
7577 // aren't the same.
Jim Grosbachf7502c42014-07-18 00:40:52 +00007578 EVT VT = N->getValueType(0);
7579 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
Jim Grosbach8f6f0852014-07-23 20:41:38 +00007580 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
7581 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
Jim Grosbachf7502c42014-07-18 00:40:52 +00007582 return SDValue();
7583
Jim Grosbach724e4382014-07-23 20:41:43 +00007584 // Now check that the other operand of the AND is a constant. We could
Jim Grosbachf7502c42014-07-18 00:40:52 +00007585 // make the transformation for non-constant splats as well, but it's unclear
7586 // that would be a benefit as it would not eliminate any operations, just
7587 // perform one more step in scalar code before moving to the vector unit.
7588 if (BuildVectorSDNode *BV =
7589 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
Jim Grosbach724e4382014-07-23 20:41:43 +00007590 // Bail out if the vector isn't a constant.
7591 if (!BV->isConstant())
Jim Grosbachf7502c42014-07-18 00:40:52 +00007592 return SDValue();
7593
7594 // Everything checks out. Build up the new and improved node.
7595 SDLoc DL(N);
7596 EVT IntVT = BV->getValueType(0);
7597 // Create a new constant of the appropriate type for the transformed
7598 // DAG.
7599 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
7600 // The AND node needs bitcasts to/from an integer vector type around it.
7601 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
7602 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
7603 N->getOperand(0)->getOperand(0), MaskConst);
7604 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
7605 return Res;
7606 }
7607
7608 return SDValue();
7609}
7610
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00007611static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
7612 const AArch64Subtarget *Subtarget) {
Jim Grosbachf7502c42014-07-18 00:40:52 +00007613 // First try to optimize away the conversion when it's conditionally from
7614 // a constant. Vectors only.
Ahmed Bougacha239d6352015-08-04 00:48:02 +00007615 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
Jim Grosbachf7502c42014-07-18 00:40:52 +00007616 return Res;
7617
Tim Northover3b0846e2014-05-24 12:50:23 +00007618 EVT VT = N->getValueType(0);
7619 if (VT != MVT::f32 && VT != MVT::f64)
7620 return SDValue();
Jim Grosbachf7502c42014-07-18 00:40:52 +00007621
Tim Northover3b0846e2014-05-24 12:50:23 +00007622 // Only optimize when the source and destination types have the same width.
7623 if (VT.getSizeInBits() != N->getOperand(0).getValueType().getSizeInBits())
7624 return SDValue();
7625
7626 // If the result of an integer load is only used by an integer-to-float
7627 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
Chad Rosier1f385612015-10-02 16:42:59 +00007628 // This eliminates an "integer-to-vector-move" UOP and improves throughput.
Tim Northover3b0846e2014-05-24 12:50:23 +00007629 SDValue N0 = N->getOperand(0);
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00007630 if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Tim Northover3b0846e2014-05-24 12:50:23 +00007631 // Do not change the width of a volatile load.
7632 !cast<LoadSDNode>(N0)->isVolatile()) {
7633 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7634 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
7635 LN0->getPointerInfo(), LN0->isVolatile(),
7636 LN0->isNonTemporal(), LN0->isInvariant(),
7637 LN0->getAlignment());
7638
7639 // Make sure successors of the original load stay after it by updating them
7640 // to use the new Chain.
7641 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
7642
7643 unsigned Opcode =
7644 (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
7645 return DAG.getNode(Opcode, SDLoc(N), VT, Load);
7646 }
7647
7648 return SDValue();
7649}
7650
Chad Rosierfa30c9b2015-10-07 17:39:18 +00007651/// Fold a floating-point multiply by power of two into floating-point to
7652/// fixed-point conversion.
7653static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
7654 const AArch64Subtarget *Subtarget) {
7655 if (!Subtarget->hasNEON())
7656 return SDValue();
7657
7658 SDValue Op = N->getOperand(0);
7659 if (!Op.getValueType().isVector() || Op.getOpcode() != ISD::FMUL)
7660 return SDValue();
7661
7662 SDValue ConstVec = Op->getOperand(1);
7663 if (!isa<BuildVectorSDNode>(ConstVec))
7664 return SDValue();
7665
7666 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
7667 uint32_t FloatBits = FloatTy.getSizeInBits();
7668 if (FloatBits != 32 && FloatBits != 64)
7669 return SDValue();
7670
7671 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
7672 uint32_t IntBits = IntTy.getSizeInBits();
7673 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
7674 return SDValue();
7675
7676 // Avoid conversions where iN is larger than the float (e.g., float -> i64).
7677 if (IntBits > FloatBits)
7678 return SDValue();
7679
7680 BitVector UndefElements;
7681 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
7682 int32_t Bits = IntBits == 64 ? 64 : 32;
7683 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
7684 if (C == -1 || C == 0 || C > Bits)
7685 return SDValue();
7686
7687 MVT ResTy;
7688 unsigned NumLanes = Op.getValueType().getVectorNumElements();
7689 switch (NumLanes) {
7690 default:
7691 return SDValue();
7692 case 2:
7693 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
7694 break;
7695 case 4:
7696 ResTy = MVT::v4i32;
7697 break;
7698 }
7699
7700 SDLoc DL(N);
7701 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
7702 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
7703 : Intrinsic::aarch64_neon_vcvtfp2fxu;
7704 SDValue FixConv =
7705 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
7706 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
7707 Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
7708 // We can handle smaller integers by generating an extra trunc.
7709 if (IntBits < FloatBits)
7710 FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
7711
7712 return FixConv;
7713}
7714
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00007715/// Fold a floating-point divide by power of two into fixed-point to
7716/// floating-point conversion.
7717static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
7718 const AArch64Subtarget *Subtarget) {
7719 if (!Subtarget->hasNEON())
7720 return SDValue();
7721
7722 SDValue Op = N->getOperand(0);
7723 unsigned Opc = Op->getOpcode();
7724 if (!Op.getValueType().isVector() ||
7725 (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
7726 return SDValue();
7727
7728 SDValue ConstVec = N->getOperand(1);
7729 if (!isa<BuildVectorSDNode>(ConstVec))
7730 return SDValue();
7731
7732 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
7733 int32_t IntBits = IntTy.getSizeInBits();
7734 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
7735 return SDValue();
7736
7737 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
7738 int32_t FloatBits = FloatTy.getSizeInBits();
7739 if (FloatBits != 32 && FloatBits != 64)
7740 return SDValue();
7741
7742 // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
7743 if (IntBits > FloatBits)
7744 return SDValue();
7745
7746 BitVector UndefElements;
7747 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
7748 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
7749 if (C == -1 || C == 0 || C > FloatBits)
7750 return SDValue();
7751
7752 MVT ResTy;
7753 unsigned NumLanes = Op.getValueType().getVectorNumElements();
7754 switch (NumLanes) {
7755 default:
7756 return SDValue();
7757 case 2:
7758 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
7759 break;
7760 case 4:
7761 ResTy = MVT::v4i32;
7762 break;
7763 }
7764
7765 SDLoc DL(N);
7766 SDValue ConvInput = Op.getOperand(0);
7767 bool IsSigned = Opc == ISD::SINT_TO_FP;
7768 if (IntBits < FloatBits)
7769 ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
7770 ResTy, ConvInput);
7771
7772 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
7773 : Intrinsic::aarch64_neon_vcvtfxu2fp;
7774 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
7775 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
7776 DAG.getConstant(C, DL, MVT::i32));
7777}
7778
Tim Northover3b0846e2014-05-24 12:50:23 +00007779/// An EXTR instruction is made up of two shifts, ORed together. This helper
7780/// searches for and classifies those shifts.
7781static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
7782 bool &FromHi) {
7783 if (N.getOpcode() == ISD::SHL)
7784 FromHi = false;
7785 else if (N.getOpcode() == ISD::SRL)
7786 FromHi = true;
7787 else
7788 return false;
7789
7790 if (!isa<ConstantSDNode>(N.getOperand(1)))
7791 return false;
7792
7793 ShiftAmount = N->getConstantOperandVal(1);
7794 Src = N->getOperand(0);
7795 return true;
7796}
7797
7798/// EXTR instruction extracts a contiguous chunk of bits from two existing
7799/// registers viewed as a high/low pair. This function looks for the pattern:
7800/// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an
7801/// EXTR. Can't quite be done in TableGen because the two immediates aren't
7802/// independent.
7803static SDValue tryCombineToEXTR(SDNode *N,
7804 TargetLowering::DAGCombinerInfo &DCI) {
7805 SelectionDAG &DAG = DCI.DAG;
7806 SDLoc DL(N);
7807 EVT VT = N->getValueType(0);
7808
7809 assert(N->getOpcode() == ISD::OR && "Unexpected root");
7810
7811 if (VT != MVT::i32 && VT != MVT::i64)
7812 return SDValue();
7813
7814 SDValue LHS;
7815 uint32_t ShiftLHS = 0;
7816 bool LHSFromHi = 0;
7817 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
7818 return SDValue();
7819
7820 SDValue RHS;
7821 uint32_t ShiftRHS = 0;
7822 bool RHSFromHi = 0;
7823 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
7824 return SDValue();
7825
7826 // If they're both trying to come from the high part of the register, they're
7827 // not really an EXTR.
7828 if (LHSFromHi == RHSFromHi)
7829 return SDValue();
7830
7831 if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
7832 return SDValue();
7833
7834 if (LHSFromHi) {
7835 std::swap(LHS, RHS);
7836 std::swap(ShiftLHS, ShiftRHS);
7837 }
7838
7839 return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007840 DAG.getConstant(ShiftRHS, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00007841}
7842
7843static SDValue tryCombineToBSL(SDNode *N,
7844 TargetLowering::DAGCombinerInfo &DCI) {
7845 EVT VT = N->getValueType(0);
7846 SelectionDAG &DAG = DCI.DAG;
7847 SDLoc DL(N);
7848
7849 if (!VT.isVector())
7850 return SDValue();
7851
7852 SDValue N0 = N->getOperand(0);
7853 if (N0.getOpcode() != ISD::AND)
7854 return SDValue();
7855
7856 SDValue N1 = N->getOperand(1);
7857 if (N1.getOpcode() != ISD::AND)
7858 return SDValue();
7859
7860 // We only have to look for constant vectors here since the general, variable
7861 // case can be handled in TableGen.
7862 unsigned Bits = VT.getVectorElementType().getSizeInBits();
7863 uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
7864 for (int i = 1; i >= 0; --i)
7865 for (int j = 1; j >= 0; --j) {
7866 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
7867 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
7868 if (!BVN0 || !BVN1)
7869 continue;
7870
7871 bool FoundMatch = true;
7872 for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
7873 ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
7874 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
7875 if (!CN0 || !CN1 ||
7876 CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
7877 FoundMatch = false;
7878 break;
7879 }
7880 }
7881
7882 if (FoundMatch)
7883 return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
7884 N0->getOperand(1 - i), N1->getOperand(1 - j));
7885 }
7886
7887 return SDValue();
7888}
7889
7890static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
7891 const AArch64Subtarget *Subtarget) {
7892 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
7893 if (!EnableAArch64ExtrGeneration)
7894 return SDValue();
7895 SelectionDAG &DAG = DCI.DAG;
7896 EVT VT = N->getValueType(0);
7897
7898 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
7899 return SDValue();
7900
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00007901 if (SDValue Res = tryCombineToEXTR(N, DCI))
Tim Northover3b0846e2014-05-24 12:50:23 +00007902 return Res;
7903
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00007904 if (SDValue Res = tryCombineToBSL(N, DCI))
Tim Northover3b0846e2014-05-24 12:50:23 +00007905 return Res;
7906
7907 return SDValue();
7908}
7909
7910static SDValue performBitcastCombine(SDNode *N,
7911 TargetLowering::DAGCombinerInfo &DCI,
7912 SelectionDAG &DAG) {
7913 // Wait 'til after everything is legalized to try this. That way we have
7914 // legal vector types and such.
7915 if (DCI.isBeforeLegalizeOps())
7916 return SDValue();
7917
7918 // Remove extraneous bitcasts around an extract_subvector.
7919 // For example,
7920 // (v4i16 (bitconvert
7921 // (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
7922 // becomes
7923 // (extract_subvector ((v8i16 ...), (i64 4)))
7924
7925 // Only interested in 64-bit vectors as the ultimate result.
7926 EVT VT = N->getValueType(0);
7927 if (!VT.isVector())
7928 return SDValue();
7929 if (VT.getSimpleVT().getSizeInBits() != 64)
7930 return SDValue();
7931 // Is the operand an extract_subvector starting at the beginning or halfway
7932 // point of the vector? A low half may also come through as an
7933 // EXTRACT_SUBREG, so look for that, too.
7934 SDValue Op0 = N->getOperand(0);
7935 if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
7936 !(Op0->isMachineOpcode() &&
7937 Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
7938 return SDValue();
7939 uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
7940 if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
7941 if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
7942 return SDValue();
7943 } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
7944 if (idx != AArch64::dsub)
7945 return SDValue();
7946 // The dsub reference is equivalent to a lane zero subvector reference.
7947 idx = 0;
7948 }
7949 // Look through the bitcast of the input to the extract.
7950 if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
7951 return SDValue();
7952 SDValue Source = Op0->getOperand(0)->getOperand(0);
7953 // If the source type has twice the number of elements as our destination
7954 // type, we know this is an extract of the high or low half of the vector.
7955 EVT SVT = Source->getValueType(0);
7956 if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
7957 return SDValue();
7958
7959 DEBUG(dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
7960
7961 // Create the simplified form to just extract the low or high half of the
7962 // vector directly rather than bothering with the bitcasts.
7963 SDLoc dl(N);
7964 unsigned NumElements = VT.getVectorNumElements();
7965 if (idx) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007966 SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00007967 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
7968 } else {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007969 SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00007970 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
7971 Source, SubReg),
7972 0);
7973 }
7974}
7975
7976static SDValue performConcatVectorsCombine(SDNode *N,
7977 TargetLowering::DAGCombinerInfo &DCI,
7978 SelectionDAG &DAG) {
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00007979 SDLoc dl(N);
7980 EVT VT = N->getValueType(0);
7981 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
7982
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00007983 // Optimize concat_vectors of truncated vectors, where the intermediate
7984 // type is illegal, to avoid said illegality, e.g.,
7985 // (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
7986 // (v2i16 (truncate (v2i64)))))
7987 // ->
Ahmed Bougachae6bb09a2015-03-21 01:08:39 +00007988 // (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
7989 // (v4i32 (bitcast (v2i64))),
7990 // <0, 2, 4, 6>)))
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00007991 // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
7992 // on both input and result type, so we might generate worse code.
7993 // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
7994 if (N->getNumOperands() == 2 &&
7995 N0->getOpcode() == ISD::TRUNCATE &&
7996 N1->getOpcode() == ISD::TRUNCATE) {
7997 SDValue N00 = N0->getOperand(0);
7998 SDValue N10 = N1->getOperand(0);
7999 EVT N00VT = N00.getValueType();
8000
8001 if (N00VT == N10.getValueType() &&
8002 (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
8003 N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
Ahmed Bougachae6bb09a2015-03-21 01:08:39 +00008004 MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
8005 SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
8006 for (size_t i = 0; i < Mask.size(); ++i)
8007 Mask[i] = i * 2;
8008 return DAG.getNode(ISD::TRUNCATE, dl, VT,
8009 DAG.getVectorShuffle(
8010 MidVT, dl,
8011 DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
8012 DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00008013 }
8014 }
8015
Tim Northover3b0846e2014-05-24 12:50:23 +00008016 // Wait 'til after everything is legalized to try this. That way we have
8017 // legal vector types and such.
8018 if (DCI.isBeforeLegalizeOps())
8019 return SDValue();
8020
Tim Northover3b0846e2014-05-24 12:50:23 +00008021 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
8022 // splat. The indexed instructions are going to be expecting a DUPLANE64, so
8023 // canonicalise to that.
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00008024 if (N0 == N1 && VT.getVectorNumElements() == 2) {
Tim Northover3b0846e2014-05-24 12:50:23 +00008025 assert(VT.getVectorElementType().getSizeInBits() == 64);
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00008026 return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008027 DAG.getConstant(0, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008028 }
8029
8030 // Canonicalise concat_vectors so that the right-hand vector has as few
8031 // bit-casts as possible before its real operation. The primary matching
8032 // destination for these operations will be the narrowing "2" instructions,
8033 // which depend on the operation being performed on this right-hand vector.
8034 // For example,
8035 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS))))
8036 // becomes
8037 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
8038
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00008039 if (N1->getOpcode() != ISD::BITCAST)
Tim Northover3b0846e2014-05-24 12:50:23 +00008040 return SDValue();
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00008041 SDValue RHS = N1->getOperand(0);
Tim Northover3b0846e2014-05-24 12:50:23 +00008042 MVT RHSTy = RHS.getValueType().getSimpleVT();
8043 // If the RHS is not a vector, this is not the pattern we're looking for.
8044 if (!RHSTy.isVector())
8045 return SDValue();
8046
8047 DEBUG(dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
8048
8049 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
8050 RHSTy.getVectorNumElements() * 2);
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00008051 return DAG.getNode(ISD::BITCAST, dl, VT,
8052 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
8053 DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
8054 RHS));
Tim Northover3b0846e2014-05-24 12:50:23 +00008055}
8056
8057static SDValue tryCombineFixedPointConvert(SDNode *N,
8058 TargetLowering::DAGCombinerInfo &DCI,
8059 SelectionDAG &DAG) {
8060 // Wait 'til after everything is legalized to try this. That way we have
8061 // legal vector types and such.
8062 if (DCI.isBeforeLegalizeOps())
8063 return SDValue();
8064 // Transform a scalar conversion of a value from a lane extract into a
8065 // lane extract of a vector conversion. E.g., from foo1 to foo2:
8066 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
8067 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
8068 //
8069 // The second form interacts better with instruction selection and the
8070 // register allocator to avoid cross-class register copies that aren't
8071 // coalescable due to a lane reference.
8072
8073 // Check the operand and see if it originates from a lane extract.
8074 SDValue Op1 = N->getOperand(1);
8075 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8076 // Yep, no additional predication needed. Perform the transform.
8077 SDValue IID = N->getOperand(0);
8078 SDValue Shift = N->getOperand(2);
8079 SDValue Vec = Op1.getOperand(0);
8080 SDValue Lane = Op1.getOperand(1);
8081 EVT ResTy = N->getValueType(0);
8082 EVT VecResTy;
8083 SDLoc DL(N);
8084
8085 // The vector width should be 128 bits by the time we get here, even
8086 // if it started as 64 bits (the extract_vector handling will have
8087 // done so).
8088 assert(Vec.getValueType().getSizeInBits() == 128 &&
8089 "unexpected vector size on extract_vector_elt!");
8090 if (Vec.getValueType() == MVT::v4i32)
8091 VecResTy = MVT::v4f32;
8092 else if (Vec.getValueType() == MVT::v2i64)
8093 VecResTy = MVT::v2f64;
8094 else
Craig Topper2a30d782014-06-18 05:05:13 +00008095 llvm_unreachable("unexpected vector type!");
Tim Northover3b0846e2014-05-24 12:50:23 +00008096
8097 SDValue Convert =
8098 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
8099 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
8100 }
8101 return SDValue();
8102}
8103
8104// AArch64 high-vector "long" operations are formed by performing the non-high
8105// version on an extract_subvector of each operand which gets the high half:
8106//
8107// (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
8108//
8109// However, there are cases which don't have an extract_high explicitly, but
8110// have another operation that can be made compatible with one for free. For
8111// example:
8112//
8113// (dupv64 scalar) --> (extract_high (dup128 scalar))
8114//
8115// This routine does the actual conversion of such DUPs, once outer routines
8116// have determined that everything else is in order.
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008117// It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
8118// similarly here.
Tim Northover3b0846e2014-05-24 12:50:23 +00008119static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00008120 switch (N.getOpcode()) {
8121 case AArch64ISD::DUP:
Tim Northover3b0846e2014-05-24 12:50:23 +00008122 case AArch64ISD::DUPLANE8:
8123 case AArch64ISD::DUPLANE16:
8124 case AArch64ISD::DUPLANE32:
8125 case AArch64ISD::DUPLANE64:
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008126 case AArch64ISD::MOVI:
8127 case AArch64ISD::MOVIshift:
8128 case AArch64ISD::MOVIedit:
8129 case AArch64ISD::MOVImsl:
8130 case AArch64ISD::MVNIshift:
8131 case AArch64ISD::MVNImsl:
Tim Northover3b0846e2014-05-24 12:50:23 +00008132 break;
8133 default:
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008134 // FMOV could be supported, but isn't very useful, as it would only occur
8135 // if you passed a bitcast' floating point immediate to an eligible long
8136 // integer op (addl, smull, ...).
Tim Northover3b0846e2014-05-24 12:50:23 +00008137 return SDValue();
8138 }
8139
8140 MVT NarrowTy = N.getSimpleValueType();
8141 if (!NarrowTy.is64BitVector())
8142 return SDValue();
8143
8144 MVT ElementTy = NarrowTy.getVectorElementType();
8145 unsigned NumElems = NarrowTy.getVectorNumElements();
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008146 MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
Tim Northover3b0846e2014-05-24 12:50:23 +00008147
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008148 SDLoc dl(N);
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008149 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
8150 DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008151 DAG.getConstant(NumElems, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008152}
8153
8154static bool isEssentiallyExtractSubvector(SDValue N) {
8155 if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
8156 return true;
8157
8158 return N.getOpcode() == ISD::BITCAST &&
8159 N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
8160}
8161
8162/// \brief Helper structure to keep track of ISD::SET_CC operands.
8163struct GenericSetCCInfo {
8164 const SDValue *Opnd0;
8165 const SDValue *Opnd1;
8166 ISD::CondCode CC;
8167};
8168
8169/// \brief Helper structure to keep track of a SET_CC lowered into AArch64 code.
8170struct AArch64SetCCInfo {
8171 const SDValue *Cmp;
8172 AArch64CC::CondCode CC;
8173};
8174
8175/// \brief Helper structure to keep track of SetCC information.
8176union SetCCInfo {
8177 GenericSetCCInfo Generic;
8178 AArch64SetCCInfo AArch64;
8179};
8180
8181/// \brief Helper structure to be able to read SetCC information. If set to
8182/// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
8183/// GenericSetCCInfo.
8184struct SetCCInfoAndKind {
8185 SetCCInfo Info;
8186 bool IsAArch64;
8187};
8188
8189/// \brief Check whether or not \p Op is a SET_CC operation, either a generic or
8190/// an
8191/// AArch64 lowered one.
8192/// \p SetCCInfo is filled accordingly.
8193/// \post SetCCInfo is meanginfull only when this function returns true.
8194/// \return True when Op is a kind of SET_CC operation.
8195static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
8196 // If this is a setcc, this is straight forward.
8197 if (Op.getOpcode() == ISD::SETCC) {
8198 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
8199 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
8200 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8201 SetCCInfo.IsAArch64 = false;
8202 return true;
8203 }
8204 // Otherwise, check if this is a matching csel instruction.
8205 // In other words:
8206 // - csel 1, 0, cc
8207 // - csel 0, 1, !cc
8208 if (Op.getOpcode() != AArch64ISD::CSEL)
8209 return false;
8210 // Set the information about the operands.
8211 // TODO: we want the operands of the Cmp not the csel
8212 SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
8213 SetCCInfo.IsAArch64 = true;
8214 SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
8215 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
8216
8217 // Check that the operands matches the constraints:
8218 // (1) Both operands must be constants.
8219 // (2) One must be 1 and the other must be 0.
8220 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
8221 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8222
8223 // Check (1).
8224 if (!TValue || !FValue)
8225 return false;
8226
8227 // Check (2).
8228 if (!TValue->isOne()) {
8229 // Update the comparison when we are interested in !cc.
8230 std::swap(TValue, FValue);
8231 SetCCInfo.Info.AArch64.CC =
8232 AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
8233 }
8234 return TValue->isOne() && FValue->isNullValue();
8235}
8236
8237// Returns true if Op is setcc or zext of setcc.
8238static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
8239 if (isSetCC(Op, Info))
8240 return true;
8241 return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
8242 isSetCC(Op->getOperand(0), Info));
8243}
8244
8245// The folding we want to perform is:
8246// (add x, [zext] (setcc cc ...) )
8247// -->
8248// (csel x, (add x, 1), !cc ...)
8249//
8250// The latter will get matched to a CSINC instruction.
8251static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
8252 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
8253 SDValue LHS = Op->getOperand(0);
8254 SDValue RHS = Op->getOperand(1);
8255 SetCCInfoAndKind InfoAndKind;
8256
8257 // If neither operand is a SET_CC, give up.
8258 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
8259 std::swap(LHS, RHS);
8260 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
8261 return SDValue();
8262 }
8263
8264 // FIXME: This could be generatized to work for FP comparisons.
8265 EVT CmpVT = InfoAndKind.IsAArch64
8266 ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
8267 : InfoAndKind.Info.Generic.Opnd0->getValueType();
8268 if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
8269 return SDValue();
8270
8271 SDValue CCVal;
8272 SDValue Cmp;
8273 SDLoc dl(Op);
8274 if (InfoAndKind.IsAArch64) {
8275 CCVal = DAG.getConstant(
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008276 AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
8277 MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00008278 Cmp = *InfoAndKind.Info.AArch64.Cmp;
8279 } else
8280 Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
8281 *InfoAndKind.Info.Generic.Opnd1,
8282 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
8283 CCVal, DAG, dl);
8284
8285 EVT VT = Op->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008286 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
Tim Northover3b0846e2014-05-24 12:50:23 +00008287 return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
8288}
8289
8290// The basic add/sub long vector instructions have variants with "2" on the end
8291// which act on the high-half of their inputs. They are normally matched by
8292// patterns like:
8293//
8294// (add (zeroext (extract_high LHS)),
8295// (zeroext (extract_high RHS)))
8296// -> uaddl2 vD, vN, vM
8297//
8298// However, if one of the extracts is something like a duplicate, this
8299// instruction can still be used profitably. This function puts the DAG into a
8300// more appropriate form for those patterns to trigger.
8301static SDValue performAddSubLongCombine(SDNode *N,
8302 TargetLowering::DAGCombinerInfo &DCI,
8303 SelectionDAG &DAG) {
8304 if (DCI.isBeforeLegalizeOps())
8305 return SDValue();
8306
8307 MVT VT = N->getSimpleValueType(0);
8308 if (!VT.is128BitVector()) {
8309 if (N->getOpcode() == ISD::ADD)
8310 return performSetccAddFolding(N, DAG);
8311 return SDValue();
8312 }
8313
8314 // Make sure both branches are extended in the same way.
8315 SDValue LHS = N->getOperand(0);
8316 SDValue RHS = N->getOperand(1);
8317 if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
8318 LHS.getOpcode() != ISD::SIGN_EXTEND) ||
8319 LHS.getOpcode() != RHS.getOpcode())
8320 return SDValue();
8321
8322 unsigned ExtType = LHS.getOpcode();
8323
8324 // It's not worth doing if at least one of the inputs isn't already an
8325 // extract, but we don't know which it'll be so we have to try both.
8326 if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
8327 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
8328 if (!RHS.getNode())
8329 return SDValue();
8330
8331 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
8332 } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
8333 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
8334 if (!LHS.getNode())
8335 return SDValue();
8336
8337 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
8338 }
8339
8340 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
8341}
8342
8343// Massage DAGs which we can use the high-half "long" operations on into
8344// something isel will recognize better. E.g.
8345//
8346// (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
8347// (aarch64_neon_umull (extract_high (v2i64 vec)))
8348// (extract_high (v2i64 (dup128 scalar)))))
8349//
Hal Finkelcd8664c2015-12-11 23:11:52 +00008350static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
Tim Northover3b0846e2014-05-24 12:50:23 +00008351 TargetLowering::DAGCombinerInfo &DCI,
8352 SelectionDAG &DAG) {
8353 if (DCI.isBeforeLegalizeOps())
8354 return SDValue();
8355
Hal Finkelcd8664c2015-12-11 23:11:52 +00008356 SDValue LHS = N->getOperand(1);
8357 SDValue RHS = N->getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00008358 assert(LHS.getValueType().is64BitVector() &&
8359 RHS.getValueType().is64BitVector() &&
8360 "unexpected shape for long operation");
8361
8362 // Either node could be a DUP, but it's not worth doing both of them (you'd
8363 // just as well use the non-high version) so look for a corresponding extract
8364 // operation on the other "wing".
8365 if (isEssentiallyExtractSubvector(LHS)) {
8366 RHS = tryExtendDUPToExtractHigh(RHS, DAG);
8367 if (!RHS.getNode())
8368 return SDValue();
8369 } else if (isEssentiallyExtractSubvector(RHS)) {
8370 LHS = tryExtendDUPToExtractHigh(LHS, DAG);
8371 if (!LHS.getNode())
8372 return SDValue();
8373 }
8374
Hal Finkelcd8664c2015-12-11 23:11:52 +00008375 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
8376 N->getOperand(0), LHS, RHS);
Tim Northover3b0846e2014-05-24 12:50:23 +00008377}
8378
8379static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
8380 MVT ElemTy = N->getSimpleValueType(0).getScalarType();
8381 unsigned ElemBits = ElemTy.getSizeInBits();
8382
8383 int64_t ShiftAmount;
8384 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
8385 APInt SplatValue, SplatUndef;
8386 unsigned SplatBitSize;
8387 bool HasAnyUndefs;
8388 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
8389 HasAnyUndefs, ElemBits) ||
8390 SplatBitSize != ElemBits)
8391 return SDValue();
8392
8393 ShiftAmount = SplatValue.getSExtValue();
8394 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
8395 ShiftAmount = CVN->getSExtValue();
8396 } else
8397 return SDValue();
8398
8399 unsigned Opcode;
8400 bool IsRightShift;
8401 switch (IID) {
8402 default:
8403 llvm_unreachable("Unknown shift intrinsic");
8404 case Intrinsic::aarch64_neon_sqshl:
8405 Opcode = AArch64ISD::SQSHL_I;
8406 IsRightShift = false;
8407 break;
8408 case Intrinsic::aarch64_neon_uqshl:
8409 Opcode = AArch64ISD::UQSHL_I;
8410 IsRightShift = false;
8411 break;
8412 case Intrinsic::aarch64_neon_srshl:
8413 Opcode = AArch64ISD::SRSHR_I;
8414 IsRightShift = true;
8415 break;
8416 case Intrinsic::aarch64_neon_urshl:
8417 Opcode = AArch64ISD::URSHR_I;
8418 IsRightShift = true;
8419 break;
8420 case Intrinsic::aarch64_neon_sqshlu:
8421 Opcode = AArch64ISD::SQSHLU_I;
8422 IsRightShift = false;
8423 break;
8424 }
8425
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008426 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
8427 SDLoc dl(N);
8428 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8429 DAG.getConstant(-ShiftAmount, dl, MVT::i32));
8430 } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
8431 SDLoc dl(N);
8432 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8433 DAG.getConstant(ShiftAmount, dl, MVT::i32));
8434 }
Tim Northover3b0846e2014-05-24 12:50:23 +00008435
8436 return SDValue();
8437}
8438
8439// The CRC32[BH] instructions ignore the high bits of their data operand. Since
8440// the intrinsics must be legal and take an i32, this means there's almost
8441// certainly going to be a zext in the DAG which we can eliminate.
8442static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
8443 SDValue AndN = N->getOperand(2);
8444 if (AndN.getOpcode() != ISD::AND)
8445 return SDValue();
8446
8447 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
8448 if (!CMask || CMask->getZExtValue() != Mask)
8449 return SDValue();
8450
8451 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
8452 N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
8453}
8454
Ahmed Bougachafab58922015-03-10 20:45:38 +00008455static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
8456 SelectionDAG &DAG) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008457 SDLoc dl(N);
8458 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
8459 DAG.getNode(Opc, dl,
Ahmed Bougachafab58922015-03-10 20:45:38 +00008460 N->getOperand(1).getSimpleValueType(),
8461 N->getOperand(1)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008462 DAG.getConstant(0, dl, MVT::i64));
Ahmed Bougachafab58922015-03-10 20:45:38 +00008463}
8464
Tim Northover3b0846e2014-05-24 12:50:23 +00008465static SDValue performIntrinsicCombine(SDNode *N,
8466 TargetLowering::DAGCombinerInfo &DCI,
8467 const AArch64Subtarget *Subtarget) {
8468 SelectionDAG &DAG = DCI.DAG;
8469 unsigned IID = getIntrinsicID(N);
8470 switch (IID) {
8471 default:
8472 break;
8473 case Intrinsic::aarch64_neon_vcvtfxs2fp:
8474 case Intrinsic::aarch64_neon_vcvtfxu2fp:
8475 return tryCombineFixedPointConvert(N, DCI, DAG);
Ahmed Bougachafab58922015-03-10 20:45:38 +00008476 case Intrinsic::aarch64_neon_saddv:
8477 return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
8478 case Intrinsic::aarch64_neon_uaddv:
8479 return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
8480 case Intrinsic::aarch64_neon_sminv:
8481 return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
8482 case Intrinsic::aarch64_neon_uminv:
8483 return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
8484 case Intrinsic::aarch64_neon_smaxv:
8485 return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
8486 case Intrinsic::aarch64_neon_umaxv:
8487 return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00008488 case Intrinsic::aarch64_neon_fmax:
James Molloyedf38f02015-08-11 12:06:33 +00008489 return DAG.getNode(ISD::FMAXNAN, SDLoc(N), N->getValueType(0),
Tim Northover3b0846e2014-05-24 12:50:23 +00008490 N->getOperand(1), N->getOperand(2));
8491 case Intrinsic::aarch64_neon_fmin:
James Molloyedf38f02015-08-11 12:06:33 +00008492 return DAG.getNode(ISD::FMINNAN, SDLoc(N), N->getValueType(0),
Tim Northover3b0846e2014-05-24 12:50:23 +00008493 N->getOperand(1), N->getOperand(2));
James Molloyb7b2a1e2015-08-11 12:06:37 +00008494 case Intrinsic::aarch64_neon_fmaxnm:
8495 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
8496 N->getOperand(1), N->getOperand(2));
8497 case Intrinsic::aarch64_neon_fminnm:
8498 return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
8499 N->getOperand(1), N->getOperand(2));
Tim Northover3b0846e2014-05-24 12:50:23 +00008500 case Intrinsic::aarch64_neon_smull:
8501 case Intrinsic::aarch64_neon_umull:
8502 case Intrinsic::aarch64_neon_pmull:
8503 case Intrinsic::aarch64_neon_sqdmull:
Hal Finkelcd8664c2015-12-11 23:11:52 +00008504 return tryCombineLongOpWithDup(IID, N, DCI, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00008505 case Intrinsic::aarch64_neon_sqshl:
8506 case Intrinsic::aarch64_neon_uqshl:
8507 case Intrinsic::aarch64_neon_sqshlu:
8508 case Intrinsic::aarch64_neon_srshl:
8509 case Intrinsic::aarch64_neon_urshl:
8510 return tryCombineShiftImm(IID, N, DAG);
8511 case Intrinsic::aarch64_crc32b:
8512 case Intrinsic::aarch64_crc32cb:
8513 return tryCombineCRC32(0xff, N, DAG);
8514 case Intrinsic::aarch64_crc32h:
8515 case Intrinsic::aarch64_crc32ch:
8516 return tryCombineCRC32(0xffff, N, DAG);
8517 }
8518 return SDValue();
8519}
8520
8521static SDValue performExtendCombine(SDNode *N,
8522 TargetLowering::DAGCombinerInfo &DCI,
8523 SelectionDAG &DAG) {
8524 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
8525 // we can convert that DUP into another extract_high (of a bigger DUP), which
8526 // helps the backend to decide that an sabdl2 would be useful, saving a real
8527 // extract_high operation.
8528 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
Hal Finkelcd8664c2015-12-11 23:11:52 +00008529 N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
Tim Northover3b0846e2014-05-24 12:50:23 +00008530 SDNode *ABDNode = N->getOperand(0).getNode();
Hal Finkelcd8664c2015-12-11 23:11:52 +00008531 unsigned IID = getIntrinsicID(ABDNode);
8532 if (IID == Intrinsic::aarch64_neon_sabd ||
8533 IID == Intrinsic::aarch64_neon_uabd) {
8534 SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
8535 if (!NewABD.getNode())
8536 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00008537
Hal Finkelcd8664c2015-12-11 23:11:52 +00008538 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
8539 NewABD);
8540 }
Tim Northover3b0846e2014-05-24 12:50:23 +00008541 }
8542
8543 // This is effectively a custom type legalization for AArch64.
8544 //
8545 // Type legalization will split an extend of a small, legal, type to a larger
8546 // illegal type by first splitting the destination type, often creating
8547 // illegal source types, which then get legalized in isel-confusing ways,
8548 // leading to really terrible codegen. E.g.,
8549 // %result = v8i32 sext v8i8 %value
8550 // becomes
8551 // %losrc = extract_subreg %value, ...
8552 // %hisrc = extract_subreg %value, ...
8553 // %lo = v4i32 sext v4i8 %losrc
8554 // %hi = v4i32 sext v4i8 %hisrc
8555 // Things go rapidly downhill from there.
8556 //
8557 // For AArch64, the [sz]ext vector instructions can only go up one element
8558 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
8559 // take two instructions.
8560 //
8561 // This implies that the most efficient way to do the extend from v8i8
8562 // to two v4i32 values is to first extend the v8i8 to v8i16, then do
8563 // the normal splitting to happen for the v8i16->v8i32.
8564
8565 // This is pre-legalization to catch some cases where the default
8566 // type legalization will create ill-tempered code.
8567 if (!DCI.isBeforeLegalizeOps())
8568 return SDValue();
8569
8570 // We're only interested in cleaning things up for non-legal vector types
8571 // here. If both the source and destination are legal, things will just
8572 // work naturally without any fiddling.
Matthew Simpson13dddb02015-12-17 21:29:47 +00008573 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00008574 EVT ResVT = N->getValueType(0);
8575 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
8576 return SDValue();
8577 // If the vector type isn't a simple VT, it's beyond the scope of what
8578 // we're worried about here. Let legalization do its thing and hope for
8579 // the best.
Jim Grosbachec2b0d02014-08-28 22:08:28 +00008580 SDValue Src = N->getOperand(0);
8581 EVT SrcVT = Src->getValueType(0);
8582 if (!ResVT.isSimple() || !SrcVT.isSimple())
Tim Northover3b0846e2014-05-24 12:50:23 +00008583 return SDValue();
8584
Tim Northover3b0846e2014-05-24 12:50:23 +00008585 // If the source VT is a 64-bit vector, we can play games and get the
8586 // better results we want.
8587 if (SrcVT.getSizeInBits() != 64)
8588 return SDValue();
8589
8590 unsigned SrcEltSize = SrcVT.getVectorElementType().getSizeInBits();
8591 unsigned ElementCount = SrcVT.getVectorNumElements();
8592 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
8593 SDLoc DL(N);
8594 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
8595
8596 // Now split the rest of the operation into two halves, each with a 64
8597 // bit source.
8598 EVT LoVT, HiVT;
8599 SDValue Lo, Hi;
8600 unsigned NumElements = ResVT.getVectorNumElements();
8601 assert(!(NumElements & 1) && "Splitting vector, but not in half!");
8602 LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
8603 ResVT.getVectorElementType(), NumElements / 2);
8604
8605 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
8606 LoVT.getVectorNumElements());
8607 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008608 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008609 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008610 DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008611 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
8612 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
8613
8614 // Now combine the parts back together so we still have a single result
8615 // like the combiner expects.
8616 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
8617}
8618
8619/// Replace a splat of a scalar to a vector store by scalar stores of the scalar
8620/// value. The load store optimizer pass will merge them to store pair stores.
8621/// This has better performance than a splat of the scalar followed by a split
8622/// vector store. Even if the stores are not merged it is four stores vs a dup,
8623/// followed by an ext.b and two stores.
8624static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode *St) {
8625 SDValue StVal = St->getValue();
8626 EVT VT = StVal.getValueType();
8627
8628 // Don't replace floating point stores, they possibly won't be transformed to
8629 // stp because of the store pair suppress pass.
8630 if (VT.isFloatingPoint())
8631 return SDValue();
8632
8633 // Check for insert vector elements.
8634 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
8635 return SDValue();
8636
8637 // We can express a splat as store pair(s) for 2 or 4 elements.
8638 unsigned NumVecElts = VT.getVectorNumElements();
8639 if (NumVecElts != 4 && NumVecElts != 2)
8640 return SDValue();
8641 SDValue SplatVal = StVal.getOperand(1);
8642 unsigned RemainInsertElts = NumVecElts - 1;
8643
8644 // Check that this is a splat.
8645 while (--RemainInsertElts) {
8646 SDValue NextInsertElt = StVal.getOperand(0);
8647 if (NextInsertElt.getOpcode() != ISD::INSERT_VECTOR_ELT)
8648 return SDValue();
8649 if (NextInsertElt.getOperand(1) != SplatVal)
8650 return SDValue();
8651 StVal = NextInsertElt;
8652 }
8653 unsigned OrigAlignment = St->getAlignment();
8654 unsigned EltOffset = NumVecElts == 4 ? 4 : 8;
8655 unsigned Alignment = std::min(OrigAlignment, EltOffset);
8656
8657 // Create scalar stores. This is at least as good as the code sequence for a
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00008658 // split unaligned store which is a dup.s, ext.b, and two stores.
Tim Northover3b0846e2014-05-24 12:50:23 +00008659 // Most of the time the three stores should be replaced by store pair
8660 // instructions (stp).
8661 SDLoc DL(St);
8662 SDValue BasePtr = St->getBasePtr();
8663 SDValue NewST1 =
8664 DAG.getStore(St->getChain(), DL, SplatVal, BasePtr, St->getPointerInfo(),
8665 St->isVolatile(), St->isNonTemporal(), St->getAlignment());
8666
8667 unsigned Offset = EltOffset;
8668 while (--NumVecElts) {
8669 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008670 DAG.getConstant(Offset, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008671 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
8672 St->getPointerInfo(), St->isVolatile(),
8673 St->isNonTemporal(), Alignment);
8674 Offset += EltOffset;
8675 }
8676 return NewST1;
8677}
8678
Tim Northover339c83e2015-11-10 00:44:23 +00008679static SDValue split16BStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
8680 SelectionDAG &DAG,
8681 const AArch64Subtarget *Subtarget) {
Tim Northover3b0846e2014-05-24 12:50:23 +00008682 if (!DCI.isBeforeLegalize())
8683 return SDValue();
8684
8685 StoreSDNode *S = cast<StoreSDNode>(N);
8686 if (S->isVolatile())
8687 return SDValue();
8688
Sanjay Patelbbbf9a12015-09-25 21:49:48 +00008689 // FIXME: The logic for deciding if an unaligned store should be split should
8690 // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
8691 // a call to that function here.
8692
Tim Northover3b0846e2014-05-24 12:50:23 +00008693 // Cyclone has bad performance on unaligned 16B stores when crossing line and
Sanjay Patel08efcd92015-01-28 22:37:32 +00008694 // page boundaries. We want to split such stores.
Tim Northover3b0846e2014-05-24 12:50:23 +00008695 if (!Subtarget->isCyclone())
8696 return SDValue();
8697
Sanjay Patel924879a2015-08-04 15:49:57 +00008698 // Don't split at -Oz.
8699 if (DAG.getMachineFunction().getFunction()->optForMinSize())
Tim Northover3b0846e2014-05-24 12:50:23 +00008700 return SDValue();
8701
8702 SDValue StVal = S->getValue();
8703 EVT VT = StVal.getValueType();
8704
8705 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
8706 // those up regresses performance on micro-benchmarks and olden/bh.
8707 if (!VT.isVector() || VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
8708 return SDValue();
8709
8710 // Split unaligned 16B stores. They are terrible for performance.
8711 // Don't split stores with alignment of 1 or 2. Code that uses clang vector
8712 // extensions can use this to mark that it does not want splitting to happen
8713 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
8714 // eliminating alignment hazards is only 1 in 8 for alignment of 2.
8715 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
8716 S->getAlignment() <= 2)
8717 return SDValue();
8718
8719 // If we get a splat of a scalar convert this vector store to a store of
8720 // scalars. They will be merged into store pairs thereby removing two
8721 // instructions.
Ahmed Bougacha239d6352015-08-04 00:48:02 +00008722 if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, S))
Tim Northover3b0846e2014-05-24 12:50:23 +00008723 return ReplacedSplat;
8724
8725 SDLoc DL(S);
8726 unsigned NumElts = VT.getVectorNumElements() / 2;
8727 // Split VT into two.
8728 EVT HalfVT =
8729 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
8730 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008731 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008732 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008733 DAG.getConstant(NumElts, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008734 SDValue BasePtr = S->getBasePtr();
8735 SDValue NewST1 =
8736 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
8737 S->isVolatile(), S->isNonTemporal(), S->getAlignment());
8738 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008739 DAG.getConstant(8, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008740 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
8741 S->getPointerInfo(), S->isVolatile(), S->isNonTemporal(),
8742 S->getAlignment());
8743}
8744
8745/// Target-specific DAG combine function for post-increment LD1 (lane) and
8746/// post-increment LD1R.
8747static SDValue performPostLD1Combine(SDNode *N,
8748 TargetLowering::DAGCombinerInfo &DCI,
8749 bool IsLaneOp) {
8750 if (DCI.isBeforeLegalizeOps())
8751 return SDValue();
8752
8753 SelectionDAG &DAG = DCI.DAG;
8754 EVT VT = N->getValueType(0);
8755
8756 unsigned LoadIdx = IsLaneOp ? 1 : 0;
8757 SDNode *LD = N->getOperand(LoadIdx).getNode();
8758 // If it is not LOAD, can not do such combine.
8759 if (LD->getOpcode() != ISD::LOAD)
8760 return SDValue();
8761
8762 LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
8763 EVT MemVT = LoadSDN->getMemoryVT();
8764 // Check if memory operand is the same type as the vector element.
8765 if (MemVT != VT.getVectorElementType())
8766 return SDValue();
8767
8768 // Check if there are other uses. If so, do not combine as it will introduce
8769 // an extra load.
8770 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
8771 ++UI) {
8772 if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
8773 continue;
8774 if (*UI != N)
8775 return SDValue();
8776 }
8777
8778 SDValue Addr = LD->getOperand(1);
8779 SDValue Vector = N->getOperand(0);
8780 // Search for a use of the address operand that is an increment.
8781 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
8782 Addr.getNode()->use_end(); UI != UE; ++UI) {
8783 SDNode *User = *UI;
8784 if (User->getOpcode() != ISD::ADD
8785 || UI.getUse().getResNo() != Addr.getResNo())
8786 continue;
8787
8788 // Check that the add is independent of the load. Otherwise, folding it
8789 // would create a cycle.
8790 if (User->isPredecessorOf(LD) || LD->isPredecessorOf(User))
8791 continue;
8792 // Also check that add is not used in the vector operand. This would also
8793 // create a cycle.
8794 if (User->isPredecessorOf(Vector.getNode()))
8795 continue;
8796
8797 // If the increment is a constant, it must match the memory ref size.
8798 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
8799 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
8800 uint32_t IncVal = CInc->getZExtValue();
8801 unsigned NumBytes = VT.getScalarSizeInBits() / 8;
8802 if (IncVal != NumBytes)
8803 continue;
8804 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
8805 }
8806
Ahmed Bougacha2448ef52015-04-17 21:02:30 +00008807 // Finally, check that the vector doesn't depend on the load.
8808 // Again, this would create a cycle.
8809 // The load depending on the vector is fine, as that's the case for the
8810 // LD1*post we'll eventually generate anyway.
8811 if (LoadSDN->isPredecessorOf(Vector.getNode()))
8812 continue;
8813
Tim Northover3b0846e2014-05-24 12:50:23 +00008814 SmallVector<SDValue, 8> Ops;
8815 Ops.push_back(LD->getOperand(0)); // Chain
8816 if (IsLaneOp) {
8817 Ops.push_back(Vector); // The vector to be inserted
8818 Ops.push_back(N->getOperand(2)); // The lane to be inserted in the vector
8819 }
8820 Ops.push_back(Addr);
8821 Ops.push_back(Inc);
8822
8823 EVT Tys[3] = { VT, MVT::i64, MVT::Other };
Craig Toppere1d12942014-08-27 05:25:25 +00008824 SDVTList SDTys = DAG.getVTList(Tys);
Tim Northover3b0846e2014-05-24 12:50:23 +00008825 unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
8826 SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
8827 MemVT,
8828 LoadSDN->getMemOperand());
8829
8830 // Update the uses.
Ahmed Bougacha4c2b0782015-02-19 23:13:10 +00008831 SmallVector<SDValue, 2> NewResults;
Tim Northover3b0846e2014-05-24 12:50:23 +00008832 NewResults.push_back(SDValue(LD, 0)); // The result of load
8833 NewResults.push_back(SDValue(UpdN.getNode(), 2)); // Chain
8834 DCI.CombineTo(LD, NewResults);
8835 DCI.CombineTo(N, SDValue(UpdN.getNode(), 0)); // Dup/Inserted Result
8836 DCI.CombineTo(User, SDValue(UpdN.getNode(), 1)); // Write back register
8837
8838 break;
8839 }
8840 return SDValue();
8841}
8842
Tim Northover339c83e2015-11-10 00:44:23 +00008843/// Simplify \Addr given that the top byte of it is ignored by HW during
8844/// address translation.
8845static bool performTBISimplification(SDValue Addr,
8846 TargetLowering::DAGCombinerInfo &DCI,
8847 SelectionDAG &DAG) {
8848 APInt DemandedMask = APInt::getLowBitsSet(64, 56);
8849 APInt KnownZero, KnownOne;
8850 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
8851 DCI.isBeforeLegalizeOps());
8852 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8853 if (TLI.SimplifyDemandedBits(Addr, DemandedMask, KnownZero, KnownOne, TLO)) {
8854 DCI.CommitTargetLoweringOpt(TLO);
8855 return true;
8856 }
8857 return false;
8858}
8859
8860static SDValue performSTORECombine(SDNode *N,
8861 TargetLowering::DAGCombinerInfo &DCI,
8862 SelectionDAG &DAG,
8863 const AArch64Subtarget *Subtarget) {
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00008864 if (SDValue Split = split16BStores(N, DCI, DAG, Subtarget))
Tim Northover339c83e2015-11-10 00:44:23 +00008865 return Split;
8866
8867 if (Subtarget->supportsAddressTopByteIgnored() &&
8868 performTBISimplification(N->getOperand(2), DCI, DAG))
8869 return SDValue(N, 0);
8870
8871 return SDValue();
8872}
8873
8874 /// This function handles the log2-shuffle pattern produced by the
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008875/// LoopVectorizer for the across vector reduction. It consists of
8876/// log2(NumVectorElements) steps and, in each step, 2^(s) elements
8877/// are reduced, where s is an induction variable from 0 to
8878/// log2(NumVectorElements).
8879static SDValue tryMatchAcrossLaneShuffleForReduction(SDNode *N, SDValue OpV,
8880 unsigned Op,
8881 SelectionDAG &DAG) {
8882 EVT VTy = OpV->getOperand(0).getValueType();
8883 if (!VTy.isVector())
Chad Rosier6c36eff2015-09-03 18:13:57 +00008884 return SDValue();
8885
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008886 int NumVecElts = VTy.getVectorNumElements();
Jun Bum Lim0aace132015-10-09 14:11:25 +00008887 if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) {
8888 if (NumVecElts != 4)
8889 return SDValue();
8890 } else {
8891 if (NumVecElts != 4 && NumVecElts != 8 && NumVecElts != 16)
8892 return SDValue();
8893 }
Chad Rosier6c36eff2015-09-03 18:13:57 +00008894
8895 int NumExpectedSteps = APInt(8, NumVecElts).logBase2();
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008896 SDValue PreOp = OpV;
Chad Rosier6c36eff2015-09-03 18:13:57 +00008897 // Iterate over each step of the across vector reduction.
8898 for (int CurStep = 0; CurStep != NumExpectedSteps; ++CurStep) {
Chad Rosier6c36eff2015-09-03 18:13:57 +00008899 SDValue CurOp = PreOp.getOperand(0);
8900 SDValue Shuffle = PreOp.getOperand(1);
8901 if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE) {
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008902 // Try to swap the 1st and 2nd operand as add and min/max instructions
8903 // are commutative.
Chad Rosier6c36eff2015-09-03 18:13:57 +00008904 CurOp = PreOp.getOperand(1);
8905 Shuffle = PreOp.getOperand(0);
8906 if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE)
8907 return SDValue();
8908 }
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008909
8910 // Check if the input vector is fed by the operator we want to handle,
8911 // except the last step; the very first input vector is not necessarily
8912 // the same operator we are handling.
8913 if (CurOp.getOpcode() != Op && (CurStep != (NumExpectedSteps - 1)))
8914 return SDValue();
8915
Chad Rosier6c36eff2015-09-03 18:13:57 +00008916 // Check if it forms one step of the across vector reduction.
8917 // E.g.,
8918 // %cur = add %1, %0
8919 // %shuffle = vector_shuffle %cur, <2, 3, u, u>
8920 // %pre = add %cur, %shuffle
8921 if (Shuffle.getOperand(0) != CurOp)
8922 return SDValue();
8923
8924 int NumMaskElts = 1 << CurStep;
8925 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Shuffle)->getMask();
8926 // Check mask values in each step.
8927 // We expect the shuffle mask in each step follows a specific pattern
8928 // denoted here by the <M, U> form, where M is a sequence of integers
8929 // starting from NumMaskElts, increasing by 1, and the number integers
8930 // in M should be NumMaskElts. U is a sequence of UNDEFs and the number
8931 // of undef in U should be NumVecElts - NumMaskElts.
8932 // E.g., for <8 x i16>, mask values in each step should be :
8933 // step 0 : <1,u,u,u,u,u,u,u>
8934 // step 1 : <2,3,u,u,u,u,u,u>
8935 // step 2 : <4,5,6,7,u,u,u,u>
8936 for (int i = 0; i < NumVecElts; ++i)
8937 if ((i < NumMaskElts && Mask[i] != (NumMaskElts + i)) ||
8938 (i >= NumMaskElts && !(Mask[i] < 0)))
8939 return SDValue();
8940
8941 PreOp = CurOp;
8942 }
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008943 unsigned Opcode;
Jun Bum Lim0aace132015-10-09 14:11:25 +00008944 bool IsIntrinsic = false;
8945
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008946 switch (Op) {
8947 default:
8948 llvm_unreachable("Unexpected operator for across vector reduction");
8949 case ISD::ADD:
8950 Opcode = AArch64ISD::UADDV;
8951 break;
8952 case ISD::SMAX:
8953 Opcode = AArch64ISD::SMAXV;
8954 break;
8955 case ISD::UMAX:
8956 Opcode = AArch64ISD::UMAXV;
8957 break;
8958 case ISD::SMIN:
8959 Opcode = AArch64ISD::SMINV;
8960 break;
8961 case ISD::UMIN:
8962 Opcode = AArch64ISD::UMINV;
8963 break;
Jun Bum Lim0aace132015-10-09 14:11:25 +00008964 case ISD::FMAXNUM:
8965 Opcode = Intrinsic::aarch64_neon_fmaxnmv;
8966 IsIntrinsic = true;
8967 break;
8968 case ISD::FMINNUM:
8969 Opcode = Intrinsic::aarch64_neon_fminnmv;
8970 IsIntrinsic = true;
8971 break;
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008972 }
Chad Rosier6c36eff2015-09-03 18:13:57 +00008973 SDLoc DL(N);
Jun Bum Lim0aace132015-10-09 14:11:25 +00008974
8975 return IsIntrinsic
8976 ? DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, N->getValueType(0),
8977 DAG.getConstant(Opcode, DL, MVT::i32), PreOp)
8978 : DAG.getNode(
8979 ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0),
8980 DAG.getNode(Opcode, DL, PreOp.getSimpleValueType(), PreOp),
8981 DAG.getConstant(0, DL, MVT::i64));
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00008982}
8983
8984/// Target-specific DAG combine for the across vector min/max reductions.
8985/// This function specifically handles the final clean-up step of the vector
8986/// min/max reductions produced by the LoopVectorizer. It is the log2-shuffle
8987/// pattern, which narrows down and finds the final min/max value from all
8988/// elements of the vector.
8989/// For example, for a <16 x i8> vector :
8990/// svn0 = vector_shuffle %0, undef<8,9,10,11,12,13,14,15,u,u,u,u,u,u,u,u>
8991/// %smax0 = smax %arr, svn0
8992/// %svn1 = vector_shuffle %smax0, undef<4,5,6,7,u,u,u,u,u,u,u,u,u,u,u,u>
8993/// %smax1 = smax %smax0, %svn1
8994/// %svn2 = vector_shuffle %smax1, undef<2,3,u,u,u,u,u,u,u,u,u,u,u,u,u,u>
8995/// %smax2 = smax %smax1, svn2
8996/// %svn3 = vector_shuffle %smax2, undef<1,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u>
8997/// %sc = setcc %smax2, %svn3, gt
8998/// %n0 = extract_vector_elt %sc, #0
8999/// %n1 = extract_vector_elt %smax2, #0
9000/// %n2 = extract_vector_elt $smax2, #1
9001/// %result = select %n0, %n1, n2
9002/// becomes :
9003/// %1 = smaxv %0
9004/// %result = extract_vector_elt %1, 0
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009005static SDValue
9006performAcrossLaneMinMaxReductionCombine(SDNode *N, SelectionDAG &DAG,
9007 const AArch64Subtarget *Subtarget) {
9008 if (!Subtarget->hasNEON())
9009 return SDValue();
9010
9011 SDValue N0 = N->getOperand(0);
9012 SDValue IfTrue = N->getOperand(1);
9013 SDValue IfFalse = N->getOperand(2);
9014
9015 // Check if the SELECT merges up the final result of the min/max
9016 // from a vector.
9017 if (N0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9018 IfTrue.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9019 IfFalse.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9020 return SDValue();
9021
9022 // Expect N0 is fed by SETCC.
9023 SDValue SetCC = N0.getOperand(0);
9024 EVT SetCCVT = SetCC.getValueType();
9025 if (SetCC.getOpcode() != ISD::SETCC || !SetCCVT.isVector() ||
9026 SetCCVT.getVectorElementType() != MVT::i1)
9027 return SDValue();
9028
9029 SDValue VectorOp = SetCC.getOperand(0);
9030 unsigned Op = VectorOp->getOpcode();
9031 // Check if the input vector is fed by the operator we want to handle.
Jun Bum Lim0aace132015-10-09 14:11:25 +00009032 if (Op != ISD::SMAX && Op != ISD::UMAX && Op != ISD::SMIN &&
9033 Op != ISD::UMIN && Op != ISD::FMAXNUM && Op != ISD::FMINNUM)
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009034 return SDValue();
9035
9036 EVT VTy = VectorOp.getValueType();
9037 if (!VTy.isVector())
9038 return SDValue();
9039
Jun Bum Lim0aace132015-10-09 14:11:25 +00009040 if (VTy.getSizeInBits() < 64)
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009041 return SDValue();
9042
Jun Bum Lim0aace132015-10-09 14:11:25 +00009043 EVT EltTy = VTy.getVectorElementType();
9044 if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) {
9045 if (EltTy != MVT::f32)
9046 return SDValue();
9047 } else {
9048 if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8)
9049 return SDValue();
9050 }
9051
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009052 // Check if extracting from the same vector.
9053 // For example,
9054 // %sc = setcc %vector, %svn1, gt
9055 // %n0 = extract_vector_elt %sc, #0
9056 // %n1 = extract_vector_elt %vector, #0
9057 // %n2 = extract_vector_elt $vector, #1
9058 if (!(VectorOp == IfTrue->getOperand(0) &&
9059 VectorOp == IfFalse->getOperand(0)))
9060 return SDValue();
9061
9062 // Check if the condition code is matched with the operator type.
9063 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get();
9064 if ((Op == ISD::SMAX && CC != ISD::SETGT && CC != ISD::SETGE) ||
9065 (Op == ISD::UMAX && CC != ISD::SETUGT && CC != ISD::SETUGE) ||
9066 (Op == ISD::SMIN && CC != ISD::SETLT && CC != ISD::SETLE) ||
Jun Bum Lim0aace132015-10-09 14:11:25 +00009067 (Op == ISD::UMIN && CC != ISD::SETULT && CC != ISD::SETULE) ||
9068 (Op == ISD::FMAXNUM && CC != ISD::SETOGT && CC != ISD::SETOGE &&
9069 CC != ISD::SETUGT && CC != ISD::SETUGE && CC != ISD::SETGT &&
9070 CC != ISD::SETGE) ||
9071 (Op == ISD::FMINNUM && CC != ISD::SETOLT && CC != ISD::SETOLE &&
9072 CC != ISD::SETULT && CC != ISD::SETULE && CC != ISD::SETLT &&
9073 CC != ISD::SETLE))
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009074 return SDValue();
9075
9076 // Expect to check only lane 0 from the vector SETCC.
Artyom Skrobov314ee042015-11-25 19:41:11 +00009077 if (!isNullConstant(N0.getOperand(1)))
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009078 return SDValue();
9079
9080 // Expect to extract the true value from lane 0.
Artyom Skrobov314ee042015-11-25 19:41:11 +00009081 if (!isNullConstant(IfTrue.getOperand(1)))
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009082 return SDValue();
9083
9084 // Expect to extract the false value from lane 1.
Artyom Skrobov314ee042015-11-25 19:41:11 +00009085 if (!isOneConstant(IfFalse.getOperand(1)))
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009086 return SDValue();
9087
9088 return tryMatchAcrossLaneShuffleForReduction(N, SetCC, Op, DAG);
9089}
9090
9091/// Target-specific DAG combine for the across vector add reduction.
9092/// This function specifically handles the final clean-up step of the vector
9093/// add reduction produced by the LoopVectorizer. It is the log2-shuffle
9094/// pattern, which adds all elements of a vector together.
9095/// For example, for a <4 x i32> vector :
9096/// %1 = vector_shuffle %0, <2,3,u,u>
9097/// %2 = add %0, %1
9098/// %3 = vector_shuffle %2, <1,u,u,u>
9099/// %4 = add %2, %3
9100/// %result = extract_vector_elt %4, 0
9101/// becomes :
9102/// %0 = uaddv %0
9103/// %result = extract_vector_elt %0, 0
9104static SDValue
9105performAcrossLaneAddReductionCombine(SDNode *N, SelectionDAG &DAG,
9106 const AArch64Subtarget *Subtarget) {
9107 if (!Subtarget->hasNEON())
9108 return SDValue();
9109 SDValue N0 = N->getOperand(0);
9110 SDValue N1 = N->getOperand(1);
9111
9112 // Check if the input vector is fed by the ADD.
9113 if (N0->getOpcode() != ISD::ADD)
9114 return SDValue();
9115
9116 // The vector extract idx must constant zero because we only expect the final
9117 // result of the reduction is placed in lane 0.
Artyom Skrobov314ee042015-11-25 19:41:11 +00009118 if (!isNullConstant(N1))
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009119 return SDValue();
9120
9121 EVT VTy = N0.getValueType();
9122 if (!VTy.isVector())
9123 return SDValue();
9124
9125 EVT EltTy = VTy.getVectorElementType();
9126 if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8)
9127 return SDValue();
9128
Jun Bum Lim0aace132015-10-09 14:11:25 +00009129 if (VTy.getSizeInBits() < 64)
9130 return SDValue();
9131
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009132 return tryMatchAcrossLaneShuffleForReduction(N, N0, ISD::ADD, DAG);
Chad Rosier6c36eff2015-09-03 18:13:57 +00009133}
9134
Tim Northover3b0846e2014-05-24 12:50:23 +00009135/// Target-specific DAG combine function for NEON load/store intrinsics
9136/// to merge base address updates.
9137static SDValue performNEONPostLDSTCombine(SDNode *N,
9138 TargetLowering::DAGCombinerInfo &DCI,
9139 SelectionDAG &DAG) {
9140 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9141 return SDValue();
9142
9143 unsigned AddrOpIdx = N->getNumOperands() - 1;
9144 SDValue Addr = N->getOperand(AddrOpIdx);
9145
9146 // Search for a use of the address operand that is an increment.
9147 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9148 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9149 SDNode *User = *UI;
9150 if (User->getOpcode() != ISD::ADD ||
9151 UI.getUse().getResNo() != Addr.getResNo())
9152 continue;
9153
9154 // Check that the add is independent of the load/store. Otherwise, folding
9155 // it would create a cycle.
9156 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9157 continue;
9158
9159 // Find the new opcode for the updating load/store.
9160 bool IsStore = false;
9161 bool IsLaneOp = false;
9162 bool IsDupOp = false;
9163 unsigned NewOpc = 0;
9164 unsigned NumVecs = 0;
9165 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9166 switch (IntNo) {
9167 default: llvm_unreachable("unexpected intrinsic for Neon base update");
9168 case Intrinsic::aarch64_neon_ld2: NewOpc = AArch64ISD::LD2post;
9169 NumVecs = 2; break;
9170 case Intrinsic::aarch64_neon_ld3: NewOpc = AArch64ISD::LD3post;
9171 NumVecs = 3; break;
9172 case Intrinsic::aarch64_neon_ld4: NewOpc = AArch64ISD::LD4post;
9173 NumVecs = 4; break;
9174 case Intrinsic::aarch64_neon_st2: NewOpc = AArch64ISD::ST2post;
9175 NumVecs = 2; IsStore = true; break;
9176 case Intrinsic::aarch64_neon_st3: NewOpc = AArch64ISD::ST3post;
9177 NumVecs = 3; IsStore = true; break;
9178 case Intrinsic::aarch64_neon_st4: NewOpc = AArch64ISD::ST4post;
9179 NumVecs = 4; IsStore = true; break;
9180 case Intrinsic::aarch64_neon_ld1x2: NewOpc = AArch64ISD::LD1x2post;
9181 NumVecs = 2; break;
9182 case Intrinsic::aarch64_neon_ld1x3: NewOpc = AArch64ISD::LD1x3post;
9183 NumVecs = 3; break;
9184 case Intrinsic::aarch64_neon_ld1x4: NewOpc = AArch64ISD::LD1x4post;
9185 NumVecs = 4; break;
9186 case Intrinsic::aarch64_neon_st1x2: NewOpc = AArch64ISD::ST1x2post;
9187 NumVecs = 2; IsStore = true; break;
9188 case Intrinsic::aarch64_neon_st1x3: NewOpc = AArch64ISD::ST1x3post;
9189 NumVecs = 3; IsStore = true; break;
9190 case Intrinsic::aarch64_neon_st1x4: NewOpc = AArch64ISD::ST1x4post;
9191 NumVecs = 4; IsStore = true; break;
9192 case Intrinsic::aarch64_neon_ld2r: NewOpc = AArch64ISD::LD2DUPpost;
9193 NumVecs = 2; IsDupOp = true; break;
9194 case Intrinsic::aarch64_neon_ld3r: NewOpc = AArch64ISD::LD3DUPpost;
9195 NumVecs = 3; IsDupOp = true; break;
9196 case Intrinsic::aarch64_neon_ld4r: NewOpc = AArch64ISD::LD4DUPpost;
9197 NumVecs = 4; IsDupOp = true; break;
9198 case Intrinsic::aarch64_neon_ld2lane: NewOpc = AArch64ISD::LD2LANEpost;
9199 NumVecs = 2; IsLaneOp = true; break;
9200 case Intrinsic::aarch64_neon_ld3lane: NewOpc = AArch64ISD::LD3LANEpost;
9201 NumVecs = 3; IsLaneOp = true; break;
9202 case Intrinsic::aarch64_neon_ld4lane: NewOpc = AArch64ISD::LD4LANEpost;
9203 NumVecs = 4; IsLaneOp = true; break;
9204 case Intrinsic::aarch64_neon_st2lane: NewOpc = AArch64ISD::ST2LANEpost;
9205 NumVecs = 2; IsStore = true; IsLaneOp = true; break;
9206 case Intrinsic::aarch64_neon_st3lane: NewOpc = AArch64ISD::ST3LANEpost;
9207 NumVecs = 3; IsStore = true; IsLaneOp = true; break;
9208 case Intrinsic::aarch64_neon_st4lane: NewOpc = AArch64ISD::ST4LANEpost;
9209 NumVecs = 4; IsStore = true; IsLaneOp = true; break;
9210 }
9211
9212 EVT VecTy;
9213 if (IsStore)
9214 VecTy = N->getOperand(2).getValueType();
9215 else
9216 VecTy = N->getValueType(0);
9217
9218 // If the increment is a constant, it must match the memory ref size.
9219 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9220 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9221 uint32_t IncVal = CInc->getZExtValue();
9222 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9223 if (IsLaneOp || IsDupOp)
9224 NumBytes /= VecTy.getVectorNumElements();
9225 if (IncVal != NumBytes)
9226 continue;
9227 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
9228 }
9229 SmallVector<SDValue, 8> Ops;
9230 Ops.push_back(N->getOperand(0)); // Incoming chain
9231 // Load lane and store have vector list as input.
9232 if (IsLaneOp || IsStore)
9233 for (unsigned i = 2; i < AddrOpIdx; ++i)
9234 Ops.push_back(N->getOperand(i));
9235 Ops.push_back(Addr); // Base register
9236 Ops.push_back(Inc);
9237
9238 // Return Types.
9239 EVT Tys[6];
9240 unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
9241 unsigned n;
9242 for (n = 0; n < NumResultVecs; ++n)
9243 Tys[n] = VecTy;
9244 Tys[n++] = MVT::i64; // Type of write back register
9245 Tys[n] = MVT::Other; // Type of the chain
Craig Toppere1d12942014-08-27 05:25:25 +00009246 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
Tim Northover3b0846e2014-05-24 12:50:23 +00009247
9248 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9249 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
9250 MemInt->getMemoryVT(),
9251 MemInt->getMemOperand());
9252
9253 // Update the uses.
9254 std::vector<SDValue> NewResults;
9255 for (unsigned i = 0; i < NumResultVecs; ++i) {
9256 NewResults.push_back(SDValue(UpdN.getNode(), i));
9257 }
9258 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
9259 DCI.CombineTo(N, NewResults);
9260 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9261
9262 break;
9263 }
9264 return SDValue();
9265}
9266
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009267// Checks to see if the value is the prescribed width and returns information
9268// about its extension mode.
9269static
9270bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
9271 ExtType = ISD::NON_EXTLOAD;
9272 switch(V.getNode()->getOpcode()) {
9273 default:
9274 return false;
9275 case ISD::LOAD: {
9276 LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
9277 if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
9278 || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
9279 ExtType = LoadNode->getExtensionType();
9280 return true;
9281 }
9282 return false;
9283 }
9284 case ISD::AssertSext: {
9285 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9286 if ((TypeNode->getVT() == MVT::i8 && width == 8)
9287 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9288 ExtType = ISD::SEXTLOAD;
9289 return true;
9290 }
9291 return false;
9292 }
9293 case ISD::AssertZext: {
9294 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9295 if ((TypeNode->getVT() == MVT::i8 && width == 8)
9296 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9297 ExtType = ISD::ZEXTLOAD;
9298 return true;
9299 }
9300 return false;
9301 }
9302 case ISD::Constant:
9303 case ISD::TargetConstant: {
Eric Christopher114fa1c2016-02-29 22:50:49 +00009304 return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
9305 1LL << (width - 1);
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009306 }
9307 }
9308
9309 return true;
9310}
9311
9312// This function does a whole lot of voodoo to determine if the tests are
9313// equivalent without and with a mask. Essentially what happens is that given a
9314// DAG resembling:
9315//
9316// +-------------+ +-------------+ +-------------+ +-------------+
9317// | Input | | AddConstant | | CompConstant| | CC |
9318// +-------------+ +-------------+ +-------------+ +-------------+
9319// | | | |
9320// V V | +----------+
9321// +-------------+ +----+ | |
9322// | ADD | |0xff| | |
9323// +-------------+ +----+ | |
9324// | | | |
9325// V V | |
9326// +-------------+ | |
9327// | AND | | |
9328// +-------------+ | |
9329// | | |
9330// +-----+ | |
9331// | | |
9332// V V V
9333// +-------------+
9334// | CMP |
9335// +-------------+
9336//
9337// The AND node may be safely removed for some combinations of inputs. In
9338// particular we need to take into account the extension type of the Input,
9339// the exact values of AddConstant, CompConstant, and CC, along with the nominal
9340// width of the input (this can work for any width inputs, the above graph is
9341// specific to 8 bits.
9342//
9343// The specific equations were worked out by generating output tables for each
9344// AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
9345// problem was simplified by working with 4 bit inputs, which means we only
9346// needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
9347// extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
9348// patterns present in both extensions (0,7). For every distinct set of
9349// AddConstant and CompConstants bit patterns we can consider the masked and
9350// unmasked versions to be equivalent if the result of this function is true for
9351// all 16 distinct bit patterns of for the current extension type of Input (w0).
9352//
9353// sub w8, w0, w1
9354// and w10, w8, #0x0f
9355// cmp w8, w2
9356// cset w9, AArch64CC
9357// cmp w10, w2
9358// cset w11, AArch64CC
9359// cmp w9, w11
9360// cset w0, eq
9361// ret
9362//
9363// Since the above function shows when the outputs are equivalent it defines
9364// when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
9365// would be expensive to run during compiles. The equations below were written
9366// in a test harness that confirmed they gave equivalent outputs to the above
9367// for all inputs function, so they can be used determine if the removal is
9368// legal instead.
9369//
9370// isEquivalentMaskless() is the code for testing if the AND can be removed
9371// factored out of the DAG recognition as the DAG can take several forms.
9372
9373static
9374bool isEquivalentMaskless(unsigned CC, unsigned width,
9375 ISD::LoadExtType ExtType, signed AddConstant,
9376 signed CompConstant) {
9377 // By being careful about our equations and only writing the in term
9378 // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
9379 // make them generally applicable to all bit widths.
9380 signed MaxUInt = (1 << width);
9381
9382 // For the purposes of these comparisons sign extending the type is
9383 // equivalent to zero extending the add and displacing it by half the integer
9384 // width. Provided we are careful and make sure our equations are valid over
9385 // the whole range we can just adjust the input and avoid writing equations
9386 // for sign extended inputs.
9387 if (ExtType == ISD::SEXTLOAD)
9388 AddConstant -= (1 << (width-1));
9389
9390 switch(CC) {
9391 case AArch64CC::LE:
9392 case AArch64CC::GT: {
9393 if ((AddConstant == 0) ||
9394 (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
9395 (AddConstant >= 0 && CompConstant < 0) ||
9396 (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
9397 return true;
9398 } break;
9399 case AArch64CC::LT:
9400 case AArch64CC::GE: {
9401 if ((AddConstant == 0) ||
9402 (AddConstant >= 0 && CompConstant <= 0) ||
9403 (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
9404 return true;
9405 } break;
9406 case AArch64CC::HI:
9407 case AArch64CC::LS: {
9408 if ((AddConstant >= 0 && CompConstant < 0) ||
9409 (AddConstant <= 0 && CompConstant >= -1 &&
9410 CompConstant < AddConstant + MaxUInt))
9411 return true;
9412 } break;
9413 case AArch64CC::PL:
9414 case AArch64CC::MI: {
9415 if ((AddConstant == 0) ||
9416 (AddConstant > 0 && CompConstant <= 0) ||
9417 (AddConstant < 0 && CompConstant <= AddConstant))
9418 return true;
9419 } break;
9420 case AArch64CC::LO:
9421 case AArch64CC::HS: {
9422 if ((AddConstant >= 0 && CompConstant <= 0) ||
9423 (AddConstant <= 0 && CompConstant >= 0 &&
9424 CompConstant <= AddConstant + MaxUInt))
9425 return true;
9426 } break;
9427 case AArch64CC::EQ:
9428 case AArch64CC::NE: {
9429 if ((AddConstant > 0 && CompConstant < 0) ||
9430 (AddConstant < 0 && CompConstant >= 0 &&
9431 CompConstant < AddConstant + MaxUInt) ||
9432 (AddConstant >= 0 && CompConstant >= 0 &&
9433 CompConstant >= AddConstant) ||
9434 (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
9435
9436 return true;
9437 } break;
9438 case AArch64CC::VS:
9439 case AArch64CC::VC:
9440 case AArch64CC::AL:
9441 case AArch64CC::NV:
9442 return true;
9443 case AArch64CC::Invalid:
9444 break;
9445 }
9446
9447 return false;
9448}
9449
9450static
9451SDValue performCONDCombine(SDNode *N,
9452 TargetLowering::DAGCombinerInfo &DCI,
9453 SelectionDAG &DAG, unsigned CCIndex,
9454 unsigned CmpIndex) {
9455 unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
9456 SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
9457 unsigned CondOpcode = SubsNode->getOpcode();
9458
9459 if (CondOpcode != AArch64ISD::SUBS)
9460 return SDValue();
9461
9462 // There is a SUBS feeding this condition. Is it fed by a mask we can
9463 // use?
9464
9465 SDNode *AndNode = SubsNode->getOperand(0).getNode();
9466 unsigned MaskBits = 0;
9467
9468 if (AndNode->getOpcode() != ISD::AND)
9469 return SDValue();
9470
9471 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
9472 uint32_t CNV = CN->getZExtValue();
9473 if (CNV == 255)
9474 MaskBits = 8;
9475 else if (CNV == 65535)
9476 MaskBits = 16;
9477 }
9478
9479 if (!MaskBits)
9480 return SDValue();
9481
9482 SDValue AddValue = AndNode->getOperand(0);
9483
9484 if (AddValue.getOpcode() != ISD::ADD)
9485 return SDValue();
9486
9487 // The basic dag structure is correct, grab the inputs and validate them.
9488
9489 SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
9490 SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
9491 SDValue SubsInputValue = SubsNode->getOperand(1);
9492
9493 // The mask is present and the provenance of all the values is a smaller type,
9494 // lets see if the mask is superfluous.
9495
9496 if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
9497 !isa<ConstantSDNode>(SubsInputValue.getNode()))
9498 return SDValue();
9499
9500 ISD::LoadExtType ExtType;
9501
9502 if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
9503 !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
9504 !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
9505 return SDValue();
9506
9507 if(!isEquivalentMaskless(CC, MaskBits, ExtType,
9508 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
9509 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
9510 return SDValue();
9511
9512 // The AND is not necessary, remove it.
9513
9514 SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
9515 SubsNode->getValueType(1));
9516 SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
9517
9518 SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
9519 DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
9520
9521 return SDValue(N, 0);
9522}
9523
Tim Northover3b0846e2014-05-24 12:50:23 +00009524// Optimize compare with zero and branch.
9525static SDValue performBRCONDCombine(SDNode *N,
9526 TargetLowering::DAGCombinerInfo &DCI,
9527 SelectionDAG &DAG) {
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00009528 if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3))
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009529 N = NV.getNode();
Tim Northover3b0846e2014-05-24 12:50:23 +00009530 SDValue Chain = N->getOperand(0);
9531 SDValue Dest = N->getOperand(1);
9532 SDValue CCVal = N->getOperand(2);
9533 SDValue Cmp = N->getOperand(3);
9534
9535 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
9536 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
9537 if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
9538 return SDValue();
9539
9540 unsigned CmpOpc = Cmp.getOpcode();
9541 if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
9542 return SDValue();
9543
9544 // Only attempt folding if there is only one use of the flag and no use of the
9545 // value.
9546 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
9547 return SDValue();
9548
9549 SDValue LHS = Cmp.getOperand(0);
9550 SDValue RHS = Cmp.getOperand(1);
9551
9552 assert(LHS.getValueType() == RHS.getValueType() &&
9553 "Expected the value type to be the same for both operands!");
9554 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
9555 return SDValue();
9556
Artyom Skrobov314ee042015-11-25 19:41:11 +00009557 if (isNullConstant(LHS))
Tim Northover3b0846e2014-05-24 12:50:23 +00009558 std::swap(LHS, RHS);
9559
Artyom Skrobov314ee042015-11-25 19:41:11 +00009560 if (!isNullConstant(RHS))
Tim Northover3b0846e2014-05-24 12:50:23 +00009561 return SDValue();
9562
9563 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
9564 LHS.getOpcode() == ISD::SRL)
9565 return SDValue();
9566
9567 // Fold the compare into the branch instruction.
9568 SDValue BR;
9569 if (CC == AArch64CC::EQ)
9570 BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9571 else
9572 BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
9573
9574 // Do not add new nodes to DAG combiner worklist.
9575 DCI.CombineTo(N, BR, false);
9576
9577 return SDValue();
9578}
9579
Geoff Berry9e934b02016-01-04 18:55:47 +00009580// Optimize some simple tbz/tbnz cases. Returns the new operand and bit to test
9581// as well as whether the test should be inverted. This code is required to
9582// catch these cases (as opposed to standard dag combines) because
9583// AArch64ISD::TBZ is matched during legalization.
9584static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert,
9585 SelectionDAG &DAG) {
9586
9587 if (!Op->hasOneUse())
9588 return Op;
9589
9590 // We don't handle undef/constant-fold cases below, as they should have
9591 // already been taken care of (e.g. and of 0, test of undefined shifted bits,
9592 // etc.)
9593
9594 // (tbz (trunc x), b) -> (tbz x, b)
9595 // This case is just here to enable more of the below cases to be caught.
9596 if (Op->getOpcode() == ISD::TRUNCATE &&
9597 Bit < Op->getValueType(0).getSizeInBits()) {
9598 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9599 }
9600
9601 if (Op->getNumOperands() != 2)
9602 return Op;
9603
9604 auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
9605 if (!C)
9606 return Op;
9607
9608 switch (Op->getOpcode()) {
9609 default:
9610 return Op;
9611
9612 // (tbz (and x, m), b) -> (tbz x, b)
9613 case ISD::AND:
9614 if ((C->getZExtValue() >> Bit) & 1)
9615 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9616 return Op;
9617
9618 // (tbz (shl x, c), b) -> (tbz x, b-c)
9619 case ISD::SHL:
9620 if (C->getZExtValue() <= Bit &&
9621 (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
9622 Bit = Bit - C->getZExtValue();
9623 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9624 }
9625 return Op;
9626
9627 // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
9628 case ISD::SRA:
9629 Bit = Bit + C->getZExtValue();
9630 if (Bit >= Op->getValueType(0).getSizeInBits())
9631 Bit = Op->getValueType(0).getSizeInBits() - 1;
9632 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9633
9634 // (tbz (srl x, c), b) -> (tbz x, b+c)
9635 case ISD::SRL:
9636 if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
9637 Bit = Bit + C->getZExtValue();
9638 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9639 }
9640 return Op;
9641
9642 // (tbz (xor x, -1), b) -> (tbnz x, b)
9643 case ISD::XOR:
9644 if ((C->getZExtValue() >> Bit) & 1)
9645 Invert = !Invert;
9646 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
9647 }
9648}
9649
9650// Optimize test single bit zero/non-zero and branch.
9651static SDValue performTBZCombine(SDNode *N,
9652 TargetLowering::DAGCombinerInfo &DCI,
9653 SelectionDAG &DAG) {
9654 unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
9655 bool Invert = false;
9656 SDValue TestSrc = N->getOperand(1);
9657 SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG);
9658
9659 if (TestSrc == NewTestSrc)
9660 return SDValue();
9661
9662 unsigned NewOpc = N->getOpcode();
9663 if (Invert) {
9664 if (NewOpc == AArch64ISD::TBZ)
9665 NewOpc = AArch64ISD::TBNZ;
9666 else {
9667 assert(NewOpc == AArch64ISD::TBNZ);
9668 NewOpc = AArch64ISD::TBZ;
9669 }
9670 }
9671
9672 SDLoc DL(N);
9673 return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc,
9674 DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3));
9675}
9676
Tim Northover3b0846e2014-05-24 12:50:23 +00009677// vselect (v1i1 setcc) ->
9678// vselect (v1iXX setcc) (XX is the size of the compared operand type)
9679// FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
9680// condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
9681// such VSELECT.
9682static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
9683 SDValue N0 = N->getOperand(0);
9684 EVT CCVT = N0.getValueType();
9685
9686 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
9687 CCVT.getVectorElementType() != MVT::i1)
9688 return SDValue();
9689
9690 EVT ResVT = N->getValueType(0);
9691 EVT CmpVT = N0.getOperand(0).getValueType();
9692 // Only combine when the result type is of the same size as the compared
9693 // operands.
9694 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
9695 return SDValue();
9696
9697 SDValue IfTrue = N->getOperand(1);
9698 SDValue IfFalse = N->getOperand(2);
9699 SDValue SetCC =
9700 DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
9701 N0.getOperand(0), N0.getOperand(1),
9702 cast<CondCodeSDNode>(N0.getOperand(2))->get());
9703 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
9704 IfTrue, IfFalse);
9705}
9706
9707/// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
9708/// the compare-mask instructions rather than going via NZCV, even if LHS and
9709/// RHS are really scalar. This replaces any scalar setcc in the above pattern
9710/// with a vector one followed by a DUP shuffle on the result.
Ahmed Bougachac004c602015-04-27 21:43:12 +00009711static SDValue performSelectCombine(SDNode *N,
9712 TargetLowering::DAGCombinerInfo &DCI) {
9713 SelectionDAG &DAG = DCI.DAG;
Tim Northover3b0846e2014-05-24 12:50:23 +00009714 SDValue N0 = N->getOperand(0);
9715 EVT ResVT = N->getValueType(0);
Tim Northover3c0915e2014-08-29 15:34:58 +00009716
Ahmed Bougachac004c602015-04-27 21:43:12 +00009717 if (N0.getOpcode() != ISD::SETCC)
Tim Northover3c0915e2014-08-29 15:34:58 +00009718 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00009719
Ahmed Bougachac004c602015-04-27 21:43:12 +00009720 // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
9721 // scalar SetCCResultType. We also don't expect vectors, because we assume
9722 // that selects fed by vector SETCCs are canonicalized to VSELECT.
9723 assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
9724 "Scalar-SETCC feeding SELECT has unexpected result type!");
9725
Tim Northoverc1c05ae2014-08-29 13:05:18 +00009726 // If NumMaskElts == 0, the comparison is larger than select result. The
9727 // largest real NEON comparison is 64-bits per lane, which means the result is
9728 // at most 32-bits and an illegal vector. Just bail out for now.
Tim Northover3c0915e2014-08-29 15:34:58 +00009729 EVT SrcVT = N0.getOperand(0).getValueType();
Ahmed Bougachad0ce0582014-12-01 20:59:00 +00009730
9731 // Don't try to do this optimization when the setcc itself has i1 operands.
9732 // There are no legal vectors of i1, so this would be pointless.
9733 if (SrcVT == MVT::i1)
9734 return SDValue();
9735
Tim Northover3c0915e2014-08-29 15:34:58 +00009736 int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
Tim Northoverc1c05ae2014-08-29 13:05:18 +00009737 if (!ResVT.isVector() || NumMaskElts == 0)
Tim Northover3b0846e2014-05-24 12:50:23 +00009738 return SDValue();
9739
Tim Northoverc1c05ae2014-08-29 13:05:18 +00009740 SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
Tim Northover3b0846e2014-05-24 12:50:23 +00009741 EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
9742
Ahmed Bougacha89bba612015-04-27 21:01:20 +00009743 // Also bail out if the vector CCVT isn't the same size as ResVT.
9744 // This can happen if the SETCC operand size doesn't divide the ResVT size
9745 // (e.g., f64 vs v3f32).
9746 if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
9747 return SDValue();
9748
Ahmed Bougachac004c602015-04-27 21:43:12 +00009749 // Make sure we didn't create illegal types, if we're not supposed to.
9750 assert(DCI.isBeforeLegalize() ||
9751 DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
9752
Tim Northover3b0846e2014-05-24 12:50:23 +00009753 // First perform a vector comparison, where lane 0 is the one we're interested
9754 // in.
Tim Northoverc1c05ae2014-08-29 13:05:18 +00009755 SDLoc DL(N0);
Tim Northover3b0846e2014-05-24 12:50:23 +00009756 SDValue LHS =
9757 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
9758 SDValue RHS =
9759 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
9760 SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
9761
9762 // Now duplicate the comparison mask we want across all other lanes.
9763 SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
9764 SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask.data());
Tim Northoverc1c05ae2014-08-29 13:05:18 +00009765 Mask = DAG.getNode(ISD::BITCAST, DL,
9766 ResVT.changeVectorElementTypeToInteger(), Mask);
Tim Northover3b0846e2014-05-24 12:50:23 +00009767
9768 return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
9769}
9770
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009771/// Get rid of unnecessary NVCASTs (that don't change the type).
9772static SDValue performNVCASTCombine(SDNode *N) {
9773 if (N->getValueType(0) == N->getOperand(0).getValueType())
9774 return N->getOperand(0);
9775
9776 return SDValue();
9777}
9778
Tim Northover3b0846e2014-05-24 12:50:23 +00009779SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
9780 DAGCombinerInfo &DCI) const {
9781 SelectionDAG &DAG = DCI.DAG;
9782 switch (N->getOpcode()) {
9783 default:
9784 break;
9785 case ISD::ADD:
9786 case ISD::SUB:
9787 return performAddSubLongCombine(N, DCI, DAG);
9788 case ISD::XOR:
9789 return performXorCombine(N, DAG, DCI, Subtarget);
9790 case ISD::MUL:
9791 return performMulCombine(N, DAG, DCI, Subtarget);
9792 case ISD::SINT_TO_FP:
9793 case ISD::UINT_TO_FP:
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00009794 return performIntToFpCombine(N, DAG, Subtarget);
Chad Rosierfa30c9b2015-10-07 17:39:18 +00009795 case ISD::FP_TO_SINT:
9796 case ISD::FP_TO_UINT:
9797 return performFpToIntCombine(N, DAG, Subtarget);
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00009798 case ISD::FDIV:
9799 return performFDivCombine(N, DAG, Subtarget);
Tim Northover3b0846e2014-05-24 12:50:23 +00009800 case ISD::OR:
9801 return performORCombine(N, DCI, Subtarget);
9802 case ISD::INTRINSIC_WO_CHAIN:
9803 return performIntrinsicCombine(N, DCI, Subtarget);
9804 case ISD::ANY_EXTEND:
9805 case ISD::ZERO_EXTEND:
9806 case ISD::SIGN_EXTEND:
9807 return performExtendCombine(N, DCI, DAG);
9808 case ISD::BITCAST:
9809 return performBitcastCombine(N, DCI, DAG);
9810 case ISD::CONCAT_VECTORS:
9811 return performConcatVectorsCombine(N, DCI, DAG);
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009812 case ISD::SELECT: {
9813 SDValue RV = performSelectCombine(N, DCI);
9814 if (!RV.getNode())
9815 RV = performAcrossLaneMinMaxReductionCombine(N, DAG, Subtarget);
9816 return RV;
9817 }
Tim Northover3b0846e2014-05-24 12:50:23 +00009818 case ISD::VSELECT:
9819 return performVSelectCombine(N, DCI.DAG);
Tim Northover339c83e2015-11-10 00:44:23 +00009820 case ISD::LOAD:
9821 if (performTBISimplification(N->getOperand(1), DCI, DAG))
9822 return SDValue(N, 0);
9823 break;
Tim Northover3b0846e2014-05-24 12:50:23 +00009824 case ISD::STORE:
9825 return performSTORECombine(N, DCI, DAG, Subtarget);
9826 case AArch64ISD::BRCOND:
9827 return performBRCONDCombine(N, DCI, DAG);
Geoff Berry9e934b02016-01-04 18:55:47 +00009828 case AArch64ISD::TBNZ:
9829 case AArch64ISD::TBZ:
9830 return performTBZCombine(N, DCI, DAG);
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009831 case AArch64ISD::CSEL:
9832 return performCONDCombine(N, DCI, DAG, 2, 3);
Tim Northover3b0846e2014-05-24 12:50:23 +00009833 case AArch64ISD::DUP:
9834 return performPostLD1Combine(N, DCI, false);
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00009835 case AArch64ISD::NVCAST:
9836 return performNVCASTCombine(N);
Tim Northover3b0846e2014-05-24 12:50:23 +00009837 case ISD::INSERT_VECTOR_ELT:
9838 return performPostLD1Combine(N, DCI, true);
Chad Rosier6c36eff2015-09-03 18:13:57 +00009839 case ISD::EXTRACT_VECTOR_ELT:
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009840 return performAcrossLaneAddReductionCombine(N, DAG, Subtarget);
Tim Northover3b0846e2014-05-24 12:50:23 +00009841 case ISD::INTRINSIC_VOID:
9842 case ISD::INTRINSIC_W_CHAIN:
9843 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
9844 case Intrinsic::aarch64_neon_ld2:
9845 case Intrinsic::aarch64_neon_ld3:
9846 case Intrinsic::aarch64_neon_ld4:
9847 case Intrinsic::aarch64_neon_ld1x2:
9848 case Intrinsic::aarch64_neon_ld1x3:
9849 case Intrinsic::aarch64_neon_ld1x4:
9850 case Intrinsic::aarch64_neon_ld2lane:
9851 case Intrinsic::aarch64_neon_ld3lane:
9852 case Intrinsic::aarch64_neon_ld4lane:
9853 case Intrinsic::aarch64_neon_ld2r:
9854 case Intrinsic::aarch64_neon_ld3r:
9855 case Intrinsic::aarch64_neon_ld4r:
9856 case Intrinsic::aarch64_neon_st2:
9857 case Intrinsic::aarch64_neon_st3:
9858 case Intrinsic::aarch64_neon_st4:
9859 case Intrinsic::aarch64_neon_st1x2:
9860 case Intrinsic::aarch64_neon_st1x3:
9861 case Intrinsic::aarch64_neon_st1x4:
9862 case Intrinsic::aarch64_neon_st2lane:
9863 case Intrinsic::aarch64_neon_st3lane:
9864 case Intrinsic::aarch64_neon_st4lane:
9865 return performNEONPostLDSTCombine(N, DCI, DAG);
9866 default:
9867 break;
9868 }
9869 }
9870 return SDValue();
9871}
9872
9873// Check if the return value is used as only a return value, as otherwise
9874// we can't perform a tail-call. In particular, we need to check for
9875// target ISD nodes that are returns and any other "odd" constructs
9876// that the generic analysis code won't necessarily catch.
9877bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
9878 SDValue &Chain) const {
9879 if (N->getNumValues() != 1)
9880 return false;
9881 if (!N->hasNUsesOfValue(1, 0))
9882 return false;
9883
9884 SDValue TCChain = Chain;
9885 SDNode *Copy = *N->use_begin();
9886 if (Copy->getOpcode() == ISD::CopyToReg) {
9887 // If the copy has a glue operand, we conservatively assume it isn't safe to
9888 // perform a tail call.
9889 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
9890 MVT::Glue)
9891 return false;
9892 TCChain = Copy->getOperand(0);
9893 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
9894 return false;
9895
9896 bool HasRet = false;
9897 for (SDNode *Node : Copy->uses()) {
9898 if (Node->getOpcode() != AArch64ISD::RET_FLAG)
9899 return false;
9900 HasRet = true;
9901 }
9902
9903 if (!HasRet)
9904 return false;
9905
9906 Chain = TCChain;
9907 return true;
9908}
9909
9910// Return whether the an instruction can potentially be optimized to a tail
9911// call. This will cause the optimizers to attempt to move, or duplicate,
9912// return instructions to help enable tail call optimizations for this
9913// instruction.
9914bool AArch64TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
Eric Christopher114fa1c2016-02-29 22:50:49 +00009915 return CI->isTailCall();
Tim Northover3b0846e2014-05-24 12:50:23 +00009916}
9917
9918bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
9919 SDValue &Offset,
9920 ISD::MemIndexedMode &AM,
9921 bool &IsInc,
9922 SelectionDAG &DAG) const {
9923 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
9924 return false;
9925
9926 Base = Op->getOperand(0);
9927 // All of the indexed addressing mode instructions take a signed
9928 // 9 bit immediate offset.
9929 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
9930 int64_t RHSC = (int64_t)RHS->getZExtValue();
9931 if (RHSC >= 256 || RHSC <= -256)
9932 return false;
9933 IsInc = (Op->getOpcode() == ISD::ADD);
9934 Offset = Op->getOperand(1);
9935 return true;
9936 }
9937 return false;
9938}
9939
9940bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
9941 SDValue &Offset,
9942 ISD::MemIndexedMode &AM,
9943 SelectionDAG &DAG) const {
9944 EVT VT;
9945 SDValue Ptr;
9946 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9947 VT = LD->getMemoryVT();
9948 Ptr = LD->getBasePtr();
9949 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9950 VT = ST->getMemoryVT();
9951 Ptr = ST->getBasePtr();
9952 } else
9953 return false;
9954
9955 bool IsInc;
9956 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
9957 return false;
9958 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
9959 return true;
9960}
9961
9962bool AArch64TargetLowering::getPostIndexedAddressParts(
9963 SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
9964 ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
9965 EVT VT;
9966 SDValue Ptr;
9967 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
9968 VT = LD->getMemoryVT();
9969 Ptr = LD->getBasePtr();
9970 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
9971 VT = ST->getMemoryVT();
9972 Ptr = ST->getBasePtr();
9973 } else
9974 return false;
9975
9976 bool IsInc;
9977 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
9978 return false;
9979 // Post-indexing updates the base, so it's not a valid transform
9980 // if that's not the same as the load's pointer.
9981 if (Ptr != Base)
9982 return false;
9983 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
9984 return true;
9985}
9986
Tim Northoverf8bfe212014-07-18 13:07:05 +00009987static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
9988 SelectionDAG &DAG) {
Tim Northoverf8bfe212014-07-18 13:07:05 +00009989 SDLoc DL(N);
9990 SDValue Op = N->getOperand(0);
Ahmed Bougacha87946322014-12-01 20:52:32 +00009991
9992 if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
9993 return;
9994
Tim Northoverf8bfe212014-07-18 13:07:05 +00009995 Op = SDValue(
9996 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
9997 DAG.getUNDEF(MVT::i32), Op,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009998 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
Tim Northoverf8bfe212014-07-18 13:07:05 +00009999 0);
10000 Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
10001 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
10002}
10003
Charlie Turner434d4592015-10-16 15:38:25 +000010004static void ReplaceReductionResults(SDNode *N,
10005 SmallVectorImpl<SDValue> &Results,
10006 SelectionDAG &DAG, unsigned InterOp,
10007 unsigned AcrossOp) {
10008 EVT LoVT, HiVT;
10009 SDValue Lo, Hi;
10010 SDLoc dl(N);
10011 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
10012 std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
10013 SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
10014 SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
10015 Results.push_back(SplitVal);
10016}
10017
Tim Northover3b0846e2014-05-24 12:50:23 +000010018void AArch64TargetLowering::ReplaceNodeResults(
10019 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
10020 switch (N->getOpcode()) {
10021 default:
10022 llvm_unreachable("Don't know how to custom expand this");
Tim Northoverf8bfe212014-07-18 13:07:05 +000010023 case ISD::BITCAST:
10024 ReplaceBITCASTResults(N, Results, DAG);
10025 return;
Charlie Turner434d4592015-10-16 15:38:25 +000010026 case AArch64ISD::SADDV:
10027 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
10028 return;
10029 case AArch64ISD::UADDV:
10030 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
10031 return;
10032 case AArch64ISD::SMINV:
10033 ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
10034 return;
10035 case AArch64ISD::UMINV:
10036 ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
10037 return;
10038 case AArch64ISD::SMAXV:
10039 ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
10040 return;
10041 case AArch64ISD::UMAXV:
10042 ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
10043 return;
Tim Northover3b0846e2014-05-24 12:50:23 +000010044 case ISD::FP_TO_UINT:
10045 case ISD::FP_TO_SINT:
10046 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
10047 // Let normal code take care of it by not adding anything to Results.
10048 return;
10049 }
10050}
10051
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +000010052bool AArch64TargetLowering::useLoadStackGuardNode() const {
10053 return true;
10054}
10055
Sanjay Patel1dd15592015-07-28 23:05:48 +000010056unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
Hao Liu44e5d7a2014-11-21 06:39:58 +000010057 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
10058 // reciprocal if there are three or more FDIVs.
Sanjay Patel1dd15592015-07-28 23:05:48 +000010059 return 3;
Hao Liu44e5d7a2014-11-21 06:39:58 +000010060}
10061
Chandler Carruth9d010ff2014-07-03 00:23:43 +000010062TargetLoweringBase::LegalizeTypeAction
10063AArch64TargetLowering::getPreferredVectorAction(EVT VT) const {
10064 MVT SVT = VT.getSimpleVT();
10065 // During type legalization, we prefer to widen v1i8, v1i16, v1i32 to v8i8,
10066 // v4i16, v2i32 instead of to promote.
10067 if (SVT == MVT::v1i8 || SVT == MVT::v1i16 || SVT == MVT::v1i32
10068 || SVT == MVT::v1f32)
10069 return TypeWidenVector;
10070
10071 return TargetLoweringBase::getPreferredVectorAction(VT);
10072}
10073
Robin Morisseted3d48f2014-09-03 21:29:59 +000010074// Loads and stores less than 128-bits are already atomic; ones above that
10075// are doomed anyway, so defer to the default libcall and blame the OS when
10076// things go wrong.
10077bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
10078 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
10079 return Size == 128;
10080}
10081
10082// Loads and stores less than 128-bits are already atomic; ones above that
10083// are doomed anyway, so defer to the default libcall and blame the OS when
10084// things go wrong.
Ahmed Bougacha52468672015-09-11 17:08:28 +000010085TargetLowering::AtomicExpansionKind
10086AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
Robin Morisseted3d48f2014-09-03 21:29:59 +000010087 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
Ahmed Bougacha52468672015-09-11 17:08:28 +000010088 return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
Robin Morisseted3d48f2014-09-03 21:29:59 +000010089}
10090
10091// For the real atomic operations, we have ldxr/stxr up to 128 bits,
Ahmed Bougacha52468672015-09-11 17:08:28 +000010092TargetLowering::AtomicExpansionKind
JF Bastienf14889e2015-03-04 15:47:57 +000010093AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
Robin Morisseted3d48f2014-09-03 21:29:59 +000010094 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
Ahmed Bougacha9d677132015-09-11 17:08:17 +000010095 return Size <= 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
Robin Morisseted3d48f2014-09-03 21:29:59 +000010096}
10097
Ahmed Bougacha52468672015-09-11 17:08:28 +000010098bool AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
10099 AtomicCmpXchgInst *AI) const {
Robin Morisset25c8e312014-09-17 00:06:58 +000010100 return true;
10101}
10102
Tim Northover3b0846e2014-05-24 12:50:23 +000010103Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
10104 AtomicOrdering Ord) const {
10105 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10106 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
Robin Morissetb155f522014-08-18 16:48:58 +000010107 bool IsAcquire = isAtLeastAcquire(Ord);
Tim Northover3b0846e2014-05-24 12:50:23 +000010108
10109 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
10110 // intrinsic must return {i64, i64} and we have to recombine them into a
10111 // single i128 here.
10112 if (ValTy->getPrimitiveSizeInBits() == 128) {
10113 Intrinsic::ID Int =
10114 IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
10115 Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int);
10116
10117 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10118 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
10119
10120 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
10121 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
10122 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
10123 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
10124 return Builder.CreateOr(
10125 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
10126 }
10127
10128 Type *Tys[] = { Addr->getType() };
10129 Intrinsic::ID Int =
10130 IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
10131 Function *Ldxr = llvm::Intrinsic::getDeclaration(M, Int, Tys);
10132
10133 return Builder.CreateTruncOrBitCast(
10134 Builder.CreateCall(Ldxr, Addr),
10135 cast<PointerType>(Addr->getType())->getElementType());
10136}
10137
Ahmed Bougacha07a844d2015-09-22 17:21:44 +000010138void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
10139 IRBuilder<> &Builder) const {
10140 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10141 Builder.CreateCall(
10142 llvm::Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
10143}
10144
Tim Northover3b0846e2014-05-24 12:50:23 +000010145Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
10146 Value *Val, Value *Addr,
10147 AtomicOrdering Ord) const {
10148 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
Robin Morissetb155f522014-08-18 16:48:58 +000010149 bool IsRelease = isAtLeastRelease(Ord);
Tim Northover3b0846e2014-05-24 12:50:23 +000010150
10151 // Since the intrinsics must have legal type, the i128 intrinsics take two
10152 // parameters: "i64, i64". We must marshal Val into the appropriate form
10153 // before the call.
10154 if (Val->getType()->getPrimitiveSizeInBits() == 128) {
10155 Intrinsic::ID Int =
10156 IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
10157 Function *Stxr = Intrinsic::getDeclaration(M, Int);
10158 Type *Int64Ty = Type::getInt64Ty(M->getContext());
10159
10160 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
10161 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
10162 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
David Blaikieff6409d2015-05-18 22:13:54 +000010163 return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
Tim Northover3b0846e2014-05-24 12:50:23 +000010164 }
10165
10166 Intrinsic::ID Int =
10167 IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
10168 Type *Tys[] = { Addr->getType() };
10169 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
10170
David Blaikieff6409d2015-05-18 22:13:54 +000010171 return Builder.CreateCall(Stxr,
10172 {Builder.CreateZExtOrBitCast(
10173 Val, Stxr->getFunctionType()->getParamType(0)),
10174 Addr});
Tim Northover3b0846e2014-05-24 12:50:23 +000010175}
Tim Northover3c55cca2014-11-27 21:02:42 +000010176
10177bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
10178 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
10179 return Ty->isArrayTy();
10180}
Matthias Braunaf7d7702015-07-16 20:02:37 +000010181
10182bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
10183 EVT) const {
10184 return false;
10185}
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000010186
10187Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
10188 if (!Subtarget->isTargetAndroid())
10189 return TargetLowering::getSafeStackPointerLocation(IRB);
10190
10191 // Android provides a fixed TLS slot for the SafeStack pointer. See the
10192 // definition of TLS_SLOT_SAFESTACK in
10193 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
10194 const unsigned TlsOffset = 0x48;
10195 Module *M = IRB.GetInsertBlock()->getParent()->getParent();
10196 Function *ThreadPointerFunc =
10197 Intrinsic::getDeclaration(M, Intrinsic::aarch64_thread_pointer);
10198 return IRB.CreatePointerCast(
10199 IRB.CreateConstGEP1_32(IRB.CreateCall(ThreadPointerFunc), TlsOffset),
10200 Type::getInt8PtrTy(IRB.getContext())->getPointerTo(0));
10201}
Manman Rencbe4f942015-12-16 21:04:19 +000010202
10203void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
10204 // Update IsSplitCSR in AArch64unctionInfo.
10205 AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>();
10206 AFI->setIsSplitCSR(true);
10207}
10208
10209void AArch64TargetLowering::insertCopiesSplitCSR(
10210 MachineBasicBlock *Entry,
10211 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
10212 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
10213 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
10214 if (!IStart)
10215 return;
10216
10217 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10218 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
Manman Ren4632e8e2016-01-15 20:13:28 +000010219 MachineBasicBlock::iterator MBBI = Entry->begin();
Manman Rencbe4f942015-12-16 21:04:19 +000010220 for (const MCPhysReg *I = IStart; *I; ++I) {
10221 const TargetRegisterClass *RC = nullptr;
10222 if (AArch64::GPR64RegClass.contains(*I))
10223 RC = &AArch64::GPR64RegClass;
10224 else if (AArch64::FPR64RegClass.contains(*I))
10225 RC = &AArch64::FPR64RegClass;
10226 else
10227 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
10228
10229 unsigned NewVR = MRI->createVirtualRegister(RC);
10230 // Create copy from CSR to a virtual register.
10231 // FIXME: this currently does not emit CFI pseudo-instructions, it works
10232 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
10233 // nounwind. If we want to generalize this later, we may need to emit
10234 // CFI pseudo-instructions.
10235 assert(Entry->getParent()->getFunction()->hasFnAttribute(
10236 Attribute::NoUnwind) &&
10237 "Function should be nounwind in insertCopiesSplitCSR!");
10238 Entry->addLiveIn(*I);
Manman Ren4632e8e2016-01-15 20:13:28 +000010239 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
Manman Rencbe4f942015-12-16 21:04:19 +000010240 .addReg(*I);
10241
Manman Ren4632e8e2016-01-15 20:13:28 +000010242 // Insert the copy-back instructions right before the terminator.
Manman Rencbe4f942015-12-16 21:04:19 +000010243 for (auto *Exit : Exits)
Manman Ren4632e8e2016-01-15 20:13:28 +000010244 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
10245 TII->get(TargetOpcode::COPY), *I)
Manman Rencbe4f942015-12-16 21:04:19 +000010246 .addReg(NewVR);
10247 }
10248}