blob: 504cb5615b69bd04a13ece712d0fa31feae3677b [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
Tim Northover3c55cca2014-11-27 21:02:42 +000014#include "AArch64CallingConvention.h"
Benjamin Kramer1f8930e2014-07-25 11:42:14 +000015#include "AArch64MachineFunctionInfo.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000016#include "AArch64ISelLowering.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000017#include "AArch64PerfectShuffle.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000018#include "AArch64RegisterInfo.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000019#include "AArch64Subtarget.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000020#include "MCTargetDesc/AArch64AddressingModes.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000021#include "Utils/AArch64BaseInfo.h"
22#include "llvm/ADT/APFloat.h"
23#include "llvm/ADT/APInt.h"
24#include "llvm/ADT/ArrayRef.h"
25#include "llvm/ADT/SmallVector.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000026#include "llvm/ADT/Statistic.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000027#include "llvm/ADT/STLExtras.h"
28#include "llvm/ADT/StringRef.h"
29#include "llvm/ADT/StringSwitch.h"
30#include "llvm/ADT/Triple.h"
31#include "llvm/ADT/Twine.h"
Matthew Simpsonba5cf9d2017-02-01 17:45:46 +000032#include "llvm/Analysis/VectorUtils.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000033#include "llvm/CodeGen/CallingConvLower.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000034#include "llvm/CodeGen/MachineBasicBlock.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000035#include "llvm/CodeGen/MachineFrameInfo.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000036#include "llvm/CodeGen/MachineFunction.h"
37#include "llvm/CodeGen/MachineInstr.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000038#include "llvm/CodeGen/MachineInstrBuilder.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000039#include "llvm/CodeGen/MachineMemOperand.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000040#include "llvm/CodeGen/MachineRegisterInfo.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000041#include "llvm/CodeGen/MachineValueType.h"
42#include "llvm/CodeGen/RuntimeLibcalls.h"
43#include "llvm/CodeGen/SelectionDAG.h"
44#include "llvm/CodeGen/SelectionDAGNodes.h"
45#include "llvm/CodeGen/ValueTypes.h"
46#include "llvm/IR/Attributes.h"
47#include "llvm/IR/Constants.h"
48#include "llvm/IR/DataLayout.h"
49#include "llvm/IR/DebugLoc.h"
50#include "llvm/IR/DerivedTypes.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000051#include "llvm/IR/Function.h"
David Blaikie457343d2015-05-21 21:12:43 +000052#include "llvm/IR/GetElementPtrTypeIterator.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000053#include "llvm/IR/GlobalValue.h"
54#include "llvm/IR/Instruction.h"
55#include "llvm/IR/Instructions.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000056#include "llvm/IR/Intrinsics.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000057#include "llvm/IR/IRBuilder.h"
58#include "llvm/IR/Module.h"
59#include "llvm/IR/OperandTraits.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000060#include "llvm/IR/Type.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000061#include "llvm/IR/Use.h"
62#include "llvm/IR/Value.h"
63#include "llvm/MC/MCRegisterInfo.h"
64#include "llvm/Support/Casting.h"
65#include "llvm/Support/CodeGen.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000066#include "llvm/Support/CommandLine.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000067#include "llvm/Support/Compiler.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000068#include "llvm/Support/Debug.h"
69#include "llvm/Support/ErrorHandling.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000070#include "llvm/Support/MathExtras.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000071#include "llvm/Support/raw_ostream.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000072#include "llvm/Target/TargetCallingConv.h"
73#include "llvm/Target/TargetInstrInfo.h"
74#include "llvm/Target/TargetMachine.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000075#include "llvm/Target/TargetOptions.h"
Eugene Zelenko049b0172017-01-06 00:30:53 +000076#include <algorithm>
77#include <bitset>
78#include <cassert>
79#include <cctype>
80#include <cstdint>
81#include <cstdlib>
82#include <iterator>
83#include <limits>
84#include <tuple>
85#include <utility>
86#include <vector>
87
Tim Northover3b0846e2014-05-24 12:50:23 +000088using namespace llvm;
89
90#define DEBUG_TYPE "aarch64-lower"
91
92STATISTIC(NumTailCalls, "Number of tail calls");
93STATISTIC(NumShiftInserts, "Number of vector shift inserts");
94
Tim Northover3b0846e2014-05-24 12:50:23 +000095static cl::opt<bool>
96EnableAArch64SlrGeneration("aarch64-shift-insert-generation", cl::Hidden,
Kristof Beylsaea84612015-03-04 09:12:08 +000097 cl::desc("Allow AArch64 SLI/SRI formation"),
98 cl::init(false));
99
100// FIXME: The necessary dtprel relocations don't seem to be supported
101// well in the GNU bfd and gold linkers at the moment. Therefore, by
102// default, for now, fall back to GeneralDynamic code generation.
103cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration(
104 "aarch64-elf-ldtls-generation", cl::Hidden,
105 cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
106 cl::init(false));
Tim Northover3b0846e2014-05-24 12:50:23 +0000107
Matthias Braunaf7d7702015-07-16 20:02:37 +0000108/// Value type used for condition codes.
109static const MVT MVT_CC = MVT::i32;
110
Eric Christopher905f12d2015-01-29 00:19:42 +0000111AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
112 const AArch64Subtarget &STI)
113 : TargetLowering(TM), Subtarget(&STI) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000114 // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
115 // we have to make something up. Arbitrarily, choose ZeroOrOne.
116 setBooleanContents(ZeroOrOneBooleanContent);
117 // When comparing vectors the result sets the different elements in the
118 // vector to all-one or all-zero.
119 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
120
121 // Set up the register classes.
122 addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
123 addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
124
125 if (Subtarget->hasFPARMv8()) {
126 addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
127 addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
128 addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
129 addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
130 }
131
132 if (Subtarget->hasNEON()) {
133 addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
134 addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
135 // Someone set us up the NEON.
136 addDRTypeForNEON(MVT::v2f32);
137 addDRTypeForNEON(MVT::v8i8);
138 addDRTypeForNEON(MVT::v4i16);
139 addDRTypeForNEON(MVT::v2i32);
140 addDRTypeForNEON(MVT::v1i64);
141 addDRTypeForNEON(MVT::v1f64);
Oliver Stannard89d15422014-08-27 16:16:04 +0000142 addDRTypeForNEON(MVT::v4f16);
Tim Northover3b0846e2014-05-24 12:50:23 +0000143
144 addQRTypeForNEON(MVT::v4f32);
145 addQRTypeForNEON(MVT::v2f64);
146 addQRTypeForNEON(MVT::v16i8);
147 addQRTypeForNEON(MVT::v8i16);
148 addQRTypeForNEON(MVT::v4i32);
149 addQRTypeForNEON(MVT::v2i64);
Oliver Stannard89d15422014-08-27 16:16:04 +0000150 addQRTypeForNEON(MVT::v8f16);
Tim Northover3b0846e2014-05-24 12:50:23 +0000151 }
152
153 // Compute derived properties from the register classes
Eric Christopher23a3a7c2015-02-26 00:00:24 +0000154 computeRegisterProperties(Subtarget->getRegisterInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +0000155
156 // Provide all sorts of operation actions
157 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
158 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
159 setOperationAction(ISD::SETCC, MVT::i32, Custom);
160 setOperationAction(ISD::SETCC, MVT::i64, Custom);
161 setOperationAction(ISD::SETCC, MVT::f32, Custom);
162 setOperationAction(ISD::SETCC, MVT::f64, Custom);
Chad Rosier3daffbf2017-01-10 17:20:33 +0000163 setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
164 setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000165 setOperationAction(ISD::BRCOND, MVT::Other, Expand);
166 setOperationAction(ISD::BR_CC, MVT::i32, Custom);
167 setOperationAction(ISD::BR_CC, MVT::i64, Custom);
168 setOperationAction(ISD::BR_CC, MVT::f32, Custom);
169 setOperationAction(ISD::BR_CC, MVT::f64, Custom);
170 setOperationAction(ISD::SELECT, MVT::i32, Custom);
171 setOperationAction(ISD::SELECT, MVT::i64, Custom);
172 setOperationAction(ISD::SELECT, MVT::f32, Custom);
173 setOperationAction(ISD::SELECT, MVT::f64, Custom);
174 setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
175 setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
176 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
177 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
178 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
179 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
180
181 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
182 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
183 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
184
185 setOperationAction(ISD::FREM, MVT::f32, Expand);
186 setOperationAction(ISD::FREM, MVT::f64, Expand);
187 setOperationAction(ISD::FREM, MVT::f80, Expand);
188
189 // Custom lowering hooks are needed for XOR
190 // to fold it into CSINC/CSINV.
191 setOperationAction(ISD::XOR, MVT::i32, Custom);
192 setOperationAction(ISD::XOR, MVT::i64, Custom);
193
194 // Virtually no operation on f128 is legal, but LLVM can't expand them when
195 // there's a valid register class, so we need custom operations in most cases.
196 setOperationAction(ISD::FABS, MVT::f128, Expand);
197 setOperationAction(ISD::FADD, MVT::f128, Custom);
198 setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
199 setOperationAction(ISD::FCOS, MVT::f128, Expand);
200 setOperationAction(ISD::FDIV, MVT::f128, Custom);
201 setOperationAction(ISD::FMA, MVT::f128, Expand);
202 setOperationAction(ISD::FMUL, MVT::f128, Custom);
203 setOperationAction(ISD::FNEG, MVT::f128, Expand);
204 setOperationAction(ISD::FPOW, MVT::f128, Expand);
205 setOperationAction(ISD::FREM, MVT::f128, Expand);
206 setOperationAction(ISD::FRINT, MVT::f128, Expand);
207 setOperationAction(ISD::FSIN, MVT::f128, Expand);
208 setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
209 setOperationAction(ISD::FSQRT, MVT::f128, Expand);
210 setOperationAction(ISD::FSUB, MVT::f128, Custom);
211 setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
212 setOperationAction(ISD::SETCC, MVT::f128, Custom);
213 setOperationAction(ISD::BR_CC, MVT::f128, Custom);
214 setOperationAction(ISD::SELECT, MVT::f128, Custom);
215 setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
216 setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
217
218 // Lowering for many of the conversions is actually specified by the non-f128
219 // type. The LowerXXX function will be trivial when f128 isn't involved.
220 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
221 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
222 setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
223 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
224 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
225 setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
226 setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
227 setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
228 setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
229 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
230 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
231 setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
232 setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
233 setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
234
235 // Variable arguments.
236 setOperationAction(ISD::VASTART, MVT::Other, Custom);
237 setOperationAction(ISD::VAARG, MVT::Other, Custom);
238 setOperationAction(ISD::VACOPY, MVT::Other, Custom);
239 setOperationAction(ISD::VAEND, MVT::Other, Expand);
240
241 // Variable-sized objects.
242 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
243 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
244 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
245
Tim Northover3b0846e2014-05-24 12:50:23 +0000246 // Constant pool entries
247 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
248
249 // BlockAddress
250 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
251
252 // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
253 setOperationAction(ISD::ADDC, MVT::i32, Custom);
254 setOperationAction(ISD::ADDE, MVT::i32, Custom);
255 setOperationAction(ISD::SUBC, MVT::i32, Custom);
256 setOperationAction(ISD::SUBE, MVT::i32, Custom);
257 setOperationAction(ISD::ADDC, MVT::i64, Custom);
258 setOperationAction(ISD::ADDE, MVT::i64, Custom);
259 setOperationAction(ISD::SUBC, MVT::i64, Custom);
260 setOperationAction(ISD::SUBE, MVT::i64, Custom);
261
262 // AArch64 lacks both left-rotate and popcount instructions.
263 setOperationAction(ISD::ROTL, MVT::i32, Expand);
264 setOperationAction(ISD::ROTL, MVT::i64, Expand);
Charlie Turner458e79b2015-10-27 10:25:20 +0000265 for (MVT VT : MVT::vector_valuetypes()) {
266 setOperationAction(ISD::ROTL, VT, Expand);
267 setOperationAction(ISD::ROTR, VT, Expand);
268 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000269
270 // AArch64 doesn't have {U|S}MUL_LOHI.
271 setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
272 setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
273
Tim Northover3b0846e2014-05-24 12:50:23 +0000274 setOperationAction(ISD::CTPOP, MVT::i32, Custom);
275 setOperationAction(ISD::CTPOP, MVT::i64, Custom);
276
277 setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
278 setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
Chad Rosierf3491492015-12-04 21:38:44 +0000279 for (MVT VT : MVT::vector_valuetypes()) {
280 setOperationAction(ISD::SDIVREM, VT, Expand);
281 setOperationAction(ISD::UDIVREM, VT, Expand);
282 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000283 setOperationAction(ISD::SREM, MVT::i32, Expand);
284 setOperationAction(ISD::SREM, MVT::i64, Expand);
285 setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
286 setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
287 setOperationAction(ISD::UREM, MVT::i32, Expand);
288 setOperationAction(ISD::UREM, MVT::i64, Expand);
289
290 // Custom lower Add/Sub/Mul with overflow.
291 setOperationAction(ISD::SADDO, MVT::i32, Custom);
292 setOperationAction(ISD::SADDO, MVT::i64, Custom);
293 setOperationAction(ISD::UADDO, MVT::i32, Custom);
294 setOperationAction(ISD::UADDO, MVT::i64, Custom);
295 setOperationAction(ISD::SSUBO, MVT::i32, Custom);
296 setOperationAction(ISD::SSUBO, MVT::i64, Custom);
297 setOperationAction(ISD::USUBO, MVT::i32, Custom);
298 setOperationAction(ISD::USUBO, MVT::i64, Custom);
299 setOperationAction(ISD::SMULO, MVT::i32, Custom);
300 setOperationAction(ISD::SMULO, MVT::i64, Custom);
301 setOperationAction(ISD::UMULO, MVT::i32, Custom);
302 setOperationAction(ISD::UMULO, MVT::i64, Custom);
303
304 setOperationAction(ISD::FSIN, MVT::f32, Expand);
305 setOperationAction(ISD::FSIN, MVT::f64, Expand);
306 setOperationAction(ISD::FCOS, MVT::f32, Expand);
307 setOperationAction(ISD::FCOS, MVT::f64, Expand);
308 setOperationAction(ISD::FPOW, MVT::f32, Expand);
309 setOperationAction(ISD::FPOW, MVT::f64, Expand);
310 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
311 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
312
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +0000313 // f16 is a storage-only type, always promote it to f32.
314 setOperationAction(ISD::SETCC, MVT::f16, Promote);
315 setOperationAction(ISD::BR_CC, MVT::f16, Promote);
316 setOperationAction(ISD::SELECT_CC, MVT::f16, Promote);
317 setOperationAction(ISD::SELECT, MVT::f16, Promote);
318 setOperationAction(ISD::FADD, MVT::f16, Promote);
319 setOperationAction(ISD::FSUB, MVT::f16, Promote);
320 setOperationAction(ISD::FMUL, MVT::f16, Promote);
321 setOperationAction(ISD::FDIV, MVT::f16, Promote);
322 setOperationAction(ISD::FREM, MVT::f16, Promote);
323 setOperationAction(ISD::FMA, MVT::f16, Promote);
324 setOperationAction(ISD::FNEG, MVT::f16, Promote);
325 setOperationAction(ISD::FABS, MVT::f16, Promote);
326 setOperationAction(ISD::FCEIL, MVT::f16, Promote);
327 setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote);
328 setOperationAction(ISD::FCOS, MVT::f16, Promote);
329 setOperationAction(ISD::FFLOOR, MVT::f16, Promote);
330 setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote);
331 setOperationAction(ISD::FPOW, MVT::f16, Promote);
332 setOperationAction(ISD::FPOWI, MVT::f16, Promote);
333 setOperationAction(ISD::FRINT, MVT::f16, Promote);
334 setOperationAction(ISD::FSIN, MVT::f16, Promote);
335 setOperationAction(ISD::FSINCOS, MVT::f16, Promote);
336 setOperationAction(ISD::FSQRT, MVT::f16, Promote);
337 setOperationAction(ISD::FEXP, MVT::f16, Promote);
338 setOperationAction(ISD::FEXP2, MVT::f16, Promote);
339 setOperationAction(ISD::FLOG, MVT::f16, Promote);
340 setOperationAction(ISD::FLOG2, MVT::f16, Promote);
341 setOperationAction(ISD::FLOG10, MVT::f16, Promote);
342 setOperationAction(ISD::FROUND, MVT::f16, Promote);
343 setOperationAction(ISD::FTRUNC, MVT::f16, Promote);
344 setOperationAction(ISD::FMINNUM, MVT::f16, Promote);
345 setOperationAction(ISD::FMAXNUM, MVT::f16, Promote);
James Molloy63be1982015-08-14 09:08:50 +0000346 setOperationAction(ISD::FMINNAN, MVT::f16, Promote);
347 setOperationAction(ISD::FMAXNAN, MVT::f16, Promote);
Oliver Stannardf5469be2014-08-18 14:22:39 +0000348
Oliver Stannard89d15422014-08-27 16:16:04 +0000349 // v4f16 is also a storage-only type, so promote it to v4f32 when that is
350 // known to be safe.
351 setOperationAction(ISD::FADD, MVT::v4f16, Promote);
352 setOperationAction(ISD::FSUB, MVT::v4f16, Promote);
353 setOperationAction(ISD::FMUL, MVT::v4f16, Promote);
354 setOperationAction(ISD::FDIV, MVT::v4f16, Promote);
355 setOperationAction(ISD::FP_EXTEND, MVT::v4f16, Promote);
356 setOperationAction(ISD::FP_ROUND, MVT::v4f16, Promote);
357 AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32);
358 AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32);
359 AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32);
360 AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32);
361 AddPromotedToType(ISD::FP_EXTEND, MVT::v4f16, MVT::v4f32);
362 AddPromotedToType(ISD::FP_ROUND, MVT::v4f16, MVT::v4f32);
363
364 // Expand all other v4f16 operations.
365 // FIXME: We could generate better code by promoting some operations to
366 // a pair of v4f32s
367 setOperationAction(ISD::FABS, MVT::v4f16, Expand);
368 setOperationAction(ISD::FCEIL, MVT::v4f16, Expand);
369 setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand);
370 setOperationAction(ISD::FCOS, MVT::v4f16, Expand);
371 setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand);
372 setOperationAction(ISD::FMA, MVT::v4f16, Expand);
373 setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand);
374 setOperationAction(ISD::FNEG, MVT::v4f16, Expand);
375 setOperationAction(ISD::FPOW, MVT::v4f16, Expand);
376 setOperationAction(ISD::FPOWI, MVT::v4f16, Expand);
377 setOperationAction(ISD::FREM, MVT::v4f16, Expand);
378 setOperationAction(ISD::FROUND, MVT::v4f16, Expand);
379 setOperationAction(ISD::FRINT, MVT::v4f16, Expand);
380 setOperationAction(ISD::FSIN, MVT::v4f16, Expand);
381 setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand);
382 setOperationAction(ISD::FSQRT, MVT::v4f16, Expand);
383 setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand);
384 setOperationAction(ISD::SETCC, MVT::v4f16, Expand);
385 setOperationAction(ISD::BR_CC, MVT::v4f16, Expand);
386 setOperationAction(ISD::SELECT, MVT::v4f16, Expand);
387 setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand);
388 setOperationAction(ISD::FEXP, MVT::v4f16, Expand);
389 setOperationAction(ISD::FEXP2, MVT::v4f16, Expand);
390 setOperationAction(ISD::FLOG, MVT::v4f16, Expand);
391 setOperationAction(ISD::FLOG2, MVT::v4f16, Expand);
392 setOperationAction(ISD::FLOG10, MVT::v4f16, Expand);
393
394
395 // v8f16 is also a storage-only type, so expand it.
396 setOperationAction(ISD::FABS, MVT::v8f16, Expand);
397 setOperationAction(ISD::FADD, MVT::v8f16, Expand);
398 setOperationAction(ISD::FCEIL, MVT::v8f16, Expand);
399 setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand);
400 setOperationAction(ISD::FCOS, MVT::v8f16, Expand);
401 setOperationAction(ISD::FDIV, MVT::v8f16, Expand);
402 setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand);
403 setOperationAction(ISD::FMA, MVT::v8f16, Expand);
404 setOperationAction(ISD::FMUL, MVT::v8f16, Expand);
405 setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand);
406 setOperationAction(ISD::FNEG, MVT::v8f16, Expand);
407 setOperationAction(ISD::FPOW, MVT::v8f16, Expand);
408 setOperationAction(ISD::FPOWI, MVT::v8f16, Expand);
409 setOperationAction(ISD::FREM, MVT::v8f16, Expand);
410 setOperationAction(ISD::FROUND, MVT::v8f16, Expand);
411 setOperationAction(ISD::FRINT, MVT::v8f16, Expand);
412 setOperationAction(ISD::FSIN, MVT::v8f16, Expand);
413 setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
414 setOperationAction(ISD::FSQRT, MVT::v8f16, Expand);
415 setOperationAction(ISD::FSUB, MVT::v8f16, Expand);
416 setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand);
417 setOperationAction(ISD::SETCC, MVT::v8f16, Expand);
418 setOperationAction(ISD::BR_CC, MVT::v8f16, Expand);
419 setOperationAction(ISD::SELECT, MVT::v8f16, Expand);
420 setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand);
421 setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand);
422 setOperationAction(ISD::FEXP, MVT::v8f16, Expand);
423 setOperationAction(ISD::FEXP2, MVT::v8f16, Expand);
424 setOperationAction(ISD::FLOG, MVT::v8f16, Expand);
425 setOperationAction(ISD::FLOG2, MVT::v8f16, Expand);
426 setOperationAction(ISD::FLOG10, MVT::v8f16, Expand);
427
Tim Northover3b0846e2014-05-24 12:50:23 +0000428 // AArch64 has implementations of a lot of rounding-like FP operations.
Benjamin Kramer57a3d082015-03-08 16:07:39 +0000429 for (MVT Ty : {MVT::f32, MVT::f64}) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000430 setOperationAction(ISD::FFLOOR, Ty, Legal);
431 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
432 setOperationAction(ISD::FCEIL, Ty, Legal);
433 setOperationAction(ISD::FRINT, Ty, Legal);
434 setOperationAction(ISD::FTRUNC, Ty, Legal);
435 setOperationAction(ISD::FROUND, Ty, Legal);
James Molloyb7b2a1e2015-08-11 12:06:37 +0000436 setOperationAction(ISD::FMINNUM, Ty, Legal);
437 setOperationAction(ISD::FMAXNUM, Ty, Legal);
James Molloy88edc822015-08-17 07:13:20 +0000438 setOperationAction(ISD::FMINNAN, Ty, Legal);
439 setOperationAction(ISD::FMAXNAN, Ty, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000440 }
441
442 setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
443
Tim Northovercdf15292016-04-14 17:03:29 +0000444 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
445
Ahmed Bougachab0ff6432015-09-01 16:23:45 +0000446 // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
447 // This requires the Performance Monitors extension.
448 if (Subtarget->hasPerfMon())
449 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
450
Tim Northover3b0846e2014-05-24 12:50:23 +0000451 if (Subtarget->isTargetMachO()) {
452 // For iOS, we don't want to the normal expansion of a libcall to
453 // sincos. We want to issue a libcall to __sincos_stret to avoid memory
454 // traffic.
455 setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
456 setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
457 } else {
458 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
459 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
460 }
461
Juergen Ributzka23266502014-12-10 19:43:32 +0000462 // Make floating-point constants legal for the large code model, so they don't
463 // become loads from the constant pool.
464 if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
465 setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
466 setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
467 }
468
Tim Northover3b0846e2014-05-24 12:50:23 +0000469 // AArch64 does not have floating-point extending loads, i1 sign-extending
470 // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000471 for (MVT VT : MVT::fp_valuetypes()) {
472 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
473 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
474 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
475 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
476 }
477 for (MVT VT : MVT::integer_valuetypes())
478 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
479
Tim Northover3b0846e2014-05-24 12:50:23 +0000480 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
481 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
482 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
483 setTruncStoreAction(MVT::f128, MVT::f80, Expand);
484 setTruncStoreAction(MVT::f128, MVT::f64, Expand);
485 setTruncStoreAction(MVT::f128, MVT::f32, Expand);
486 setTruncStoreAction(MVT::f128, MVT::f16, Expand);
Tim Northoverf8bfe212014-07-18 13:07:05 +0000487
488 setOperationAction(ISD::BITCAST, MVT::i16, Custom);
489 setOperationAction(ISD::BITCAST, MVT::f16, Custom);
490
Tim Northover3b0846e2014-05-24 12:50:23 +0000491 // Indexed loads and stores are supported.
492 for (unsigned im = (unsigned)ISD::PRE_INC;
493 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
494 setIndexedLoadAction(im, MVT::i8, Legal);
495 setIndexedLoadAction(im, MVT::i16, Legal);
496 setIndexedLoadAction(im, MVT::i32, Legal);
497 setIndexedLoadAction(im, MVT::i64, Legal);
498 setIndexedLoadAction(im, MVT::f64, Legal);
499 setIndexedLoadAction(im, MVT::f32, Legal);
Ahmed Bougachae0e12db2015-08-04 01:29:38 +0000500 setIndexedLoadAction(im, MVT::f16, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000501 setIndexedStoreAction(im, MVT::i8, Legal);
502 setIndexedStoreAction(im, MVT::i16, Legal);
503 setIndexedStoreAction(im, MVT::i32, Legal);
504 setIndexedStoreAction(im, MVT::i64, Legal);
505 setIndexedStoreAction(im, MVT::f64, Legal);
506 setIndexedStoreAction(im, MVT::f32, Legal);
Ahmed Bougachae0e12db2015-08-04 01:29:38 +0000507 setIndexedStoreAction(im, MVT::f16, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000508 }
509
510 // Trap.
511 setOperationAction(ISD::TRAP, MVT::Other, Legal);
512
513 // We combine OR nodes for bitfield operations.
514 setTargetDAGCombine(ISD::OR);
515
516 // Vector add and sub nodes may conceal a high-half opportunity.
517 // Also, try to fold ADD into CSINC/CSINV..
518 setTargetDAGCombine(ISD::ADD);
519 setTargetDAGCombine(ISD::SUB);
Chad Rosier14aa2ad2016-05-26 19:41:33 +0000520 setTargetDAGCombine(ISD::SRL);
Tim Northover3b0846e2014-05-24 12:50:23 +0000521 setTargetDAGCombine(ISD::XOR);
522 setTargetDAGCombine(ISD::SINT_TO_FP);
523 setTargetDAGCombine(ISD::UINT_TO_FP);
524
Chad Rosierfa30c9b2015-10-07 17:39:18 +0000525 setTargetDAGCombine(ISD::FP_TO_SINT);
526 setTargetDAGCombine(ISD::FP_TO_UINT);
Chad Rosier7c6ac2b2015-10-07 17:51:37 +0000527 setTargetDAGCombine(ISD::FDIV);
Chad Rosierfa30c9b2015-10-07 17:39:18 +0000528
Tim Northover3b0846e2014-05-24 12:50:23 +0000529 setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
530
531 setTargetDAGCombine(ISD::ANY_EXTEND);
532 setTargetDAGCombine(ISD::ZERO_EXTEND);
533 setTargetDAGCombine(ISD::SIGN_EXTEND);
534 setTargetDAGCombine(ISD::BITCAST);
535 setTargetDAGCombine(ISD::CONCAT_VECTORS);
536 setTargetDAGCombine(ISD::STORE);
Tim Northover339c83e2015-11-10 00:44:23 +0000537 if (Subtarget->supportsAddressTopByteIgnored())
538 setTargetDAGCombine(ISD::LOAD);
Tim Northover3b0846e2014-05-24 12:50:23 +0000539
540 setTargetDAGCombine(ISD::MUL);
541
542 setTargetDAGCombine(ISD::SELECT);
543 setTargetDAGCombine(ISD::VSELECT);
544
545 setTargetDAGCombine(ISD::INTRINSIC_VOID);
546 setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
547 setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
Chad Rosier6c36eff2015-09-03 18:13:57 +0000548 setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
Tim Northover3b0846e2014-05-24 12:50:23 +0000549
550 MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 8;
551 MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 4;
552 MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = 4;
553
554 setStackPointerRegisterToSaveRestore(AArch64::SP);
555
556 setSchedulingPreference(Sched::Hybrid);
557
Quentin Colombet6843ac42015-03-31 20:52:32 +0000558 EnableExtLdPromotion = true;
Tim Northover3b0846e2014-05-24 12:50:23 +0000559
Evandro Menezesa3a0a602016-06-10 16:00:18 +0000560 // Set required alignment.
Tim Northover3b0846e2014-05-24 12:50:23 +0000561 setMinFunctionAlignment(2);
Evandro Menezesa3a0a602016-06-10 16:00:18 +0000562 // Set preferred alignments.
563 setPrefFunctionAlignment(STI.getPrefFunctionAlignment());
564 setPrefLoopAlignment(STI.getPrefLoopAlignment());
Tim Northover3b0846e2014-05-24 12:50:23 +0000565
Evandro Menezese45de8a2016-09-26 15:32:33 +0000566 // Only change the limit for entries in a jump table if specified by
567 // the subtarget, but not at the command line.
568 unsigned MaxJT = STI.getMaximumJumpTableSize();
569 if (MaxJT && getMaximumJumpTableSize() == 0)
570 setMaximumJumpTableSize(MaxJT);
571
Tim Northover3b0846e2014-05-24 12:50:23 +0000572 setHasExtractBitsInsn(true);
573
Adhemerval Zanella7bc33192015-07-28 13:03:31 +0000574 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
575
Tim Northover3b0846e2014-05-24 12:50:23 +0000576 if (Subtarget->hasNEON()) {
577 // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
578 // silliness like this:
579 setOperationAction(ISD::FABS, MVT::v1f64, Expand);
580 setOperationAction(ISD::FADD, MVT::v1f64, Expand);
581 setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
582 setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
583 setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
584 setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
585 setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
586 setOperationAction(ISD::FMA, MVT::v1f64, Expand);
587 setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
588 setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
589 setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
590 setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
591 setOperationAction(ISD::FREM, MVT::v1f64, Expand);
592 setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
593 setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
594 setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
595 setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
596 setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
597 setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
598 setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
599 setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
600 setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
601 setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
602 setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
603 setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
604
605 setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
606 setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
607 setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
608 setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
609 setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
610
611 setOperationAction(ISD::MUL, MVT::v1i64, Expand);
612
613 // AArch64 doesn't have a direct vector ->f32 conversion instructions for
614 // elements smaller than i32, so promote the input to i32 first.
615 setOperationAction(ISD::UINT_TO_FP, MVT::v4i8, Promote);
616 setOperationAction(ISD::SINT_TO_FP, MVT::v4i8, Promote);
617 setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Promote);
618 setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Promote);
Pirama Arumuga Nainarb1881532015-04-23 17:16:27 +0000619 // i8 and i16 vector elements also need promotion to i32 for v8i8 or v8i16
620 // -> v8f16 conversions.
621 setOperationAction(ISD::SINT_TO_FP, MVT::v8i8, Promote);
622 setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Promote);
623 setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Promote);
624 setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Promote);
Tim Northover3b0846e2014-05-24 12:50:23 +0000625 // Similarly, there is no direct i32 -> f64 vector conversion instruction.
626 setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
627 setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
628 setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
629 setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
Pirama Arumuga Nainarb1881532015-04-23 17:16:27 +0000630 // Or, direct i32 -> f16 vector conversion. Set it so custom, so the
631 // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
632 setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
633 setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000634
Craig Topperc5551bf2016-04-26 05:26:51 +0000635 setOperationAction(ISD::CTLZ, MVT::v1i64, Expand);
636 setOperationAction(ISD::CTLZ, MVT::v2i64, Expand);
637
Craig Topper3b4842b2016-04-28 01:58:21 +0000638 setOperationAction(ISD::CTTZ, MVT::v2i8, Expand);
639 setOperationAction(ISD::CTTZ, MVT::v4i16, Expand);
640 setOperationAction(ISD::CTTZ, MVT::v2i32, Expand);
641 setOperationAction(ISD::CTTZ, MVT::v1i64, Expand);
642 setOperationAction(ISD::CTTZ, MVT::v16i8, Expand);
643 setOperationAction(ISD::CTTZ, MVT::v8i16, Expand);
644 setOperationAction(ISD::CTTZ, MVT::v4i32, Expand);
645 setOperationAction(ISD::CTTZ, MVT::v2i64, Expand);
646
Tim Northover3b0846e2014-05-24 12:50:23 +0000647 // AArch64 doesn't have MUL.2d:
648 setOperationAction(ISD::MUL, MVT::v2i64, Expand);
Chad Rosierd9d0f862014-10-08 02:31:24 +0000649 // Custom handling for some quad-vector types to detect MULL.
650 setOperationAction(ISD::MUL, MVT::v8i16, Custom);
651 setOperationAction(ISD::MUL, MVT::v4i32, Custom);
652 setOperationAction(ISD::MUL, MVT::v2i64, Custom);
653
Tim Northover3b0846e2014-05-24 12:50:23 +0000654 setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
655 setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
656 // Likewise, narrowing and extending vector loads/stores aren't handled
657 // directly.
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000658 for (MVT VT : MVT::vector_valuetypes()) {
659 setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000660
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000661 setOperationAction(ISD::MULHS, VT, Expand);
662 setOperationAction(ISD::SMUL_LOHI, VT, Expand);
663 setOperationAction(ISD::MULHU, VT, Expand);
664 setOperationAction(ISD::UMUL_LOHI, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000665
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000666 setOperationAction(ISD::BSWAP, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000667
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000668 for (MVT InnerVT : MVT::vector_valuetypes()) {
Ahmed Bougacha67dd2d22015-01-07 21:27:10 +0000669 setTruncStoreAction(VT, InnerVT, Expand);
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000670 setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
671 setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
672 setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
673 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000674 }
675
676 // AArch64 has implementations of a lot of rounding-like FP operations.
Benjamin Kramer57a3d082015-03-08 16:07:39 +0000677 for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000678 setOperationAction(ISD::FFLOOR, Ty, Legal);
679 setOperationAction(ISD::FNEARBYINT, Ty, Legal);
680 setOperationAction(ISD::FCEIL, Ty, Legal);
681 setOperationAction(ISD::FRINT, Ty, Legal);
682 setOperationAction(ISD::FTRUNC, Ty, Legal);
683 setOperationAction(ISD::FROUND, Ty, Legal);
684 }
685 }
James Molloyf089ab72014-08-06 10:42:18 +0000686
Matthias Braun651cff42016-06-02 18:03:53 +0000687 PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive();
Tim Northover3b0846e2014-05-24 12:50:23 +0000688}
689
Craig Topper18e69f42016-04-15 06:20:21 +0000690void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) {
Jiangning Liu08f4cda2014-08-29 01:31:42 +0000691 if (VT == MVT::v2f32 || VT == MVT::v4f16) {
Craig Topper18e69f42016-04-15 06:20:21 +0000692 setOperationAction(ISD::LOAD, VT, Promote);
693 AddPromotedToType(ISD::LOAD, VT, MVT::v2i32);
Tim Northover3b0846e2014-05-24 12:50:23 +0000694
Craig Topper18e69f42016-04-15 06:20:21 +0000695 setOperationAction(ISD::STORE, VT, Promote);
696 AddPromotedToType(ISD::STORE, VT, MVT::v2i32);
Jiangning Liu08f4cda2014-08-29 01:31:42 +0000697 } else if (VT == MVT::v2f64 || VT == MVT::v4f32 || VT == MVT::v8f16) {
Craig Topper18e69f42016-04-15 06:20:21 +0000698 setOperationAction(ISD::LOAD, VT, Promote);
699 AddPromotedToType(ISD::LOAD, VT, MVT::v2i64);
Tim Northover3b0846e2014-05-24 12:50:23 +0000700
Craig Topper18e69f42016-04-15 06:20:21 +0000701 setOperationAction(ISD::STORE, VT, Promote);
702 AddPromotedToType(ISD::STORE, VT, MVT::v2i64);
Tim Northover3b0846e2014-05-24 12:50:23 +0000703 }
704
705 // Mark vector float intrinsics as expand.
706 if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
Craig Topper18e69f42016-04-15 06:20:21 +0000707 setOperationAction(ISD::FSIN, VT, Expand);
708 setOperationAction(ISD::FCOS, VT, Expand);
709 setOperationAction(ISD::FPOWI, VT, Expand);
710 setOperationAction(ISD::FPOW, VT, Expand);
711 setOperationAction(ISD::FLOG, VT, Expand);
712 setOperationAction(ISD::FLOG2, VT, Expand);
713 setOperationAction(ISD::FLOG10, VT, Expand);
714 setOperationAction(ISD::FEXP, VT, Expand);
715 setOperationAction(ISD::FEXP2, VT, Expand);
Ahmed Bougachab0ae36f2015-08-04 00:42:34 +0000716
717 // But we do support custom-lowering for FCOPYSIGN.
Craig Topper18e69f42016-04-15 06:20:21 +0000718 setOperationAction(ISD::FCOPYSIGN, VT, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000719 }
720
Craig Topper18e69f42016-04-15 06:20:21 +0000721 setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
722 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
723 setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
724 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
725 setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
726 setOperationAction(ISD::SRA, VT, Custom);
727 setOperationAction(ISD::SRL, VT, Custom);
728 setOperationAction(ISD::SHL, VT, Custom);
729 setOperationAction(ISD::AND, VT, Custom);
730 setOperationAction(ISD::OR, VT, Custom);
731 setOperationAction(ISD::SETCC, VT, Custom);
732 setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000733
Craig Topper18e69f42016-04-15 06:20:21 +0000734 setOperationAction(ISD::SELECT, VT, Expand);
735 setOperationAction(ISD::SELECT_CC, VT, Expand);
736 setOperationAction(ISD::VSELECT, VT, Expand);
Ahmed Bougacha2b6917b2015-01-08 00:51:32 +0000737 for (MVT InnerVT : MVT::all_valuetypes())
Craig Topper18e69f42016-04-15 06:20:21 +0000738 setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000739
740 // CNT supports only B element sizes.
741 if (VT != MVT::v8i8 && VT != MVT::v16i8)
Craig Topper18e69f42016-04-15 06:20:21 +0000742 setOperationAction(ISD::CTPOP, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000743
Craig Topper18e69f42016-04-15 06:20:21 +0000744 setOperationAction(ISD::UDIV, VT, Expand);
745 setOperationAction(ISD::SDIV, VT, Expand);
746 setOperationAction(ISD::UREM, VT, Expand);
747 setOperationAction(ISD::SREM, VT, Expand);
748 setOperationAction(ISD::FREM, VT, Expand);
Tim Northover3b0846e2014-05-24 12:50:23 +0000749
Craig Topper18e69f42016-04-15 06:20:21 +0000750 setOperationAction(ISD::FP_TO_SINT, VT, Custom);
751 setOperationAction(ISD::FP_TO_UINT, VT, Custom);
Tim Northover3b0846e2014-05-24 12:50:23 +0000752
Hal Finkelcd8664c2015-12-11 23:11:52 +0000753 // [SU][MIN|MAX] are available for all NEON types apart from i64.
Craig Topper18e69f42016-04-15 06:20:21 +0000754 if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64)
Hal Finkelcd8664c2015-12-11 23:11:52 +0000755 for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
Craig Topper18e69f42016-04-15 06:20:21 +0000756 setOperationAction(Opcode, VT, Legal);
James Molloycfb04432015-05-15 16:15:57 +0000757
James Molloy63be1982015-08-14 09:08:50 +0000758 // F[MIN|MAX][NUM|NAN] are available for all FP NEON types (not f16 though!).
759 if (VT.isFloatingPoint() && VT.getVectorElementType() != MVT::f16)
James Molloyb7b2a1e2015-08-11 12:06:37 +0000760 for (unsigned Opcode : {ISD::FMINNAN, ISD::FMAXNAN,
761 ISD::FMINNUM, ISD::FMAXNUM})
Craig Topper18e69f42016-04-15 06:20:21 +0000762 setOperationAction(Opcode, VT, Legal);
James Molloyedf38f02015-08-11 12:06:33 +0000763
Tim Northover3b0846e2014-05-24 12:50:23 +0000764 if (Subtarget->isLittleEndian()) {
765 for (unsigned im = (unsigned)ISD::PRE_INC;
766 im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
Craig Topper18e69f42016-04-15 06:20:21 +0000767 setIndexedLoadAction(im, VT, Legal);
768 setIndexedStoreAction(im, VT, Legal);
Tim Northover3b0846e2014-05-24 12:50:23 +0000769 }
770 }
771}
772
773void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
774 addRegisterClass(VT, &AArch64::FPR64RegClass);
775 addTypeForNEON(VT, MVT::v2i32);
776}
777
778void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
779 addRegisterClass(VT, &AArch64::FPR128RegClass);
780 addTypeForNEON(VT, MVT::v4i32);
781}
782
Mehdi Amini44ede332015-07-09 02:09:04 +0000783EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
784 EVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +0000785 if (!VT.isVector())
786 return MVT::i32;
787 return VT.changeVectorElementTypeToInteger();
788}
789
790/// computeKnownBitsForTargetNode - Determine which of the bits specified in
791/// Mask are known to be either zero or one and return them in the
792/// KnownZero/KnownOne bitsets.
793void AArch64TargetLowering::computeKnownBitsForTargetNode(
794 const SDValue Op, APInt &KnownZero, APInt &KnownOne,
Simon Pilgrim37b536e2017-03-31 11:24:16 +0000795 const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const {
Tim Northover3b0846e2014-05-24 12:50:23 +0000796 switch (Op.getOpcode()) {
797 default:
798 break;
799 case AArch64ISD::CSEL: {
800 APInt KnownZero2, KnownOne2;
801 DAG.computeKnownBits(Op->getOperand(0), KnownZero, KnownOne, Depth + 1);
802 DAG.computeKnownBits(Op->getOperand(1), KnownZero2, KnownOne2, Depth + 1);
803 KnownZero &= KnownZero2;
804 KnownOne &= KnownOne2;
805 break;
806 }
807 case ISD::INTRINSIC_W_CHAIN: {
Jun Bum Lim4d3c5982015-09-08 16:11:22 +0000808 ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +0000809 Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
810 switch (IntID) {
811 default: return;
812 case Intrinsic::aarch64_ldaxr:
813 case Intrinsic::aarch64_ldxr: {
814 unsigned BitWidth = KnownOne.getBitWidth();
815 EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
Sanjay Patelbd6fca12016-09-14 15:21:00 +0000816 unsigned MemBits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +0000817 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
818 return;
819 }
820 }
821 break;
822 }
823 case ISD::INTRINSIC_WO_CHAIN:
824 case ISD::INTRINSIC_VOID: {
825 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
826 switch (IntNo) {
827 default:
828 break;
829 case Intrinsic::aarch64_neon_umaxv:
830 case Intrinsic::aarch64_neon_uminv: {
831 // Figure out the datatype of the vector operand. The UMINV instruction
832 // will zero extend the result, so we can mark as known zero all the
833 // bits larger than the element datatype. 32-bit or larget doesn't need
834 // this as those are legal types and will be handled by isel directly.
835 MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
836 unsigned BitWidth = KnownZero.getBitWidth();
837 if (VT == MVT::v8i8 || VT == MVT::v16i8) {
838 assert(BitWidth >= 8 && "Unexpected width!");
839 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
840 KnownZero |= Mask;
841 } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
842 assert(BitWidth >= 16 && "Unexpected width!");
843 APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
844 KnownZero |= Mask;
845 }
846 break;
847 } break;
848 }
849 }
850 }
851}
852
Mehdi Aminieaabc512015-07-09 15:12:23 +0000853MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
854 EVT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +0000855 return MVT::i64;
856}
857
Akira Hatanakaf53b0402015-07-29 14:17:26 +0000858bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
859 unsigned AddrSpace,
860 unsigned Align,
861 bool *Fast) const {
862 if (Subtarget->requiresStrictAlign())
863 return false;
Sanjay Patelbbbf9a12015-09-25 21:49:48 +0000864
Sanjay Patelbbbf9a12015-09-25 21:49:48 +0000865 if (Fast) {
Matthias Braun651cff42016-06-02 18:03:53 +0000866 // Some CPUs are fine with unaligned stores except for 128-bit ones.
867 *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 ||
Sanjay Patelbbbf9a12015-09-25 21:49:48 +0000868 // See comments in performSTORECombine() for more details about
869 // these conditions.
870
871 // Code that uses clang vector extensions can mark that it
872 // wants unaligned accesses to be treated as fast by
873 // underspecifying alignment to be 1 or 2.
874 Align <= 2 ||
875
876 // Disregard v2i64. Memcpy lowering produces those and splitting
877 // them regresses performance on micro-benchmarks and olden/bh.
878 VT == MVT::v2i64;
879 }
Akira Hatanakaf53b0402015-07-29 14:17:26 +0000880 return true;
881}
882
Tim Northover3b0846e2014-05-24 12:50:23 +0000883FastISel *
884AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
885 const TargetLibraryInfo *libInfo) const {
886 return AArch64::createFastISel(funcInfo, libInfo);
887}
888
889const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
Matthias Braund04893f2015-05-07 21:33:59 +0000890 switch ((AArch64ISD::NodeType)Opcode) {
891 case AArch64ISD::FIRST_NUMBER: break;
Tim Northover3b0846e2014-05-24 12:50:23 +0000892 case AArch64ISD::CALL: return "AArch64ISD::CALL";
893 case AArch64ISD::ADRP: return "AArch64ISD::ADRP";
894 case AArch64ISD::ADDlow: return "AArch64ISD::ADDlow";
895 case AArch64ISD::LOADgot: return "AArch64ISD::LOADgot";
896 case AArch64ISD::RET_FLAG: return "AArch64ISD::RET_FLAG";
897 case AArch64ISD::BRCOND: return "AArch64ISD::BRCOND";
898 case AArch64ISD::CSEL: return "AArch64ISD::CSEL";
899 case AArch64ISD::FCSEL: return "AArch64ISD::FCSEL";
900 case AArch64ISD::CSINV: return "AArch64ISD::CSINV";
901 case AArch64ISD::CSNEG: return "AArch64ISD::CSNEG";
902 case AArch64ISD::CSINC: return "AArch64ISD::CSINC";
903 case AArch64ISD::THREAD_POINTER: return "AArch64ISD::THREAD_POINTER";
Kristof Beylsaea84612015-03-04 09:12:08 +0000904 case AArch64ISD::TLSDESC_CALLSEQ: return "AArch64ISD::TLSDESC_CALLSEQ";
Tim Northover3b0846e2014-05-24 12:50:23 +0000905 case AArch64ISD::ADC: return "AArch64ISD::ADC";
906 case AArch64ISD::SBC: return "AArch64ISD::SBC";
907 case AArch64ISD::ADDS: return "AArch64ISD::ADDS";
908 case AArch64ISD::SUBS: return "AArch64ISD::SUBS";
909 case AArch64ISD::ADCS: return "AArch64ISD::ADCS";
910 case AArch64ISD::SBCS: return "AArch64ISD::SBCS";
911 case AArch64ISD::ANDS: return "AArch64ISD::ANDS";
Matthias Braunaf7d7702015-07-16 20:02:37 +0000912 case AArch64ISD::CCMP: return "AArch64ISD::CCMP";
913 case AArch64ISD::CCMN: return "AArch64ISD::CCMN";
914 case AArch64ISD::FCCMP: return "AArch64ISD::FCCMP";
Tim Northover3b0846e2014-05-24 12:50:23 +0000915 case AArch64ISD::FCMP: return "AArch64ISD::FCMP";
Tim Northover3b0846e2014-05-24 12:50:23 +0000916 case AArch64ISD::DUP: return "AArch64ISD::DUP";
917 case AArch64ISD::DUPLANE8: return "AArch64ISD::DUPLANE8";
918 case AArch64ISD::DUPLANE16: return "AArch64ISD::DUPLANE16";
919 case AArch64ISD::DUPLANE32: return "AArch64ISD::DUPLANE32";
920 case AArch64ISD::DUPLANE64: return "AArch64ISD::DUPLANE64";
921 case AArch64ISD::MOVI: return "AArch64ISD::MOVI";
922 case AArch64ISD::MOVIshift: return "AArch64ISD::MOVIshift";
923 case AArch64ISD::MOVIedit: return "AArch64ISD::MOVIedit";
924 case AArch64ISD::MOVImsl: return "AArch64ISD::MOVImsl";
925 case AArch64ISD::FMOV: return "AArch64ISD::FMOV";
926 case AArch64ISD::MVNIshift: return "AArch64ISD::MVNIshift";
927 case AArch64ISD::MVNImsl: return "AArch64ISD::MVNImsl";
928 case AArch64ISD::BICi: return "AArch64ISD::BICi";
929 case AArch64ISD::ORRi: return "AArch64ISD::ORRi";
930 case AArch64ISD::BSL: return "AArch64ISD::BSL";
931 case AArch64ISD::NEG: return "AArch64ISD::NEG";
932 case AArch64ISD::EXTR: return "AArch64ISD::EXTR";
933 case AArch64ISD::ZIP1: return "AArch64ISD::ZIP1";
934 case AArch64ISD::ZIP2: return "AArch64ISD::ZIP2";
935 case AArch64ISD::UZP1: return "AArch64ISD::UZP1";
936 case AArch64ISD::UZP2: return "AArch64ISD::UZP2";
937 case AArch64ISD::TRN1: return "AArch64ISD::TRN1";
938 case AArch64ISD::TRN2: return "AArch64ISD::TRN2";
939 case AArch64ISD::REV16: return "AArch64ISD::REV16";
940 case AArch64ISD::REV32: return "AArch64ISD::REV32";
941 case AArch64ISD::REV64: return "AArch64ISD::REV64";
942 case AArch64ISD::EXT: return "AArch64ISD::EXT";
943 case AArch64ISD::VSHL: return "AArch64ISD::VSHL";
944 case AArch64ISD::VLSHR: return "AArch64ISD::VLSHR";
945 case AArch64ISD::VASHR: return "AArch64ISD::VASHR";
946 case AArch64ISD::CMEQ: return "AArch64ISD::CMEQ";
947 case AArch64ISD::CMGE: return "AArch64ISD::CMGE";
948 case AArch64ISD::CMGT: return "AArch64ISD::CMGT";
949 case AArch64ISD::CMHI: return "AArch64ISD::CMHI";
950 case AArch64ISD::CMHS: return "AArch64ISD::CMHS";
951 case AArch64ISD::FCMEQ: return "AArch64ISD::FCMEQ";
952 case AArch64ISD::FCMGE: return "AArch64ISD::FCMGE";
953 case AArch64ISD::FCMGT: return "AArch64ISD::FCMGT";
954 case AArch64ISD::CMEQz: return "AArch64ISD::CMEQz";
955 case AArch64ISD::CMGEz: return "AArch64ISD::CMGEz";
956 case AArch64ISD::CMGTz: return "AArch64ISD::CMGTz";
957 case AArch64ISD::CMLEz: return "AArch64ISD::CMLEz";
958 case AArch64ISD::CMLTz: return "AArch64ISD::CMLTz";
959 case AArch64ISD::FCMEQz: return "AArch64ISD::FCMEQz";
960 case AArch64ISD::FCMGEz: return "AArch64ISD::FCMGEz";
961 case AArch64ISD::FCMGTz: return "AArch64ISD::FCMGTz";
962 case AArch64ISD::FCMLEz: return "AArch64ISD::FCMLEz";
963 case AArch64ISD::FCMLTz: return "AArch64ISD::FCMLTz";
Ahmed Bougachafab58922015-03-10 20:45:38 +0000964 case AArch64ISD::SADDV: return "AArch64ISD::SADDV";
965 case AArch64ISD::UADDV: return "AArch64ISD::UADDV";
966 case AArch64ISD::SMINV: return "AArch64ISD::SMINV";
967 case AArch64ISD::UMINV: return "AArch64ISD::UMINV";
968 case AArch64ISD::SMAXV: return "AArch64ISD::SMAXV";
969 case AArch64ISD::UMAXV: return "AArch64ISD::UMAXV";
Tim Northover3b0846e2014-05-24 12:50:23 +0000970 case AArch64ISD::NOT: return "AArch64ISD::NOT";
971 case AArch64ISD::BIT: return "AArch64ISD::BIT";
972 case AArch64ISD::CBZ: return "AArch64ISD::CBZ";
973 case AArch64ISD::CBNZ: return "AArch64ISD::CBNZ";
974 case AArch64ISD::TBZ: return "AArch64ISD::TBZ";
975 case AArch64ISD::TBNZ: return "AArch64ISD::TBNZ";
976 case AArch64ISD::TC_RETURN: return "AArch64ISD::TC_RETURN";
Matthias Braund04893f2015-05-07 21:33:59 +0000977 case AArch64ISD::PREFETCH: return "AArch64ISD::PREFETCH";
Tim Northover3b0846e2014-05-24 12:50:23 +0000978 case AArch64ISD::SITOF: return "AArch64ISD::SITOF";
979 case AArch64ISD::UITOF: return "AArch64ISD::UITOF";
Asiri Rathnayake530b3ed2014-10-01 09:59:45 +0000980 case AArch64ISD::NVCAST: return "AArch64ISD::NVCAST";
Tim Northover3b0846e2014-05-24 12:50:23 +0000981 case AArch64ISD::SQSHL_I: return "AArch64ISD::SQSHL_I";
982 case AArch64ISD::UQSHL_I: return "AArch64ISD::UQSHL_I";
983 case AArch64ISD::SRSHR_I: return "AArch64ISD::SRSHR_I";
984 case AArch64ISD::URSHR_I: return "AArch64ISD::URSHR_I";
985 case AArch64ISD::SQSHLU_I: return "AArch64ISD::SQSHLU_I";
986 case AArch64ISD::WrapperLarge: return "AArch64ISD::WrapperLarge";
987 case AArch64ISD::LD2post: return "AArch64ISD::LD2post";
988 case AArch64ISD::LD3post: return "AArch64ISD::LD3post";
989 case AArch64ISD::LD4post: return "AArch64ISD::LD4post";
990 case AArch64ISD::ST2post: return "AArch64ISD::ST2post";
991 case AArch64ISD::ST3post: return "AArch64ISD::ST3post";
992 case AArch64ISD::ST4post: return "AArch64ISD::ST4post";
993 case AArch64ISD::LD1x2post: return "AArch64ISD::LD1x2post";
994 case AArch64ISD::LD1x3post: return "AArch64ISD::LD1x3post";
995 case AArch64ISD::LD1x4post: return "AArch64ISD::LD1x4post";
996 case AArch64ISD::ST1x2post: return "AArch64ISD::ST1x2post";
997 case AArch64ISD::ST1x3post: return "AArch64ISD::ST1x3post";
998 case AArch64ISD::ST1x4post: return "AArch64ISD::ST1x4post";
999 case AArch64ISD::LD1DUPpost: return "AArch64ISD::LD1DUPpost";
1000 case AArch64ISD::LD2DUPpost: return "AArch64ISD::LD2DUPpost";
1001 case AArch64ISD::LD3DUPpost: return "AArch64ISD::LD3DUPpost";
1002 case AArch64ISD::LD4DUPpost: return "AArch64ISD::LD4DUPpost";
1003 case AArch64ISD::LD1LANEpost: return "AArch64ISD::LD1LANEpost";
1004 case AArch64ISD::LD2LANEpost: return "AArch64ISD::LD2LANEpost";
1005 case AArch64ISD::LD3LANEpost: return "AArch64ISD::LD3LANEpost";
1006 case AArch64ISD::LD4LANEpost: return "AArch64ISD::LD4LANEpost";
1007 case AArch64ISD::ST2LANEpost: return "AArch64ISD::ST2LANEpost";
1008 case AArch64ISD::ST3LANEpost: return "AArch64ISD::ST3LANEpost";
1009 case AArch64ISD::ST4LANEpost: return "AArch64ISD::ST4LANEpost";
Chad Rosierd9d0f862014-10-08 02:31:24 +00001010 case AArch64ISD::SMULL: return "AArch64ISD::SMULL";
1011 case AArch64ISD::UMULL: return "AArch64ISD::UMULL";
Evandro Menezeseff2bd92016-10-24 16:14:58 +00001012 case AArch64ISD::FRECPE: return "AArch64ISD::FRECPE";
Evandro Menezes9fc54822016-11-14 23:29:01 +00001013 case AArch64ISD::FRECPS: return "AArch64ISD::FRECPS";
1014 case AArch64ISD::FRSQRTE: return "AArch64ISD::FRSQRTE";
1015 case AArch64ISD::FRSQRTS: return "AArch64ISD::FRSQRTS";
Tim Northover3b0846e2014-05-24 12:50:23 +00001016 }
Matthias Braund04893f2015-05-07 21:33:59 +00001017 return nullptr;
Tim Northover3b0846e2014-05-24 12:50:23 +00001018}
1019
1020MachineBasicBlock *
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001021AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI,
Tim Northover3b0846e2014-05-24 12:50:23 +00001022 MachineBasicBlock *MBB) const {
1023 // We materialise the F128CSEL pseudo-instruction as some control flow and a
1024 // phi node:
1025
1026 // OrigBB:
1027 // [... previous instrs leading to comparison ...]
1028 // b.ne TrueBB
1029 // b EndBB
1030 // TrueBB:
1031 // ; Fallthrough
1032 // EndBB:
1033 // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
1034
Tim Northover3b0846e2014-05-24 12:50:23 +00001035 MachineFunction *MF = MBB->getParent();
Eric Christopher905f12d2015-01-29 00:19:42 +00001036 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00001037 const BasicBlock *LLVM_BB = MBB->getBasicBlock();
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001038 DebugLoc DL = MI.getDebugLoc();
Duncan P. N. Exon Smithd3b9df02015-10-13 20:02:15 +00001039 MachineFunction::iterator It = ++MBB->getIterator();
Tim Northover3b0846e2014-05-24 12:50:23 +00001040
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001041 unsigned DestReg = MI.getOperand(0).getReg();
1042 unsigned IfTrueReg = MI.getOperand(1).getReg();
1043 unsigned IfFalseReg = MI.getOperand(2).getReg();
1044 unsigned CondCode = MI.getOperand(3).getImm();
1045 bool NZCVKilled = MI.getOperand(4).isKill();
Tim Northover3b0846e2014-05-24 12:50:23 +00001046
1047 MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
1048 MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
1049 MF->insert(It, TrueBB);
1050 MF->insert(It, EndBB);
1051
1052 // Transfer rest of current basic-block to EndBB
1053 EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
1054 MBB->end());
1055 EndBB->transferSuccessorsAndUpdatePHIs(MBB);
1056
1057 BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
1058 BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
1059 MBB->addSuccessor(TrueBB);
1060 MBB->addSuccessor(EndBB);
1061
1062 // TrueBB falls through to the end.
1063 TrueBB->addSuccessor(EndBB);
1064
1065 if (!NZCVKilled) {
1066 TrueBB->addLiveIn(AArch64::NZCV);
1067 EndBB->addLiveIn(AArch64::NZCV);
1068 }
1069
1070 BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
1071 .addReg(IfTrueReg)
1072 .addMBB(TrueBB)
1073 .addReg(IfFalseReg)
1074 .addMBB(MBB);
1075
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001076 MI.eraseFromParent();
Tim Northover3b0846e2014-05-24 12:50:23 +00001077 return EndBB;
1078}
1079
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001080MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter(
1081 MachineInstr &MI, MachineBasicBlock *BB) const {
1082 switch (MI.getOpcode()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001083 default:
1084#ifndef NDEBUG
Duncan P. N. Exon Smithe4f5e4f2016-06-30 22:52:52 +00001085 MI.dump();
Tim Northover3b0846e2014-05-24 12:50:23 +00001086#endif
Craig Topper35b2f752014-06-19 06:10:58 +00001087 llvm_unreachable("Unexpected instruction for custom inserter!");
Tim Northover3b0846e2014-05-24 12:50:23 +00001088
1089 case AArch64::F128CSEL:
1090 return EmitF128CSEL(MI, BB);
1091
1092 case TargetOpcode::STACKMAP:
1093 case TargetOpcode::PATCHPOINT:
1094 return emitPatchPoint(MI, BB);
1095 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001096}
1097
1098//===----------------------------------------------------------------------===//
1099// AArch64 Lowering private implementation.
1100//===----------------------------------------------------------------------===//
1101
1102//===----------------------------------------------------------------------===//
1103// Lowering Code
1104//===----------------------------------------------------------------------===//
1105
1106/// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
1107/// CC
1108static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
1109 switch (CC) {
1110 default:
1111 llvm_unreachable("Unknown condition code!");
1112 case ISD::SETNE:
1113 return AArch64CC::NE;
1114 case ISD::SETEQ:
1115 return AArch64CC::EQ;
1116 case ISD::SETGT:
1117 return AArch64CC::GT;
1118 case ISD::SETGE:
1119 return AArch64CC::GE;
1120 case ISD::SETLT:
1121 return AArch64CC::LT;
1122 case ISD::SETLE:
1123 return AArch64CC::LE;
1124 case ISD::SETUGT:
1125 return AArch64CC::HI;
1126 case ISD::SETUGE:
1127 return AArch64CC::HS;
1128 case ISD::SETULT:
1129 return AArch64CC::LO;
1130 case ISD::SETULE:
1131 return AArch64CC::LS;
1132 }
1133}
1134
1135/// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
1136static void changeFPCCToAArch64CC(ISD::CondCode CC,
1137 AArch64CC::CondCode &CondCode,
1138 AArch64CC::CondCode &CondCode2) {
1139 CondCode2 = AArch64CC::AL;
1140 switch (CC) {
1141 default:
1142 llvm_unreachable("Unknown FP condition!");
1143 case ISD::SETEQ:
1144 case ISD::SETOEQ:
1145 CondCode = AArch64CC::EQ;
1146 break;
1147 case ISD::SETGT:
1148 case ISD::SETOGT:
1149 CondCode = AArch64CC::GT;
1150 break;
1151 case ISD::SETGE:
1152 case ISD::SETOGE:
1153 CondCode = AArch64CC::GE;
1154 break;
1155 case ISD::SETOLT:
1156 CondCode = AArch64CC::MI;
1157 break;
1158 case ISD::SETOLE:
1159 CondCode = AArch64CC::LS;
1160 break;
1161 case ISD::SETONE:
1162 CondCode = AArch64CC::MI;
1163 CondCode2 = AArch64CC::GT;
1164 break;
1165 case ISD::SETO:
1166 CondCode = AArch64CC::VC;
1167 break;
1168 case ISD::SETUO:
1169 CondCode = AArch64CC::VS;
1170 break;
1171 case ISD::SETUEQ:
1172 CondCode = AArch64CC::EQ;
1173 CondCode2 = AArch64CC::VS;
1174 break;
1175 case ISD::SETUGT:
1176 CondCode = AArch64CC::HI;
1177 break;
1178 case ISD::SETUGE:
1179 CondCode = AArch64CC::PL;
1180 break;
1181 case ISD::SETLT:
1182 case ISD::SETULT:
1183 CondCode = AArch64CC::LT;
1184 break;
1185 case ISD::SETLE:
1186 case ISD::SETULE:
1187 CondCode = AArch64CC::LE;
1188 break;
1189 case ISD::SETNE:
1190 case ISD::SETUNE:
1191 CondCode = AArch64CC::NE;
1192 break;
1193 }
1194}
1195
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001196/// Convert a DAG fp condition code to an AArch64 CC.
1197/// This differs from changeFPCCToAArch64CC in that it returns cond codes that
1198/// should be AND'ed instead of OR'ed.
1199static void changeFPCCToANDAArch64CC(ISD::CondCode CC,
1200 AArch64CC::CondCode &CondCode,
1201 AArch64CC::CondCode &CondCode2) {
1202 CondCode2 = AArch64CC::AL;
1203 switch (CC) {
1204 default:
1205 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1206 assert(CondCode2 == AArch64CC::AL);
1207 break;
1208 case ISD::SETONE:
1209 // (a one b)
1210 // == ((a olt b) || (a ogt b))
1211 // == ((a ord b) && (a une b))
1212 CondCode = AArch64CC::VC;
1213 CondCode2 = AArch64CC::NE;
1214 break;
1215 case ISD::SETUEQ:
1216 // (a ueq b)
1217 // == ((a uno b) || (a oeq b))
1218 // == ((a ule b) && (a uge b))
1219 CondCode = AArch64CC::PL;
1220 CondCode2 = AArch64CC::LE;
1221 break;
1222 }
1223}
1224
Tim Northover3b0846e2014-05-24 12:50:23 +00001225/// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
1226/// CC usable with the vector instructions. Fewer operations are available
1227/// without a real NZCV register, so we have to use less efficient combinations
1228/// to get the same effect.
1229static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
1230 AArch64CC::CondCode &CondCode,
1231 AArch64CC::CondCode &CondCode2,
1232 bool &Invert) {
1233 Invert = false;
1234 switch (CC) {
1235 default:
1236 // Mostly the scalar mappings work fine.
1237 changeFPCCToAArch64CC(CC, CondCode, CondCode2);
1238 break;
1239 case ISD::SETUO:
Justin Bognerb03fd122016-08-17 05:10:15 +00001240 Invert = true;
1241 LLVM_FALLTHROUGH;
Tim Northover3b0846e2014-05-24 12:50:23 +00001242 case ISD::SETO:
1243 CondCode = AArch64CC::MI;
1244 CondCode2 = AArch64CC::GE;
1245 break;
1246 case ISD::SETUEQ:
1247 case ISD::SETULT:
1248 case ISD::SETULE:
1249 case ISD::SETUGT:
1250 case ISD::SETUGE:
1251 // All of the compare-mask comparisons are ordered, but we can switch
1252 // between the two by a double inversion. E.g. ULE == !OGT.
1253 Invert = true;
1254 changeFPCCToAArch64CC(getSetCCInverse(CC, false), CondCode, CondCode2);
1255 break;
1256 }
1257}
1258
1259static bool isLegalArithImmed(uint64_t C) {
1260 // Matches AArch64DAGToDAGISel::SelectArithImmed().
1261 return (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
1262}
1263
1264static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00001265 const SDLoc &dl, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001266 EVT VT = LHS.getValueType();
1267
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001268 if (VT.isFloatingPoint()) {
1269 assert(VT != MVT::f128);
1270 if (VT == MVT::f16) {
1271 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
1272 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
Weiming Zhao095c2712016-05-11 01:26:32 +00001273 VT = MVT::f32;
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001274 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001275 return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001276 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001277
1278 // The CMP instruction is just an alias for SUBS, and representing it as
1279 // SUBS means that it's possible to get CSE with subtract operations.
1280 // A later phase can perform the optimization of setting the destination
1281 // register to WZR/XZR if it ends up being unused.
1282 unsigned Opcode = AArch64ISD::SUBS;
1283
Artyom Skrobov314ee042015-11-25 19:41:11 +00001284 if (RHS.getOpcode() == ISD::SUB && isNullConstant(RHS.getOperand(0)) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001285 (CC == ISD::SETEQ || CC == ISD::SETNE)) {
1286 // We'd like to combine a (CMP op1, (sub 0, op2) into a CMN instruction on
1287 // the grounds that "op1 - (-op2) == op1 + op2". However, the C and V flags
1288 // can be set differently by this operation. It comes down to whether
1289 // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
1290 // everything is fine. If not then the optimization is wrong. Thus general
1291 // comparisons are only valid if op2 != 0.
1292
1293 // So, finally, the only LLVM-native comparisons that don't mention C and V
1294 // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
1295 // the absence of information about op2.
1296 Opcode = AArch64ISD::ADDS;
1297 RHS = RHS.getOperand(1);
Artyom Skrobov314ee042015-11-25 19:41:11 +00001298 } else if (LHS.getOpcode() == ISD::AND && isNullConstant(RHS) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001299 !isUnsignedIntSetCC(CC)) {
1300 // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
1301 // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
1302 // of the signed comparisons.
1303 Opcode = AArch64ISD::ANDS;
1304 RHS = LHS.getOperand(1);
1305 LHS = LHS.getOperand(0);
1306 }
1307
Matthias Braunaf7d7702015-07-16 20:02:37 +00001308 return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
Tim Northover3b0846e2014-05-24 12:50:23 +00001309 .getValue(1);
1310}
1311
Matthias Braunaf7d7702015-07-16 20:02:37 +00001312/// \defgroup AArch64CCMP CMP;CCMP matching
1313///
1314/// These functions deal with the formation of CMP;CCMP;... sequences.
1315/// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
1316/// a comparison. They set the NZCV flags to a predefined value if their
1317/// predicate is false. This allows to express arbitrary conjunctions, for
1318/// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B))))"
1319/// expressed as:
1320/// cmp A
1321/// ccmp B, inv(CB), CA
1322/// check for CB flags
1323///
1324/// In general we can create code for arbitrary "... (and (and A B) C)"
1325/// sequences. We can also implement some "or" expressions, because "(or A B)"
1326/// is equivalent to "not (and (not A) (not B))" and we can implement some
1327/// negation operations:
1328/// We can negate the results of a single comparison by inverting the flags
1329/// used when the predicate fails and inverting the flags tested in the next
1330/// instruction; We can also negate the results of the whole previous
1331/// conditional compare sequence by inverting the flags tested in the next
1332/// instruction. However there is no way to negate the result of a partial
1333/// sequence.
1334///
1335/// Therefore on encountering an "or" expression we can negate the subtree on
1336/// one side and have to be able to push the negate to the leafs of the subtree
1337/// on the other side (see also the comments in code). As complete example:
1338/// "or (or (setCA (cmp A)) (setCB (cmp B)))
1339/// (and (setCC (cmp C)) (setCD (cmp D)))"
1340/// is transformed to
1341/// "not (and (not (and (setCC (cmp C)) (setCC (cmp D))))
1342/// (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
1343/// and implemented as:
1344/// cmp C
1345/// ccmp D, inv(CD), CC
1346/// ccmp A, CA, inv(CD)
1347/// ccmp B, CB, inv(CA)
1348/// check for CB flags
1349/// A counterexample is "or (and A B) (and C D)" which cannot be implemented
1350/// by conditional compare sequences.
1351/// @{
1352
Geoff Berrye41c2df2015-07-20 22:03:52 +00001353/// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001354static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
1355 ISD::CondCode CC, SDValue CCOp,
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001356 AArch64CC::CondCode Predicate,
1357 AArch64CC::CondCode OutCC,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00001358 const SDLoc &DL, SelectionDAG &DAG) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001359 unsigned Opcode = 0;
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001360 if (LHS.getValueType().isFloatingPoint()) {
1361 assert(LHS.getValueType() != MVT::f128);
1362 if (LHS.getValueType() == MVT::f16) {
1363 LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS);
1364 RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS);
1365 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001366 Opcode = AArch64ISD::FCCMP;
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001367 } else if (RHS.getOpcode() == ISD::SUB) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001368 SDValue SubOp0 = RHS.getOperand(0);
Artyom Skrobov314ee042015-11-25 19:41:11 +00001369 if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
Matthias Braunfd13c142016-01-23 04:05:16 +00001370 // See emitComparison() on why we can only do this for SETEQ and SETNE.
1371 Opcode = AArch64ISD::CCMN;
1372 RHS = RHS.getOperand(1);
1373 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001374 }
1375 if (Opcode == 0)
1376 Opcode = AArch64ISD::CCMP;
1377
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001378 SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC);
1379 AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
1380 unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001381 SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
1382 return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
1383}
1384
1385/// Returns true if @p Val is a tree of AND/OR/SETCC operations.
1386/// CanPushNegate is set to true if we can push a negate operation through
1387/// the tree in a was that we are left with AND operations and negate operations
1388/// at the leafs only. i.e. "not (or (or x y) z)" can be changed to
1389/// "and (and (not x) (not y)) (not z)"; "not (or (and x y) z)" cannot be
1390/// brought into such a form.
Matthias Braunfdef49b2016-01-23 04:05:22 +00001391static bool isConjunctionDisjunctionTree(const SDValue Val, bool &CanNegate,
Matthias Braunaf7d7702015-07-16 20:02:37 +00001392 unsigned Depth = 0) {
1393 if (!Val.hasOneUse())
1394 return false;
1395 unsigned Opcode = Val->getOpcode();
1396 if (Opcode == ISD::SETCC) {
Ahmed Bougacha171f7b92016-03-11 22:02:58 +00001397 if (Val->getOperand(0).getValueType() == MVT::f128)
1398 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001399 CanNegate = true;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001400 return true;
1401 }
Matthias Braun985bdf92016-01-23 04:05:18 +00001402 // Protect against exponential runtime and stack overflow.
1403 if (Depth > 6)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001404 return false;
1405 if (Opcode == ISD::AND || Opcode == ISD::OR) {
1406 SDValue O0 = Val->getOperand(0);
1407 SDValue O1 = Val->getOperand(1);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001408 bool CanNegateL;
1409 if (!isConjunctionDisjunctionTree(O0, CanNegateL, Depth+1))
Matthias Braunaf7d7702015-07-16 20:02:37 +00001410 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001411 bool CanNegateR;
1412 if (!isConjunctionDisjunctionTree(O1, CanNegateR, Depth+1))
Matthias Braunaf7d7702015-07-16 20:02:37 +00001413 return false;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001414
1415 if (Opcode == ISD::OR) {
1416 // For an OR expression we need to be able to negate at least one side or
1417 // we cannot do the transformation at all.
1418 if (!CanNegateL && !CanNegateR)
1419 return false;
1420 // We can however change a (not (or x y)) to (and (not x) (not y)) if we
1421 // can negate the x and y subtrees.
1422 CanNegate = CanNegateL && CanNegateR;
1423 } else {
1424 // If the operands are OR expressions then we finally need to negate their
1425 // outputs, we can only do that for the operand with emitted last by
1426 // negating OutCC, not for both operands.
1427 bool NeedsNegOutL = O0->getOpcode() == ISD::OR;
1428 bool NeedsNegOutR = O1->getOpcode() == ISD::OR;
1429 if (NeedsNegOutL && NeedsNegOutR)
1430 return false;
1431 // We cannot negate an AND operation (it would become an OR),
1432 CanNegate = false;
1433 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001434 return true;
1435 }
1436 return false;
1437}
1438
1439/// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1440/// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1441/// Tries to transform the given i1 producing node @p Val to a series compare
1442/// and conditional compare operations. @returns an NZCV flags producing node
1443/// and sets @p OutCC to the flags that should be tested or returns SDValue() if
1444/// transformation was not possible.
1445/// On recursive invocations @p PushNegate may be set to true to have negation
1446/// effects pushed to the tree leafs; @p Predicate is an NZCV flag predicate
1447/// for the comparisons in the current subtree; @p Depth limits the search
1448/// depth to avoid stack overflow.
Matthias Braunfdef49b2016-01-23 04:05:22 +00001449static SDValue emitConjunctionDisjunctionTreeRec(SelectionDAG &DAG, SDValue Val,
1450 AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp,
1451 AArch64CC::CondCode Predicate) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001452 // We're at a tree leaf, produce a conditional comparison operation.
1453 unsigned Opcode = Val->getOpcode();
1454 if (Opcode == ISD::SETCC) {
1455 SDValue LHS = Val->getOperand(0);
1456 SDValue RHS = Val->getOperand(1);
1457 ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
1458 bool isInteger = LHS.getValueType().isInteger();
Matthias Braunfdef49b2016-01-23 04:05:22 +00001459 if (Negate)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001460 CC = getSetCCInverse(CC, isInteger);
1461 SDLoc DL(Val);
1462 // Determine OutCC and handle FP special case.
1463 if (isInteger) {
1464 OutCC = changeIntCCToAArch64CC(CC);
1465 } else {
1466 assert(LHS.getValueType().isFloatingPoint());
1467 AArch64CC::CondCode ExtraCC;
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001468 changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
1469 // Some floating point conditions can't be tested with a single condition
1470 // code. Construct an additional comparison in this case.
Matthias Braunaf7d7702015-07-16 20:02:37 +00001471 if (ExtraCC != AArch64CC::AL) {
1472 SDValue ExtraCmp;
1473 if (!CCOp.getNode())
1474 ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001475 else
1476 ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate,
1477 ExtraCC, DL, DAG);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001478 CCOp = ExtraCmp;
Ahmed Bougacha99209b92016-01-22 19:43:54 +00001479 Predicate = ExtraCC;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001480 }
1481 }
1482
1483 // Produce a normal comparison if we are first in the chain
Matthias Braunfdef49b2016-01-23 04:05:22 +00001484 if (!CCOp)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001485 return emitComparison(LHS, RHS, CC, DL, DAG);
1486 // Otherwise produce a ccmp.
Ahmed Bougacha78d6efd2016-01-22 19:43:57 +00001487 return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL,
Matthias Braunaf7d7702015-07-16 20:02:37 +00001488 DAG);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001489 }
Junmo Park3ca3e192016-01-25 10:17:17 +00001490 assert((Opcode == ISD::AND || (Opcode == ISD::OR && Val->hasOneUse())) &&
1491 "Valid conjunction/disjunction tree");
Matthias Braunaf7d7702015-07-16 20:02:37 +00001492
1493 // Check if both sides can be transformed.
1494 SDValue LHS = Val->getOperand(0);
1495 SDValue RHS = Val->getOperand(1);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001496
Matthias Braunfdef49b2016-01-23 04:05:22 +00001497 // In case of an OR we need to negate our operands and the result.
1498 // (A v B) <=> not(not(A) ^ not(B))
1499 bool NegateOpsAndResult = Opcode == ISD::OR;
Matthias Braunaf7d7702015-07-16 20:02:37 +00001500 // We can negate the results of all previous operations by inverting the
Matthias Braunfdef49b2016-01-23 04:05:22 +00001501 // predicate flags giving us a free negation for one side. The other side
1502 // must be negatable by itself.
1503 if (NegateOpsAndResult) {
1504 // See which side we can negate.
1505 bool CanNegateL;
1506 bool isValidL = isConjunctionDisjunctionTree(LHS, CanNegateL);
1507 assert(isValidL && "Valid conjunction/disjunction tree");
1508 (void)isValidL;
1509
1510#ifndef NDEBUG
1511 bool CanNegateR;
1512 bool isValidR = isConjunctionDisjunctionTree(RHS, CanNegateR);
1513 assert(isValidR && "Valid conjunction/disjunction tree");
1514 assert((CanNegateL || CanNegateR) && "Valid conjunction/disjunction tree");
1515#endif
1516
1517 // Order the side which we cannot negate to RHS so we can emit it first.
1518 if (!CanNegateL)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001519 std::swap(LHS, RHS);
Matthias Braun46e56392015-08-20 23:33:34 +00001520 } else {
1521 bool NeedsNegOutL = LHS->getOpcode() == ISD::OR;
Matthias Braun327bca72016-01-23 06:49:29 +00001522 assert((!NeedsNegOutL || RHS->getOpcode() != ISD::OR) &&
Matthias Braunfdef49b2016-01-23 04:05:22 +00001523 "Valid conjunction/disjunction tree");
Matthias Braun46e56392015-08-20 23:33:34 +00001524 // Order the side where we need to negate the output flags to RHS so it
1525 // gets emitted first.
1526 if (NeedsNegOutL)
1527 std::swap(LHS, RHS);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001528 }
1529
1530 // Emit RHS. If we want to negate the tree we only need to push a negate
1531 // through if we are already in a PushNegate case, otherwise we can negate
1532 // the "flags to test" afterwards.
1533 AArch64CC::CondCode RHSCC;
Matthias Braunfdef49b2016-01-23 04:05:22 +00001534 SDValue CmpR = emitConjunctionDisjunctionTreeRec(DAG, RHS, RHSCC, Negate,
1535 CCOp, Predicate);
1536 if (NegateOpsAndResult && !Negate)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001537 RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
Matthias Braunfdef49b2016-01-23 04:05:22 +00001538 // Emit LHS. We may need to negate it.
1539 SDValue CmpL = emitConjunctionDisjunctionTreeRec(DAG, LHS, OutCC,
1540 NegateOpsAndResult, CmpR,
1541 RHSCC);
Matthias Braunaf7d7702015-07-16 20:02:37 +00001542 // If we transformed an OR to and AND then we have to negate the result
Matthias Braunfdef49b2016-01-23 04:05:22 +00001543 // (or absorb the Negate parameter).
1544 if (NegateOpsAndResult && !Negate)
Matthias Braunaf7d7702015-07-16 20:02:37 +00001545 OutCC = AArch64CC::getInvertedCondCode(OutCC);
1546 return CmpL;
1547}
1548
Matthias Braunfdef49b2016-01-23 04:05:22 +00001549/// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
1550/// of CCMP/CFCMP ops. See @ref AArch64CCMP.
1551/// \see emitConjunctionDisjunctionTreeRec().
1552static SDValue emitConjunctionDisjunctionTree(SelectionDAG &DAG, SDValue Val,
1553 AArch64CC::CondCode &OutCC) {
1554 bool CanNegate;
1555 if (!isConjunctionDisjunctionTree(Val, CanNegate))
1556 return SDValue();
1557
1558 return emitConjunctionDisjunctionTreeRec(DAG, Val, OutCC, false, SDValue(),
1559 AArch64CC::AL);
1560}
1561
Matthias Braunaf7d7702015-07-16 20:02:37 +00001562/// @}
1563
Tim Northover3b0846e2014-05-24 12:50:23 +00001564static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00001565 SDValue &AArch64cc, SelectionDAG &DAG,
1566 const SDLoc &dl) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001567 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
1568 EVT VT = RHS.getValueType();
1569 uint64_t C = RHSC->getZExtValue();
1570 if (!isLegalArithImmed(C)) {
1571 // Constant does not fit, try adjusting it by one?
1572 switch (CC) {
1573 default:
1574 break;
1575 case ISD::SETLT:
1576 case ISD::SETGE:
1577 if ((VT == MVT::i32 && C != 0x80000000 &&
1578 isLegalArithImmed((uint32_t)(C - 1))) ||
1579 (VT == MVT::i64 && C != 0x80000000ULL &&
1580 isLegalArithImmed(C - 1ULL))) {
1581 CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
1582 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001583 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001584 }
1585 break;
1586 case ISD::SETULT:
1587 case ISD::SETUGE:
1588 if ((VT == MVT::i32 && C != 0 &&
1589 isLegalArithImmed((uint32_t)(C - 1))) ||
1590 (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
1591 CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
1592 C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001593 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001594 }
1595 break;
1596 case ISD::SETLE:
1597 case ISD::SETGT:
Oliver Stannard269a275c2014-11-03 15:28:40 +00001598 if ((VT == MVT::i32 && C != INT32_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001599 isLegalArithImmed((uint32_t)(C + 1))) ||
Oliver Stannard269a275c2014-11-03 15:28:40 +00001600 (VT == MVT::i64 && C != INT64_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001601 isLegalArithImmed(C + 1ULL))) {
1602 CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
1603 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001604 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001605 }
1606 break;
1607 case ISD::SETULE:
1608 case ISD::SETUGT:
Oliver Stannard269a275c2014-11-03 15:28:40 +00001609 if ((VT == MVT::i32 && C != UINT32_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001610 isLegalArithImmed((uint32_t)(C + 1))) ||
Oliver Stannard269a275c2014-11-03 15:28:40 +00001611 (VT == MVT::i64 && C != UINT64_MAX &&
Tim Northover3b0846e2014-05-24 12:50:23 +00001612 isLegalArithImmed(C + 1ULL))) {
1613 CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
1614 C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001615 RHS = DAG.getConstant(C, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00001616 }
1617 break;
1618 }
1619 }
1620 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001621 SDValue Cmp;
1622 AArch64CC::CondCode AArch64CC;
David Xuee978202014-08-28 04:59:53 +00001623 if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
Matthias Braunaf7d7702015-07-16 20:02:37 +00001624 const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
1625
1626 // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
1627 // For the i8 operand, the largest immediate is 255, so this can be easily
1628 // encoded in the compare instruction. For the i16 operand, however, the
1629 // largest immediate cannot be encoded in the compare.
1630 // Therefore, use a sign extending load and cmn to avoid materializing the
1631 // -1 constant. For example,
1632 // movz w1, #65535
1633 // ldrh w0, [x0, #0]
1634 // cmp w0, w1
1635 // >
1636 // ldrsh w0, [x0, #0]
1637 // cmn w0, #1
1638 // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
1639 // if and only if (sext LHS) == (sext RHS). The checks are in place to
Benjamin Kramerdf005cb2015-08-08 18:27:36 +00001640 // ensure both the LHS and RHS are truly zero extended and to make sure the
Matthias Braunaf7d7702015-07-16 20:02:37 +00001641 // transformation is profitable.
1642 if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
1643 cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
1644 cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
1645 LHS.getNode()->hasNUsesOfValue(1, 0)) {
1646 int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
1647 if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
1648 SDValue SExt =
1649 DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
1650 DAG.getValueType(MVT::i16));
1651 Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
1652 RHS.getValueType()),
1653 CC, dl, DAG);
1654 AArch64CC = changeIntCCToAArch64CC(CC);
1655 }
1656 }
1657
1658 if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
1659 if ((Cmp = emitConjunctionDisjunctionTree(DAG, LHS, AArch64CC))) {
1660 if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
1661 AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
David Xuee978202014-08-28 04:59:53 +00001662 }
1663 }
1664 }
Matthias Braunaf7d7702015-07-16 20:02:37 +00001665
1666 if (!Cmp) {
1667 Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
1668 AArch64CC = changeIntCCToAArch64CC(CC);
1669 }
1670 AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
Tim Northover3b0846e2014-05-24 12:50:23 +00001671 return Cmp;
1672}
1673
1674static std::pair<SDValue, SDValue>
1675getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
1676 assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
1677 "Unsupported value type");
1678 SDValue Value, Overflow;
1679 SDLoc DL(Op);
1680 SDValue LHS = Op.getOperand(0);
1681 SDValue RHS = Op.getOperand(1);
1682 unsigned Opc = 0;
1683 switch (Op.getOpcode()) {
1684 default:
1685 llvm_unreachable("Unknown overflow instruction!");
1686 case ISD::SADDO:
1687 Opc = AArch64ISD::ADDS;
1688 CC = AArch64CC::VS;
1689 break;
1690 case ISD::UADDO:
1691 Opc = AArch64ISD::ADDS;
1692 CC = AArch64CC::HS;
1693 break;
1694 case ISD::SSUBO:
1695 Opc = AArch64ISD::SUBS;
1696 CC = AArch64CC::VS;
1697 break;
1698 case ISD::USUBO:
1699 Opc = AArch64ISD::SUBS;
1700 CC = AArch64CC::LO;
1701 break;
1702 // Multiply needs a little bit extra work.
1703 case ISD::SMULO:
1704 case ISD::UMULO: {
1705 CC = AArch64CC::NE;
David Blaikie186d2cb2015-03-24 16:24:01 +00001706 bool IsSigned = Op.getOpcode() == ISD::SMULO;
Tim Northover3b0846e2014-05-24 12:50:23 +00001707 if (Op.getValueType() == MVT::i32) {
1708 unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
1709 // For a 32 bit multiply with overflow check we want the instruction
1710 // selector to generate a widening multiply (SMADDL/UMADDL). For that we
1711 // need to generate the following pattern:
1712 // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
1713 LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
1714 RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
1715 SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1716 SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001717 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001718 // On AArch64 the upper 32 bits are always zero extended for a 32 bit
1719 // operation. We need to clear out the upper 32 bits, because we used a
1720 // widening multiply that wrote all 64 bits. In the end this should be a
1721 // noop.
1722 Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
1723 if (IsSigned) {
1724 // The signed overflow check requires more than just a simple check for
1725 // any bit set in the upper 32 bits of the result. These bits could be
1726 // just the sign bits of a negative number. To perform the overflow
1727 // check we have to arithmetic shift right the 32nd bit of the result by
1728 // 31 bits. Then we compare the result to the upper 32 bits.
1729 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001730 DAG.getConstant(32, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001731 UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
1732 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001733 DAG.getConstant(31, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001734 // It is important that LowerBits is last, otherwise the arithmetic
1735 // shift will not be folded into the compare (SUBS).
1736 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
1737 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1738 .getValue(1);
1739 } else {
1740 // The overflow check for unsigned multiply is easy. We only need to
1741 // check if any of the upper 32 bits are set. This can be done with a
1742 // CMP (shifted register). For that we need to generate the following
1743 // pattern:
1744 // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
1745 SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001746 DAG.getConstant(32, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001747 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1748 Overflow =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001749 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1750 DAG.getConstant(0, DL, MVT::i64),
Tim Northover3b0846e2014-05-24 12:50:23 +00001751 UpperBits).getValue(1);
1752 }
1753 break;
1754 }
1755 assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
1756 // For the 64 bit multiply
1757 Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
1758 if (IsSigned) {
1759 SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
1760 SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001761 DAG.getConstant(63, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00001762 // It is important that LowerBits is last, otherwise the arithmetic
1763 // shift will not be folded into the compare (SUBS).
1764 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1765 Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
1766 .getValue(1);
1767 } else {
1768 SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
1769 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
1770 Overflow =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001771 DAG.getNode(AArch64ISD::SUBS, DL, VTs,
1772 DAG.getConstant(0, DL, MVT::i64),
Tim Northover3b0846e2014-05-24 12:50:23 +00001773 UpperBits).getValue(1);
1774 }
1775 break;
1776 }
1777 } // switch (...)
1778
1779 if (Opc) {
1780 SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
1781
1782 // Emit the AArch64 operation with overflow check.
1783 Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
1784 Overflow = Value.getValue(1);
1785 }
1786 return std::make_pair(Value, Overflow);
1787}
1788
1789SDValue AArch64TargetLowering::LowerF128Call(SDValue Op, SelectionDAG &DAG,
1790 RTLIB::Libcall Call) const {
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00001791 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
Craig Topper8fe40e02015-10-22 17:05:00 +00001792 return makeLibCall(DAG, Call, MVT::f128, Ops, false, SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00001793}
1794
1795static SDValue LowerXOR(SDValue Op, SelectionDAG &DAG) {
1796 SDValue Sel = Op.getOperand(0);
1797 SDValue Other = Op.getOperand(1);
1798
1799 // If neither operand is a SELECT_CC, give up.
1800 if (Sel.getOpcode() != ISD::SELECT_CC)
1801 std::swap(Sel, Other);
1802 if (Sel.getOpcode() != ISD::SELECT_CC)
1803 return Op;
1804
1805 // The folding we want to perform is:
1806 // (xor x, (select_cc a, b, cc, 0, -1) )
1807 // -->
1808 // (csel x, (xor x, -1), cc ...)
1809 //
1810 // The latter will get matched to a CSINV instruction.
1811
1812 ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
1813 SDValue LHS = Sel.getOperand(0);
1814 SDValue RHS = Sel.getOperand(1);
1815 SDValue TVal = Sel.getOperand(2);
1816 SDValue FVal = Sel.getOperand(3);
1817 SDLoc dl(Sel);
1818
1819 // FIXME: This could be generalized to non-integer comparisons.
1820 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
1821 return Op;
1822
1823 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
1824 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
1825
Eric Christopher572e03a2015-06-19 01:53:21 +00001826 // The values aren't constants, this isn't the pattern we're looking for.
Tim Northover3b0846e2014-05-24 12:50:23 +00001827 if (!CFVal || !CTVal)
1828 return Op;
1829
1830 // We can commute the SELECT_CC by inverting the condition. This
1831 // might be needed to make this fit into a CSINV pattern.
1832 if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
1833 std::swap(TVal, FVal);
1834 std::swap(CTVal, CFVal);
1835 CC = ISD::getSetCCInverse(CC, true);
1836 }
1837
1838 // If the constants line up, perform the transform!
1839 if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
1840 SDValue CCVal;
1841 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
1842
1843 FVal = Other;
1844 TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001845 DAG.getConstant(-1ULL, dl, Other.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00001846
1847 return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
1848 CCVal, Cmp);
1849 }
1850
1851 return Op;
1852}
1853
1854static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
1855 EVT VT = Op.getValueType();
1856
1857 // Let legalize expand this if it isn't a legal type yet.
1858 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
1859 return SDValue();
1860
1861 SDVTList VTs = DAG.getVTList(VT, MVT::i32);
1862
1863 unsigned Opc;
1864 bool ExtraOp = false;
1865 switch (Op.getOpcode()) {
1866 default:
Craig Topper2a30d782014-06-18 05:05:13 +00001867 llvm_unreachable("Invalid code");
Tim Northover3b0846e2014-05-24 12:50:23 +00001868 case ISD::ADDC:
1869 Opc = AArch64ISD::ADDS;
1870 break;
1871 case ISD::SUBC:
1872 Opc = AArch64ISD::SUBS;
1873 break;
1874 case ISD::ADDE:
1875 Opc = AArch64ISD::ADCS;
1876 ExtraOp = true;
1877 break;
1878 case ISD::SUBE:
1879 Opc = AArch64ISD::SBCS;
1880 ExtraOp = true;
1881 break;
1882 }
1883
1884 if (!ExtraOp)
1885 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
1886 return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
1887 Op.getOperand(2));
1888}
1889
1890static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
1891 // Let legalize expand this if it isn't a legal type yet.
1892 if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
1893 return SDValue();
1894
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001895 SDLoc dl(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00001896 AArch64CC::CondCode CC;
1897 // The actual operation that sets the overflow or carry flag.
1898 SDValue Value, Overflow;
1899 std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
1900
1901 // We use 0 and 1 as false and true values.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001902 SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
1903 SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00001904
1905 // We use an inverted condition, because the conditional select is inverted
1906 // too. This will allow it to be selected to a single instruction:
1907 // CSINC Wd, WZR, WZR, invert(cond).
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001908 SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
1909 Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
Tim Northover3b0846e2014-05-24 12:50:23 +00001910 CCVal, Overflow);
1911
1912 SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001913 return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
Tim Northover3b0846e2014-05-24 12:50:23 +00001914}
1915
1916// Prefetch operands are:
1917// 1: Address to prefetch
1918// 2: bool isWrite
1919// 3: int locality (0 = no locality ... 3 = extreme locality)
1920// 4: bool isDataCache
1921static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
1922 SDLoc DL(Op);
1923 unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
1924 unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
Yi Konge56de692014-08-05 12:46:47 +00001925 unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00001926
1927 bool IsStream = !Locality;
1928 // When the locality number is set
1929 if (Locality) {
1930 // The front-end should have filtered out the out-of-range values
1931 assert(Locality <= 3 && "Prefetch locality out-of-range");
1932 // The locality degree is the opposite of the cache speed.
1933 // Put the number the other way around.
1934 // The encoding starts at 0 for level 1
1935 Locality = 3 - Locality;
1936 }
1937
1938 // built the mask value encoding the expected behavior.
1939 unsigned PrfOp = (IsWrite << 4) | // Load/Store bit
Yi Konge56de692014-08-05 12:46:47 +00001940 (!IsData << 3) | // IsDataCache bit
Tim Northover3b0846e2014-05-24 12:50:23 +00001941 (Locality << 1) | // Cache level bits
1942 (unsigned)IsStream; // Stream bit
1943 return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00001944 DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00001945}
1946
1947SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
1948 SelectionDAG &DAG) const {
1949 assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
1950
1951 RTLIB::Libcall LC;
1952 LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
1953
1954 return LowerF128Call(Op, DAG, LC);
1955}
1956
1957SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
1958 SelectionDAG &DAG) const {
1959 if (Op.getOperand(0).getValueType() != MVT::f128) {
1960 // It's legal except when f128 is involved
1961 return Op;
1962 }
1963
1964 RTLIB::Libcall LC;
1965 LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
1966
1967 // FP_ROUND node has a second operand indicating whether it is known to be
1968 // precise. That doesn't take part in the LibCall so we can't directly use
1969 // LowerF128Call.
1970 SDValue SrcVal = Op.getOperand(0);
Craig Topper8fe40e02015-10-22 17:05:00 +00001971 return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
1972 SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00001973}
1974
1975static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
1976 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
1977 // Any additional optimization in this function should be recorded
1978 // in the cost tables.
1979 EVT InVT = Op.getOperand(0).getValueType();
1980 EVT VT = Op.getValueType();
Pirama Arumuga Nainar1317d5f2015-12-10 17:16:49 +00001981 unsigned NumElts = InVT.getVectorNumElements();
1982
1983 // f16 vectors are promoted to f32 before a conversion.
1984 if (InVT.getVectorElementType() == MVT::f16) {
1985 MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
1986 SDLoc dl(Op);
1987 return DAG.getNode(
1988 Op.getOpcode(), dl, Op.getValueType(),
1989 DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
1990 }
Tim Northover3b0846e2014-05-24 12:50:23 +00001991
Tim Northoverdbecc3b2014-06-15 09:27:15 +00001992 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00001993 SDLoc dl(Op);
1994 SDValue Cv =
1995 DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
1996 Op.getOperand(0));
1997 return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
Tim Northoverdbecc3b2014-06-15 09:27:15 +00001998 }
1999
2000 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00002001 SDLoc dl(Op);
Oliver Stannard89d15422014-08-27 16:16:04 +00002002 MVT ExtVT =
2003 MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
2004 VT.getVectorNumElements());
2005 SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
Tim Northover3b0846e2014-05-24 12:50:23 +00002006 return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
2007 }
2008
2009 // Type changing conversions are illegal.
Tim Northoverdbecc3b2014-06-15 09:27:15 +00002010 return Op;
Tim Northover3b0846e2014-05-24 12:50:23 +00002011}
2012
2013SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
2014 SelectionDAG &DAG) const {
2015 if (Op.getOperand(0).getValueType().isVector())
2016 return LowerVectorFP_TO_INT(Op, DAG);
2017
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00002018 // f16 conversions are promoted to f32.
2019 if (Op.getOperand(0).getValueType() == MVT::f16) {
2020 SDLoc dl(Op);
2021 return DAG.getNode(
2022 Op.getOpcode(), dl, Op.getValueType(),
2023 DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, Op.getOperand(0)));
2024 }
2025
Tim Northover3b0846e2014-05-24 12:50:23 +00002026 if (Op.getOperand(0).getValueType() != MVT::f128) {
2027 // It's legal except when f128 is involved
2028 return Op;
2029 }
2030
2031 RTLIB::Libcall LC;
2032 if (Op.getOpcode() == ISD::FP_TO_SINT)
2033 LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(), Op.getValueType());
2034 else
2035 LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(), Op.getValueType());
2036
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002037 SmallVector<SDValue, 2> Ops(Op->op_begin(), Op->op_end());
Craig Topper8fe40e02015-10-22 17:05:00 +00002038 return makeLibCall(DAG, LC, Op.getValueType(), Ops, false, SDLoc(Op)).first;
Tim Northover3b0846e2014-05-24 12:50:23 +00002039}
2040
2041static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
2042 // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
2043 // Any additional optimization in this function should be recorded
2044 // in the cost tables.
2045 EVT VT = Op.getValueType();
2046 SDLoc dl(Op);
2047 SDValue In = Op.getOperand(0);
2048 EVT InVT = In.getValueType();
2049
Tim Northoveref0d7602014-06-15 09:27:06 +00002050 if (VT.getSizeInBits() < InVT.getSizeInBits()) {
2051 MVT CastVT =
2052 MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
2053 InVT.getVectorNumElements());
2054 In = DAG.getNode(Op.getOpcode(), dl, CastVT, In);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002055 return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
Tim Northover3b0846e2014-05-24 12:50:23 +00002056 }
2057
Tim Northoveref0d7602014-06-15 09:27:06 +00002058 if (VT.getSizeInBits() > InVT.getSizeInBits()) {
2059 unsigned CastOpc =
2060 Op.getOpcode() == ISD::SINT_TO_FP ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
2061 EVT CastVT = VT.changeVectorElementTypeToInteger();
2062 In = DAG.getNode(CastOpc, dl, CastVT, In);
2063 return DAG.getNode(Op.getOpcode(), dl, VT, In);
Tim Northover3b0846e2014-05-24 12:50:23 +00002064 }
2065
Tim Northoveref0d7602014-06-15 09:27:06 +00002066 return Op;
Tim Northover3b0846e2014-05-24 12:50:23 +00002067}
2068
2069SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
2070 SelectionDAG &DAG) const {
2071 if (Op.getValueType().isVector())
2072 return LowerVectorINT_TO_FP(Op, DAG);
2073
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00002074 // f16 conversions are promoted to f32.
2075 if (Op.getValueType() == MVT::f16) {
2076 SDLoc dl(Op);
2077 return DAG.getNode(
2078 ISD::FP_ROUND, dl, MVT::f16,
2079 DAG.getNode(Op.getOpcode(), dl, MVT::f32, Op.getOperand(0)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002080 DAG.getIntPtrConstant(0, dl));
Ahmed Bougacha1ffe7c72015-04-10 00:08:48 +00002081 }
2082
Tim Northover3b0846e2014-05-24 12:50:23 +00002083 // i128 conversions are libcalls.
2084 if (Op.getOperand(0).getValueType() == MVT::i128)
2085 return SDValue();
2086
2087 // Other conversions are legal, unless it's to the completely software-based
2088 // fp128.
2089 if (Op.getValueType() != MVT::f128)
2090 return Op;
2091
2092 RTLIB::Libcall LC;
2093 if (Op.getOpcode() == ISD::SINT_TO_FP)
2094 LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2095 else
2096 LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(), Op.getValueType());
2097
2098 return LowerF128Call(Op, DAG, LC);
2099}
2100
2101SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
2102 SelectionDAG &DAG) const {
2103 // For iOS, we want to call an alternative entry point: __sincos_stret,
2104 // which returns the values in two S / D registers.
2105 SDLoc dl(Op);
2106 SDValue Arg = Op.getOperand(0);
2107 EVT ArgVT = Arg.getValueType();
2108 Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2109
2110 ArgListTy Args;
2111 ArgListEntry Entry;
2112
2113 Entry.Node = Arg;
2114 Entry.Ty = ArgTy;
Nirav Dave6de2c772017-03-18 00:43:57 +00002115 Entry.IsSExt = false;
2116 Entry.IsZExt = false;
Tim Northover3b0846e2014-05-24 12:50:23 +00002117 Args.push_back(Entry);
2118
2119 const char *LibcallName =
2120 (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
Mehdi Amini44ede332015-07-09 02:09:04 +00002121 SDValue Callee =
2122 DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00002123
Reid Kleckner343c3952014-11-20 23:51:47 +00002124 StructType *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
Tim Northover3b0846e2014-05-24 12:50:23 +00002125 TargetLowering::CallLoweringInfo CLI(DAG);
Nirav Daveac6081c2017-03-18 00:44:07 +00002126 CLI.setDebugLoc(dl)
2127 .setChain(DAG.getEntryNode())
2128 .setLibCallee(CallingConv::Fast, RetTy, Callee, std::move(Args));
Tim Northover3b0846e2014-05-24 12:50:23 +00002129
2130 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2131 return CallResult.first;
2132}
2133
Tim Northoverf8bfe212014-07-18 13:07:05 +00002134static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
2135 if (Op.getValueType() != MVT::f16)
2136 return SDValue();
2137
2138 assert(Op.getOperand(0).getValueType() == MVT::i16);
2139 SDLoc DL(Op);
2140
2141 Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
2142 Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
2143 return SDValue(
2144 DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, MVT::f16, Op,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002145 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
Tim Northoverf8bfe212014-07-18 13:07:05 +00002146 0);
2147}
2148
Chad Rosierd9d0f862014-10-08 02:31:24 +00002149static EVT getExtensionTo64Bits(const EVT &OrigVT) {
2150 if (OrigVT.getSizeInBits() >= 64)
2151 return OrigVT;
2152
2153 assert(OrigVT.isSimple() && "Expecting a simple value type");
2154
2155 MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
2156 switch (OrigSimpleTy) {
2157 default: llvm_unreachable("Unexpected Vector Type");
2158 case MVT::v2i8:
2159 case MVT::v2i16:
2160 return MVT::v2i32;
2161 case MVT::v4i8:
2162 return MVT::v4i16;
2163 }
2164}
2165
2166static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
2167 const EVT &OrigTy,
2168 const EVT &ExtTy,
2169 unsigned ExtOpcode) {
2170 // The vector originally had a size of OrigTy. It was then extended to ExtTy.
2171 // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
2172 // 64-bits we need to insert a new extension so that it will be 64-bits.
2173 assert(ExtTy.is128BitVector() && "Unexpected extension size");
2174 if (OrigTy.getSizeInBits() >= 64)
2175 return N;
2176
2177 // Must extend size to at least 64 bits to be used as an operand for VMULL.
2178 EVT NewVT = getExtensionTo64Bits(OrigTy);
2179
2180 return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
2181}
2182
2183static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
2184 bool isSigned) {
2185 EVT VT = N->getValueType(0);
2186
2187 if (N->getOpcode() != ISD::BUILD_VECTOR)
2188 return false;
2189
Pete Cooper3af9a252015-06-26 18:17:36 +00002190 for (const SDValue &Elt : N->op_values()) {
Chad Rosierd9d0f862014-10-08 02:31:24 +00002191 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
Sanjay Patel1ed771f2016-09-14 16:37:15 +00002192 unsigned EltSize = VT.getScalarSizeInBits();
Chad Rosierd9d0f862014-10-08 02:31:24 +00002193 unsigned HalfSize = EltSize / 2;
2194 if (isSigned) {
2195 if (!isIntN(HalfSize, C->getSExtValue()))
2196 return false;
2197 } else {
2198 if (!isUIntN(HalfSize, C->getZExtValue()))
2199 return false;
2200 }
2201 continue;
2202 }
2203 return false;
2204 }
2205
2206 return true;
2207}
2208
2209static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
2210 if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
2211 return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
2212 N->getOperand(0)->getValueType(0),
2213 N->getValueType(0),
2214 N->getOpcode());
2215
2216 assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
2217 EVT VT = N->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002218 SDLoc dl(N);
Sanjay Patel1ed771f2016-09-14 16:37:15 +00002219 unsigned EltSize = VT.getScalarSizeInBits() / 2;
Chad Rosierd9d0f862014-10-08 02:31:24 +00002220 unsigned NumElts = VT.getVectorNumElements();
2221 MVT TruncVT = MVT::getIntegerVT(EltSize);
2222 SmallVector<SDValue, 8> Ops;
2223 for (unsigned i = 0; i != NumElts; ++i) {
2224 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
2225 const APInt &CInt = C->getAPIntValue();
2226 // Element types smaller than 32 bits are not legal, so use i32 elements.
2227 // The values are implicitly truncated so sext vs. zext doesn't matter.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00002228 Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
Chad Rosierd9d0f862014-10-08 02:31:24 +00002229 }
Ahmed Bougacha128f8732016-04-26 21:15:30 +00002230 return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002231}
2232
2233static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
Davide Italianode056862017-03-30 19:46:18 +00002234 return N->getOpcode() == ISD::SIGN_EXTEND ||
2235 isExtendedBUILD_VECTOR(N, DAG, true);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002236}
2237
2238static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
Davide Italianode056862017-03-30 19:46:18 +00002239 return N->getOpcode() == ISD::ZERO_EXTEND ||
2240 isExtendedBUILD_VECTOR(N, DAG, false);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002241}
2242
2243static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
2244 unsigned Opcode = N->getOpcode();
2245 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2246 SDNode *N0 = N->getOperand(0).getNode();
2247 SDNode *N1 = N->getOperand(1).getNode();
2248 return N0->hasOneUse() && N1->hasOneUse() &&
2249 isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
2250 }
2251 return false;
2252}
2253
2254static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
2255 unsigned Opcode = N->getOpcode();
2256 if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
2257 SDNode *N0 = N->getOperand(0).getNode();
2258 SDNode *N1 = N->getOperand(1).getNode();
2259 return N0->hasOneUse() && N1->hasOneUse() &&
2260 isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
2261 }
2262 return false;
2263}
2264
2265static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
2266 // Multiplications are only custom-lowered for 128-bit vectors so that
2267 // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
2268 EVT VT = Op.getValueType();
2269 assert(VT.is128BitVector() && VT.isInteger() &&
2270 "unexpected type for custom-lowering ISD::MUL");
2271 SDNode *N0 = Op.getOperand(0).getNode();
2272 SDNode *N1 = Op.getOperand(1).getNode();
2273 unsigned NewOpc = 0;
2274 bool isMLA = false;
2275 bool isN0SExt = isSignExtended(N0, DAG);
2276 bool isN1SExt = isSignExtended(N1, DAG);
2277 if (isN0SExt && isN1SExt)
2278 NewOpc = AArch64ISD::SMULL;
2279 else {
2280 bool isN0ZExt = isZeroExtended(N0, DAG);
2281 bool isN1ZExt = isZeroExtended(N1, DAG);
2282 if (isN0ZExt && isN1ZExt)
2283 NewOpc = AArch64ISD::UMULL;
2284 else if (isN1SExt || isN1ZExt) {
2285 // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
2286 // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
2287 if (isN1SExt && isAddSubSExt(N0, DAG)) {
2288 NewOpc = AArch64ISD::SMULL;
2289 isMLA = true;
2290 } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
2291 NewOpc = AArch64ISD::UMULL;
2292 isMLA = true;
2293 } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
2294 std::swap(N0, N1);
2295 NewOpc = AArch64ISD::UMULL;
2296 isMLA = true;
2297 }
2298 }
2299
2300 if (!NewOpc) {
2301 if (VT == MVT::v2i64)
2302 // Fall through to expand this. It is not legal.
2303 return SDValue();
2304 else
2305 // Other vector multiplications are legal.
2306 return Op;
2307 }
2308 }
2309
2310 // Legalize to a S/UMULL instruction
2311 SDLoc DL(Op);
2312 SDValue Op0;
2313 SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
2314 if (!isMLA) {
2315 Op0 = skipExtensionForVectorMULL(N0, DAG);
2316 assert(Op0.getValueType().is64BitVector() &&
2317 Op1.getValueType().is64BitVector() &&
2318 "unexpected types for extended operands to VMULL");
2319 return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
2320 }
2321 // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
2322 // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
2323 // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
2324 SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
2325 SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
2326 EVT Op1VT = Op1.getValueType();
2327 return DAG.getNode(N0->getOpcode(), DL, VT,
2328 DAG.getNode(NewOpc, DL, VT,
2329 DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
2330 DAG.getNode(NewOpc, DL, VT,
2331 DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
2332}
Tim Northoverf8bfe212014-07-18 13:07:05 +00002333
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002334SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2335 SelectionDAG &DAG) const {
2336 unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
2337 SDLoc dl(Op);
2338 switch (IntNo) {
2339 default: return SDValue(); // Don't custom lower most intrinsics.
Marcin Koscielnicki3fdc2572016-04-19 20:51:05 +00002340 case Intrinsic::thread_pointer: {
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002341 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2342 return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
2343 }
Silviu Barangadb1ddb32015-08-26 11:11:14 +00002344 case Intrinsic::aarch64_neon_smax:
2345 return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
2346 Op.getOperand(1), Op.getOperand(2));
2347 case Intrinsic::aarch64_neon_umax:
2348 return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
2349 Op.getOperand(1), Op.getOperand(2));
2350 case Intrinsic::aarch64_neon_smin:
2351 return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
2352 Op.getOperand(1), Op.getOperand(2));
2353 case Intrinsic::aarch64_neon_umin:
2354 return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
2355 Op.getOperand(1), Op.getOperand(2));
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002356 }
2357}
2358
Tim Northover3b0846e2014-05-24 12:50:23 +00002359SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
2360 SelectionDAG &DAG) const {
2361 switch (Op.getOpcode()) {
2362 default:
2363 llvm_unreachable("unimplemented operand");
2364 return SDValue();
Tim Northoverf8bfe212014-07-18 13:07:05 +00002365 case ISD::BITCAST:
2366 return LowerBITCAST(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002367 case ISD::GlobalAddress:
2368 return LowerGlobalAddress(Op, DAG);
2369 case ISD::GlobalTLSAddress:
2370 return LowerGlobalTLSAddress(Op, DAG);
2371 case ISD::SETCC:
2372 return LowerSETCC(Op, DAG);
2373 case ISD::BR_CC:
2374 return LowerBR_CC(Op, DAG);
2375 case ISD::SELECT:
2376 return LowerSELECT(Op, DAG);
2377 case ISD::SELECT_CC:
2378 return LowerSELECT_CC(Op, DAG);
2379 case ISD::JumpTable:
2380 return LowerJumpTable(Op, DAG);
2381 case ISD::ConstantPool:
2382 return LowerConstantPool(Op, DAG);
2383 case ISD::BlockAddress:
2384 return LowerBlockAddress(Op, DAG);
2385 case ISD::VASTART:
2386 return LowerVASTART(Op, DAG);
2387 case ISD::VACOPY:
2388 return LowerVACOPY(Op, DAG);
2389 case ISD::VAARG:
2390 return LowerVAARG(Op, DAG);
2391 case ISD::ADDC:
2392 case ISD::ADDE:
2393 case ISD::SUBC:
2394 case ISD::SUBE:
2395 return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
2396 case ISD::SADDO:
2397 case ISD::UADDO:
2398 case ISD::SSUBO:
2399 case ISD::USUBO:
2400 case ISD::SMULO:
2401 case ISD::UMULO:
2402 return LowerXALUO(Op, DAG);
2403 case ISD::FADD:
2404 return LowerF128Call(Op, DAG, RTLIB::ADD_F128);
2405 case ISD::FSUB:
2406 return LowerF128Call(Op, DAG, RTLIB::SUB_F128);
2407 case ISD::FMUL:
2408 return LowerF128Call(Op, DAG, RTLIB::MUL_F128);
2409 case ISD::FDIV:
2410 return LowerF128Call(Op, DAG, RTLIB::DIV_F128);
2411 case ISD::FP_ROUND:
2412 return LowerFP_ROUND(Op, DAG);
2413 case ISD::FP_EXTEND:
2414 return LowerFP_EXTEND(Op, DAG);
2415 case ISD::FRAMEADDR:
2416 return LowerFRAMEADDR(Op, DAG);
2417 case ISD::RETURNADDR:
2418 return LowerRETURNADDR(Op, DAG);
2419 case ISD::INSERT_VECTOR_ELT:
2420 return LowerINSERT_VECTOR_ELT(Op, DAG);
2421 case ISD::EXTRACT_VECTOR_ELT:
2422 return LowerEXTRACT_VECTOR_ELT(Op, DAG);
2423 case ISD::BUILD_VECTOR:
2424 return LowerBUILD_VECTOR(Op, DAG);
2425 case ISD::VECTOR_SHUFFLE:
2426 return LowerVECTOR_SHUFFLE(Op, DAG);
2427 case ISD::EXTRACT_SUBVECTOR:
2428 return LowerEXTRACT_SUBVECTOR(Op, DAG);
2429 case ISD::SRA:
2430 case ISD::SRL:
2431 case ISD::SHL:
2432 return LowerVectorSRA_SRL_SHL(Op, DAG);
2433 case ISD::SHL_PARTS:
2434 return LowerShiftLeftParts(Op, DAG);
2435 case ISD::SRL_PARTS:
2436 case ISD::SRA_PARTS:
2437 return LowerShiftRightParts(Op, DAG);
2438 case ISD::CTPOP:
2439 return LowerCTPOP(Op, DAG);
2440 case ISD::FCOPYSIGN:
2441 return LowerFCOPYSIGN(Op, DAG);
2442 case ISD::AND:
Balaram Makamd4acd7e2016-07-05 20:24:05 +00002443 return LowerVectorAND(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002444 case ISD::OR:
Balaram Makamd4acd7e2016-07-05 20:24:05 +00002445 return LowerVectorOR(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002446 case ISD::XOR:
2447 return LowerXOR(Op, DAG);
2448 case ISD::PREFETCH:
2449 return LowerPREFETCH(Op, DAG);
2450 case ISD::SINT_TO_FP:
2451 case ISD::UINT_TO_FP:
2452 return LowerINT_TO_FP(Op, DAG);
2453 case ISD::FP_TO_SINT:
2454 case ISD::FP_TO_UINT:
2455 return LowerFP_TO_INT(Op, DAG);
2456 case ISD::FSINCOS:
2457 return LowerFSINCOS(Op, DAG);
Chad Rosierd9d0f862014-10-08 02:31:24 +00002458 case ISD::MUL:
2459 return LowerMUL(Op, DAG);
Adhemerval Zanella7bc33192015-07-28 13:03:31 +00002460 case ISD::INTRINSIC_WO_CHAIN:
2461 return LowerINTRINSIC_WO_CHAIN(Op, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00002462 }
2463}
2464
Tim Northover3b0846e2014-05-24 12:50:23 +00002465//===----------------------------------------------------------------------===//
2466// Calling Convention Implementation
2467//===----------------------------------------------------------------------===//
2468
2469#include "AArch64GenCallingConv.inc"
2470
Robin Morisset039781e2014-08-29 21:53:01 +00002471/// Selects the correct CCAssignFn for a given CallingConvention value.
Tim Northover3b0846e2014-05-24 12:50:23 +00002472CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
2473 bool IsVarArg) const {
2474 switch (CC) {
2475 default:
2476 llvm_unreachable("Unsupported calling convention.");
2477 case CallingConv::WebKit_JS:
2478 return CC_AArch64_WebKit_JS;
Greg Fitzgeraldfa78d082015-01-19 17:40:05 +00002479 case CallingConv::GHC:
2480 return CC_AArch64_GHC;
Tim Northover3b0846e2014-05-24 12:50:23 +00002481 case CallingConv::C:
2482 case CallingConv::Fast:
Roman Levenstein2792b3f2016-03-10 04:35:09 +00002483 case CallingConv::PreserveMost:
Manman Ren2828c572016-03-18 23:38:49 +00002484 case CallingConv::CXX_FAST_TLS:
Manman Ren66b54e92016-08-26 19:28:17 +00002485 case CallingConv::Swift:
Tim Northover3b0846e2014-05-24 12:50:23 +00002486 if (!Subtarget->isTargetDarwin())
2487 return CC_AArch64_AAPCS;
2488 return IsVarArg ? CC_AArch64_DarwinPCS_VarArg : CC_AArch64_DarwinPCS;
2489 }
2490}
2491
Tim Northover406024a2016-08-10 21:44:01 +00002492CCAssignFn *
2493AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const {
2494 return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
2495 : RetCC_AArch64_AAPCS;
2496}
2497
Tim Northover3b0846e2014-05-24 12:50:23 +00002498SDValue AArch64TargetLowering::LowerFormalArguments(
2499 SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00002500 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2501 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00002502 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braun941a7052016-07-28 18:40:00 +00002503 MachineFrameInfo &MFI = MF.getFrameInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00002504
2505 // Assign locations to all of the incoming arguments.
2506 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002507 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2508 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002509
2510 // At this point, Ins[].VT may already be promoted to i32. To correctly
2511 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
2512 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
2513 // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
2514 // we use a special version of AnalyzeFormalArguments to pass in ValVT and
2515 // LocVT.
2516 unsigned NumArgs = Ins.size();
2517 Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
2518 unsigned CurArgIdx = 0;
2519 for (unsigned i = 0; i != NumArgs; ++i) {
2520 MVT ValVT = Ins[i].VT;
Andrew Trick05938a52015-02-16 18:10:47 +00002521 if (Ins[i].isOrigArg()) {
2522 std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
2523 CurArgIdx = Ins[i].getOrigArgIndex();
Tim Northover3b0846e2014-05-24 12:50:23 +00002524
Andrew Trick05938a52015-02-16 18:10:47 +00002525 // Get type of the original argument.
Mehdi Amini44ede332015-07-09 02:09:04 +00002526 EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
2527 /*AllowUnknown*/ true);
Andrew Trick05938a52015-02-16 18:10:47 +00002528 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
2529 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
2530 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
2531 ValVT = MVT::i8;
2532 else if (ActualMVT == MVT::i16)
2533 ValVT = MVT::i16;
2534 }
Tim Northover3b0846e2014-05-24 12:50:23 +00002535 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
2536 bool Res =
Tim Northover47e003c2014-05-26 17:21:53 +00002537 AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00002538 assert(!Res && "Call operand has unhandled type");
2539 (void)Res;
2540 }
2541 assert(ArgLocs.size() == Ins.size());
2542 SmallVector<SDValue, 16> ArgValues;
2543 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2544 CCValAssign &VA = ArgLocs[i];
2545
2546 if (Ins[i].Flags.isByVal()) {
2547 // Byval is used for HFAs in the PCS, but the system should work in a
2548 // non-compliant manner for larger structs.
Mehdi Amini44ede332015-07-09 02:09:04 +00002549 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00002550 int Size = Ins[i].Flags.getByValSize();
2551 unsigned NumRegs = (Size + 7) / 8;
2552
2553 // FIXME: This works on big-endian for composite byvals, which are the common
2554 // case. It should also work for fundamental types too.
2555 unsigned FrameIdx =
Matthias Braun941a7052016-07-28 18:40:00 +00002556 MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
Mehdi Amini44ede332015-07-09 02:09:04 +00002557 SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00002558 InVals.push_back(FrameIdxN);
2559
2560 continue;
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002561 }
Junmo Park3b8c7152016-01-05 09:36:47 +00002562
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002563 if (VA.isRegLoc()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00002564 // Arguments stored in registers.
2565 EVT RegVT = VA.getLocVT();
2566
2567 SDValue ArgValue;
2568 const TargetRegisterClass *RC;
2569
2570 if (RegVT == MVT::i32)
2571 RC = &AArch64::GPR32RegClass;
2572 else if (RegVT == MVT::i64)
2573 RC = &AArch64::GPR64RegClass;
Oliver Stannard6eda6ff2014-07-11 13:33:46 +00002574 else if (RegVT == MVT::f16)
2575 RC = &AArch64::FPR16RegClass;
Tim Northover3b0846e2014-05-24 12:50:23 +00002576 else if (RegVT == MVT::f32)
2577 RC = &AArch64::FPR32RegClass;
2578 else if (RegVT == MVT::f64 || RegVT.is64BitVector())
2579 RC = &AArch64::FPR64RegClass;
2580 else if (RegVT == MVT::f128 || RegVT.is128BitVector())
2581 RC = &AArch64::FPR128RegClass;
2582 else
2583 llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
2584
2585 // Transform the arguments in physical registers into virtual ones.
2586 unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2587 ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2588
2589 // If this is an 8, 16 or 32-bit value, it is really passed promoted
2590 // to 64 bits. Insert an assert[sz]ext to capture this, then
2591 // truncate to the right size.
2592 switch (VA.getLocInfo()) {
2593 default:
2594 llvm_unreachable("Unknown loc info!");
2595 case CCValAssign::Full:
2596 break;
2597 case CCValAssign::BCvt:
2598 ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
2599 break;
Tim Northover47e003c2014-05-26 17:21:53 +00002600 case CCValAssign::AExt:
Tim Northover3b0846e2014-05-24 12:50:23 +00002601 case CCValAssign::SExt:
Tim Northover3b0846e2014-05-24 12:50:23 +00002602 case CCValAssign::ZExt:
Tim Northover47e003c2014-05-26 17:21:53 +00002603 // SelectionDAGBuilder will insert appropriate AssertZExt & AssertSExt
2604 // nodes after our lowering.
2605 assert(RegVT == Ins[i].VT && "incorrect register location selected");
Tim Northover3b0846e2014-05-24 12:50:23 +00002606 break;
2607 }
2608
2609 InVals.push_back(ArgValue);
2610
2611 } else { // VA.isRegLoc()
2612 assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
2613 unsigned ArgOffset = VA.getLocMemOffset();
Amara Emerson82da7d02014-08-15 14:29:57 +00002614 unsigned ArgSize = VA.getValVT().getSizeInBits() / 8;
Tim Northover3b0846e2014-05-24 12:50:23 +00002615
2616 uint32_t BEAlign = 0;
Tim Northover293d4142014-12-03 17:49:26 +00002617 if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
2618 !Ins[i].Flags.isInConsecutiveRegs())
Tim Northover3b0846e2014-05-24 12:50:23 +00002619 BEAlign = 8 - ArgSize;
2620
Matthias Braun941a7052016-07-28 18:40:00 +00002621 int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
Tim Northover3b0846e2014-05-24 12:50:23 +00002622
2623 // Create load nodes to retrieve arguments from the stack.
Mehdi Amini44ede332015-07-09 02:09:04 +00002624 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00002625 SDValue ArgValue;
2626
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002627 // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
Tim Northover47e003c2014-05-26 17:21:53 +00002628 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
Jiangning Liucc4f38b2014-06-03 03:25:09 +00002629 MVT MemVT = VA.getValVT();
2630
Tim Northover47e003c2014-05-26 17:21:53 +00002631 switch (VA.getLocInfo()) {
2632 default:
2633 break;
Tim Northover6890add2014-06-03 13:54:53 +00002634 case CCValAssign::BCvt:
2635 MemVT = VA.getLocVT();
2636 break;
Tim Northover47e003c2014-05-26 17:21:53 +00002637 case CCValAssign::SExt:
2638 ExtType = ISD::SEXTLOAD;
2639 break;
2640 case CCValAssign::ZExt:
2641 ExtType = ISD::ZEXTLOAD;
2642 break;
2643 case CCValAssign::AExt:
2644 ExtType = ISD::EXTLOAD;
2645 break;
Tim Northover3b0846e2014-05-24 12:50:23 +00002646 }
2647
Alex Lorenze40c8a22015-08-11 23:09:45 +00002648 ArgValue = DAG.getExtLoad(
2649 ExtType, DL, VA.getLocVT(), Chain, FIN,
2650 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
Justin Lebar9c375812016-07-15 18:27:10 +00002651 MemVT);
Tim Northover47e003c2014-05-26 17:21:53 +00002652
Tim Northover3b0846e2014-05-24 12:50:23 +00002653 InVals.push_back(ArgValue);
2654 }
2655 }
2656
2657 // varargs
Matthias Braundff243e2016-04-12 02:16:13 +00002658 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Tim Northover3b0846e2014-05-24 12:50:23 +00002659 if (isVarArg) {
2660 if (!Subtarget->isTargetDarwin()) {
2661 // The AAPCS variadic function ABI is identical to the non-variadic
2662 // one. As a result there may be more arguments in registers and we should
2663 // save them for future reference.
2664 saveVarArgRegisters(CCInfo, DAG, DL, Chain);
2665 }
2666
Tim Northover3b0846e2014-05-24 12:50:23 +00002667 // This will point to the next argument passed via stack.
2668 unsigned StackOffset = CCInfo.getNextStackOffset();
2669 // We currently pass all varargs at 8-byte alignment.
2670 StackOffset = ((StackOffset + 7) & ~7);
Matthias Braun941a7052016-07-28 18:40:00 +00002671 FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true));
Tim Northover3b0846e2014-05-24 12:50:23 +00002672 }
2673
Tim Northover3b0846e2014-05-24 12:50:23 +00002674 unsigned StackArgSize = CCInfo.getNextStackOffset();
2675 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2676 if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
2677 // This is a non-standard ABI so by fiat I say we're allowed to make full
2678 // use of the stack area to be popped, which must be aligned to 16 bytes in
2679 // any case:
Rui Ueyamada00f2f2016-01-14 21:06:47 +00002680 StackArgSize = alignTo(StackArgSize, 16);
Tim Northover3b0846e2014-05-24 12:50:23 +00002681
2682 // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
2683 // a multiple of 16.
2684 FuncInfo->setArgumentStackToRestore(StackArgSize);
2685
2686 // This realignment carries over to the available bytes below. Our own
2687 // callers will guarantee the space is free by giving an aligned value to
2688 // CALLSEQ_START.
2689 }
2690 // Even if we're not expected to free up the space, it's useful to know how
2691 // much is there while considering tail calls (because we can reuse it).
2692 FuncInfo->setBytesInStackArgArea(StackArgSize);
2693
2694 return Chain;
2695}
2696
2697void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00002698 SelectionDAG &DAG,
2699 const SDLoc &DL,
Tim Northover3b0846e2014-05-24 12:50:23 +00002700 SDValue &Chain) const {
2701 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braun941a7052016-07-28 18:40:00 +00002702 MachineFrameInfo &MFI = MF.getFrameInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00002703 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Mehdi Amini44ede332015-07-09 02:09:04 +00002704 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00002705
2706 SmallVector<SDValue, 8> MemOps;
2707
2708 static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
2709 AArch64::X3, AArch64::X4, AArch64::X5,
2710 AArch64::X6, AArch64::X7 };
2711 static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
Tim Northover3b6b7ca2015-02-21 02:11:17 +00002712 unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
Tim Northover3b0846e2014-05-24 12:50:23 +00002713
2714 unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
2715 int GPRIdx = 0;
2716 if (GPRSaveSize != 0) {
Matthias Braun941a7052016-07-28 18:40:00 +00002717 GPRIdx = MFI.CreateStackObject(GPRSaveSize, 8, false);
Tim Northover3b0846e2014-05-24 12:50:23 +00002718
Mehdi Amini44ede332015-07-09 02:09:04 +00002719 SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00002720
2721 for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
2722 unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
2723 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
Alex Lorenze40c8a22015-08-11 23:09:45 +00002724 SDValue Store = DAG.getStore(
2725 Val.getValue(1), DL, Val, FIN,
Justin Lebar9c375812016-07-15 18:27:10 +00002726 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00002727 MemOps.push_back(Store);
Mehdi Amini44ede332015-07-09 02:09:04 +00002728 FIN =
2729 DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00002730 }
2731 }
2732 FuncInfo->setVarArgsGPRIndex(GPRIdx);
2733 FuncInfo->setVarArgsGPRSize(GPRSaveSize);
2734
2735 if (Subtarget->hasFPARMv8()) {
2736 static const MCPhysReg FPRArgRegs[] = {
2737 AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
2738 AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
2739 static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
Tim Northover3b6b7ca2015-02-21 02:11:17 +00002740 unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
Tim Northover3b0846e2014-05-24 12:50:23 +00002741
2742 unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
2743 int FPRIdx = 0;
2744 if (FPRSaveSize != 0) {
Matthias Braun941a7052016-07-28 18:40:00 +00002745 FPRIdx = MFI.CreateStackObject(FPRSaveSize, 16, false);
Tim Northover3b0846e2014-05-24 12:50:23 +00002746
Mehdi Amini44ede332015-07-09 02:09:04 +00002747 SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00002748
2749 for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
2750 unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
2751 SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
2752
Alex Lorenze40c8a22015-08-11 23:09:45 +00002753 SDValue Store = DAG.getStore(
2754 Val.getValue(1), DL, Val, FIN,
Justin Lebar9c375812016-07-15 18:27:10 +00002755 MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16));
Tim Northover3b0846e2014-05-24 12:50:23 +00002756 MemOps.push_back(Store);
Mehdi Amini44ede332015-07-09 02:09:04 +00002757 FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
2758 DAG.getConstant(16, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00002759 }
2760 }
2761 FuncInfo->setVarArgsFPRIndex(FPRIdx);
2762 FuncInfo->setVarArgsFPRSize(FPRSaveSize);
2763 }
2764
2765 if (!MemOps.empty()) {
2766 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
2767 }
2768}
2769
2770/// LowerCallResult - Lower the result values of a call into the
2771/// appropriate copies out of appropriate physical registers.
2772SDValue AArch64TargetLowering::LowerCallResult(
2773 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00002774 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2775 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
Tim Northover3b0846e2014-05-24 12:50:23 +00002776 SDValue ThisVal) const {
2777 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
2778 ? RetCC_AArch64_WebKit_JS
2779 : RetCC_AArch64_AAPCS;
2780 // Assign locations to each value returned by this call.
2781 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00002782 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2783 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00002784 CCInfo.AnalyzeCallResult(Ins, RetCC);
2785
2786 // Copy all of the result registers out of their specified physreg.
2787 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2788 CCValAssign VA = RVLocs[i];
2789
2790 // Pass 'this' value directly from the argument to return value, to avoid
2791 // reg unit interference
David Majnemer5d261272016-07-20 04:13:01 +00002792 if (i == 0 && isThisReturn) {
Tim Northover3b0846e2014-05-24 12:50:23 +00002793 assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
2794 "unexpected return calling convention register assignment");
2795 InVals.push_back(ThisVal);
2796 continue;
2797 }
2798
2799 SDValue Val =
2800 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2801 Chain = Val.getValue(1);
2802 InFlag = Val.getValue(2);
2803
2804 switch (VA.getLocInfo()) {
2805 default:
2806 llvm_unreachable("Unknown loc info!");
2807 case CCValAssign::Full:
2808 break;
2809 case CCValAssign::BCvt:
2810 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2811 break;
2812 }
2813
2814 InVals.push_back(Val);
2815 }
2816
2817 return Chain;
2818}
2819
Matthias Braun1af14142016-09-13 19:27:38 +00002820/// Return true if the calling convention is one that we can guarantee TCO for.
2821static bool canGuaranteeTCO(CallingConv::ID CC) {
2822 return CC == CallingConv::Fast;
2823}
2824
2825/// Return true if we might ever do TCO for calls with this calling convention.
2826static bool mayTailCallThisCC(CallingConv::ID CC) {
2827 switch (CC) {
2828 case CallingConv::C:
2829 case CallingConv::PreserveMost:
2830 case CallingConv::Swift:
2831 return true;
2832 default:
2833 return canGuaranteeTCO(CC);
2834 }
2835}
2836
Tim Northover3b0846e2014-05-24 12:50:23 +00002837bool AArch64TargetLowering::isEligibleForTailCallOptimization(
2838 SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
Tim Northover3b0846e2014-05-24 12:50:23 +00002839 const SmallVectorImpl<ISD::OutputArg> &Outs,
2840 const SmallVectorImpl<SDValue> &OutVals,
2841 const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
Matthias Braun1af14142016-09-13 19:27:38 +00002842 if (!mayTailCallThisCC(CalleeCC))
Tim Northover3b0846e2014-05-24 12:50:23 +00002843 return false;
2844
Matthias Braun8d414362016-03-30 22:46:04 +00002845 MachineFunction &MF = DAG.getMachineFunction();
Tim Northover3b0846e2014-05-24 12:50:23 +00002846 const Function *CallerF = MF.getFunction();
2847 CallingConv::ID CallerCC = CallerF->getCallingConv();
2848 bool CCMatch = CallerCC == CalleeCC;
2849
2850 // Byval parameters hand the function a pointer directly into the stack area
2851 // we want to reuse during a tail call. Working around this *is* possible (see
2852 // X86) but less efficient and uglier in LowerCall.
2853 for (Function::const_arg_iterator i = CallerF->arg_begin(),
2854 e = CallerF->arg_end();
2855 i != e; ++i)
2856 if (i->hasByValAttr())
2857 return false;
2858
Matthias Braun1af14142016-09-13 19:27:38 +00002859 if (getTargetMachine().Options.GuaranteedTailCallOpt)
2860 return canGuaranteeTCO(CalleeCC) && CCMatch;
Tim Northover3b0846e2014-05-24 12:50:23 +00002861
Oliver Stannard12993dd2014-08-18 12:42:15 +00002862 // Externally-defined functions with weak linkage should not be
2863 // tail-called on AArch64 when the OS does not support dynamic
2864 // pre-emption of symbols, as the AAELF spec requires normal calls
2865 // to undefined weak functions to be replaced with a NOP or jump to the
2866 // next instruction. The behaviour of branch instructions in this
2867 // situation (as used for tail calls) is implementation-defined, so we
2868 // cannot rely on the linker replacing the tail call with a return.
2869 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2870 const GlobalValue *GV = G->getGlobal();
Daniel Sandersc81f4502015-06-16 15:44:21 +00002871 const Triple &TT = getTargetMachine().getTargetTriple();
Saleem Abdulrasool67f72992015-01-03 21:35:00 +00002872 if (GV->hasExternalWeakLinkage() &&
2873 (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
Oliver Stannard12993dd2014-08-18 12:42:15 +00002874 return false;
2875 }
2876
Tim Northover3b0846e2014-05-24 12:50:23 +00002877 // Now we search for cases where we can use a tail call without changing the
2878 // ABI. Sibcall is used in some places (particularly gcc) to refer to this
2879 // concept.
2880
2881 // I want anyone implementing a new calling convention to think long and hard
2882 // about this assert.
2883 assert((!isVarArg || CalleeCC == CallingConv::C) &&
2884 "Unexpected variadic calling convention");
2885
Matthias Braun8d414362016-03-30 22:46:04 +00002886 LLVMContext &C = *DAG.getContext();
Tim Northover3b0846e2014-05-24 12:50:23 +00002887 if (isVarArg && !Outs.empty()) {
2888 // At least two cases here: if caller is fastcc then we can't have any
2889 // memory arguments (we'd be expected to clean up the stack afterwards). If
2890 // caller is C then we could potentially use its argument area.
2891
2892 // FIXME: for now we take the most conservative of these in both cases:
2893 // disallow all variadic memory operands.
2894 SmallVector<CCValAssign, 16> ArgLocs;
Matthias Braun8d414362016-03-30 22:46:04 +00002895 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
Tim Northover3b0846e2014-05-24 12:50:23 +00002896
2897 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
Pete Cooper7be8f8f2015-08-03 19:04:32 +00002898 for (const CCValAssign &ArgLoc : ArgLocs)
2899 if (!ArgLoc.isRegLoc())
Tim Northover3b0846e2014-05-24 12:50:23 +00002900 return false;
2901 }
2902
Matthias Braun8d414362016-03-30 22:46:04 +00002903 // Check that the call results are passed in the same way.
2904 if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
2905 CCAssignFnForCall(CalleeCC, isVarArg),
2906 CCAssignFnForCall(CallerCC, isVarArg)))
2907 return false;
Matthias Braun870c34f2016-04-04 18:56:13 +00002908 // The callee has to preserve all registers the caller needs to preserve.
Matthias Braun74a0bd32016-04-13 21:43:16 +00002909 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
2910 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
Matthias Braun870c34f2016-04-04 18:56:13 +00002911 if (!CCMatch) {
Matthias Braun74a0bd32016-04-13 21:43:16 +00002912 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2913 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
Matthias Braun870c34f2016-04-04 18:56:13 +00002914 return false;
2915 }
Tim Northover3b0846e2014-05-24 12:50:23 +00002916
2917 // Nothing more to check if the callee is taking no arguments
2918 if (Outs.empty())
2919 return true;
2920
2921 SmallVector<CCValAssign, 16> ArgLocs;
Matthias Braun8d414362016-03-30 22:46:04 +00002922 CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
Tim Northover3b0846e2014-05-24 12:50:23 +00002923
2924 CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2925
2926 const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2927
Matthias Braun74a0bd32016-04-13 21:43:16 +00002928 // If the stack arguments for this call do not fit into our own save area then
2929 // the call cannot be made tail.
2930 if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2931 return false;
2932
Matthias Braun46b0f032016-04-14 01:10:42 +00002933 const MachineRegisterInfo &MRI = MF.getRegInfo();
2934 if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
2935 return false;
Matthias Braun74a0bd32016-04-13 21:43:16 +00002936
2937 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +00002938}
2939
2940SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
2941 SelectionDAG &DAG,
Matthias Braun941a7052016-07-28 18:40:00 +00002942 MachineFrameInfo &MFI,
Tim Northover3b0846e2014-05-24 12:50:23 +00002943 int ClobberedFI) const {
2944 SmallVector<SDValue, 8> ArgChains;
Matthias Braun941a7052016-07-28 18:40:00 +00002945 int64_t FirstByte = MFI.getObjectOffset(ClobberedFI);
2946 int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1;
Tim Northover3b0846e2014-05-24 12:50:23 +00002947
2948 // Include the original chain at the beginning of the list. When this is
2949 // used by target LowerCall hooks, this helps legalize find the
2950 // CALLSEQ_BEGIN node.
2951 ArgChains.push_back(Chain);
2952
2953 // Add a chain value for each stack argument corresponding
2954 for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
2955 UE = DAG.getEntryNode().getNode()->use_end();
2956 U != UE; ++U)
2957 if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
2958 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
2959 if (FI->getIndex() < 0) {
Matthias Braun941a7052016-07-28 18:40:00 +00002960 int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex());
Tim Northover3b0846e2014-05-24 12:50:23 +00002961 int64_t InLastByte = InFirstByte;
Matthias Braun941a7052016-07-28 18:40:00 +00002962 InLastByte += MFI.getObjectSize(FI->getIndex()) - 1;
Tim Northover3b0846e2014-05-24 12:50:23 +00002963
2964 if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
2965 (FirstByte <= InFirstByte && InFirstByte <= LastByte))
2966 ArgChains.push_back(SDValue(L, 1));
2967 }
2968
2969 // Build a tokenfactor for all the chains.
2970 return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
2971}
2972
2973bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
2974 bool TailCallOpt) const {
2975 return CallCC == CallingConv::Fast && TailCallOpt;
2976}
2977
Tim Northover3b0846e2014-05-24 12:50:23 +00002978/// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
2979/// and add input and output parameter nodes.
2980SDValue
2981AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
2982 SmallVectorImpl<SDValue> &InVals) const {
2983 SelectionDAG &DAG = CLI.DAG;
2984 SDLoc &DL = CLI.DL;
2985 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2986 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2987 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2988 SDValue Chain = CLI.Chain;
2989 SDValue Callee = CLI.Callee;
2990 bool &IsTailCall = CLI.IsTailCall;
2991 CallingConv::ID CallConv = CLI.CallConv;
2992 bool IsVarArg = CLI.IsVarArg;
2993
2994 MachineFunction &MF = DAG.getMachineFunction();
Tim Northover3b0846e2014-05-24 12:50:23 +00002995 bool IsThisReturn = false;
2996
2997 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
2998 bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2999 bool IsSibCall = false;
3000
3001 if (IsTailCall) {
3002 // Check if it's really possible to do a tail call.
3003 IsTailCall = isEligibleForTailCallOptimization(
Matthias Brauncc7fba42016-04-01 02:49:17 +00003004 Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00003005 if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
3006 report_fatal_error("failed to perform tail call elimination on a call "
3007 "site marked musttail");
3008
3009 // A sibling call is one where we're under the usual C ABI and not planning
3010 // to change that but can still do a tail call:
3011 if (!TailCallOpt && IsTailCall)
3012 IsSibCall = true;
3013
3014 if (IsTailCall)
3015 ++NumTailCalls;
3016 }
3017
3018 // Analyze operands of the call, assigning locations to each operand.
3019 SmallVector<CCValAssign, 16> ArgLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003020 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
3021 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00003022
3023 if (IsVarArg) {
3024 // Handle fixed and variable vector arguments differently.
3025 // Variable vector arguments always go into memory.
3026 unsigned NumArgs = Outs.size();
3027
3028 for (unsigned i = 0; i != NumArgs; ++i) {
3029 MVT ArgVT = Outs[i].VT;
3030 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3031 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
3032 /*IsVarArg=*/ !Outs[i].IsFixed);
3033 bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3034 assert(!Res && "Call operand has unhandled type");
3035 (void)Res;
3036 }
3037 } else {
3038 // At this point, Outs[].VT may already be promoted to i32. To correctly
3039 // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
3040 // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
3041 // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
3042 // we use a special version of AnalyzeCallOperands to pass in ValVT and
3043 // LocVT.
3044 unsigned NumArgs = Outs.size();
3045 for (unsigned i = 0; i != NumArgs; ++i) {
3046 MVT ValVT = Outs[i].VT;
3047 // Get type of the original argument.
Mehdi Amini44ede332015-07-09 02:09:04 +00003048 EVT ActualVT = getValueType(DAG.getDataLayout(),
3049 CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
Tim Northover3b0846e2014-05-24 12:50:23 +00003050 /*AllowUnknown*/ true);
3051 MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
3052 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
3053 // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
Tim Northover3b0846e2014-05-24 12:50:23 +00003054 if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
Tim Northover47e003c2014-05-26 17:21:53 +00003055 ValVT = MVT::i8;
Tim Northover3b0846e2014-05-24 12:50:23 +00003056 else if (ActualMVT == MVT::i16)
Tim Northover47e003c2014-05-26 17:21:53 +00003057 ValVT = MVT::i16;
Tim Northover3b0846e2014-05-24 12:50:23 +00003058
3059 CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
Tim Northover47e003c2014-05-26 17:21:53 +00003060 bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00003061 assert(!Res && "Call operand has unhandled type");
3062 (void)Res;
3063 }
3064 }
3065
3066 // Get a count of how many bytes are to be pushed on the stack.
3067 unsigned NumBytes = CCInfo.getNextStackOffset();
3068
3069 if (IsSibCall) {
3070 // Since we're not changing the ABI to make this a tail call, the memory
3071 // operands are already available in the caller's incoming argument space.
3072 NumBytes = 0;
3073 }
3074
3075 // FPDiff is the byte offset of the call's argument area from the callee's.
3076 // Stores to callee stack arguments will be placed in FixedStackSlots offset
3077 // by this amount for a tail call. In a sibling call it must be 0 because the
3078 // caller will deallocate the entire stack and the callee still expects its
3079 // arguments to begin at SP+0. Completely unused for non-tail calls.
3080 int FPDiff = 0;
3081
3082 if (IsTailCall && !IsSibCall) {
3083 unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
3084
3085 // Since callee will pop argument stack as a tail call, we must keep the
3086 // popped size 16-byte aligned.
Rui Ueyamada00f2f2016-01-14 21:06:47 +00003087 NumBytes = alignTo(NumBytes, 16);
Tim Northover3b0846e2014-05-24 12:50:23 +00003088
3089 // FPDiff will be negative if this tail call requires more space than we
3090 // would automatically have in our incoming argument space. Positive if we
3091 // can actually shrink the stack.
3092 FPDiff = NumReusableBytes - NumBytes;
3093
3094 // The stack pointer must be 16-byte aligned at all times it's used for a
3095 // memory operation, which in practice means at *all* times and in
3096 // particular across call boundaries. Therefore our own arguments started at
3097 // a 16-byte aligned SP and the delta applied for the tail call should
3098 // satisfy the same constraint.
3099 assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
3100 }
3101
3102 // Adjust the stack pointer for the new arguments...
3103 // These operations are automatically eliminated by the prolog/epilog pass
3104 if (!IsSibCall)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003105 Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(NumBytes, DL,
3106 true),
3107 DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003108
Mehdi Amini44ede332015-07-09 02:09:04 +00003109 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
3110 getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00003111
3112 SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
3113 SmallVector<SDValue, 8> MemOpChains;
Mehdi Amini44ede332015-07-09 02:09:04 +00003114 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003115
3116 // Walk the register/memloc assignments, inserting copies/loads.
3117 for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
3118 ++i, ++realArgIdx) {
3119 CCValAssign &VA = ArgLocs[i];
3120 SDValue Arg = OutVals[realArgIdx];
3121 ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
3122
3123 // Promote the value if needed.
3124 switch (VA.getLocInfo()) {
3125 default:
3126 llvm_unreachable("Unknown loc info!");
3127 case CCValAssign::Full:
3128 break;
3129 case CCValAssign::SExt:
3130 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3131 break;
3132 case CCValAssign::ZExt:
3133 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3134 break;
3135 case CCValAssign::AExt:
Tim Northover68ae5032014-05-26 17:22:07 +00003136 if (Outs[realArgIdx].ArgVT == MVT::i1) {
3137 // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
3138 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3139 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
3140 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003141 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3142 break;
3143 case CCValAssign::BCvt:
3144 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3145 break;
3146 case CCValAssign::FPExt:
3147 Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3148 break;
3149 }
3150
3151 if (VA.isRegLoc()) {
Arnold Schwaighoferdb7bbcb2017-02-08 22:30:47 +00003152 if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
3153 Outs[0].VT == MVT::i64) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003154 assert(VA.getLocVT() == MVT::i64 &&
3155 "unexpected calling convention register assignment");
3156 assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
3157 "unexpected use of 'returned'");
3158 IsThisReturn = true;
3159 }
3160 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3161 } else {
3162 assert(VA.isMemLoc());
3163
3164 SDValue DstAddr;
3165 MachinePointerInfo DstInfo;
3166
3167 // FIXME: This works on big-endian for composite byvals, which are the
3168 // common case. It should also work for fundamental types too.
3169 uint32_t BEAlign = 0;
3170 unsigned OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
Amara Emerson82da7d02014-08-15 14:29:57 +00003171 : VA.getValVT().getSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00003172 OpSize = (OpSize + 7) / 8;
Tim Northover293d4142014-12-03 17:49:26 +00003173 if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
3174 !Flags.isInConsecutiveRegs()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003175 if (OpSize < 8)
3176 BEAlign = 8 - OpSize;
3177 }
3178 unsigned LocMemOffset = VA.getLocMemOffset();
3179 int32_t Offset = LocMemOffset + BEAlign;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003180 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
Mehdi Amini44ede332015-07-09 02:09:04 +00003181 PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
Tim Northover3b0846e2014-05-24 12:50:23 +00003182
3183 if (IsTailCall) {
3184 Offset = Offset + FPDiff;
Matthias Braun941a7052016-07-28 18:40:00 +00003185 int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
Tim Northover3b0846e2014-05-24 12:50:23 +00003186
Mehdi Amini44ede332015-07-09 02:09:04 +00003187 DstAddr = DAG.getFrameIndex(FI, PtrVT);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003188 DstInfo =
3189 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
Tim Northover3b0846e2014-05-24 12:50:23 +00003190
3191 // Make sure any stack arguments overlapping with where we're storing
3192 // are loaded before this eventual operation. Otherwise they'll be
3193 // clobbered.
3194 Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
3195 } else {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003196 SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003197
Mehdi Amini44ede332015-07-09 02:09:04 +00003198 DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
Alex Lorenze40c8a22015-08-11 23:09:45 +00003199 DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
3200 LocMemOffset);
Tim Northover3b0846e2014-05-24 12:50:23 +00003201 }
3202
3203 if (Outs[i].Flags.isByVal()) {
3204 SDValue SizeNode =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003205 DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00003206 SDValue Cpy = DAG.getMemcpy(
3207 Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
Krzysztof Parzyszeka46c36b2015-04-13 17:16:45 +00003208 /*isVol = */ false, /*AlwaysInline = */ false,
3209 /*isTailCall = */ false,
3210 DstInfo, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00003211
3212 MemOpChains.push_back(Cpy);
3213 } else {
3214 // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
3215 // promoted to a legal register type i32, we should truncate Arg back to
3216 // i1/i8/i16.
Tim Northover6890add2014-06-03 13:54:53 +00003217 if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
3218 VA.getValVT() == MVT::i16)
3219 Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
Tim Northover3b0846e2014-05-24 12:50:23 +00003220
Justin Lebar9c375812016-07-15 18:27:10 +00003221 SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
Tim Northover3b0846e2014-05-24 12:50:23 +00003222 MemOpChains.push_back(Store);
3223 }
3224 }
3225 }
3226
3227 if (!MemOpChains.empty())
3228 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3229
3230 // Build a sequence of copy-to-reg nodes chained together with token chain
3231 // and flag operands which copy the outgoing args into the appropriate regs.
3232 SDValue InFlag;
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003233 for (auto &RegToPass : RegsToPass) {
3234 Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3235 RegToPass.second, InFlag);
Tim Northover3b0846e2014-05-24 12:50:23 +00003236 InFlag = Chain.getValue(1);
3237 }
3238
3239 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3240 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3241 // node so that legalize doesn't hack it.
3242 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
3243 Subtarget->isTargetMachO()) {
3244 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3245 const GlobalValue *GV = G->getGlobal();
3246 bool InternalLinkage = GV->hasInternalLinkage();
3247 if (InternalLinkage)
Mehdi Amini44ede332015-07-09 02:09:04 +00003248 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00003249 else {
Mehdi Amini44ede332015-07-09 02:09:04 +00003250 Callee =
3251 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_GOT);
3252 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
Tim Northover3b0846e2014-05-24 12:50:23 +00003253 }
3254 } else if (ExternalSymbolSDNode *S =
3255 dyn_cast<ExternalSymbolSDNode>(Callee)) {
3256 const char *Sym = S->getSymbol();
Mehdi Amini44ede332015-07-09 02:09:04 +00003257 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
3258 Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
Tim Northover3b0846e2014-05-24 12:50:23 +00003259 }
3260 } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3261 const GlobalValue *GV = G->getGlobal();
Mehdi Amini44ede332015-07-09 02:09:04 +00003262 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00003263 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3264 const char *Sym = S->getSymbol();
Mehdi Amini44ede332015-07-09 02:09:04 +00003265 Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
Tim Northover3b0846e2014-05-24 12:50:23 +00003266 }
3267
3268 // We don't usually want to end the call-sequence here because we would tidy
3269 // the frame up *after* the call, however in the ABI-changing tail-call case
3270 // we've carefully laid out the parameters so that when sp is reset they'll be
3271 // in the correct location.
3272 if (IsTailCall && !IsSibCall) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003273 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3274 DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
Tim Northover3b0846e2014-05-24 12:50:23 +00003275 InFlag = Chain.getValue(1);
3276 }
3277
3278 std::vector<SDValue> Ops;
3279 Ops.push_back(Chain);
3280 Ops.push_back(Callee);
3281
3282 if (IsTailCall) {
3283 // Each tail call may have to adjust the stack by a different amount, so
3284 // this information must travel along with the operation for eventual
3285 // consumption by emitEpilogue.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003286 Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00003287 }
3288
3289 // Add argument registers to the end of the list so that they are known live
3290 // into the call.
Pete Cooper7be8f8f2015-08-03 19:04:32 +00003291 for (auto &RegToPass : RegsToPass)
3292 Ops.push_back(DAG.getRegister(RegToPass.first,
3293 RegToPass.second.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00003294
3295 // Add a register mask operand representing the call-preserved registers.
3296 const uint32_t *Mask;
Eric Christopher905f12d2015-01-29 00:19:42 +00003297 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00003298 if (IsThisReturn) {
3299 // For 'this' returns, use the X0-preserving mask if applicable
Eric Christopher9deb75d2015-03-11 22:42:13 +00003300 Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003301 if (!Mask) {
3302 IsThisReturn = false;
Eric Christopher9deb75d2015-03-11 22:42:13 +00003303 Mask = TRI->getCallPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003304 }
3305 } else
Eric Christopher9deb75d2015-03-11 22:42:13 +00003306 Mask = TRI->getCallPreservedMask(MF, CallConv);
Tim Northover3b0846e2014-05-24 12:50:23 +00003307
3308 assert(Mask && "Missing call preserved mask for calling convention");
3309 Ops.push_back(DAG.getRegisterMask(Mask));
3310
3311 if (InFlag.getNode())
3312 Ops.push_back(InFlag);
3313
3314 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3315
3316 // If we're doing a tall call, use a TC_RETURN here rather than an
3317 // actual call instruction.
Arnold Schwaighoferf54b73d2015-05-08 23:52:00 +00003318 if (IsTailCall) {
Matthias Braun941a7052016-07-28 18:40:00 +00003319 MF.getFrameInfo().setHasTailCall();
Tim Northover3b0846e2014-05-24 12:50:23 +00003320 return DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
Arnold Schwaighoferf54b73d2015-05-08 23:52:00 +00003321 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003322
3323 // Returns a chain and a flag for retval copy to use.
3324 Chain = DAG.getNode(AArch64ISD::CALL, DL, NodeTys, Ops);
3325 InFlag = Chain.getValue(1);
3326
Rui Ueyamada00f2f2016-01-14 21:06:47 +00003327 uint64_t CalleePopBytes =
3328 DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00003329
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003330 Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
3331 DAG.getIntPtrConstant(CalleePopBytes, DL, true),
Tim Northover3b0846e2014-05-24 12:50:23 +00003332 InFlag, DL);
3333 if (!Ins.empty())
3334 InFlag = Chain.getValue(1);
3335
3336 // Handle result values, copying them out of physregs into vregs that we
3337 // return.
3338 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3339 InVals, IsThisReturn,
3340 IsThisReturn ? OutVals[0] : SDValue());
3341}
3342
3343bool AArch64TargetLowering::CanLowerReturn(
3344 CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
3345 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
3346 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3347 ? RetCC_AArch64_WebKit_JS
3348 : RetCC_AArch64_AAPCS;
3349 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003350 CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
Tim Northover3b0846e2014-05-24 12:50:23 +00003351 return CCInfo.CheckReturn(Outs, RetCC);
3352}
3353
3354SDValue
3355AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3356 bool isVarArg,
3357 const SmallVectorImpl<ISD::OutputArg> &Outs,
3358 const SmallVectorImpl<SDValue> &OutVals,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003359 const SDLoc &DL, SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00003360 CCAssignFn *RetCC = CallConv == CallingConv::WebKit_JS
3361 ? RetCC_AArch64_WebKit_JS
3362 : RetCC_AArch64_AAPCS;
3363 SmallVector<CCValAssign, 16> RVLocs;
Eric Christopherb5217502014-08-06 18:45:26 +00003364 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
3365 *DAG.getContext());
Tim Northover3b0846e2014-05-24 12:50:23 +00003366 CCInfo.AnalyzeReturn(Outs, RetCC);
3367
3368 // Copy the result values into the output registers.
3369 SDValue Flag;
3370 SmallVector<SDValue, 4> RetOps(1, Chain);
3371 for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
3372 ++i, ++realRVLocIdx) {
3373 CCValAssign &VA = RVLocs[i];
3374 assert(VA.isRegLoc() && "Can only return in registers!");
3375 SDValue Arg = OutVals[realRVLocIdx];
3376
3377 switch (VA.getLocInfo()) {
3378 default:
3379 llvm_unreachable("Unknown loc info!");
3380 case CCValAssign::Full:
Tim Northover68ae5032014-05-26 17:22:07 +00003381 if (Outs[i].ArgVT == MVT::i1) {
3382 // AAPCS requires i1 to be zero-extended to i8 by the producer of the
3383 // value. This is strictly redundant on Darwin (which uses "zeroext
3384 // i1"), but will be optimised out before ISel.
3385 Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
3386 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3387 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003388 break;
3389 case CCValAssign::BCvt:
3390 Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3391 break;
3392 }
3393
3394 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
3395 Flag = Chain.getValue(1);
3396 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3397 }
Manman Rencbe4f942015-12-16 21:04:19 +00003398 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
3399 const MCPhysReg *I =
3400 TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
3401 if (I) {
3402 for (; *I; ++I) {
3403 if (AArch64::GPR64RegClass.contains(*I))
3404 RetOps.push_back(DAG.getRegister(*I, MVT::i64));
3405 else if (AArch64::FPR64RegClass.contains(*I))
3406 RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
3407 else
3408 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
3409 }
3410 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003411
3412 RetOps[0] = Chain; // Update chain.
3413
3414 // Add the flag if we have it.
3415 if (Flag.getNode())
3416 RetOps.push_back(Flag);
3417
3418 return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
3419}
3420
3421//===----------------------------------------------------------------------===//
3422// Other Lowering Code
3423//===----------------------------------------------------------------------===//
3424
3425SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
3426 SelectionDAG &DAG) const {
Mehdi Amini44ede332015-07-09 02:09:04 +00003427 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003428 SDLoc DL(Op);
Asiri Rathnayake369c0302014-09-10 13:54:38 +00003429 const GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
3430 const GlobalValue *GV = GN->getGlobal();
Tim Northover3b0846e2014-05-24 12:50:23 +00003431 unsigned char OpFlags =
3432 Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
3433
3434 assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
3435 "unexpected offset in global node");
3436
3437 // This also catched the large code model case for Darwin.
3438 if ((OpFlags & AArch64II::MO_GOT) != 0) {
3439 SDValue GotAddr = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
3440 // FIXME: Once remat is capable of dealing with instructions with register
3441 // operands, expand this into two nodes instead of using a wrapper node.
3442 return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
3443 }
3444
3445 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
3446 const unsigned char MO_NC = AArch64II::MO_NC;
3447 return DAG.getNode(
3448 AArch64ISD::WrapperLarge, DL, PtrVT,
3449 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G3),
3450 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
3451 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
3452 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
3453 } else {
3454 // Use ADRP/ADD or ADRP/LDR for everything else: the small model on ELF and
3455 // the only correct model on Darwin.
3456 SDValue Hi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
3457 OpFlags | AArch64II::MO_PAGE);
3458 unsigned char LoFlags = OpFlags | AArch64II::MO_PAGEOFF | AArch64II::MO_NC;
3459 SDValue Lo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, LoFlags);
3460
3461 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
3462 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
3463 }
3464}
3465
3466/// \brief Convert a TLS address reference into the correct sequence of loads
3467/// and calls to compute the variable's address (for Darwin, currently) and
3468/// return an SDValue containing the final node.
3469
3470/// Darwin only has one TLS scheme which must be capable of dealing with the
3471/// fully general situation, in the worst case. This means:
3472/// + "extern __thread" declaration.
3473/// + Defined in a possibly unknown dynamic library.
3474///
3475/// The general system is that each __thread variable has a [3 x i64] descriptor
3476/// which contains information used by the runtime to calculate the address. The
3477/// only part of this the compiler needs to know about is the first xword, which
3478/// contains a function pointer that must be called with the address of the
3479/// entire descriptor in "x0".
3480///
3481/// Since this descriptor may be in a different unit, in general even the
3482/// descriptor must be accessed via an indirect load. The "ideal" code sequence
3483/// is:
3484/// adrp x0, _var@TLVPPAGE
3485/// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor
3486/// ldr x1, [x0] ; x1 contains 1st entry of descriptor,
3487/// ; the function pointer
3488/// blr x1 ; Uses descriptor address in x0
3489/// ; Address of _var is now in x0.
3490///
3491/// If the address of _var's descriptor *is* known to the linker, then it can
3492/// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
3493/// a slight efficiency gain.
3494SDValue
3495AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
3496 SelectionDAG &DAG) const {
3497 assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
3498
3499 SDLoc DL(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00003500 MVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003501 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3502
3503 SDValue TLVPAddr =
3504 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3505 SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
3506
3507 // The first entry in the descriptor is a function pointer that we must call
3508 // to obtain the address of the variable.
3509 SDValue Chain = DAG.getEntryNode();
Justin Lebaradbf09e2016-09-11 01:38:58 +00003510 SDValue FuncTLVGet = DAG.getLoad(
3511 MVT::i64, DL, Chain, DescAddr,
3512 MachinePointerInfo::getGOT(DAG.getMachineFunction()),
3513 /* Alignment = */ 8,
3514 MachineMemOperand::MONonTemporal | MachineMemOperand::MOInvariant |
3515 MachineMemOperand::MODereferenceable);
Tim Northover3b0846e2014-05-24 12:50:23 +00003516 Chain = FuncTLVGet.getValue(1);
3517
Matthias Braun941a7052016-07-28 18:40:00 +00003518 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
3519 MFI.setAdjustsStack(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00003520
3521 // TLS calls preserve all registers except those that absolutely must be
3522 // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
3523 // silly).
Eric Christopher6c901622015-01-28 03:51:33 +00003524 const uint32_t *Mask =
Eric Christopher905f12d2015-01-29 00:19:42 +00003525 Subtarget->getRegisterInfo()->getTLSCallPreservedMask();
Tim Northover3b0846e2014-05-24 12:50:23 +00003526
3527 // Finally, we can make the call. This is just a degenerate version of a
3528 // normal AArch64 call node: x0 takes the address of the descriptor, and
3529 // returns the address of the variable in this thread.
3530 Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
3531 Chain =
3532 DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
3533 Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
3534 DAG.getRegisterMask(Mask), Chain.getValue(1));
3535 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
3536}
3537
3538/// When accessing thread-local variables under either the general-dynamic or
3539/// local-dynamic system, we make a "TLS-descriptor" call. The variable will
3540/// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
Kristof Beylsaea84612015-03-04 09:12:08 +00003541/// is a function pointer to carry out the resolution.
Tim Northover3b0846e2014-05-24 12:50:23 +00003542///
Kristof Beylsaea84612015-03-04 09:12:08 +00003543/// The sequence is:
3544/// adrp x0, :tlsdesc:var
3545/// ldr x1, [x0, #:tlsdesc_lo12:var]
3546/// add x0, x0, #:tlsdesc_lo12:var
3547/// .tlsdesccall var
3548/// blr x1
3549/// (TPIDR_EL0 offset now in x0)
Tim Northover3b0846e2014-05-24 12:50:23 +00003550///
Kristof Beylsaea84612015-03-04 09:12:08 +00003551/// The above sequence must be produced unscheduled, to enable the linker to
3552/// optimize/relax this sequence.
3553/// Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
3554/// above sequence, and expanded really late in the compilation flow, to ensure
3555/// the sequence is produced as per above.
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003556SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr,
3557 const SDLoc &DL,
Kristof Beylsaea84612015-03-04 09:12:08 +00003558 SelectionDAG &DAG) const {
Mehdi Amini44ede332015-07-09 02:09:04 +00003559 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003560
Kristof Beylsaea84612015-03-04 09:12:08 +00003561 SDValue Chain = DAG.getEntryNode();
Tim Northover3b0846e2014-05-24 12:50:23 +00003562 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
Kristof Beylsaea84612015-03-04 09:12:08 +00003563
Benjamin Kramer3bc1edf2016-07-02 11:41:39 +00003564 Chain =
3565 DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr});
Kristof Beylsaea84612015-03-04 09:12:08 +00003566 SDValue Glue = Chain.getValue(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00003567
3568 return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
3569}
3570
3571SDValue
3572AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
3573 SelectionDAG &DAG) const {
3574 assert(Subtarget->isTargetELF() && "This function expects an ELF target");
Petr Hosek9eb0a1e2017-04-04 19:51:53 +00003575 assert(Subtarget->useSmallAddressing() &&
Tim Northover3b0846e2014-05-24 12:50:23 +00003576 "ELF TLS only supported in small memory model");
Kristof Beylsaea84612015-03-04 09:12:08 +00003577 // Different choices can be made for the maximum size of the TLS area for a
3578 // module. For the small address model, the default TLS size is 16MiB and the
3579 // maximum TLS size is 4GiB.
3580 // FIXME: add -mtls-size command line option and make it control the 16MiB
3581 // vs. 4GiB code sequence generation.
Tim Northover3b0846e2014-05-24 12:50:23 +00003582 const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3583
3584 TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
Chih-Hung Hsieh1e859582015-07-28 16:24:05 +00003585
3586 if (DAG.getTarget().Options.EmulatedTLS)
3587 return LowerToTLSEmulatedModel(GA, DAG);
3588
Kristof Beylsaea84612015-03-04 09:12:08 +00003589 if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
3590 if (Model == TLSModel::LocalDynamic)
3591 Model = TLSModel::GeneralDynamic;
3592 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003593
3594 SDValue TPOff;
Mehdi Amini44ede332015-07-09 02:09:04 +00003595 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00003596 SDLoc DL(Op);
3597 const GlobalValue *GV = GA->getGlobal();
3598
3599 SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
3600
3601 if (Model == TLSModel::LocalExec) {
3602 SDValue HiVar = DAG.getTargetGlobalAddress(
Kristof Beylsaea84612015-03-04 09:12:08 +00003603 GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
Tim Northover3b0846e2014-05-24 12:50:23 +00003604 SDValue LoVar = DAG.getTargetGlobalAddress(
3605 GV, DL, PtrVT, 0,
Kristof Beylsaea84612015-03-04 09:12:08 +00003606 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
Tim Northover3b0846e2014-05-24 12:50:23 +00003607
Kristof Beylsaea84612015-03-04 09:12:08 +00003608 SDValue TPWithOff_lo =
3609 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003610 HiVar,
3611 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003612 0);
3613 SDValue TPWithOff =
3614 SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPWithOff_lo,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003615 LoVar,
3616 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003617 0);
3618 return TPWithOff;
Tim Northover3b0846e2014-05-24 12:50:23 +00003619 } else if (Model == TLSModel::InitialExec) {
3620 TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3621 TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
3622 } else if (Model == TLSModel::LocalDynamic) {
3623 // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
3624 // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
3625 // the beginning of the module's TLS region, followed by a DTPREL offset
3626 // calculation.
3627
3628 // These accesses will need deduplicating if there's more than one.
3629 AArch64FunctionInfo *MFI =
3630 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
3631 MFI->incNumLocalDynamicTLSAccesses();
3632
Tim Northover3b0846e2014-05-24 12:50:23 +00003633 // The call needs a relocation too for linker relaxation. It doesn't make
3634 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3635 // the address.
3636 SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
3637 AArch64II::MO_TLS);
3638
3639 // Now we can calculate the offset from TPIDR_EL0 to this module's
3640 // thread-local area.
Kristof Beylsaea84612015-03-04 09:12:08 +00003641 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00003642
3643 // Now use :dtprel_whatever: operations to calculate this variable's offset
3644 // in its thread-storage area.
3645 SDValue HiVar = DAG.getTargetGlobalAddress(
Kristof Beylsaea84612015-03-04 09:12:08 +00003646 GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
Tim Northover3b0846e2014-05-24 12:50:23 +00003647 SDValue LoVar = DAG.getTargetGlobalAddress(
3648 GV, DL, MVT::i64, 0,
Tim Northover3b0846e2014-05-24 12:50:23 +00003649 AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
3650
Kristof Beylsaea84612015-03-04 09:12:08 +00003651 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003652 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003653 0);
3654 TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003655 DAG.getTargetConstant(0, DL, MVT::i32)),
Kristof Beylsaea84612015-03-04 09:12:08 +00003656 0);
3657 } else if (Model == TLSModel::GeneralDynamic) {
Tim Northover3b0846e2014-05-24 12:50:23 +00003658 // The call needs a relocation too for linker relaxation. It doesn't make
3659 // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
3660 // the address.
3661 SDValue SymAddr =
3662 DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
3663
3664 // Finally we can make a call to calculate the offset from tpidr_el0.
Kristof Beylsaea84612015-03-04 09:12:08 +00003665 TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00003666 } else
3667 llvm_unreachable("Unsupported ELF TLS access model");
3668
3669 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
3670}
3671
3672SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
3673 SelectionDAG &DAG) const {
3674 if (Subtarget->isTargetDarwin())
3675 return LowerDarwinGlobalTLSAddress(Op, DAG);
Davide Italianoa0bd28c2017-03-30 19:52:31 +00003676 if (Subtarget->isTargetELF())
Tim Northover3b0846e2014-05-24 12:50:23 +00003677 return LowerELFGlobalTLSAddress(Op, DAG);
3678
3679 llvm_unreachable("Unexpected platform trying to use TLS");
3680}
Eugene Zelenko049b0172017-01-06 00:30:53 +00003681
Tim Northover3b0846e2014-05-24 12:50:23 +00003682SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
3683 SDValue Chain = Op.getOperand(0);
3684 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
3685 SDValue LHS = Op.getOperand(2);
3686 SDValue RHS = Op.getOperand(3);
3687 SDValue Dest = Op.getOperand(4);
3688 SDLoc dl(Op);
3689
3690 // Handle f128 first, since lowering it will result in comparing the return
3691 // value of a libcall against zero, which is just what the rest of LowerBR_CC
3692 // is expecting to deal with.
3693 if (LHS.getValueType() == MVT::f128) {
3694 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3695
3696 // If softenSetCCOperands returned a scalar, we need to compare the result
3697 // against zero to select between true and false values.
3698 if (!RHS.getNode()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003699 RHS = DAG.getConstant(0, dl, LHS.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00003700 CC = ISD::SETNE;
3701 }
3702 }
3703
3704 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
3705 // instruction.
3706 unsigned Opc = LHS.getOpcode();
Artyom Skrobov314ee042015-11-25 19:41:11 +00003707 if (LHS.getResNo() == 1 && isOneConstant(RHS) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00003708 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3709 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
3710 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
3711 "Unexpected condition code.");
3712 // Only lower legal XALUO ops.
3713 if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
3714 return SDValue();
3715
3716 // The actual operation with overflow check.
3717 AArch64CC::CondCode OFCC;
3718 SDValue Value, Overflow;
3719 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
3720
3721 if (CC == ISD::SETNE)
3722 OFCC = getInvertedCondCode(OFCC);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003723 SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003724
Ahmed Bougachadf956a22015-02-06 23:15:39 +00003725 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3726 Overflow);
Tim Northover3b0846e2014-05-24 12:50:23 +00003727 }
3728
3729 if (LHS.getValueType().isInteger()) {
3730 assert((LHS.getValueType() == RHS.getValueType()) &&
3731 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
3732
3733 // If the RHS of the comparison is zero, we can potentially fold this
3734 // to a specialized branch.
3735 const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
3736 if (RHSC && RHSC->getZExtValue() == 0) {
3737 if (CC == ISD::SETEQ) {
3738 // See if we can use a TBZ to fold in an AND as well.
3739 // TBZ has a smaller branch displacement than CBZ. If the offset is
3740 // out of bounds, a late MI-layer pass rewrites branches.
3741 // 403.gcc is an example that hits this case.
3742 if (LHS.getOpcode() == ISD::AND &&
3743 isa<ConstantSDNode>(LHS.getOperand(1)) &&
3744 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3745 SDValue Test = LHS.getOperand(0);
3746 uint64_t Mask = LHS.getConstantOperandVal(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00003747 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003748 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3749 Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00003750 }
3751
3752 return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
3753 } else if (CC == ISD::SETNE) {
3754 // See if we can use a TBZ to fold in an AND as well.
3755 // TBZ has a smaller branch displacement than CBZ. If the offset is
3756 // out of bounds, a late MI-layer pass rewrites branches.
3757 // 403.gcc is an example that hits this case.
3758 if (LHS.getOpcode() == ISD::AND &&
3759 isa<ConstantSDNode>(LHS.getOperand(1)) &&
3760 isPowerOf2_64(LHS.getConstantOperandVal(1))) {
3761 SDValue Test = LHS.getOperand(0);
3762 uint64_t Mask = LHS.getConstantOperandVal(1);
Tim Northover3b0846e2014-05-24 12:50:23 +00003763 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003764 DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
3765 Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00003766 }
3767
3768 return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
Chad Rosier579c02c2014-08-01 14:48:56 +00003769 } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
3770 // Don't combine AND since emitComparison converts the AND to an ANDS
3771 // (a.k.a. TST) and the test in the test bit and branch instruction
3772 // becomes redundant. This would also increase register pressure.
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00003773 uint64_t Mask = LHS.getValueSizeInBits() - 1;
Chad Rosier579c02c2014-08-01 14:48:56 +00003774 return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003775 DAG.getConstant(Mask, dl, MVT::i64), Dest);
Tim Northover3b0846e2014-05-24 12:50:23 +00003776 }
3777 }
Chad Rosier579c02c2014-08-01 14:48:56 +00003778 if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
3779 LHS.getOpcode() != ISD::AND) {
3780 // Don't combine AND since emitComparison converts the AND to an ANDS
3781 // (a.k.a. TST) and the test in the test bit and branch instruction
3782 // becomes redundant. This would also increase register pressure.
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00003783 uint64_t Mask = LHS.getValueSizeInBits() - 1;
Chad Rosier579c02c2014-08-01 14:48:56 +00003784 return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003785 DAG.getConstant(Mask, dl, MVT::i64), Dest);
Chad Rosier579c02c2014-08-01 14:48:56 +00003786 }
Tim Northover3b0846e2014-05-24 12:50:23 +00003787
3788 SDValue CCVal;
3789 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
3790 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
3791 Cmp);
3792 }
3793
3794 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3795
3796 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
3797 // clean. Some of them require two branches to implement.
3798 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3799 AArch64CC::CondCode CC1, CC2;
3800 changeFPCCToAArch64CC(CC, CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003801 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003802 SDValue BR1 =
3803 DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
3804 if (CC2 != AArch64CC::AL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003805 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003806 return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
3807 Cmp);
3808 }
3809
3810 return BR1;
3811}
3812
3813SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
3814 SelectionDAG &DAG) const {
3815 EVT VT = Op.getValueType();
3816 SDLoc DL(Op);
3817
3818 SDValue In1 = Op.getOperand(0);
3819 SDValue In2 = Op.getOperand(1);
3820 EVT SrcVT = In2.getValueType();
Ahmed Bougacha2a97b1b2015-08-13 01:13:56 +00003821
3822 if (SrcVT.bitsLT(VT))
3823 In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
3824 else if (SrcVT.bitsGT(VT))
3825 In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
Tim Northover3b0846e2014-05-24 12:50:23 +00003826
3827 EVT VecVT;
3828 EVT EltVT;
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00003829 uint64_t EltMask;
3830 SDValue VecVal1, VecVal2;
Tim Northover3b0846e2014-05-24 12:50:23 +00003831 if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
3832 EltVT = MVT::i32;
Ahmed Bougachab0ae36f2015-08-04 00:42:34 +00003833 VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00003834 EltMask = 0x80000000ULL;
Tim Northover3b0846e2014-05-24 12:50:23 +00003835
3836 if (!VT.isVector()) {
3837 VecVal1 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3838 DAG.getUNDEF(VecVT), In1);
3839 VecVal2 = DAG.getTargetInsertSubreg(AArch64::ssub, DL, VecVT,
3840 DAG.getUNDEF(VecVT), In2);
3841 } else {
3842 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3843 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3844 }
3845 } else if (VT == MVT::f64 || VT == MVT::v2f64) {
3846 EltVT = MVT::i64;
3847 VecVT = MVT::v2i64;
3848
Eric Christopher572e03a2015-06-19 01:53:21 +00003849 // We want to materialize a mask with the high bit set, but the AdvSIMD
Tim Northover3b0846e2014-05-24 12:50:23 +00003850 // immediate moves cannot materialize that in a single instruction for
3851 // 64-bit elements. Instead, materialize zero and then negate it.
Benjamin Kramer5fbfe2f2015-02-28 13:20:15 +00003852 EltMask = 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00003853
3854 if (!VT.isVector()) {
3855 VecVal1 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3856 DAG.getUNDEF(VecVT), In1);
3857 VecVal2 = DAG.getTargetInsertSubreg(AArch64::dsub, DL, VecVT,
3858 DAG.getUNDEF(VecVT), In2);
3859 } else {
3860 VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
3861 VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
3862 }
3863 } else {
3864 llvm_unreachable("Invalid type for copysign!");
3865 }
3866
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003867 SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00003868
3869 // If we couldn't materialize the mask above, then the mask vector will be
3870 // the zero vector, and we need to negate it here.
3871 if (VT == MVT::f64 || VT == MVT::v2f64) {
3872 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
3873 BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
3874 BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
3875 }
3876
3877 SDValue Sel =
3878 DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
3879
3880 if (VT == MVT::f32)
3881 return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
3882 else if (VT == MVT::f64)
3883 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
3884 else
3885 return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
3886}
3887
3888SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
Duncan P. N. Exon Smith003bb7d2015-02-14 02:09:06 +00003889 if (DAG.getMachineFunction().getFunction()->hasFnAttribute(
3890 Attribute::NoImplicitFloat))
Tim Northover3b0846e2014-05-24 12:50:23 +00003891 return SDValue();
3892
Weiming Zhao7a2d1562014-11-19 00:29:14 +00003893 if (!Subtarget->hasNEON())
3894 return SDValue();
3895
Tim Northover3b0846e2014-05-24 12:50:23 +00003896 // While there is no integer popcount instruction, it can
3897 // be more efficiently lowered to the following sequence that uses
3898 // AdvSIMD registers/instructions as long as the copies to/from
3899 // the AdvSIMD registers are cheap.
3900 // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd
3901 // CNT V0.8B, V0.8B // 8xbyte pop-counts
3902 // ADDV B0, V0.8B // sum 8xbyte pop-counts
3903 // UMOV X0, V0.B[0] // copy byte result back to integer reg
3904 SDValue Val = Op.getOperand(0);
3905 SDLoc DL(Op);
3906 EVT VT = Op.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00003907
Hao Liue0335d72015-01-30 02:13:53 +00003908 if (VT == MVT::i32)
3909 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
3910 Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
Tim Northover3b0846e2014-05-24 12:50:23 +00003911
Hao Liue0335d72015-01-30 02:13:53 +00003912 SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
Tim Northover3b0846e2014-05-24 12:50:23 +00003913 SDValue UaddLV = DAG.getNode(
3914 ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003915 DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
Tim Northover3b0846e2014-05-24 12:50:23 +00003916
3917 if (VT == MVT::i64)
3918 UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
3919 return UaddLV;
3920}
3921
3922SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
3923
3924 if (Op.getValueType().isVector())
3925 return LowerVSETCC(Op, DAG);
3926
3927 SDValue LHS = Op.getOperand(0);
3928 SDValue RHS = Op.getOperand(1);
3929 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
3930 SDLoc dl(Op);
3931
3932 // We chose ZeroOrOneBooleanContents, so use zero and one.
3933 EVT VT = Op.getValueType();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003934 SDValue TVal = DAG.getConstant(1, dl, VT);
3935 SDValue FVal = DAG.getConstant(0, dl, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00003936
3937 // Handle f128 first, since one possible outcome is a normal integer
3938 // comparison which gets picked up by the next if statement.
3939 if (LHS.getValueType() == MVT::f128) {
3940 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
3941
3942 // If softenSetCCOperands returned a scalar, use it.
3943 if (!RHS.getNode()) {
3944 assert(LHS.getValueType() == Op.getValueType() &&
3945 "Unexpected setcc expansion!");
3946 return LHS;
3947 }
3948 }
3949
3950 if (LHS.getValueType().isInteger()) {
3951 SDValue CCVal;
3952 SDValue Cmp =
3953 getAArch64Cmp(LHS, RHS, ISD::getSetCCInverse(CC, true), CCVal, DAG, dl);
3954
3955 // Note that we inverted the condition above, so we reverse the order of
3956 // the true and false operands here. This will allow the setcc to be
3957 // matched to a single CSINC instruction.
3958 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
3959 }
3960
3961 // Now we know we're dealing with FP values.
3962 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
3963
3964 // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
3965 // and do the comparison.
3966 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
3967
3968 AArch64CC::CondCode CC1, CC2;
3969 changeFPCCToAArch64CC(CC, CC1, CC2);
3970 if (CC2 == AArch64CC::AL) {
3971 changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, false), CC1, CC2);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003972 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003973
3974 // Note that we inverted the condition above, so we reverse the order of
3975 // the true and false operands here. This will allow the setcc to be
3976 // matched to a single CSINC instruction.
3977 return DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
3978 } else {
3979 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
3980 // totally clean. Some of them require two CSELs to implement. As is in
3981 // this case, we emit the first CSEL and then emit a second using the output
3982 // of the first as the RHS. We're effectively OR'ing the two CC's together.
3983
3984 // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003985 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003986 SDValue CS1 =
3987 DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
3988
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00003989 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00003990 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
3991 }
3992}
3993
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00003994SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
3995 SDValue RHS, SDValue TVal,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00003996 SDValue FVal, const SDLoc &dl,
Tim Northover3b0846e2014-05-24 12:50:23 +00003997 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00003998 // Handle f128 first, because it will result in a comparison of some RTLIB
3999 // call result against zero.
4000 if (LHS.getValueType() == MVT::f128) {
4001 softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl);
4002
4003 // If softenSetCCOperands returned a scalar, we need to compare the result
4004 // against zero to select between true and false values.
4005 if (!RHS.getNode()) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004006 RHS = DAG.getConstant(0, dl, LHS.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00004007 CC = ISD::SETNE;
4008 }
4009 }
4010
Ahmed Bougacha88ddeae2015-11-17 16:45:40 +00004011 // Also handle f16, for which we need to do a f32 comparison.
4012 if (LHS.getValueType() == MVT::f16) {
4013 LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
4014 RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
4015 }
4016
4017 // Next, handle integers.
Tim Northover3b0846e2014-05-24 12:50:23 +00004018 if (LHS.getValueType().isInteger()) {
4019 assert((LHS.getValueType() == RHS.getValueType()) &&
4020 (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
4021
4022 unsigned Opcode = AArch64ISD::CSEL;
4023
4024 // If both the TVal and the FVal are constants, see if we can swap them in
4025 // order to for a CSINV or CSINC out of them.
4026 ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
4027 ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
4028
4029 if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
4030 std::swap(TVal, FVal);
4031 std::swap(CTVal, CFVal);
4032 CC = ISD::getSetCCInverse(CC, true);
4033 } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
4034 std::swap(TVal, FVal);
4035 std::swap(CTVal, CFVal);
4036 CC = ISD::getSetCCInverse(CC, true);
4037 } else if (TVal.getOpcode() == ISD::XOR) {
4038 // If TVal is a NOT we want to swap TVal and FVal so that we can match
4039 // with a CSINV rather than a CSEL.
Artyom Skrobov314ee042015-11-25 19:41:11 +00004040 if (isAllOnesConstant(TVal.getOperand(1))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004041 std::swap(TVal, FVal);
4042 std::swap(CTVal, CFVal);
4043 CC = ISD::getSetCCInverse(CC, true);
4044 }
4045 } else if (TVal.getOpcode() == ISD::SUB) {
4046 // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
4047 // that we can match with a CSNEG rather than a CSEL.
Artyom Skrobov314ee042015-11-25 19:41:11 +00004048 if (isNullConstant(TVal.getOperand(0))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00004049 std::swap(TVal, FVal);
4050 std::swap(CTVal, CFVal);
4051 CC = ISD::getSetCCInverse(CC, true);
4052 }
4053 } else if (CTVal && CFVal) {
4054 const int64_t TrueVal = CTVal->getSExtValue();
4055 const int64_t FalseVal = CFVal->getSExtValue();
4056 bool Swap = false;
4057
4058 // If both TVal and FVal are constants, see if FVal is the
4059 // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
4060 // instead of a CSEL in that case.
4061 if (TrueVal == ~FalseVal) {
4062 Opcode = AArch64ISD::CSINV;
4063 } else if (TrueVal == -FalseVal) {
4064 Opcode = AArch64ISD::CSNEG;
4065 } else if (TVal.getValueType() == MVT::i32) {
4066 // If our operands are only 32-bit wide, make sure we use 32-bit
4067 // arithmetic for the check whether we can use CSINC. This ensures that
4068 // the addition in the check will wrap around properly in case there is
4069 // an overflow (which would not be the case if we do the check with
4070 // 64-bit arithmetic).
4071 const uint32_t TrueVal32 = CTVal->getZExtValue();
4072 const uint32_t FalseVal32 = CFVal->getZExtValue();
4073
4074 if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
4075 Opcode = AArch64ISD::CSINC;
4076
4077 if (TrueVal32 > FalseVal32) {
4078 Swap = true;
4079 }
4080 }
4081 // 64-bit check whether we can use CSINC.
4082 } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
4083 Opcode = AArch64ISD::CSINC;
4084
4085 if (TrueVal > FalseVal) {
4086 Swap = true;
4087 }
4088 }
4089
4090 // Swap TVal and FVal if necessary.
4091 if (Swap) {
4092 std::swap(TVal, FVal);
4093 std::swap(CTVal, CFVal);
4094 CC = ISD::getSetCCInverse(CC, true);
4095 }
4096
4097 if (Opcode != AArch64ISD::CSEL) {
4098 // Drop FVal since we can get its value by simply inverting/negating
4099 // TVal.
4100 FVal = TVal;
4101 }
4102 }
4103
Chad Rosier58f505b2016-08-26 18:05:50 +00004104 // Avoid materializing a constant when possible by reusing a known value in
4105 // a register. However, don't perform this optimization if the known value
Chad Rosier0c621fd2016-10-26 18:15:32 +00004106 // is one, zero or negative one in the case of a CSEL. We can always
4107 // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the
4108 // FVal, respectively.
Chad Rosier58f505b2016-08-26 18:05:50 +00004109 ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS);
4110 if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() &&
4111 !RHSVal->isNullValue() && !RHSVal->isAllOnesValue()) {
4112 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
4113 // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to
4114 // "a != C ? x : a" to avoid materializing C.
4115 if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ)
4116 TVal = LHS;
4117 else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE)
4118 FVal = LHS;
Chad Rosier0c621fd2016-10-26 18:15:32 +00004119 } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) {
4120 assert (CTVal && CFVal && "Expected constant operands for CSNEG.");
4121 // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to
4122 // avoid materializing C.
4123 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
4124 if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) {
4125 Opcode = AArch64ISD::CSINV;
4126 TVal = LHS;
4127 FVal = DAG.getConstant(0, dl, FVal.getValueType());
4128 }
Chad Rosier58f505b2016-08-26 18:05:50 +00004129 }
4130
Tim Northover3b0846e2014-05-24 12:50:23 +00004131 SDValue CCVal;
4132 SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
4133
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004134 EVT VT = TVal.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00004135 return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
4136 }
4137
4138 // Now we know we're dealing with FP values.
4139 assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
4140 assert(LHS.getValueType() == RHS.getValueType());
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004141 EVT VT = TVal.getValueType();
Tim Northover3b0846e2014-05-24 12:50:23 +00004142 SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
4143
4144 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
4145 // clean. Some of them require two CSELs to implement.
4146 AArch64CC::CondCode CC1, CC2;
4147 changeFPCCToAArch64CC(CC, CC1, CC2);
Evandro Menezesce8d6012016-10-18 20:37:35 +00004148
4149 if (DAG.getTarget().Options.UnsafeFPMath) {
4150 // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and
4151 // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0.
4152 ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS);
4153 if (RHSVal && RHSVal->isZero()) {
4154 ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal);
4155 ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal);
4156
4157 if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) &&
Roger Ferrer Ibanez80c0f332016-11-08 13:34:41 +00004158 CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType())
Evandro Menezesce8d6012016-10-18 20:37:35 +00004159 TVal = LHS;
4160 else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) &&
Roger Ferrer Ibanez80c0f332016-11-08 13:34:41 +00004161 CFVal && CFVal->isZero() &&
4162 FVal.getValueType() == LHS.getValueType())
Evandro Menezesce8d6012016-10-18 20:37:35 +00004163 FVal = LHS;
4164 }
4165 }
4166
4167 // Emit first, and possibly only, CSEL.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004168 SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004169 SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
4170
4171 // If we need a second CSEL, emit it, using the output of the first as the
4172 // RHS. We're effectively OR'ing the two CC's together.
4173 if (CC2 != AArch64CC::AL) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004174 SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00004175 return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
4176 }
4177
4178 // Otherwise, return the output of the first CSEL.
4179 return CS1;
4180}
4181
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004182SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
4183 SelectionDAG &DAG) const {
4184 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4185 SDValue LHS = Op.getOperand(0);
4186 SDValue RHS = Op.getOperand(1);
4187 SDValue TVal = Op.getOperand(2);
4188 SDValue FVal = Op.getOperand(3);
4189 SDLoc DL(Op);
4190 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4191}
4192
4193SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
4194 SelectionDAG &DAG) const {
4195 SDValue CCVal = Op->getOperand(0);
4196 SDValue TVal = Op->getOperand(1);
4197 SDValue FVal = Op->getOperand(2);
4198 SDLoc DL(Op);
4199
4200 unsigned Opc = CCVal.getOpcode();
4201 // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
4202 // instruction.
4203 if (CCVal.getResNo() == 1 &&
4204 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4205 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
4206 // Only lower legal XALUO ops.
4207 if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
4208 return SDValue();
4209
4210 AArch64CC::CondCode OFCC;
4211 SDValue Value, Overflow;
4212 std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004213 SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004214
4215 return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
4216 CCVal, Overflow);
4217 }
4218
4219 // Lower it the same way as we would lower a SELECT_CC node.
4220 ISD::CondCode CC;
4221 SDValue LHS, RHS;
4222 if (CCVal.getOpcode() == ISD::SETCC) {
4223 LHS = CCVal.getOperand(0);
4224 RHS = CCVal.getOperand(1);
4225 CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
4226 } else {
4227 LHS = CCVal;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004228 RHS = DAG.getConstant(0, DL, CCVal.getValueType());
Matthias Braunb6ac8fa2015-04-07 17:33:05 +00004229 CC = ISD::SETNE;
4230 }
4231 return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
4232}
4233
Tim Northover3b0846e2014-05-24 12:50:23 +00004234SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
4235 SelectionDAG &DAG) const {
4236 // Jump table entries as PC relative offsets. No additional tweaking
4237 // is necessary here. Just get the address of the jump table.
4238 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00004239 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004240 SDLoc DL(Op);
4241
4242 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4243 !Subtarget->isTargetMachO()) {
4244 const unsigned char MO_NC = AArch64II::MO_NC;
4245 return DAG.getNode(
4246 AArch64ISD::WrapperLarge, DL, PtrVT,
4247 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G3),
4248 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G2 | MO_NC),
4249 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_G1 | MO_NC),
4250 DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4251 AArch64II::MO_G0 | MO_NC));
4252 }
4253
4254 SDValue Hi =
4255 DAG.getTargetJumpTable(JT->getIndex(), PtrVT, AArch64II::MO_PAGE);
4256 SDValue Lo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
4257 AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4258 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4259 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4260}
4261
4262SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
4263 SelectionDAG &DAG) const {
4264 ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00004265 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004266 SDLoc DL(Op);
4267
4268 if (getTargetMachine().getCodeModel() == CodeModel::Large) {
4269 // Use the GOT for the large code model on iOS.
4270 if (Subtarget->isTargetMachO()) {
4271 SDValue GotAddr = DAG.getTargetConstantPool(
4272 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4273 AArch64II::MO_GOT);
4274 return DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, GotAddr);
4275 }
4276
4277 const unsigned char MO_NC = AArch64II::MO_NC;
4278 return DAG.getNode(
4279 AArch64ISD::WrapperLarge, DL, PtrVT,
4280 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4281 CP->getOffset(), AArch64II::MO_G3),
4282 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4283 CP->getOffset(), AArch64II::MO_G2 | MO_NC),
4284 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4285 CP->getOffset(), AArch64II::MO_G1 | MO_NC),
4286 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4287 CP->getOffset(), AArch64II::MO_G0 | MO_NC));
4288 } else {
4289 // Use ADRP/ADD or ADRP/LDR for everything else: the small memory model on
4290 // ELF, the only valid one on Darwin.
4291 SDValue Hi =
4292 DAG.getTargetConstantPool(CP->getConstVal(), PtrVT, CP->getAlignment(),
4293 CP->getOffset(), AArch64II::MO_PAGE);
4294 SDValue Lo = DAG.getTargetConstantPool(
4295 CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(),
4296 AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
4297
4298 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4299 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4300 }
4301}
4302
4303SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
4304 SelectionDAG &DAG) const {
4305 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
Mehdi Amini44ede332015-07-09 02:09:04 +00004306 EVT PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004307 SDLoc DL(Op);
4308 if (getTargetMachine().getCodeModel() == CodeModel::Large &&
4309 !Subtarget->isTargetMachO()) {
4310 const unsigned char MO_NC = AArch64II::MO_NC;
4311 return DAG.getNode(
4312 AArch64ISD::WrapperLarge, DL, PtrVT,
4313 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G3),
4314 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G2 | MO_NC),
4315 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G1 | MO_NC),
4316 DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_G0 | MO_NC));
4317 } else {
4318 SDValue Hi = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGE);
4319 SDValue Lo = DAG.getTargetBlockAddress(BA, PtrVT, 0, AArch64II::MO_PAGEOFF |
4320 AArch64II::MO_NC);
4321 SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, Hi);
4322 return DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, Lo);
4323 }
4324}
4325
4326SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
4327 SelectionDAG &DAG) const {
4328 AArch64FunctionInfo *FuncInfo =
4329 DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
4330
4331 SDLoc DL(Op);
Mehdi Amini44ede332015-07-09 02:09:04 +00004332 SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
4333 getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00004334 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4335 return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
Justin Lebar9c375812016-07-15 18:27:10 +00004336 MachinePointerInfo(SV));
Tim Northover3b0846e2014-05-24 12:50:23 +00004337}
4338
4339SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
4340 SelectionDAG &DAG) const {
4341 // The layout of the va_list struct is specified in the AArch64 Procedure Call
4342 // Standard, section B.3.
4343 MachineFunction &MF = DAG.getMachineFunction();
4344 AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
Mehdi Amini44ede332015-07-09 02:09:04 +00004345 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004346 SDLoc DL(Op);
4347
4348 SDValue Chain = Op.getOperand(0);
4349 SDValue VAList = Op.getOperand(1);
4350 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4351 SmallVector<SDValue, 4> MemOps;
4352
4353 // void *__stack at offset 0
Mehdi Amini44ede332015-07-09 02:09:04 +00004354 SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004355 MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
Justin Lebar9c375812016-07-15 18:27:10 +00004356 MachinePointerInfo(SV), /* Alignment = */ 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00004357
4358 // void *__gr_top at offset 8
4359 int GPRSize = FuncInfo->getVarArgsGPRSize();
4360 if (GPRSize > 0) {
4361 SDValue GRTop, GRTopAddr;
4362
Mehdi Amini44ede332015-07-09 02:09:04 +00004363 GRTopAddr =
4364 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(8, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004365
Mehdi Amini44ede332015-07-09 02:09:04 +00004366 GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
4367 GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
4368 DAG.getConstant(GPRSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004369
4370 MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
Justin Lebar9c375812016-07-15 18:27:10 +00004371 MachinePointerInfo(SV, 8),
4372 /* Alignment = */ 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00004373 }
4374
4375 // void *__vr_top at offset 16
4376 int FPRSize = FuncInfo->getVarArgsFPRSize();
4377 if (FPRSize > 0) {
4378 SDValue VRTop, VRTopAddr;
Mehdi Amini44ede332015-07-09 02:09:04 +00004379 VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4380 DAG.getConstant(16, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004381
Mehdi Amini44ede332015-07-09 02:09:04 +00004382 VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
4383 VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
4384 DAG.getConstant(FPRSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004385
4386 MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
Justin Lebar9c375812016-07-15 18:27:10 +00004387 MachinePointerInfo(SV, 16),
4388 /* Alignment = */ 8));
Tim Northover3b0846e2014-05-24 12:50:23 +00004389 }
4390
4391 // int __gr_offs at offset 24
Mehdi Amini44ede332015-07-09 02:09:04 +00004392 SDValue GROffsAddr =
4393 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(24, DL, PtrVT));
Justin Lebar9c375812016-07-15 18:27:10 +00004394 MemOps.push_back(DAG.getStore(
4395 Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32), GROffsAddr,
4396 MachinePointerInfo(SV, 24), /* Alignment = */ 4));
Tim Northover3b0846e2014-05-24 12:50:23 +00004397
4398 // int __vr_offs at offset 28
Mehdi Amini44ede332015-07-09 02:09:04 +00004399 SDValue VROffsAddr =
4400 DAG.getNode(ISD::ADD, DL, PtrVT, VAList, DAG.getConstant(28, DL, PtrVT));
Justin Lebar9c375812016-07-15 18:27:10 +00004401 MemOps.push_back(DAG.getStore(
4402 Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32), VROffsAddr,
4403 MachinePointerInfo(SV, 28), /* Alignment = */ 4));
Tim Northover3b0846e2014-05-24 12:50:23 +00004404
4405 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
4406}
4407
4408SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
4409 SelectionDAG &DAG) const {
4410 return Subtarget->isTargetDarwin() ? LowerDarwin_VASTART(Op, DAG)
4411 : LowerAAPCS_VASTART(Op, DAG);
4412}
4413
4414SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
4415 SelectionDAG &DAG) const {
4416 // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
4417 // pointer.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004418 SDLoc DL(Op);
Tim Northover3b0846e2014-05-24 12:50:23 +00004419 unsigned VaListSize = Subtarget->isTargetDarwin() ? 8 : 32;
4420 const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
4421 const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
4422
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004423 return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1),
4424 Op.getOperand(2),
4425 DAG.getConstant(VaListSize, DL, MVT::i32),
Krzysztof Parzyszeka46c36b2015-04-13 17:16:45 +00004426 8, false, false, false, MachinePointerInfo(DestSV),
Tim Northover3b0846e2014-05-24 12:50:23 +00004427 MachinePointerInfo(SrcSV));
4428}
4429
4430SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
4431 assert(Subtarget->isTargetDarwin() &&
4432 "automatic va_arg instruction only works on Darwin");
4433
4434 const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
4435 EVT VT = Op.getValueType();
4436 SDLoc DL(Op);
4437 SDValue Chain = Op.getOperand(0);
4438 SDValue Addr = Op.getOperand(1);
4439 unsigned Align = Op.getConstantOperandVal(3);
Mehdi Amini44ede332015-07-09 02:09:04 +00004440 auto PtrVT = getPointerTy(DAG.getDataLayout());
Tim Northover3b0846e2014-05-24 12:50:23 +00004441
Justin Lebar9c375812016-07-15 18:27:10 +00004442 SDValue VAList = DAG.getLoad(PtrVT, DL, Chain, Addr, MachinePointerInfo(V));
Tim Northover3b0846e2014-05-24 12:50:23 +00004443 Chain = VAList.getValue(1);
4444
4445 if (Align > 8) {
4446 assert(((Align & (Align - 1)) == 0) && "Expected Align to be a power of 2");
Mehdi Amini44ede332015-07-09 02:09:04 +00004447 VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4448 DAG.getConstant(Align - 1, DL, PtrVT));
4449 VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
4450 DAG.getConstant(-(int64_t)Align, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004451 }
4452
4453 Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
Mehdi Amini44ede332015-07-09 02:09:04 +00004454 uint64_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
Tim Northover3b0846e2014-05-24 12:50:23 +00004455
4456 // Scalar integer and FP values smaller than 64 bits are implicitly extended
4457 // up to 64 bits. At the very least, we have to increase the striding of the
4458 // vaargs list to match this, and for FP values we need to introduce
4459 // FP_ROUND nodes as well.
4460 if (VT.isInteger() && !VT.isVector())
4461 ArgSize = 8;
4462 bool NeedFPTrunc = false;
4463 if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
4464 ArgSize = 8;
4465 NeedFPTrunc = true;
4466 }
4467
4468 // Increment the pointer, VAList, to the next vaarg
Mehdi Amini44ede332015-07-09 02:09:04 +00004469 SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
4470 DAG.getConstant(ArgSize, DL, PtrVT));
Tim Northover3b0846e2014-05-24 12:50:23 +00004471 // Store the incremented VAList to the legalized pointer
Justin Lebar9c375812016-07-15 18:27:10 +00004472 SDValue APStore =
4473 DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V));
Tim Northover3b0846e2014-05-24 12:50:23 +00004474
4475 // Load the actual argument out of the pointer VAList
4476 if (NeedFPTrunc) {
4477 // Load the value as an f64.
Justin Lebar9c375812016-07-15 18:27:10 +00004478 SDValue WideFP =
4479 DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00004480 // Round the value down to an f32.
4481 SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004482 DAG.getIntPtrConstant(1, DL));
Tim Northover3b0846e2014-05-24 12:50:23 +00004483 SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
4484 // Merge the rounded value with the chain output of the load.
4485 return DAG.getMergeValues(Ops, DL);
4486 }
4487
Justin Lebar9c375812016-07-15 18:27:10 +00004488 return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00004489}
4490
4491SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
4492 SelectionDAG &DAG) const {
Matthias Braun941a7052016-07-28 18:40:00 +00004493 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
4494 MFI.setFrameAddressIsTaken(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00004495
4496 EVT VT = Op.getValueType();
4497 SDLoc DL(Op);
4498 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4499 SDValue FrameAddr =
4500 DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
4501 while (Depth--)
4502 FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
Justin Lebar9c375812016-07-15 18:27:10 +00004503 MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00004504 return FrameAddr;
4505}
4506
4507// FIXME? Maybe this could be a TableGen attribute on some registers and
4508// this table could be generated automatically from RegInfo.
Pat Gavlina717f252015-07-09 17:40:29 +00004509unsigned AArch64TargetLowering::getRegisterByName(const char* RegName, EVT VT,
4510 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004511 unsigned Reg = StringSwitch<unsigned>(RegName)
4512 .Case("sp", AArch64::SP)
Petr Hosekc3a9e6d2017-04-07 20:41:58 +00004513 .Case("x18", AArch64::X18)
4514 .Case("w18", AArch64::W18)
Tim Northover3b0846e2014-05-24 12:50:23 +00004515 .Default(0);
Petr Hosekc3a9e6d2017-04-07 20:41:58 +00004516 if ((Reg == AArch64::X18 || Reg == AArch64::W18) &&
4517 !Subtarget->isX18Reserved())
4518 Reg = 0;
Tim Northover3b0846e2014-05-24 12:50:23 +00004519 if (Reg)
4520 return Reg;
Luke Cheeseman85fd06d2015-06-01 12:02:47 +00004521 report_fatal_error(Twine("Invalid register name \""
4522 + StringRef(RegName) + "\"."));
Tim Northover3b0846e2014-05-24 12:50:23 +00004523}
4524
4525SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
4526 SelectionDAG &DAG) const {
4527 MachineFunction &MF = DAG.getMachineFunction();
Matthias Braun941a7052016-07-28 18:40:00 +00004528 MachineFrameInfo &MFI = MF.getFrameInfo();
4529 MFI.setReturnAddressIsTaken(true);
Tim Northover3b0846e2014-05-24 12:50:23 +00004530
4531 EVT VT = Op.getValueType();
4532 SDLoc DL(Op);
4533 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4534 if (Depth) {
4535 SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
Mehdi Amini44ede332015-07-09 02:09:04 +00004536 SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
Tim Northover3b0846e2014-05-24 12:50:23 +00004537 return DAG.getLoad(VT, DL, DAG.getEntryNode(),
4538 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
Justin Lebar9c375812016-07-15 18:27:10 +00004539 MachinePointerInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +00004540 }
4541
4542 // Return LR, which contains the return address. Mark it an implicit live-in.
4543 unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
4544 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4545}
4546
4547/// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4548/// i64 values and take a 2 x i64 value to shift plus a shift amount.
4549SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
4550 SelectionDAG &DAG) const {
4551 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4552 EVT VT = Op.getValueType();
4553 unsigned VTBits = VT.getSizeInBits();
4554 SDLoc dl(Op);
4555 SDValue ShOpLo = Op.getOperand(0);
4556 SDValue ShOpHi = Op.getOperand(1);
4557 SDValue ShAmt = Op.getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00004558 unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4559
4560 assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4561
4562 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004563 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
Tim Northoverf3be9d52015-12-02 00:33:54 +00004564 SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4565
4566 // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
4567 // is "undef". We wanted 0, so CSEL it directly.
4568 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
4569 ISD::SETEQ, dl, DAG);
4570 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
4571 HiBitsForLo =
4572 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
4573 HiBitsForLo, CCVal, Cmp);
4574
Tim Northover3b0846e2014-05-24 12:50:23 +00004575 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004576 DAG.getConstant(VTBits, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00004577
Tim Northoverf3be9d52015-12-02 00:33:54 +00004578 SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4579 SDValue LoForNormalShift =
4580 DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
Tim Northover3b0846e2014-05-24 12:50:23 +00004581
Tim Northoverf3be9d52015-12-02 00:33:54 +00004582 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
4583 dl, DAG);
4584 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4585 SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4586 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
4587 LoForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00004588
4589 // AArch64 shifts larger than the register width are wrapped rather than
4590 // clamped, so we can't just emit "hi >> x".
Tim Northoverf3be9d52015-12-02 00:33:54 +00004591 SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4592 SDValue HiForBigShift =
4593 Opc == ISD::SRA
4594 ? DAG.getNode(Opc, dl, VT, ShOpHi,
4595 DAG.getConstant(VTBits - 1, dl, MVT::i64))
4596 : DAG.getConstant(0, dl, VT);
4597 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
4598 HiForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00004599
4600 SDValue Ops[2] = { Lo, Hi };
4601 return DAG.getMergeValues(Ops, dl);
4602}
4603
4604/// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4605/// i64 values and take a 2 x i64 value to shift plus a shift amount.
4606SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
Tim Northoverf3be9d52015-12-02 00:33:54 +00004607 SelectionDAG &DAG) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004608 assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4609 EVT VT = Op.getValueType();
4610 unsigned VTBits = VT.getSizeInBits();
4611 SDLoc dl(Op);
4612 SDValue ShOpLo = Op.getOperand(0);
4613 SDValue ShOpHi = Op.getOperand(1);
4614 SDValue ShAmt = Op.getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00004615
4616 assert(Op.getOpcode() == ISD::SHL_PARTS);
4617 SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004618 DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
Tim Northoverf3be9d52015-12-02 00:33:54 +00004619 SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4620
4621 // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
4622 // is "undef". We wanted 0, so CSEL it directly.
4623 SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
4624 ISD::SETEQ, dl, DAG);
4625 SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
4626 LoBitsForHi =
4627 DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
4628 LoBitsForHi, CCVal, Cmp);
4629
Tim Northover3b0846e2014-05-24 12:50:23 +00004630 SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00004631 DAG.getConstant(VTBits, dl, MVT::i64));
Tim Northoverf3be9d52015-12-02 00:33:54 +00004632 SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4633 SDValue HiForNormalShift =
4634 DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
Tim Northover3b0846e2014-05-24 12:50:23 +00004635
Tim Northoverf3be9d52015-12-02 00:33:54 +00004636 SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
Tim Northover3b0846e2014-05-24 12:50:23 +00004637
Tim Northoverf3be9d52015-12-02 00:33:54 +00004638 Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
4639 dl, DAG);
4640 CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
4641 SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
4642 HiForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00004643
4644 // AArch64 shifts of larger than register sizes are wrapped rather than
4645 // clamped, so we can't just emit "lo << a" if a is too big.
Tim Northoverf3be9d52015-12-02 00:33:54 +00004646 SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
4647 SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4648 SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
4649 LoForNormalShift, CCVal, Cmp);
Tim Northover3b0846e2014-05-24 12:50:23 +00004650
4651 SDValue Ops[2] = { Lo, Hi };
4652 return DAG.getMergeValues(Ops, dl);
4653}
4654
4655bool AArch64TargetLowering::isOffsetFoldingLegal(
4656 const GlobalAddressSDNode *GA) const {
4657 // The AArch64 target doesn't support folding offsets into global addresses.
4658 return false;
4659}
4660
4661bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4662 // We can materialize #0.0 as fmov $Rd, XZR for 64-bit and 32-bit cases.
4663 // FIXME: We should be able to handle f128 as well with a clever lowering.
4664 if (Imm.isPosZero() && (VT == MVT::f64 || VT == MVT::f32))
4665 return true;
4666
4667 if (VT == MVT::f64)
4668 return AArch64_AM::getFP64Imm(Imm) != -1;
4669 else if (VT == MVT::f32)
4670 return AArch64_AM::getFP32Imm(Imm) != -1;
4671 return false;
4672}
4673
4674//===----------------------------------------------------------------------===//
4675// AArch64 Optimization Hooks
4676//===----------------------------------------------------------------------===//
4677
Evandro Menezeseff2bd92016-10-24 16:14:58 +00004678static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode,
4679 SDValue Operand, SelectionDAG &DAG,
4680 int &ExtraSteps) {
4681 EVT VT = Operand.getValueType();
4682 if (ST->hasNEON() &&
4683 (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 ||
4684 VT == MVT::f32 || VT == MVT::v1f32 ||
4685 VT == MVT::v2f32 || VT == MVT::v4f32)) {
4686 if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified)
4687 // For the reciprocal estimates, convergence is quadratic, so the number
4688 // of digits is doubled after each iteration. In ARMv8, the accuracy of
4689 // the initial estimate is 2^-8. Thus the number of extra steps to refine
4690 // the result for float (23 mantissa bits) is 2 and for double (52
4691 // mantissa bits) is 3.
4692 ExtraSteps = VT == MVT::f64 ? 3 : 2;
4693
4694 return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand);
4695 }
4696
4697 return SDValue();
4698}
4699
Evandro Menezes21f9ce12016-11-10 23:31:06 +00004700SDValue AArch64TargetLowering::getSqrtEstimate(SDValue Operand,
4701 SelectionDAG &DAG, int Enabled,
4702 int &ExtraSteps,
4703 bool &UseOneConst,
4704 bool Reciprocal) const {
Evandro Menezeseff2bd92016-10-24 16:14:58 +00004705 if (Enabled == ReciprocalEstimate::Enabled ||
4706 (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt()))
4707 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, Operand,
4708 DAG, ExtraSteps)) {
Evandro Menezes9fc54822016-11-14 23:29:01 +00004709 SDLoc DL(Operand);
4710 EVT VT = Operand.getValueType();
4711
4712 SDNodeFlags Flags;
4713 Flags.setUnsafeAlgebra(true);
4714
4715 // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2)
4716 // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N)
4717 for (int i = ExtraSteps; i > 0; --i) {
4718 SDValue Step = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Estimate,
4719 &Flags);
4720 Step = DAG.getNode(AArch64ISD::FRSQRTS, DL, VT, Operand, Step, &Flags);
4721 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, &Flags);
4722 }
4723
4724 if (!Reciprocal) {
4725 EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
4726 VT);
4727 SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
4728 SDValue Eq = DAG.getSetCC(DL, CCVT, Operand, FPZero, ISD::SETEQ);
4729
4730 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Operand, Estimate, &Flags);
4731 // Correct the result if the operand is 0.0.
4732 Estimate = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT, DL,
4733 VT, Eq, Operand, Estimate);
4734 }
4735
4736 ExtraSteps = 0;
Evandro Menezeseff2bd92016-10-24 16:14:58 +00004737 return Estimate;
4738 }
4739
4740 return SDValue();
4741}
4742
4743SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand,
4744 SelectionDAG &DAG, int Enabled,
4745 int &ExtraSteps) const {
4746 if (Enabled == ReciprocalEstimate::Enabled)
4747 if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand,
Evandro Menezes9fc54822016-11-14 23:29:01 +00004748 DAG, ExtraSteps)) {
4749 SDLoc DL(Operand);
4750 EVT VT = Operand.getValueType();
4751
4752 SDNodeFlags Flags;
4753 Flags.setUnsafeAlgebra(true);
4754
4755 // Newton reciprocal iteration: E * (2 - X * E)
4756 // AArch64 reciprocal iteration instruction: (2 - M * N)
4757 for (int i = ExtraSteps; i > 0; --i) {
4758 SDValue Step = DAG.getNode(AArch64ISD::FRECPS, DL, VT, Operand,
4759 Estimate, &Flags);
4760 Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, &Flags);
4761 }
4762
4763 ExtraSteps = 0;
Evandro Menezeseff2bd92016-10-24 16:14:58 +00004764 return Estimate;
Evandro Menezes9fc54822016-11-14 23:29:01 +00004765 }
Evandro Menezeseff2bd92016-10-24 16:14:58 +00004766
4767 return SDValue();
4768}
4769
Tim Northover3b0846e2014-05-24 12:50:23 +00004770//===----------------------------------------------------------------------===//
4771// AArch64 Inline Assembly Support
4772//===----------------------------------------------------------------------===//
4773
4774// Table of Constraints
4775// TODO: This is the current set of constraints supported by ARM for the
4776// compiler, not all of them may make sense, e.g. S may be difficult to support.
4777//
4778// r - A general register
4779// w - An FP/SIMD register of some size in the range v0-v31
4780// x - An FP/SIMD register of some size in the range v0-v15
4781// I - Constant that can be used with an ADD instruction
4782// J - Constant that can be used with a SUB instruction
4783// K - Constant that can be used with a 32-bit logical instruction
4784// L - Constant that can be used with a 64-bit logical instruction
4785// M - Constant that can be used as a 32-bit MOV immediate
4786// N - Constant that can be used as a 64-bit MOV immediate
4787// Q - A memory reference with base register and no offset
4788// S - A symbolic address
4789// Y - Floating point constant zero
4790// Z - Integer constant zero
4791//
4792// Note that general register operands will be output using their 64-bit x
4793// register name, whatever the size of the variable, unless the asm operand
4794// is prefixed by the %w modifier. Floating-point and SIMD register operands
4795// will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
4796// %q modifier.
Silviu Barangaf60be282016-05-09 11:10:44 +00004797const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
4798 // At this point, we have to lower this constraint to something else, so we
4799 // lower it to an "r" or "w". However, by doing this we will force the result
4800 // to be in register, while the X constraint is much more permissive.
4801 //
4802 // Although we are correct (we are free to emit anything, without
4803 // constraints), we might break use cases that would expect us to be more
4804 // efficient and emit something else.
4805 if (!Subtarget->hasFPARMv8())
4806 return "r";
4807
4808 if (ConstraintVT.isFloatingPoint())
4809 return "w";
4810
4811 if (ConstraintVT.isVector() &&
4812 (ConstraintVT.getSizeInBits() == 64 ||
4813 ConstraintVT.getSizeInBits() == 128))
4814 return "w";
4815
4816 return "r";
4817}
Tim Northover3b0846e2014-05-24 12:50:23 +00004818
4819/// getConstraintType - Given a constraint letter, return the type of
4820/// constraint it is for this target.
4821AArch64TargetLowering::ConstraintType
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00004822AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004823 if (Constraint.size() == 1) {
4824 switch (Constraint[0]) {
4825 default:
4826 break;
4827 case 'z':
4828 return C_Other;
4829 case 'x':
4830 case 'w':
4831 return C_RegisterClass;
4832 // An address with a single base register. Due to the way we
4833 // currently handle addresses it is the same as 'r'.
4834 case 'Q':
4835 return C_Memory;
4836 }
4837 }
4838 return TargetLowering::getConstraintType(Constraint);
4839}
4840
4841/// Examine constraint type and operand type and determine a weight value.
4842/// This object must already have been set up with the operand type
4843/// and the current alternative constraint selected.
4844TargetLowering::ConstraintWeight
4845AArch64TargetLowering::getSingleConstraintMatchWeight(
4846 AsmOperandInfo &info, const char *constraint) const {
4847 ConstraintWeight weight = CW_Invalid;
4848 Value *CallOperandVal = info.CallOperandVal;
4849 // If we don't have a value, we can't do a match,
4850 // but allow it at the lowest weight.
4851 if (!CallOperandVal)
4852 return CW_Default;
4853 Type *type = CallOperandVal->getType();
4854 // Look at the constraint type.
4855 switch (*constraint) {
4856 default:
4857 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
4858 break;
4859 case 'x':
4860 case 'w':
4861 if (type->isFloatingPointTy() || type->isVectorTy())
4862 weight = CW_Register;
4863 break;
4864 case 'z':
4865 weight = CW_Constant;
4866 break;
4867 }
4868 return weight;
4869}
4870
4871std::pair<unsigned, const TargetRegisterClass *>
4872AArch64TargetLowering::getRegForInlineAsmConstraint(
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00004873 const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00004874 if (Constraint.size() == 1) {
4875 switch (Constraint[0]) {
4876 case 'r':
4877 if (VT.getSizeInBits() == 64)
4878 return std::make_pair(0U, &AArch64::GPR64commonRegClass);
4879 return std::make_pair(0U, &AArch64::GPR32commonRegClass);
4880 case 'w':
Amara Emerson614b44b2016-11-07 15:42:12 +00004881 if (VT.getSizeInBits() == 16)
4882 return std::make_pair(0U, &AArch64::FPR16RegClass);
Akira Hatanakab8d28732016-07-21 21:39:05 +00004883 if (VT.getSizeInBits() == 32)
Tim Northover3b0846e2014-05-24 12:50:23 +00004884 return std::make_pair(0U, &AArch64::FPR32RegClass);
4885 if (VT.getSizeInBits() == 64)
4886 return std::make_pair(0U, &AArch64::FPR64RegClass);
4887 if (VT.getSizeInBits() == 128)
4888 return std::make_pair(0U, &AArch64::FPR128RegClass);
4889 break;
4890 // The instructions that this constraint is designed for can
4891 // only take 128-bit registers so just use that regclass.
4892 case 'x':
4893 if (VT.getSizeInBits() == 128)
4894 return std::make_pair(0U, &AArch64::FPR128_loRegClass);
4895 break;
4896 }
4897 }
4898 if (StringRef("{cc}").equals_lower(Constraint))
4899 return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
4900
4901 // Use the default implementation in TargetLowering to convert the register
4902 // constraint into a member of a register class.
4903 std::pair<unsigned, const TargetRegisterClass *> Res;
Eric Christopher11e4df72015-02-26 22:38:43 +00004904 Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
Tim Northover3b0846e2014-05-24 12:50:23 +00004905
4906 // Not found as a standard register?
4907 if (!Res.second) {
4908 unsigned Size = Constraint.size();
4909 if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
4910 tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
Benjamin Kramer9bfb6272015-07-05 19:29:18 +00004911 int RegNo;
4912 bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
4913 if (!Failed && RegNo >= 0 && RegNo <= 31) {
Tim Northover9508a702016-05-10 22:26:45 +00004914 // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size.
Tim Northover3b0846e2014-05-24 12:50:23 +00004915 // By default we'll emit v0-v31 for this unless there's a modifier where
4916 // we'll emit the correct register as well.
Tim Northover9508a702016-05-10 22:26:45 +00004917 if (VT != MVT::Other && VT.getSizeInBits() == 64) {
4918 Res.first = AArch64::FPR64RegClass.getRegister(RegNo);
4919 Res.second = &AArch64::FPR64RegClass;
4920 } else {
4921 Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
4922 Res.second = &AArch64::FPR128RegClass;
4923 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004924 }
4925 }
4926 }
4927
4928 return Res;
4929}
4930
4931/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
4932/// vector. If it is invalid, don't add anything to Ops.
4933void AArch64TargetLowering::LowerAsmOperandForConstraint(
4934 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
4935 SelectionDAG &DAG) const {
4936 SDValue Result;
4937
4938 // Currently only support length 1 constraints.
4939 if (Constraint.length() != 1)
4940 return;
4941
4942 char ConstraintLetter = Constraint[0];
4943 switch (ConstraintLetter) {
4944 default:
4945 break;
4946
4947 // This set of constraints deal with valid constants for various instructions.
4948 // Validate and return a target constant for them if we can.
4949 case 'z': {
4950 // 'z' maps to xzr or wzr so it needs an input of 0.
Artyom Skrobov314ee042015-11-25 19:41:11 +00004951 if (!isNullConstant(Op))
Tim Northover3b0846e2014-05-24 12:50:23 +00004952 return;
4953
4954 if (Op.getValueType() == MVT::i64)
4955 Result = DAG.getRegister(AArch64::XZR, MVT::i64);
4956 else
4957 Result = DAG.getRegister(AArch64::WZR, MVT::i32);
4958 break;
4959 }
4960
4961 case 'I':
4962 case 'J':
4963 case 'K':
4964 case 'L':
4965 case 'M':
4966 case 'N':
4967 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
4968 if (!C)
4969 return;
4970
4971 // Grab the value and do some validation.
4972 uint64_t CVal = C->getZExtValue();
4973 switch (ConstraintLetter) {
4974 // The I constraint applies only to simple ADD or SUB immediate operands:
4975 // i.e. 0 to 4095 with optional shift by 12
4976 // The J constraint applies only to ADD or SUB immediates that would be
4977 // valid when negated, i.e. if [an add pattern] were to be output as a SUB
4978 // instruction [or vice versa], in other words -1 to -4095 with optional
4979 // left shift by 12.
4980 case 'I':
4981 if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
4982 break;
4983 return;
4984 case 'J': {
4985 uint64_t NVal = -C->getSExtValue();
Tim Northover2c46beb2014-07-27 07:10:29 +00004986 if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
4987 CVal = C->getSExtValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00004988 break;
Tim Northover2c46beb2014-07-27 07:10:29 +00004989 }
Tim Northover3b0846e2014-05-24 12:50:23 +00004990 return;
4991 }
4992 // The K and L constraints apply *only* to logical immediates, including
4993 // what used to be the MOVI alias for ORR (though the MOVI alias has now
4994 // been removed and MOV should be used). So these constraints have to
4995 // distinguish between bit patterns that are valid 32-bit or 64-bit
4996 // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
4997 // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
4998 // versa.
4999 case 'K':
5000 if (AArch64_AM::isLogicalImmediate(CVal, 32))
5001 break;
5002 return;
5003 case 'L':
5004 if (AArch64_AM::isLogicalImmediate(CVal, 64))
5005 break;
5006 return;
5007 // The M and N constraints are a superset of K and L respectively, for use
5008 // with the MOV (immediate) alias. As well as the logical immediates they
5009 // also match 32 or 64-bit immediates that can be loaded either using a
5010 // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
5011 // (M) or 64-bit 0x1234000000000000 (N) etc.
5012 // As a note some of this code is liberally stolen from the asm parser.
5013 case 'M': {
5014 if (!isUInt<32>(CVal))
5015 return;
5016 if (AArch64_AM::isLogicalImmediate(CVal, 32))
5017 break;
5018 if ((CVal & 0xFFFF) == CVal)
5019 break;
5020 if ((CVal & 0xFFFF0000ULL) == CVal)
5021 break;
5022 uint64_t NCVal = ~(uint32_t)CVal;
5023 if ((NCVal & 0xFFFFULL) == NCVal)
5024 break;
5025 if ((NCVal & 0xFFFF0000ULL) == NCVal)
5026 break;
5027 return;
5028 }
5029 case 'N': {
5030 if (AArch64_AM::isLogicalImmediate(CVal, 64))
5031 break;
5032 if ((CVal & 0xFFFFULL) == CVal)
5033 break;
5034 if ((CVal & 0xFFFF0000ULL) == CVal)
5035 break;
5036 if ((CVal & 0xFFFF00000000ULL) == CVal)
5037 break;
5038 if ((CVal & 0xFFFF000000000000ULL) == CVal)
5039 break;
5040 uint64_t NCVal = ~CVal;
5041 if ((NCVal & 0xFFFFULL) == NCVal)
5042 break;
5043 if ((NCVal & 0xFFFF0000ULL) == NCVal)
5044 break;
5045 if ((NCVal & 0xFFFF00000000ULL) == NCVal)
5046 break;
5047 if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
5048 break;
5049 return;
5050 }
5051 default:
5052 return;
5053 }
5054
5055 // All assembler immediates are 64-bit integers.
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005056 Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00005057 break;
5058 }
5059
5060 if (Result.getNode()) {
5061 Ops.push_back(Result);
5062 return;
5063 }
5064
5065 return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
5066}
5067
5068//===----------------------------------------------------------------------===//
5069// AArch64 Advanced SIMD Support
5070//===----------------------------------------------------------------------===//
5071
5072/// WidenVector - Given a value in the V64 register class, produce the
5073/// equivalent value in the V128 register class.
5074static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
5075 EVT VT = V64Reg.getValueType();
5076 unsigned NarrowSize = VT.getVectorNumElements();
5077 MVT EltTy = VT.getVectorElementType().getSimpleVT();
5078 MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
5079 SDLoc DL(V64Reg);
5080
5081 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005082 V64Reg, DAG.getConstant(0, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005083}
5084
5085/// getExtFactor - Determine the adjustment factor for the position when
5086/// generating an "extract from vector registers" instruction.
5087static unsigned getExtFactor(SDValue &V) {
5088 EVT EltType = V.getValueType().getVectorElementType();
5089 return EltType.getSizeInBits() / 8;
5090}
5091
5092/// NarrowVector - Given a value in the V128 register class, produce the
5093/// equivalent value in the V64 register class.
5094static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
5095 EVT VT = V128Reg.getValueType();
5096 unsigned WideSize = VT.getVectorNumElements();
5097 MVT EltTy = VT.getVectorElementType().getSimpleVT();
5098 MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
5099 SDLoc DL(V128Reg);
5100
5101 return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
5102}
5103
5104// Gather data to see if the operation can be modelled as a
5105// shuffle in combination with VEXTs.
5106SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
5107 SelectionDAG &DAG) const {
Kevin Qinf0ec9af2014-06-18 05:54:42 +00005108 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
Tim Northover3b0846e2014-05-24 12:50:23 +00005109 SDLoc dl(Op);
5110 EVT VT = Op.getValueType();
5111 unsigned NumElts = VT.getVectorNumElements();
5112
Tim Northover7324e842014-07-24 15:39:55 +00005113 struct ShuffleSourceInfo {
5114 SDValue Vec;
5115 unsigned MinElt;
5116 unsigned MaxElt;
Tim Northover3b0846e2014-05-24 12:50:23 +00005117
Tim Northover7324e842014-07-24 15:39:55 +00005118 // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
5119 // be compatible with the shuffle we intend to construct. As a result
5120 // ShuffleVec will be some sliding window into the original Vec.
5121 SDValue ShuffleVec;
5122
5123 // Code should guarantee that element i in Vec starts at element "WindowBase
5124 // + i * WindowScale in ShuffleVec".
5125 int WindowBase;
5126 int WindowScale;
5127
Tim Northover7324e842014-07-24 15:39:55 +00005128 ShuffleSourceInfo(SDValue Vec)
Eugene Zelenko049b0172017-01-06 00:30:53 +00005129 : Vec(Vec), MinElt(std::numeric_limits<unsigned>::max()), MaxElt(0),
5130 ShuffleVec(Vec), WindowBase(0), WindowScale(1) {}
5131
5132 bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
Tim Northover7324e842014-07-24 15:39:55 +00005133 };
5134
5135 // First gather all vectors used as an immediate source for this BUILD_VECTOR
5136 // node.
5137 SmallVector<ShuffleSourceInfo, 2> Sources;
Tim Northover3b0846e2014-05-24 12:50:23 +00005138 for (unsigned i = 0; i < NumElts; ++i) {
5139 SDValue V = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00005140 if (V.isUndef())
Tim Northover3b0846e2014-05-24 12:50:23 +00005141 continue;
Ahmed Bougachadfc77352016-01-14 02:12:30 +00005142 else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5143 !isa<ConstantSDNode>(V.getOperand(1))) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005144 // A shuffle can only come from building a vector from various
Ahmed Bougachadfc77352016-01-14 02:12:30 +00005145 // elements of other vectors, provided their indices are constant.
Tim Northover3b0846e2014-05-24 12:50:23 +00005146 return SDValue();
5147 }
5148
Tim Northover7324e842014-07-24 15:39:55 +00005149 // Add this element source to the list if it's not already there.
Tim Northover3b0846e2014-05-24 12:50:23 +00005150 SDValue SourceVec = V.getOperand(0);
David Majnemer0d955d02016-08-11 22:21:41 +00005151 auto Source = find(Sources, SourceVec);
Tim Northover7324e842014-07-24 15:39:55 +00005152 if (Source == Sources.end())
James Molloyf497d552014-10-17 17:06:31 +00005153 Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
Tim Northover3b0846e2014-05-24 12:50:23 +00005154
Tim Northover7324e842014-07-24 15:39:55 +00005155 // Update the minimum and maximum lane number seen.
5156 unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
5157 Source->MinElt = std::min(Source->MinElt, EltNo);
5158 Source->MaxElt = std::max(Source->MaxElt, EltNo);
Tim Northover3b0846e2014-05-24 12:50:23 +00005159 }
5160
5161 // Currently only do something sane when at most two source vectors
Tim Northover7324e842014-07-24 15:39:55 +00005162 // are involved.
5163 if (Sources.size() > 2)
Tim Northover3b0846e2014-05-24 12:50:23 +00005164 return SDValue();
5165
Kevin Qin9a2a2c52014-07-24 02:05:42 +00005166 // Find out the smallest element size among result and two sources, and use
5167 // it as element size to build the shuffle_vector.
5168 EVT SmallestEltTy = VT.getVectorElementType();
Tim Northover7324e842014-07-24 15:39:55 +00005169 for (auto &Source : Sources) {
5170 EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00005171 if (SrcEltTy.bitsLT(SmallestEltTy)) {
5172 SmallestEltTy = SrcEltTy;
5173 }
5174 }
5175 unsigned ResMultiplier =
Sanjay Patel1ed771f2016-09-14 16:37:15 +00005176 VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00005177 NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
5178 EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
Tim Northover3b0846e2014-05-24 12:50:23 +00005179
Tim Northover7324e842014-07-24 15:39:55 +00005180 // If the source vector is too wide or too narrow, we may nevertheless be able
5181 // to construct a compatible shuffle either by concatenating it with UNDEF or
5182 // extracting a suitable range of elements.
5183 for (auto &Src : Sources) {
5184 EVT SrcVT = Src.ShuffleVec.getValueType();
Kevin Qinf0ec9af2014-06-18 05:54:42 +00005185
Tim Northover7324e842014-07-24 15:39:55 +00005186 if (SrcVT.getSizeInBits() == VT.getSizeInBits())
Tim Northover3b0846e2014-05-24 12:50:23 +00005187 continue;
Tim Northover7324e842014-07-24 15:39:55 +00005188
5189 // This stage of the search produces a source with the same element type as
5190 // the original, but with a total width matching the BUILD_VECTOR output.
5191 EVT EltVT = SrcVT.getVectorElementType();
James Molloyf497d552014-10-17 17:06:31 +00005192 unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
5193 EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
Tim Northover7324e842014-07-24 15:39:55 +00005194
5195 if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
5196 assert(2 * SrcVT.getSizeInBits() == VT.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00005197 // We can pad out the smaller vector for free, so if it's part of a
5198 // shuffle...
Tim Northover7324e842014-07-24 15:39:55 +00005199 Src.ShuffleVec =
5200 DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
5201 DAG.getUNDEF(Src.ShuffleVec.getValueType()));
Tim Northover3b0846e2014-05-24 12:50:23 +00005202 continue;
5203 }
5204
Tim Northover7324e842014-07-24 15:39:55 +00005205 assert(SrcVT.getSizeInBits() == 2 * VT.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00005206
James Molloyf497d552014-10-17 17:06:31 +00005207 if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005208 // Span too large for a VEXT to cope
5209 return SDValue();
5210 }
5211
James Molloyf497d552014-10-17 17:06:31 +00005212 if (Src.MinElt >= NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005213 // The extraction can just take the second half
Tim Northover7324e842014-07-24 15:39:55 +00005214 Src.ShuffleVec =
5215 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005216 DAG.getConstant(NumSrcElts, dl, MVT::i64));
James Molloyf497d552014-10-17 17:06:31 +00005217 Src.WindowBase = -NumSrcElts;
5218 } else if (Src.MaxElt < NumSrcElts) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005219 // The extraction can just take the first half
Tim Northover5e84fe32014-12-06 00:33:37 +00005220 Src.ShuffleVec =
5221 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005222 DAG.getConstant(0, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005223 } else {
5224 // An actual VEXT is needed
Tim Northover5e84fe32014-12-06 00:33:37 +00005225 SDValue VEXTSrc1 =
5226 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005227 DAG.getConstant(0, dl, MVT::i64));
Tim Northover7324e842014-07-24 15:39:55 +00005228 SDValue VEXTSrc2 =
5229 DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005230 DAG.getConstant(NumSrcElts, dl, MVT::i64));
Tim Northover7324e842014-07-24 15:39:55 +00005231 unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
5232
5233 Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005234 VEXTSrc2,
5235 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover7324e842014-07-24 15:39:55 +00005236 Src.WindowBase = -Src.MinElt;
Tim Northover3b0846e2014-05-24 12:50:23 +00005237 }
5238 }
5239
Tim Northover7324e842014-07-24 15:39:55 +00005240 // Another possible incompatibility occurs from the vector element types. We
5241 // can fix this by bitcasting the source vectors to the same type we intend
5242 // for the shuffle.
5243 for (auto &Src : Sources) {
5244 EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
5245 if (SrcEltTy == SmallestEltTy)
5246 continue;
5247 assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
5248 Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
5249 Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
5250 Src.WindowBase *= Src.WindowScale;
5251 }
Tim Northover3b0846e2014-05-24 12:50:23 +00005252
Tim Northover7324e842014-07-24 15:39:55 +00005253 // Final sanity check before we try to actually produce a shuffle.
5254 DEBUG(
5255 for (auto Src : Sources)
5256 assert(Src.ShuffleVec.getValueType() == ShuffleVT);
5257 );
5258
5259 // The stars all align, our next step is to produce the mask for the shuffle.
5260 SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
Sanjay Patel1ed771f2016-09-14 16:37:15 +00005261 int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
Kevin Qin9a2a2c52014-07-24 02:05:42 +00005262 for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005263 SDValue Entry = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00005264 if (Entry.isUndef())
Tim Northover7324e842014-07-24 15:39:55 +00005265 continue;
Tim Northover3b0846e2014-05-24 12:50:23 +00005266
David Majnemer0d955d02016-08-11 22:21:41 +00005267 auto Src = find(Sources, Entry.getOperand(0));
Tim Northover7324e842014-07-24 15:39:55 +00005268 int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
5269
5270 // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
5271 // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
5272 // segment.
5273 EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
Sanjay Patel1ed771f2016-09-14 16:37:15 +00005274 int BitsDefined =
5275 std::min(OrigEltTy.getSizeInBits(), VT.getScalarSizeInBits());
Tim Northover7324e842014-07-24 15:39:55 +00005276 int LanesDefined = BitsDefined / BitsPerShuffleLane;
5277
5278 // This source is expected to fill ResMultiplier lanes of the final shuffle,
5279 // starting at the appropriate offset.
5280 int *LaneMask = &Mask[i * ResMultiplier];
5281
5282 int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
5283 ExtractBase += NumElts * (Src - Sources.begin());
5284 for (int j = 0; j < LanesDefined; ++j)
5285 LaneMask[j] = ExtractBase + j;
Tim Northover3b0846e2014-05-24 12:50:23 +00005286 }
5287
5288 // Final check before we try to produce nonsense...
Tim Northover7324e842014-07-24 15:39:55 +00005289 if (!isShuffleMaskLegal(Mask, ShuffleVT))
5290 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00005291
Tim Northover7324e842014-07-24 15:39:55 +00005292 SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
5293 for (unsigned i = 0; i < Sources.size(); ++i)
5294 ShuffleOps[i] = Sources[i].ShuffleVec;
5295
5296 SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
Craig Topper2bd8b4b2016-07-01 06:54:47 +00005297 ShuffleOps[1], Mask);
Tim Northover7324e842014-07-24 15:39:55 +00005298 return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
Tim Northover3b0846e2014-05-24 12:50:23 +00005299}
5300
5301// check if an EXT instruction can handle the shuffle mask when the
5302// vector sources of the shuffle are the same.
5303static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
5304 unsigned NumElts = VT.getVectorNumElements();
5305
5306 // Assume that the first shuffle index is not UNDEF. Fail if it is.
5307 if (M[0] < 0)
5308 return false;
5309
5310 Imm = M[0];
5311
5312 // If this is a VEXT shuffle, the immediate value is the index of the first
5313 // element. The other shuffle indices must be the successive elements after
5314 // the first one.
5315 unsigned ExpectedElt = Imm;
5316 for (unsigned i = 1; i < NumElts; ++i) {
5317 // Increment the expected index. If it wraps around, just follow it
5318 // back to index zero and keep going.
5319 ++ExpectedElt;
5320 if (ExpectedElt == NumElts)
5321 ExpectedElt = 0;
5322
5323 if (M[i] < 0)
5324 continue; // ignore UNDEF indices
5325 if (ExpectedElt != static_cast<unsigned>(M[i]))
5326 return false;
5327 }
5328
5329 return true;
5330}
5331
5332// check if an EXT instruction can handle the shuffle mask when the
5333// vector sources of the shuffle are different.
5334static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
5335 unsigned &Imm) {
5336 // Look for the first non-undef element.
David Majnemer562e8292016-08-12 00:18:03 +00005337 const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; });
Tim Northover3b0846e2014-05-24 12:50:23 +00005338
5339 // Benefit form APInt to handle overflow when calculating expected element.
5340 unsigned NumElts = VT.getVectorNumElements();
5341 unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
5342 APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
5343 // The following shuffle indices must be the successive elements after the
5344 // first real element.
5345 const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
5346 [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
5347 if (FirstWrongElt != M.end())
5348 return false;
5349
5350 // The index of an EXT is the first element if it is not UNDEF.
5351 // Watch out for the beginning UNDEFs. The EXT index should be the expected
Junmo Park3b8c7152016-01-05 09:36:47 +00005352 // value of the first element. E.g.
Tim Northover3b0846e2014-05-24 12:50:23 +00005353 // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
5354 // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
5355 // ExpectedElt is the last mask index plus 1.
5356 Imm = ExpectedElt.getZExtValue();
5357
5358 // There are two difference cases requiring to reverse input vectors.
5359 // For example, for vector <4 x i32> we have the following cases,
5360 // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
5361 // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
5362 // For both cases, we finally use mask <5, 6, 7, 0>, which requires
5363 // to reverse two input vectors.
5364 if (Imm < NumElts)
5365 ReverseEXT = true;
5366 else
5367 Imm -= NumElts;
5368
5369 return true;
5370}
5371
5372/// isREVMask - Check if a vector shuffle corresponds to a REV
5373/// instruction with the specified blocksize. (The order of the elements
5374/// within each block of the vector is reversed.)
5375static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5376 assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
5377 "Only possible block sizes for REV are: 16, 32, 64");
5378
Sanjay Patel1ed771f2016-09-14 16:37:15 +00005379 unsigned EltSz = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00005380 if (EltSz == 64)
5381 return false;
5382
5383 unsigned NumElts = VT.getVectorNumElements();
5384 unsigned BlockElts = M[0] + 1;
5385 // If the first shuffle index is UNDEF, be optimistic.
5386 if (M[0] < 0)
5387 BlockElts = BlockSize / EltSz;
5388
5389 if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5390 return false;
5391
5392 for (unsigned i = 0; i < NumElts; ++i) {
5393 if (M[i] < 0)
5394 continue; // ignore UNDEF indices
5395 if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
5396 return false;
5397 }
5398
5399 return true;
5400}
5401
5402static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5403 unsigned NumElts = VT.getVectorNumElements();
5404 WhichResult = (M[0] == 0 ? 0 : 1);
5405 unsigned Idx = WhichResult * NumElts / 2;
5406 for (unsigned i = 0; i != NumElts; i += 2) {
5407 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5408 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
5409 return false;
5410 Idx += 1;
5411 }
5412
5413 return true;
5414}
5415
5416static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5417 unsigned NumElts = VT.getVectorNumElements();
5418 WhichResult = (M[0] == 0 ? 0 : 1);
5419 for (unsigned i = 0; i != NumElts; ++i) {
5420 if (M[i] < 0)
5421 continue; // ignore UNDEF indices
5422 if ((unsigned)M[i] != 2 * i + WhichResult)
5423 return false;
5424 }
5425
5426 return true;
5427}
5428
5429static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5430 unsigned NumElts = VT.getVectorNumElements();
5431 WhichResult = (M[0] == 0 ? 0 : 1);
5432 for (unsigned i = 0; i < NumElts; i += 2) {
5433 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5434 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
5435 return false;
5436 }
5437 return true;
5438}
5439
5440/// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
5441/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5442/// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5443static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5444 unsigned NumElts = VT.getVectorNumElements();
5445 WhichResult = (M[0] == 0 ? 0 : 1);
5446 unsigned Idx = WhichResult * NumElts / 2;
5447 for (unsigned i = 0; i != NumElts; i += 2) {
5448 if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
5449 (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
5450 return false;
5451 Idx += 1;
5452 }
5453
5454 return true;
5455}
5456
5457/// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
5458/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5459/// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5460static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5461 unsigned Half = VT.getVectorNumElements() / 2;
5462 WhichResult = (M[0] == 0 ? 0 : 1);
5463 for (unsigned j = 0; j != 2; ++j) {
5464 unsigned Idx = WhichResult;
5465 for (unsigned i = 0; i != Half; ++i) {
5466 int MIdx = M[i + j * Half];
5467 if (MIdx >= 0 && (unsigned)MIdx != Idx)
5468 return false;
5469 Idx += 2;
5470 }
5471 }
5472
5473 return true;
5474}
5475
5476/// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
5477/// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5478/// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5479static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5480 unsigned NumElts = VT.getVectorNumElements();
5481 WhichResult = (M[0] == 0 ? 0 : 1);
5482 for (unsigned i = 0; i < NumElts; i += 2) {
5483 if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
5484 (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
5485 return false;
5486 }
5487 return true;
5488}
5489
5490static bool isINSMask(ArrayRef<int> M, int NumInputElements,
5491 bool &DstIsLeft, int &Anomaly) {
5492 if (M.size() != static_cast<size_t>(NumInputElements))
5493 return false;
5494
5495 int NumLHSMatch = 0, NumRHSMatch = 0;
5496 int LastLHSMismatch = -1, LastRHSMismatch = -1;
5497
5498 for (int i = 0; i < NumInputElements; ++i) {
5499 if (M[i] == -1) {
5500 ++NumLHSMatch;
5501 ++NumRHSMatch;
5502 continue;
5503 }
5504
5505 if (M[i] == i)
5506 ++NumLHSMatch;
5507 else
5508 LastLHSMismatch = i;
5509
5510 if (M[i] == i + NumInputElements)
5511 ++NumRHSMatch;
5512 else
5513 LastRHSMismatch = i;
5514 }
5515
5516 if (NumLHSMatch == NumInputElements - 1) {
5517 DstIsLeft = true;
5518 Anomaly = LastLHSMismatch;
5519 return true;
5520 } else if (NumRHSMatch == NumInputElements - 1) {
5521 DstIsLeft = false;
5522 Anomaly = LastRHSMismatch;
5523 return true;
5524 }
5525
5526 return false;
5527}
5528
5529static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
5530 if (VT.getSizeInBits() != 128)
5531 return false;
5532
5533 unsigned NumElts = VT.getVectorNumElements();
5534
5535 for (int I = 0, E = NumElts / 2; I != E; I++) {
5536 if (Mask[I] != I)
5537 return false;
5538 }
5539
5540 int Offset = NumElts / 2;
5541 for (int I = NumElts / 2, E = NumElts; I != E; I++) {
5542 if (Mask[I] != I + SplitLHS * Offset)
5543 return false;
5544 }
5545
5546 return true;
5547}
5548
5549static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
5550 SDLoc DL(Op);
5551 EVT VT = Op.getValueType();
5552 SDValue V0 = Op.getOperand(0);
5553 SDValue V1 = Op.getOperand(1);
5554 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
5555
5556 if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
5557 VT.getVectorElementType() != V1.getValueType().getVectorElementType())
5558 return SDValue();
5559
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00005560 bool SplitV0 = V0.getValueSizeInBits() == 128;
Tim Northover3b0846e2014-05-24 12:50:23 +00005561
5562 if (!isConcatMask(Mask, VT, SplitV0))
5563 return SDValue();
5564
5565 EVT CastVT = EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
5566 VT.getVectorNumElements() / 2);
5567 if (SplitV0) {
5568 V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005569 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005570 }
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00005571 if (V1.getValueSizeInBits() == 128) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005572 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005573 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005574 }
5575 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
5576}
5577
5578/// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
5579/// the specified operations to build the shuffle.
5580static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
5581 SDValue RHS, SelectionDAG &DAG,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00005582 const SDLoc &dl) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005583 unsigned OpNum = (PFEntry >> 26) & 0x0F;
5584 unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
5585 unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
5586
5587 enum {
5588 OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
5589 OP_VREV,
5590 OP_VDUP0,
5591 OP_VDUP1,
5592 OP_VDUP2,
5593 OP_VDUP3,
5594 OP_VEXT1,
5595 OP_VEXT2,
5596 OP_VEXT3,
5597 OP_VUZPL, // VUZP, left result
5598 OP_VUZPR, // VUZP, right result
5599 OP_VZIPL, // VZIP, left result
5600 OP_VZIPR, // VZIP, right result
5601 OP_VTRNL, // VTRN, left result
5602 OP_VTRNR // VTRN, right result
5603 };
5604
5605 if (OpNum == OP_COPY) {
5606 if (LHSID == (1 * 9 + 2) * 9 + 3)
5607 return LHS;
5608 assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
5609 return RHS;
5610 }
5611
5612 SDValue OpLHS, OpRHS;
5613 OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
5614 OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
5615 EVT VT = OpLHS.getValueType();
5616
5617 switch (OpNum) {
5618 default:
5619 llvm_unreachable("Unknown shuffle opcode!");
5620 case OP_VREV:
5621 // VREV divides the vector in half and swaps within the half.
5622 if (VT.getVectorElementType() == MVT::i32 ||
5623 VT.getVectorElementType() == MVT::f32)
5624 return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
5625 // vrev <4 x i16> -> REV32
Oliver Stannard89d15422014-08-27 16:16:04 +00005626 if (VT.getVectorElementType() == MVT::i16 ||
5627 VT.getVectorElementType() == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00005628 return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
5629 // vrev <4 x i8> -> REV16
5630 assert(VT.getVectorElementType() == MVT::i8);
5631 return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
5632 case OP_VDUP0:
5633 case OP_VDUP1:
5634 case OP_VDUP2:
5635 case OP_VDUP3: {
5636 EVT EltTy = VT.getVectorElementType();
5637 unsigned Opcode;
5638 if (EltTy == MVT::i8)
5639 Opcode = AArch64ISD::DUPLANE8;
Ahmed Bougacha941420d2015-04-16 23:57:07 +00005640 else if (EltTy == MVT::i16 || EltTy == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00005641 Opcode = AArch64ISD::DUPLANE16;
5642 else if (EltTy == MVT::i32 || EltTy == MVT::f32)
5643 Opcode = AArch64ISD::DUPLANE32;
5644 else if (EltTy == MVT::i64 || EltTy == MVT::f64)
5645 Opcode = AArch64ISD::DUPLANE64;
5646 else
5647 llvm_unreachable("Invalid vector element type?");
5648
5649 if (VT.getSizeInBits() == 64)
5650 OpLHS = WidenVector(OpLHS, DAG);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005651 SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00005652 return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
5653 }
5654 case OP_VEXT1:
5655 case OP_VEXT2:
5656 case OP_VEXT3: {
5657 unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
5658 return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005659 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005660 }
5661 case OP_VUZPL:
5662 return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
5663 OpRHS);
5664 case OP_VUZPR:
5665 return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
5666 OpRHS);
5667 case OP_VZIPL:
5668 return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
5669 OpRHS);
5670 case OP_VZIPR:
5671 return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
5672 OpRHS);
5673 case OP_VTRNL:
5674 return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
5675 OpRHS);
5676 case OP_VTRNR:
5677 return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
5678 OpRHS);
5679 }
5680}
5681
5682static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
5683 SelectionDAG &DAG) {
5684 // Check to see if we can use the TBL instruction.
5685 SDValue V1 = Op.getOperand(0);
5686 SDValue V2 = Op.getOperand(1);
5687 SDLoc DL(Op);
5688
5689 EVT EltVT = Op.getValueType().getVectorElementType();
5690 unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
5691
5692 SmallVector<SDValue, 8> TBLMask;
5693 for (int Val : ShuffleMask) {
5694 for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
5695 unsigned Offset = Byte + Val * BytesPerElt;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005696 TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005697 }
5698 }
5699
5700 MVT IndexVT = MVT::v8i8;
5701 unsigned IndexLen = 8;
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00005702 if (Op.getValueSizeInBits() == 128) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005703 IndexVT = MVT::v16i8;
5704 IndexLen = 16;
5705 }
5706
5707 SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
5708 SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
5709
5710 SDValue Shuffle;
Sanjay Patel57195842016-03-14 17:28:46 +00005711 if (V2.getNode()->isUndef()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005712 if (IndexLen == 8)
5713 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
5714 Shuffle = DAG.getNode(
5715 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005716 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00005717 DAG.getBuildVector(IndexVT, DL,
5718 makeArrayRef(TBLMask.data(), IndexLen)));
Tim Northover3b0846e2014-05-24 12:50:23 +00005719 } else {
5720 if (IndexLen == 8) {
5721 V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
5722 Shuffle = DAG.getNode(
5723 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005724 DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00005725 DAG.getBuildVector(IndexVT, DL,
5726 makeArrayRef(TBLMask.data(), IndexLen)));
Tim Northover3b0846e2014-05-24 12:50:23 +00005727 } else {
5728 // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
5729 // cannot currently represent the register constraints on the input
5730 // table registers.
5731 // Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00005732 // DAG.getBuildVector(IndexVT, DL, &TBLMask[0],
5733 // IndexLen));
Tim Northover3b0846e2014-05-24 12:50:23 +00005734 Shuffle = DAG.getNode(
5735 ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
Ahmed Bougacha128f8732016-04-26 21:15:30 +00005736 DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst,
5737 V2Cst, DAG.getBuildVector(IndexVT, DL,
5738 makeArrayRef(TBLMask.data(), IndexLen)));
Tim Northover3b0846e2014-05-24 12:50:23 +00005739 }
5740 }
5741 return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
5742}
5743
5744static unsigned getDUPLANEOp(EVT EltType) {
5745 if (EltType == MVT::i8)
5746 return AArch64ISD::DUPLANE8;
Oliver Stannard89d15422014-08-27 16:16:04 +00005747 if (EltType == MVT::i16 || EltType == MVT::f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00005748 return AArch64ISD::DUPLANE16;
5749 if (EltType == MVT::i32 || EltType == MVT::f32)
5750 return AArch64ISD::DUPLANE32;
5751 if (EltType == MVT::i64 || EltType == MVT::f64)
5752 return AArch64ISD::DUPLANE64;
5753
5754 llvm_unreachable("Invalid vector element type?");
5755}
5756
5757SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
5758 SelectionDAG &DAG) const {
5759 SDLoc dl(Op);
5760 EVT VT = Op.getValueType();
5761
5762 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
5763
5764 // Convert shuffles that are directly supported on NEON to target-specific
5765 // DAG nodes, instead of keeping them as shuffles and matching them again
5766 // during code selection. This is more efficient and avoids the possibility
5767 // of inconsistencies between legalization and selection.
5768 ArrayRef<int> ShuffleMask = SVN->getMask();
5769
5770 SDValue V1 = Op.getOperand(0);
5771 SDValue V2 = Op.getOperand(1);
5772
Craig Topperbc56e3b2016-06-30 04:38:51 +00005773 if (SVN->isSplat()) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005774 int Lane = SVN->getSplatIndex();
5775 // If this is undef splat, generate it via "just" vdup, if possible.
5776 if (Lane == -1)
5777 Lane = 0;
5778
5779 if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
5780 return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
5781 V1.getOperand(0));
5782 // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
5783 // constant. If so, we can just reference the lane's definition directly.
5784 if (V1.getOpcode() == ISD::BUILD_VECTOR &&
5785 !isa<ConstantSDNode>(V1.getOperand(Lane)))
5786 return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
5787
5788 // Otherwise, duplicate from the lane of the input vector.
5789 unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
5790
5791 // SelectionDAGBuilder may have "helpfully" already extracted or conatenated
5792 // to make a vector of the same size as this SHUFFLE. We can ignore the
5793 // extract entirely, and canonicalise the concat using WidenVector.
5794 if (V1.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
5795 Lane += cast<ConstantSDNode>(V1.getOperand(1))->getZExtValue();
5796 V1 = V1.getOperand(0);
5797 } else if (V1.getOpcode() == ISD::CONCAT_VECTORS) {
5798 unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
5799 Lane -= Idx * VT.getVectorNumElements() / 2;
5800 V1 = WidenVector(V1.getOperand(Idx), DAG);
5801 } else if (VT.getSizeInBits() == 64)
5802 V1 = WidenVector(V1, DAG);
5803
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005804 return DAG.getNode(Opcode, dl, VT, V1, DAG.getConstant(Lane, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00005805 }
5806
5807 if (isREVMask(ShuffleMask, VT, 64))
5808 return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
5809 if (isREVMask(ShuffleMask, VT, 32))
5810 return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
5811 if (isREVMask(ShuffleMask, VT, 16))
5812 return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
5813
5814 bool ReverseEXT = false;
5815 unsigned Imm;
5816 if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
5817 if (ReverseEXT)
5818 std::swap(V1, V2);
5819 Imm *= getExtFactor(V1);
5820 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005821 DAG.getConstant(Imm, dl, MVT::i32));
Sanjay Patel57195842016-03-14 17:28:46 +00005822 } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) {
Tim Northover3b0846e2014-05-24 12:50:23 +00005823 Imm *= getExtFactor(V1);
5824 return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005825 DAG.getConstant(Imm, dl, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00005826 }
5827
5828 unsigned WhichResult;
5829 if (isZIPMask(ShuffleMask, VT, WhichResult)) {
5830 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5831 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5832 }
5833 if (isUZPMask(ShuffleMask, VT, WhichResult)) {
5834 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5835 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5836 }
5837 if (isTRNMask(ShuffleMask, VT, WhichResult)) {
5838 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5839 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
5840 }
5841
5842 if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5843 unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
5844 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5845 }
5846 if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5847 unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
5848 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5849 }
5850 if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
5851 unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
5852 return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
5853 }
5854
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00005855 if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00005856 return Concat;
5857
5858 bool DstIsLeft;
5859 int Anomaly;
5860 int NumInputElements = V1.getValueType().getVectorNumElements();
5861 if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
5862 SDValue DstVec = DstIsLeft ? V1 : V2;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005863 SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00005864
5865 SDValue SrcVec = V1;
5866 int SrcLane = ShuffleMask[Anomaly];
5867 if (SrcLane >= NumInputElements) {
5868 SrcVec = V2;
5869 SrcLane -= VT.getVectorNumElements();
5870 }
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005871 SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00005872
5873 EVT ScalarVT = VT.getVectorElementType();
Oliver Stannard89d15422014-08-27 16:16:04 +00005874
5875 if (ScalarVT.getSizeInBits() < 32 && ScalarVT.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00005876 ScalarVT = MVT::i32;
5877
5878 return DAG.getNode(
5879 ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5880 DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
5881 DstLaneV);
5882 }
5883
5884 // If the shuffle is not directly supported and it has 4 elements, use
5885 // the PerfectShuffle-generated table to synthesize it from other shuffles.
5886 unsigned NumElts = VT.getVectorNumElements();
5887 if (NumElts == 4) {
5888 unsigned PFIndexes[4];
5889 for (unsigned i = 0; i != 4; ++i) {
5890 if (ShuffleMask[i] < 0)
5891 PFIndexes[i] = 8;
5892 else
5893 PFIndexes[i] = ShuffleMask[i];
5894 }
5895
5896 // Compute the index in the perfect shuffle table.
5897 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
5898 PFIndexes[2] * 9 + PFIndexes[3];
5899 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
5900 unsigned Cost = (PFEntry >> 30);
5901
5902 if (Cost <= 4)
5903 return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
5904 }
5905
5906 return GenerateTBL(Op, ShuffleMask, DAG);
5907}
5908
5909static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
5910 APInt &UndefBits) {
5911 EVT VT = BVN->getValueType(0);
5912 APInt SplatBits, SplatUndef;
5913 unsigned SplatBitSize;
5914 bool HasAnyUndefs;
5915 if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
5916 unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
5917
5918 for (unsigned i = 0; i < NumSplats; ++i) {
5919 CnstBits <<= SplatBitSize;
5920 UndefBits <<= SplatBitSize;
5921 CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
5922 UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
5923 }
5924
5925 return true;
5926 }
5927
5928 return false;
5929}
5930
5931SDValue AArch64TargetLowering::LowerVectorAND(SDValue Op,
5932 SelectionDAG &DAG) const {
5933 BuildVectorSDNode *BVN =
5934 dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
5935 SDValue LHS = Op.getOperand(0);
5936 SDLoc dl(Op);
5937 EVT VT = Op.getValueType();
5938
5939 if (!BVN)
5940 return Op;
5941
5942 APInt CnstBits(VT.getSizeInBits(), 0);
5943 APInt UndefBits(VT.getSizeInBits(), 0);
5944 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
5945 // We only have BIC vector immediate instruction, which is and-not.
5946 CnstBits = ~CnstBits;
5947
5948 // We make use of a little bit of goto ickiness in order to avoid having to
5949 // duplicate the immediate matching logic for the undef toggled case.
5950 bool SecondTry = false;
5951 AttemptModImm:
5952
5953 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
5954 CnstBits = CnstBits.zextOrTrunc(64);
5955 uint64_t CnstVal = CnstBits.getZExtValue();
5956
5957 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
5958 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
5959 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5960 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005961 DAG.getConstant(CnstVal, dl, MVT::i32),
5962 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005963 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005964 }
5965
5966 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
5967 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
5968 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5969 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005970 DAG.getConstant(CnstVal, dl, MVT::i32),
5971 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005972 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005973 }
5974
5975 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
5976 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
5977 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5978 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005979 DAG.getConstant(CnstVal, dl, MVT::i32),
5980 DAG.getConstant(16, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005981 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005982 }
5983
5984 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
5985 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
5986 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
5987 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005988 DAG.getConstant(CnstVal, dl, MVT::i32),
5989 DAG.getConstant(24, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005990 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00005991 }
5992
5993 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
5994 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
5995 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
5996 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00005997 DAG.getConstant(CnstVal, dl, MVT::i32),
5998 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00005999 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006000 }
6001
6002 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6003 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6004 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6005 SDValue Mov = DAG.getNode(AArch64ISD::BICi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006006 DAG.getConstant(CnstVal, dl, MVT::i32),
6007 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00006008 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006009 }
6010 }
6011
6012 if (SecondTry)
6013 goto FailedModImm;
6014 SecondTry = true;
6015 CnstBits = ~UndefBits;
6016 goto AttemptModImm;
6017 }
6018
6019// We can always fall back to a non-immediate AND.
6020FailedModImm:
6021 return Op;
6022}
6023
6024// Specialized code to quickly find if PotentialBVec is a BuildVector that
6025// consists of only the same constant int value, returned in reference arg
6026// ConstVal
6027static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
6028 uint64_t &ConstVal) {
6029 BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
6030 if (!Bvec)
6031 return false;
6032 ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
6033 if (!FirstElt)
6034 return false;
6035 EVT VT = Bvec->getValueType(0);
6036 unsigned NumElts = VT.getVectorNumElements();
6037 for (unsigned i = 1; i < NumElts; ++i)
6038 if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
6039 return false;
6040 ConstVal = FirstElt->getZExtValue();
6041 return true;
6042}
6043
6044static unsigned getIntrinsicID(const SDNode *N) {
6045 unsigned Opcode = N->getOpcode();
6046 switch (Opcode) {
6047 default:
6048 return Intrinsic::not_intrinsic;
6049 case ISD::INTRINSIC_WO_CHAIN: {
6050 unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
6051 if (IID < Intrinsic::num_intrinsics)
6052 return IID;
6053 return Intrinsic::not_intrinsic;
6054 }
6055 }
6056}
6057
6058// Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
6059// to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
6060// BUILD_VECTORs with constant element C1, C2 is a constant, and C1 == ~C2.
6061// Also, logical shift right -> sri, with the same structure.
6062static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
6063 EVT VT = N->getValueType(0);
6064
6065 if (!VT.isVector())
6066 return SDValue();
6067
6068 SDLoc DL(N);
6069
6070 // Is the first op an AND?
6071 const SDValue And = N->getOperand(0);
6072 if (And.getOpcode() != ISD::AND)
6073 return SDValue();
6074
6075 // Is the second op an shl or lshr?
6076 SDValue Shift = N->getOperand(1);
6077 // This will have been turned into: AArch64ISD::VSHL vector, #shift
6078 // or AArch64ISD::VLSHR vector, #shift
6079 unsigned ShiftOpc = Shift.getOpcode();
6080 if ((ShiftOpc != AArch64ISD::VSHL && ShiftOpc != AArch64ISD::VLSHR))
6081 return SDValue();
6082 bool IsShiftRight = ShiftOpc == AArch64ISD::VLSHR;
6083
6084 // Is the shift amount constant?
6085 ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
6086 if (!C2node)
6087 return SDValue();
6088
6089 // Is the and mask vector all constant?
6090 uint64_t C1;
6091 if (!isAllConstantBuildVector(And.getOperand(1), C1))
6092 return SDValue();
6093
6094 // Is C1 == ~C2, taking into account how much one can shift elements of a
6095 // particular size?
6096 uint64_t C2 = C2node->getZExtValue();
Sanjay Patel1ed771f2016-09-14 16:37:15 +00006097 unsigned ElemSizeInBits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00006098 if (C2 > ElemSizeInBits)
6099 return SDValue();
6100 unsigned ElemMask = (1 << ElemSizeInBits) - 1;
6101 if ((C1 & ElemMask) != (~C2 & ElemMask))
6102 return SDValue();
6103
6104 SDValue X = And.getOperand(0);
6105 SDValue Y = Shift.getOperand(0);
6106
6107 unsigned Intrin =
6108 IsShiftRight ? Intrinsic::aarch64_neon_vsri : Intrinsic::aarch64_neon_vsli;
6109 SDValue ResultSLI =
6110 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006111 DAG.getConstant(Intrin, DL, MVT::i32), X, Y,
6112 Shift.getOperand(1));
Tim Northover3b0846e2014-05-24 12:50:23 +00006113
6114 DEBUG(dbgs() << "aarch64-lower: transformed: \n");
6115 DEBUG(N->dump(&DAG));
6116 DEBUG(dbgs() << "into: \n");
6117 DEBUG(ResultSLI->dump(&DAG));
6118
6119 ++NumShiftInserts;
6120 return ResultSLI;
6121}
6122
6123SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
6124 SelectionDAG &DAG) const {
6125 // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
6126 if (EnableAArch64SlrGeneration) {
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00006127 if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00006128 return Res;
6129 }
6130
6131 BuildVectorSDNode *BVN =
6132 dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
6133 SDValue LHS = Op.getOperand(1);
6134 SDLoc dl(Op);
6135 EVT VT = Op.getValueType();
6136
6137 // OR commutes, so try swapping the operands.
6138 if (!BVN) {
6139 LHS = Op.getOperand(0);
6140 BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
6141 }
6142 if (!BVN)
6143 return Op;
6144
6145 APInt CnstBits(VT.getSizeInBits(), 0);
6146 APInt UndefBits(VT.getSizeInBits(), 0);
6147 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
6148 // We make use of a little bit of goto ickiness in order to avoid having to
6149 // duplicate the immediate matching logic for the undef toggled case.
6150 bool SecondTry = false;
6151 AttemptModImm:
6152
6153 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
6154 CnstBits = CnstBits.zextOrTrunc(64);
6155 uint64_t CnstVal = CnstBits.getZExtValue();
6156
6157 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6158 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6159 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6160 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006161 DAG.getConstant(CnstVal, dl, MVT::i32),
6162 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00006163 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006164 }
6165
6166 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6167 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6168 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6169 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006170 DAG.getConstant(CnstVal, dl, MVT::i32),
6171 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00006172 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006173 }
6174
6175 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6176 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6177 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6178 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006179 DAG.getConstant(CnstVal, dl, MVT::i32),
6180 DAG.getConstant(16, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00006181 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006182 }
6183
6184 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6185 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6186 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6187 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006188 DAG.getConstant(CnstVal, dl, MVT::i32),
6189 DAG.getConstant(24, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00006190 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006191 }
6192
6193 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6194 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6195 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6196 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006197 DAG.getConstant(CnstVal, dl, MVT::i32),
6198 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00006199 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006200 }
6201
6202 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6203 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6204 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6205 SDValue Mov = DAG.getNode(AArch64ISD::ORRi, dl, MovTy, LHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006206 DAG.getConstant(CnstVal, dl, MVT::i32),
6207 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverf7423fd2014-09-04 15:05:24 +00006208 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006209 }
6210 }
6211
6212 if (SecondTry)
6213 goto FailedModImm;
6214 SecondTry = true;
6215 CnstBits = UndefBits;
6216 goto AttemptModImm;
6217 }
6218
6219// We can always fall back to a non-immediate OR.
6220FailedModImm:
6221 return Op;
6222}
6223
Kevin Qin4473c192014-07-07 02:45:40 +00006224// Normalize the operands of BUILD_VECTOR. The value of constant operands will
6225// be truncated to fit element width.
6226static SDValue NormalizeBuildVector(SDValue Op,
6227 SelectionDAG &DAG) {
6228 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
Tim Northover3b0846e2014-05-24 12:50:23 +00006229 SDLoc dl(Op);
6230 EVT VT = Op.getValueType();
Kevin Qin4473c192014-07-07 02:45:40 +00006231 EVT EltTy= VT.getVectorElementType();
6232
6233 if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
6234 return Op;
6235
6236 SmallVector<SDValue, 16> Ops;
Pete Cooper7be8f8f2015-08-03 19:04:32 +00006237 for (SDValue Lane : Op->ops()) {
6238 if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
Kevin Qin4473c192014-07-07 02:45:40 +00006239 APInt LowBits(EltTy.getSizeInBits(),
Pete Cooper7be8f8f2015-08-03 19:04:32 +00006240 CstLane->getZExtValue());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006241 Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
Kevin Qin4473c192014-07-07 02:45:40 +00006242 }
6243 Ops.push_back(Lane);
6244 }
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006245 return DAG.getBuildVector(VT, dl, Ops);
Kevin Qin4473c192014-07-07 02:45:40 +00006246}
6247
6248SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
6249 SelectionDAG &DAG) const {
6250 SDLoc dl(Op);
6251 EVT VT = Op.getValueType();
6252 Op = NormalizeBuildVector(Op, DAG);
6253 BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
Tim Northover3b0846e2014-05-24 12:50:23 +00006254
6255 APInt CnstBits(VT.getSizeInBits(), 0);
6256 APInt UndefBits(VT.getSizeInBits(), 0);
6257 if (resolveBuildVector(BVN, CnstBits, UndefBits)) {
6258 // We make use of a little bit of goto ickiness in order to avoid having to
6259 // duplicate the immediate matching logic for the undef toggled case.
6260 bool SecondTry = false;
6261 AttemptModImm:
6262
6263 if (CnstBits.getHiBits(64) == CnstBits.getLoBits(64)) {
6264 CnstBits = CnstBits.zextOrTrunc(64);
6265 uint64_t CnstVal = CnstBits.getZExtValue();
6266
6267 // Certain magic vector constants (used to express things like NOT
6268 // and NEG) are passed through unmodified. This allows codegen patterns
6269 // for these operations to match. Special-purpose patterns will lower
6270 // these immediates to MOVIs if it proves necessary.
6271 if (VT.isInteger() && (CnstVal == 0 || CnstVal == ~0ULL))
6272 return Op;
6273
6274 // The many faces of MOVI...
6275 if (AArch64_AM::isAdvSIMDModImmType10(CnstVal)) {
6276 CnstVal = AArch64_AM::encodeAdvSIMDModImmType10(CnstVal);
6277 if (VT.getSizeInBits() == 128) {
6278 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::v2i64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006279 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006280 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006281 }
6282
6283 // Support the V64 version via subregister insertion.
6284 SDValue Mov = DAG.getNode(AArch64ISD::MOVIedit, dl, MVT::f64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006285 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006286 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006287 }
6288
6289 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6290 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6291 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6292 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006293 DAG.getConstant(CnstVal, dl, MVT::i32),
6294 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006295 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006296 }
6297
6298 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6299 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6300 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6301 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006302 DAG.getConstant(CnstVal, dl, MVT::i32),
6303 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006304 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006305 }
6306
6307 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6308 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6309 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6310 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006311 DAG.getConstant(CnstVal, dl, MVT::i32),
6312 DAG.getConstant(16, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006313 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006314 }
6315
6316 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6317 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6318 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6319 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006320 DAG.getConstant(CnstVal, dl, MVT::i32),
6321 DAG.getConstant(24, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006322 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006323 }
6324
6325 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6326 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6327 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6328 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006329 DAG.getConstant(CnstVal, dl, MVT::i32),
6330 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006331 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006332 }
6333
6334 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6335 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6336 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6337 SDValue Mov = DAG.getNode(AArch64ISD::MOVIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006338 DAG.getConstant(CnstVal, dl, MVT::i32),
6339 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006340 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006341 }
6342
6343 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6344 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6345 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6346 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006347 DAG.getConstant(CnstVal, dl, MVT::i32),
6348 DAG.getConstant(264, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006349 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006350 }
6351
6352 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6353 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6354 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6355 SDValue Mov = DAG.getNode(AArch64ISD::MOVImsl, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006356 DAG.getConstant(CnstVal, dl, MVT::i32),
6357 DAG.getConstant(272, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006358 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006359 }
6360
6361 if (AArch64_AM::isAdvSIMDModImmType9(CnstVal)) {
6362 CnstVal = AArch64_AM::encodeAdvSIMDModImmType9(CnstVal);
6363 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
6364 SDValue Mov = DAG.getNode(AArch64ISD::MOVI, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006365 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006366 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006367 }
6368
6369 // The few faces of FMOV...
6370 if (AArch64_AM::isAdvSIMDModImmType11(CnstVal)) {
6371 CnstVal = AArch64_AM::encodeAdvSIMDModImmType11(CnstVal);
6372 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4f32 : MVT::v2f32;
6373 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006374 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006375 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006376 }
6377
6378 if (AArch64_AM::isAdvSIMDModImmType12(CnstVal) &&
6379 VT.getSizeInBits() == 128) {
6380 CnstVal = AArch64_AM::encodeAdvSIMDModImmType12(CnstVal);
6381 SDValue Mov = DAG.getNode(AArch64ISD::FMOV, dl, MVT::v2f64,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006382 DAG.getConstant(CnstVal, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006383 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006384 }
6385
6386 // The many faces of MVNI...
6387 CnstVal = ~CnstVal;
6388 if (AArch64_AM::isAdvSIMDModImmType1(CnstVal)) {
6389 CnstVal = AArch64_AM::encodeAdvSIMDModImmType1(CnstVal);
6390 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6391 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006392 DAG.getConstant(CnstVal, dl, MVT::i32),
6393 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006394 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006395 }
6396
6397 if (AArch64_AM::isAdvSIMDModImmType2(CnstVal)) {
6398 CnstVal = AArch64_AM::encodeAdvSIMDModImmType2(CnstVal);
6399 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6400 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006401 DAG.getConstant(CnstVal, dl, MVT::i32),
6402 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006403 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006404 }
6405
6406 if (AArch64_AM::isAdvSIMDModImmType3(CnstVal)) {
6407 CnstVal = AArch64_AM::encodeAdvSIMDModImmType3(CnstVal);
6408 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6409 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006410 DAG.getConstant(CnstVal, dl, MVT::i32),
6411 DAG.getConstant(16, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006412 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006413 }
6414
6415 if (AArch64_AM::isAdvSIMDModImmType4(CnstVal)) {
6416 CnstVal = AArch64_AM::encodeAdvSIMDModImmType4(CnstVal);
6417 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6418 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006419 DAG.getConstant(CnstVal, dl, MVT::i32),
6420 DAG.getConstant(24, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006421 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006422 }
6423
6424 if (AArch64_AM::isAdvSIMDModImmType5(CnstVal)) {
6425 CnstVal = AArch64_AM::encodeAdvSIMDModImmType5(CnstVal);
6426 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6427 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006428 DAG.getConstant(CnstVal, dl, MVT::i32),
6429 DAG.getConstant(0, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006430 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006431 }
6432
6433 if (AArch64_AM::isAdvSIMDModImmType6(CnstVal)) {
6434 CnstVal = AArch64_AM::encodeAdvSIMDModImmType6(CnstVal);
6435 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
6436 SDValue Mov = DAG.getNode(AArch64ISD::MVNIshift, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006437 DAG.getConstant(CnstVal, dl, MVT::i32),
6438 DAG.getConstant(8, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006439 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006440 }
6441
6442 if (AArch64_AM::isAdvSIMDModImmType7(CnstVal)) {
6443 CnstVal = AArch64_AM::encodeAdvSIMDModImmType7(CnstVal);
6444 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6445 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006446 DAG.getConstant(CnstVal, dl, MVT::i32),
6447 DAG.getConstant(264, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006448 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006449 }
6450
6451 if (AArch64_AM::isAdvSIMDModImmType8(CnstVal)) {
6452 CnstVal = AArch64_AM::encodeAdvSIMDModImmType8(CnstVal);
6453 MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
6454 SDValue Mov = DAG.getNode(AArch64ISD::MVNImsl, dl, MovTy,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006455 DAG.getConstant(CnstVal, dl, MVT::i32),
6456 DAG.getConstant(272, dl, MVT::i32));
Tim Northoverbb72e6c2014-09-04 09:46:14 +00006457 return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
Tim Northover3b0846e2014-05-24 12:50:23 +00006458 }
6459 }
6460
6461 if (SecondTry)
6462 goto FailedModImm;
6463 SecondTry = true;
6464 CnstBits = UndefBits;
6465 goto AttemptModImm;
6466 }
6467FailedModImm:
6468
6469 // Scan through the operands to find some interesting properties we can
6470 // exploit:
6471 // 1) If only one value is used, we can use a DUP, or
6472 // 2) if only the low element is not undef, we can just insert that, or
6473 // 3) if only one constant value is used (w/ some non-constant lanes),
6474 // we can splat the constant value into the whole vector then fill
6475 // in the non-constant lanes.
6476 // 4) FIXME: If different constant values are used, but we can intelligently
6477 // select the values we'll be overwriting for the non-constant
6478 // lanes such that we can directly materialize the vector
6479 // some other way (MOVI, e.g.), we can be sneaky.
6480 unsigned NumElts = VT.getVectorNumElements();
6481 bool isOnlyLowElement = true;
6482 bool usesOnlyOneValue = true;
6483 bool usesOnlyOneConstantValue = true;
6484 bool isConstant = true;
6485 unsigned NumConstantLanes = 0;
6486 SDValue Value;
6487 SDValue ConstantValue;
6488 for (unsigned i = 0; i < NumElts; ++i) {
6489 SDValue V = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00006490 if (V.isUndef())
Tim Northover3b0846e2014-05-24 12:50:23 +00006491 continue;
6492 if (i > 0)
6493 isOnlyLowElement = false;
6494 if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6495 isConstant = false;
6496
6497 if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
6498 ++NumConstantLanes;
6499 if (!ConstantValue.getNode())
6500 ConstantValue = V;
6501 else if (ConstantValue != V)
6502 usesOnlyOneConstantValue = false;
6503 }
6504
6505 if (!Value.getNode())
6506 Value = V;
6507 else if (V != Value)
6508 usesOnlyOneValue = false;
6509 }
6510
6511 if (!Value.getNode())
6512 return DAG.getUNDEF(VT);
6513
6514 if (isOnlyLowElement)
6515 return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
6516
6517 // Use DUP for non-constant splats. For f32 constant splats, reduce to
6518 // i32 and try again.
6519 if (usesOnlyOneValue) {
6520 if (!isConstant) {
6521 if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6522 Value.getValueType() != VT)
6523 return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
6524
6525 // This is actually a DUPLANExx operation, which keeps everything vectory.
6526
6527 // DUPLANE works on 128-bit vectors, widen it if necessary.
6528 SDValue Lane = Value.getOperand(1);
6529 Value = Value.getOperand(0);
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00006530 if (Value.getValueSizeInBits() == 64)
Tim Northover3b0846e2014-05-24 12:50:23 +00006531 Value = WidenVector(Value, DAG);
6532
6533 unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
6534 return DAG.getNode(Opcode, dl, VT, Value, Lane);
6535 }
6536
6537 if (VT.getVectorElementType().isFloatingPoint()) {
6538 SmallVector<SDValue, 8> Ops;
Pirama Arumuga Nainar12aeefc2015-03-17 23:10:29 +00006539 EVT EltTy = VT.getVectorElementType();
6540 assert ((EltTy == MVT::f16 || EltTy == MVT::f32 || EltTy == MVT::f64) &&
6541 "Unsupported floating-point vector type");
6542 MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
Tim Northover3b0846e2014-05-24 12:50:23 +00006543 for (unsigned i = 0; i < NumElts; ++i)
6544 Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
6545 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
Ahmed Bougacha128f8732016-04-26 21:15:30 +00006546 SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
Tim Northover3b0846e2014-05-24 12:50:23 +00006547 Val = LowerBUILD_VECTOR(Val, DAG);
6548 if (Val.getNode())
6549 return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6550 }
6551 }
6552
6553 // If there was only one constant value used and for more than one lane,
6554 // start by splatting that value, then replace the non-constant lanes. This
6555 // is better than the default, which will perform a separate initialization
6556 // for each lane.
6557 if (NumConstantLanes > 0 && usesOnlyOneConstantValue) {
6558 SDValue Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
6559 // Now insert the non-constant lanes.
6560 for (unsigned i = 0; i < NumElts; ++i) {
6561 SDValue V = Op.getOperand(i);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006562 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006563 if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V)) {
6564 // Note that type legalization likely mucked about with the VT of the
6565 // source operand, so we may have to convert it here before inserting.
6566 Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
6567 }
6568 }
6569 return Val;
6570 }
6571
6572 // If all elements are constants and the case above didn't get hit, fall back
6573 // to the default expansion, which will generate a load from the constant
6574 // pool.
6575 if (isConstant)
6576 return SDValue();
6577
6578 // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6579 if (NumElts >= 4) {
Ahmed Bougacha239d6352015-08-04 00:48:02 +00006580 if (SDValue shuffle = ReconstructShuffle(Op, DAG))
Tim Northover3b0846e2014-05-24 12:50:23 +00006581 return shuffle;
6582 }
6583
6584 // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6585 // know the default expansion would otherwise fall back on something even
6586 // worse. For a vector with one or two non-undef values, that's
6587 // scalar_to_vector for the elements followed by a shuffle (provided the
6588 // shuffle is valid for the target) and materialization element by element
6589 // on the stack followed by a load for everything else.
6590 if (!isConstant && !usesOnlyOneValue) {
6591 SDValue Vec = DAG.getUNDEF(VT);
6592 SDValue Op0 = Op.getOperand(0);
Sanjay Patel1ed771f2016-09-14 16:37:15 +00006593 unsigned ElemSize = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00006594 unsigned i = 0;
Ahmed Bougachad3c03a52017-04-04 22:55:53 +00006595 // For 32 and 64 bit types, use SCALAR_TO_VECTOR for lane zero to
Tim Northover3b0846e2014-05-24 12:50:23 +00006596 // a) Avoid a RMW dependency on the full vector register, and
6597 // b) Allow the register coalescer to fold away the copy if the
Ahmed Bougachad3c03a52017-04-04 22:55:53 +00006598 // value is already in an S or D register, and we're forced to emit an
6599 // INSERT_SUBREG that we can't fold anywhere.
6600 if (!Op0.isUndef() && (ElemSize == 32 || ElemSize == 64)) {
6601 Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op0);
Tim Northover3b0846e2014-05-24 12:50:23 +00006602 ++i;
6603 }
6604 for (; i < NumElts; ++i) {
6605 SDValue V = Op.getOperand(i);
Sanjay Patel57195842016-03-14 17:28:46 +00006606 if (V.isUndef())
Tim Northover3b0846e2014-05-24 12:50:23 +00006607 continue;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006608 SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00006609 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6610 }
6611 return Vec;
6612 }
6613
6614 // Just use the default expansion. We failed to find a better alternative.
6615 return SDValue();
6616}
6617
6618SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
6619 SelectionDAG &DAG) const {
6620 assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
6621
Tim Northovere4b8e132014-07-15 10:00:26 +00006622 // Check for non-constant or out of range lane.
6623 EVT VT = Op.getOperand(0).getValueType();
6624 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
6625 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
Tim Northover3b0846e2014-05-24 12:50:23 +00006626 return SDValue();
6627
Tim Northover3b0846e2014-05-24 12:50:23 +00006628
6629 // Insertion/extraction are legal for V128 types.
6630 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
Oliver Stannard89d15422014-08-27 16:16:04 +00006631 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6632 VT == MVT::v8f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006633 return Op;
6634
6635 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
Oliver Stannard89d15422014-08-27 16:16:04 +00006636 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006637 return SDValue();
6638
6639 // For V64 types, we perform insertion by expanding the value
6640 // to a V128 type and perform the insertion on that.
6641 SDLoc DL(Op);
6642 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6643 EVT WideTy = WideVec.getValueType();
6644
6645 SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
6646 Op.getOperand(1), Op.getOperand(2));
6647 // Re-narrow the resultant vector.
6648 return NarrowVector(Node, DAG);
6649}
6650
6651SDValue
6652AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
6653 SelectionDAG &DAG) const {
6654 assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
6655
Tim Northovere4b8e132014-07-15 10:00:26 +00006656 // Check for non-constant or out of range lane.
6657 EVT VT = Op.getOperand(0).getValueType();
6658 ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6659 if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
Tim Northover3b0846e2014-05-24 12:50:23 +00006660 return SDValue();
6661
Tim Northover3b0846e2014-05-24 12:50:23 +00006662
6663 // Insertion/extraction are legal for V128 types.
6664 if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
Oliver Stannard89d15422014-08-27 16:16:04 +00006665 VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
6666 VT == MVT::v8f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006667 return Op;
6668
6669 if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
Oliver Stannard89d15422014-08-27 16:16:04 +00006670 VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16)
Tim Northover3b0846e2014-05-24 12:50:23 +00006671 return SDValue();
6672
6673 // For V64 types, we perform extraction by expanding the value
6674 // to a V128 type and perform the extraction on that.
6675 SDLoc DL(Op);
6676 SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
6677 EVT WideTy = WideVec.getValueType();
6678
6679 EVT ExtrTy = WideTy.getVectorElementType();
6680 if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
6681 ExtrTy = MVT::i32;
6682
6683 // For extractions, we just return the result directly.
6684 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
6685 Op.getOperand(1));
6686}
6687
6688SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
6689 SelectionDAG &DAG) const {
6690 EVT VT = Op.getOperand(0).getValueType();
6691 SDLoc dl(Op);
6692 // Just in case...
6693 if (!VT.isVector())
6694 return SDValue();
6695
6696 ConstantSDNode *Cst = dyn_cast<ConstantSDNode>(Op.getOperand(1));
6697 if (!Cst)
6698 return SDValue();
6699 unsigned Val = Cst->getZExtValue();
6700
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00006701 unsigned Size = Op.getValueSizeInBits();
Charlie Turner7b7b06f2015-11-09 12:45:11 +00006702
6703 // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
6704 if (Val == 0)
6705 return Op;
6706
Tim Northover3b0846e2014-05-24 12:50:23 +00006707 // If this is extracting the upper 64-bits of a 128-bit vector, we match
6708 // that directly.
Sanjay Patel1ed771f2016-09-14 16:37:15 +00006709 if (Size == 64 && Val * VT.getScalarSizeInBits() == 64)
Tim Northover3b0846e2014-05-24 12:50:23 +00006710 return Op;
6711
6712 return SDValue();
6713}
6714
6715bool AArch64TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
6716 EVT VT) const {
6717 if (VT.getVectorNumElements() == 4 &&
6718 (VT.is128BitVector() || VT.is64BitVector())) {
6719 unsigned PFIndexes[4];
6720 for (unsigned i = 0; i != 4; ++i) {
6721 if (M[i] < 0)
6722 PFIndexes[i] = 8;
6723 else
6724 PFIndexes[i] = M[i];
6725 }
6726
6727 // Compute the index in the perfect shuffle table.
6728 unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
6729 PFIndexes[2] * 9 + PFIndexes[3];
6730 unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6731 unsigned Cost = (PFEntry >> 30);
6732
6733 if (Cost <= 4)
6734 return true;
6735 }
6736
6737 bool DummyBool;
6738 int DummyInt;
6739 unsigned DummyUnsigned;
6740
6741 return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
6742 isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
6743 isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
6744 // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
6745 isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
6746 isZIPMask(M, VT, DummyUnsigned) ||
6747 isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
6748 isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
6749 isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
6750 isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
6751 isConcatMask(M, VT, VT.getSizeInBits() == 128));
6752}
6753
6754/// getVShiftImm - Check if this is a valid build_vector for the immediate
6755/// operand of a vector shift operation, where all the elements of the
6756/// build_vector must have the same constant integer value.
6757static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
6758 // Ignore bit_converts.
6759 while (Op.getOpcode() == ISD::BITCAST)
6760 Op = Op.getOperand(0);
6761 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
6762 APInt SplatBits, SplatUndef;
6763 unsigned SplatBitSize;
6764 bool HasAnyUndefs;
6765 if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
6766 HasAnyUndefs, ElementBits) ||
6767 SplatBitSize > ElementBits)
6768 return false;
6769 Cnt = SplatBits.getSExtValue();
6770 return true;
6771}
6772
6773/// isVShiftLImm - Check if this is a valid build_vector for the immediate
6774/// operand of a vector shift left operation. That value must be in the range:
6775/// 0 <= Value < ElementBits for a left shift; or
6776/// 0 <= Value <= ElementBits for a long left shift.
6777static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
6778 assert(VT.isVector() && "vector shift count is not a vector type");
Sanjay Patel1ed771f2016-09-14 16:37:15 +00006779 int64_t ElementBits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00006780 if (!getVShiftImm(Op, ElementBits, Cnt))
6781 return false;
6782 return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
6783}
6784
6785/// isVShiftRImm - Check if this is a valid build_vector for the immediate
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00006786/// operand of a vector shift right operation. The value must be in the range:
6787/// 1 <= Value <= ElementBits for a right shift; or
6788static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006789 assert(VT.isVector() && "vector shift count is not a vector type");
Sanjay Patel1ed771f2016-09-14 16:37:15 +00006790 int64_t ElementBits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00006791 if (!getVShiftImm(Op, ElementBits, Cnt))
6792 return false;
Tim Northover3b0846e2014-05-24 12:50:23 +00006793 return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
6794}
6795
6796SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
6797 SelectionDAG &DAG) const {
6798 EVT VT = Op.getValueType();
6799 SDLoc DL(Op);
6800 int64_t Cnt;
6801
6802 if (!Op.getOperand(1).getValueType().isVector())
6803 return Op;
Sanjay Patel1ed771f2016-09-14 16:37:15 +00006804 unsigned EltSize = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00006805
6806 switch (Op.getOpcode()) {
6807 default:
6808 llvm_unreachable("unexpected shift opcode");
6809
6810 case ISD::SHL:
6811 if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006812 return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
6813 DAG.getConstant(Cnt, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006814 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006815 DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
6816 MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00006817 Op.getOperand(0), Op.getOperand(1));
6818 case ISD::SRA:
6819 case ISD::SRL:
6820 // Right shift immediate
Luke Cheesemanb5c627a2015-07-24 09:31:48 +00006821 if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006822 unsigned Opc =
6823 (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006824 return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
6825 DAG.getConstant(Cnt, DL, MVT::i32));
Tim Northover3b0846e2014-05-24 12:50:23 +00006826 }
6827
6828 // Right shift register. Note, there is not a shift right register
6829 // instruction, but the shift left register instruction takes a signed
6830 // value, where negative numbers specify a right shift.
6831 unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
6832 : Intrinsic::aarch64_neon_ushl;
6833 // negate the shift amount
6834 SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
6835 SDValue NegShiftLeft =
6836 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00006837 DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
6838 NegShift);
Tim Northover3b0846e2014-05-24 12:50:23 +00006839 return NegShiftLeft;
6840 }
6841
6842 return SDValue();
6843}
6844
6845static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
6846 AArch64CC::CondCode CC, bool NoNans, EVT VT,
Benjamin Kramerbdc49562016-06-12 15:39:02 +00006847 const SDLoc &dl, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00006848 EVT SrcVT = LHS.getValueType();
Tim Northover45aa89c2015-02-08 00:50:47 +00006849 assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
6850 "function only supposed to emit natural comparisons");
Tim Northover3b0846e2014-05-24 12:50:23 +00006851
6852 BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
6853 APInt CnstBits(VT.getSizeInBits(), 0);
6854 APInt UndefBits(VT.getSizeInBits(), 0);
6855 bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
6856 bool IsZero = IsCnst && (CnstBits == 0);
6857
6858 if (SrcVT.getVectorElementType().isFloatingPoint()) {
6859 switch (CC) {
6860 default:
6861 return SDValue();
6862 case AArch64CC::NE: {
6863 SDValue Fcmeq;
6864 if (IsZero)
6865 Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6866 else
6867 Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6868 return DAG.getNode(AArch64ISD::NOT, dl, VT, Fcmeq);
6869 }
6870 case AArch64CC::EQ:
6871 if (IsZero)
6872 return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
6873 return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
6874 case AArch64CC::GE:
6875 if (IsZero)
6876 return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
6877 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
6878 case AArch64CC::GT:
6879 if (IsZero)
6880 return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
6881 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
6882 case AArch64CC::LS:
6883 if (IsZero)
6884 return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
6885 return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
6886 case AArch64CC::LT:
6887 if (!NoNans)
6888 return SDValue();
Justin Bognerb03fd122016-08-17 05:10:15 +00006889 // If we ignore NaNs then we can use to the MI implementation.
6890 LLVM_FALLTHROUGH;
Tim Northover3b0846e2014-05-24 12:50:23 +00006891 case AArch64CC::MI:
6892 if (IsZero)
6893 return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
6894 return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
6895 }
6896 }
6897
6898 switch (CC) {
6899 default:
6900 return SDValue();
6901 case AArch64CC::NE: {
6902 SDValue Cmeq;
6903 if (IsZero)
6904 Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6905 else
6906 Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6907 return DAG.getNode(AArch64ISD::NOT, dl, VT, Cmeq);
6908 }
6909 case AArch64CC::EQ:
6910 if (IsZero)
6911 return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
6912 return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
6913 case AArch64CC::GE:
6914 if (IsZero)
6915 return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
6916 return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
6917 case AArch64CC::GT:
6918 if (IsZero)
6919 return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
6920 return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
6921 case AArch64CC::LE:
6922 if (IsZero)
6923 return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
6924 return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
6925 case AArch64CC::LS:
6926 return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
6927 case AArch64CC::LO:
6928 return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
6929 case AArch64CC::LT:
6930 if (IsZero)
6931 return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
6932 return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
6933 case AArch64CC::HI:
6934 return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
6935 case AArch64CC::HS:
6936 return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
6937 }
6938}
6939
6940SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
6941 SelectionDAG &DAG) const {
6942 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
6943 SDValue LHS = Op.getOperand(0);
6944 SDValue RHS = Op.getOperand(1);
Tim Northover45aa89c2015-02-08 00:50:47 +00006945 EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
Tim Northover3b0846e2014-05-24 12:50:23 +00006946 SDLoc dl(Op);
6947
6948 if (LHS.getValueType().getVectorElementType().isInteger()) {
6949 assert(LHS.getValueType() == RHS.getValueType());
6950 AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
Tim Northover45aa89c2015-02-08 00:50:47 +00006951 SDValue Cmp =
6952 EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
6953 return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
Tim Northover3b0846e2014-05-24 12:50:23 +00006954 }
6955
Pirama Arumuga Nainar71e9a2a2016-01-22 01:16:57 +00006956 if (LHS.getValueType().getVectorElementType() == MVT::f16)
6957 return SDValue();
6958
Tim Northover3b0846e2014-05-24 12:50:23 +00006959 assert(LHS.getValueType().getVectorElementType() == MVT::f32 ||
6960 LHS.getValueType().getVectorElementType() == MVT::f64);
6961
6962 // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
6963 // clean. Some of them require two branches to implement.
6964 AArch64CC::CondCode CC1, CC2;
6965 bool ShouldInvert;
6966 changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
6967
6968 bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
6969 SDValue Cmp =
Tim Northover45aa89c2015-02-08 00:50:47 +00006970 EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00006971 if (!Cmp.getNode())
6972 return SDValue();
6973
6974 if (CC2 != AArch64CC::AL) {
6975 SDValue Cmp2 =
Tim Northover45aa89c2015-02-08 00:50:47 +00006976 EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00006977 if (!Cmp2.getNode())
6978 return SDValue();
6979
Tim Northover45aa89c2015-02-08 00:50:47 +00006980 Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
Tim Northover3b0846e2014-05-24 12:50:23 +00006981 }
6982
Tim Northover45aa89c2015-02-08 00:50:47 +00006983 Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
6984
Tim Northover3b0846e2014-05-24 12:50:23 +00006985 if (ShouldInvert)
6986 return Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
6987
6988 return Cmp;
6989}
6990
6991/// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
6992/// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
6993/// specified in the intrinsic calls.
6994bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
6995 const CallInst &I,
6996 unsigned Intrinsic) const {
Mehdi Aminia749f2a2015-07-09 02:09:52 +00006997 auto &DL = I.getModule()->getDataLayout();
Tim Northover3b0846e2014-05-24 12:50:23 +00006998 switch (Intrinsic) {
6999 case Intrinsic::aarch64_neon_ld2:
7000 case Intrinsic::aarch64_neon_ld3:
7001 case Intrinsic::aarch64_neon_ld4:
7002 case Intrinsic::aarch64_neon_ld1x2:
7003 case Intrinsic::aarch64_neon_ld1x3:
7004 case Intrinsic::aarch64_neon_ld1x4:
7005 case Intrinsic::aarch64_neon_ld2lane:
7006 case Intrinsic::aarch64_neon_ld3lane:
7007 case Intrinsic::aarch64_neon_ld4lane:
7008 case Intrinsic::aarch64_neon_ld2r:
7009 case Intrinsic::aarch64_neon_ld3r:
7010 case Intrinsic::aarch64_neon_ld4r: {
7011 Info.opc = ISD::INTRINSIC_W_CHAIN;
7012 // Conservatively set memVT to the entire set of vectors loaded.
Ahmed Bougacha97564c32015-12-09 01:19:50 +00007013 uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00007014 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
7015 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
7016 Info.offset = 0;
7017 Info.align = 0;
7018 Info.vol = false; // volatile loads with NEON intrinsics not supported
7019 Info.readMem = true;
7020 Info.writeMem = false;
7021 return true;
7022 }
7023 case Intrinsic::aarch64_neon_st2:
7024 case Intrinsic::aarch64_neon_st3:
7025 case Intrinsic::aarch64_neon_st4:
7026 case Intrinsic::aarch64_neon_st1x2:
7027 case Intrinsic::aarch64_neon_st1x3:
7028 case Intrinsic::aarch64_neon_st1x4:
7029 case Intrinsic::aarch64_neon_st2lane:
7030 case Intrinsic::aarch64_neon_st3lane:
7031 case Intrinsic::aarch64_neon_st4lane: {
7032 Info.opc = ISD::INTRINSIC_VOID;
7033 // Conservatively set memVT to the entire set of vectors stored.
7034 unsigned NumElts = 0;
7035 for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
7036 Type *ArgTy = I.getArgOperand(ArgI)->getType();
7037 if (!ArgTy->isVectorTy())
7038 break;
Ahmed Bougacha97564c32015-12-09 01:19:50 +00007039 NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00007040 }
7041 Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
7042 Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
7043 Info.offset = 0;
7044 Info.align = 0;
7045 Info.vol = false; // volatile stores with NEON intrinsics not supported
7046 Info.readMem = false;
7047 Info.writeMem = true;
7048 return true;
7049 }
7050 case Intrinsic::aarch64_ldaxr:
7051 case Intrinsic::aarch64_ldxr: {
7052 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
7053 Info.opc = ISD::INTRINSIC_W_CHAIN;
7054 Info.memVT = MVT::getVT(PtrTy->getElementType());
7055 Info.ptrVal = I.getArgOperand(0);
7056 Info.offset = 0;
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007057 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
Tim Northover3b0846e2014-05-24 12:50:23 +00007058 Info.vol = true;
7059 Info.readMem = true;
7060 Info.writeMem = false;
7061 return true;
7062 }
7063 case Intrinsic::aarch64_stlxr:
7064 case Intrinsic::aarch64_stxr: {
7065 PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
7066 Info.opc = ISD::INTRINSIC_W_CHAIN;
7067 Info.memVT = MVT::getVT(PtrTy->getElementType());
7068 Info.ptrVal = I.getArgOperand(1);
7069 Info.offset = 0;
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007070 Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
Tim Northover3b0846e2014-05-24 12:50:23 +00007071 Info.vol = true;
7072 Info.readMem = false;
7073 Info.writeMem = true;
7074 return true;
7075 }
7076 case Intrinsic::aarch64_ldaxp:
Eugene Zelenko049b0172017-01-06 00:30:53 +00007077 case Intrinsic::aarch64_ldxp:
Tim Northover3b0846e2014-05-24 12:50:23 +00007078 Info.opc = ISD::INTRINSIC_W_CHAIN;
7079 Info.memVT = MVT::i128;
7080 Info.ptrVal = I.getArgOperand(0);
7081 Info.offset = 0;
7082 Info.align = 16;
7083 Info.vol = true;
7084 Info.readMem = true;
7085 Info.writeMem = false;
7086 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +00007087 case Intrinsic::aarch64_stlxp:
Eugene Zelenko049b0172017-01-06 00:30:53 +00007088 case Intrinsic::aarch64_stxp:
Tim Northover3b0846e2014-05-24 12:50:23 +00007089 Info.opc = ISD::INTRINSIC_W_CHAIN;
7090 Info.memVT = MVT::i128;
7091 Info.ptrVal = I.getArgOperand(2);
7092 Info.offset = 0;
7093 Info.align = 16;
7094 Info.vol = true;
7095 Info.readMem = false;
7096 Info.writeMem = true;
7097 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +00007098 default:
7099 break;
7100 }
7101
7102 return false;
7103}
7104
7105// Truncations from 64-bit GPR to 32-bit GPR is free.
7106bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
7107 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
7108 return false;
7109 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7110 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00007111 return NumBits1 > NumBits2;
Tim Northover3b0846e2014-05-24 12:50:23 +00007112}
7113bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
Hao Liu40914502014-05-29 09:19:07 +00007114 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00007115 return false;
7116 unsigned NumBits1 = VT1.getSizeInBits();
7117 unsigned NumBits2 = VT2.getSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00007118 return NumBits1 > NumBits2;
Tim Northover3b0846e2014-05-24 12:50:23 +00007119}
7120
Chad Rosier54390052015-02-23 19:15:16 +00007121/// Check if it is profitable to hoist instruction in then/else to if.
7122/// Not profitable if I and it's user can form a FMA instruction
7123/// because we prefer FMSUB/FMADD.
7124bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
7125 if (I->getOpcode() != Instruction::FMul)
7126 return true;
7127
7128 if (I->getNumUses() != 1)
7129 return true;
7130
7131 Instruction *User = I->user_back();
7132
7133 if (User &&
7134 !(User->getOpcode() == Instruction::FSub ||
7135 User->getOpcode() == Instruction::FAdd))
7136 return true;
7137
7138 const TargetOptions &Options = getTargetMachine().Options;
Mehdi Amini44ede332015-07-09 02:09:04 +00007139 const DataLayout &DL = I->getModule()->getDataLayout();
7140 EVT VT = getValueType(DL, User->getOperand(0)->getType());
Chad Rosier54390052015-02-23 19:15:16 +00007141
Eric Christopher114fa1c2016-02-29 22:50:49 +00007142 return !(isFMAFasterThanFMulAndFAdd(VT) &&
7143 isOperationLegalOrCustom(ISD::FMA, VT) &&
7144 (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7145 Options.UnsafeFPMath));
Chad Rosier54390052015-02-23 19:15:16 +00007146}
7147
Tim Northover3b0846e2014-05-24 12:50:23 +00007148// All 32-bit GPR operations implicitly zero the high-half of the corresponding
7149// 64-bit GPR.
7150bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
7151 if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
7152 return false;
7153 unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
7154 unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00007155 return NumBits1 == 32 && NumBits2 == 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00007156}
7157bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
Hao Liu40914502014-05-29 09:19:07 +00007158 if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
Tim Northover3b0846e2014-05-24 12:50:23 +00007159 return false;
7160 unsigned NumBits1 = VT1.getSizeInBits();
7161 unsigned NumBits2 = VT2.getSizeInBits();
Hao Liu40914502014-05-29 09:19:07 +00007162 return NumBits1 == 32 && NumBits2 == 64;
Tim Northover3b0846e2014-05-24 12:50:23 +00007163}
7164
7165bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
7166 EVT VT1 = Val.getValueType();
7167 if (isZExtFree(VT1, VT2)) {
7168 return true;
7169 }
7170
7171 if (Val.getOpcode() != ISD::LOAD)
7172 return false;
7173
7174 // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
Hao Liu40914502014-05-29 09:19:07 +00007175 return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
7176 VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
7177 VT1.getSizeInBits() <= 32);
Tim Northover3b0846e2014-05-24 12:50:23 +00007178}
7179
Quentin Colombet6843ac42015-03-31 20:52:32 +00007180bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
7181 if (isa<FPExtInst>(Ext))
7182 return false;
7183
7184 // Vector types are next free.
7185 if (Ext->getType()->isVectorTy())
7186 return false;
7187
7188 for (const Use &U : Ext->uses()) {
7189 // The extension is free if we can fold it with a left shift in an
7190 // addressing mode or an arithmetic operation: add, sub, and cmp.
7191
7192 // Is there a shift?
7193 const Instruction *Instr = cast<Instruction>(U.getUser());
7194
7195 // Is this a constant shift?
7196 switch (Instr->getOpcode()) {
7197 case Instruction::Shl:
7198 if (!isa<ConstantInt>(Instr->getOperand(1)))
7199 return false;
7200 break;
7201 case Instruction::GetElementPtr: {
7202 gep_type_iterator GTI = gep_type_begin(Instr);
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007203 auto &DL = Ext->getModule()->getDataLayout();
Peter Collingbourneab85225b2016-12-02 02:24:42 +00007204 std::advance(GTI, U.getOperandNo()-1);
7205 Type *IdxTy = GTI.getIndexedType();
Quentin Colombet6843ac42015-03-31 20:52:32 +00007206 // This extension will end up with a shift because of the scaling factor.
7207 // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
7208 // Get the shift amount based on the scaling factor:
7209 // log2(sizeof(IdxTy)) - log2(8).
7210 uint64_t ShiftAmt =
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007211 countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy)) - 3;
Quentin Colombet6843ac42015-03-31 20:52:32 +00007212 // Is the constant foldable in the shift of the addressing mode?
7213 // I.e., shift amount is between 1 and 4 inclusive.
7214 if (ShiftAmt == 0 || ShiftAmt > 4)
7215 return false;
7216 break;
7217 }
7218 case Instruction::Trunc:
7219 // Check if this is a noop.
7220 // trunc(sext ty1 to ty2) to ty1.
7221 if (Instr->getType() == Ext->getOperand(0)->getType())
7222 continue;
Justin Bognercd1d5aa2016-08-17 20:30:52 +00007223 LLVM_FALLTHROUGH;
Quentin Colombet6843ac42015-03-31 20:52:32 +00007224 default:
7225 return false;
7226 }
7227
7228 // At this point we can use the bfm family, so this extension is free
7229 // for that use.
7230 }
7231 return true;
7232}
7233
Tim Northover3b0846e2014-05-24 12:50:23 +00007234bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
7235 unsigned &RequiredAligment) const {
7236 if (!LoadedType.isSimple() ||
7237 (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
7238 return false;
7239 // Cyclone supports unaligned accesses.
7240 RequiredAligment = 0;
7241 unsigned NumBits = LoadedType.getSizeInBits();
7242 return NumBits == 32 || NumBits == 64;
7243}
7244
Matthew Simpson1bfa1592017-03-02 15:11:20 +00007245/// A helper function for determining the number of interleaved accesses we
7246/// will generate when lowering accesses of the given type.
Matthew Simpson1468d3e2017-04-10 18:34:37 +00007247unsigned
7248AArch64TargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
7249 const DataLayout &DL) const {
Matthew Simpson1bfa1592017-03-02 15:11:20 +00007250 return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
7251}
7252
Matthew Simpson1468d3e2017-04-10 18:34:37 +00007253bool AArch64TargetLowering::isLegalInterleavedAccessType(
7254 VectorType *VecTy, const DataLayout &DL) const {
7255
7256 unsigned VecSize = DL.getTypeSizeInBits(VecTy);
7257 unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
7258
7259 // Ensure the number of vector elements is greater than 1.
7260 if (VecTy->getNumElements() < 2)
7261 return false;
7262
7263 // Ensure the element type is legal.
7264 if (ElSize != 8 && ElSize != 16 && ElSize != 32 && ElSize != 64)
7265 return false;
7266
7267 // Ensure the total vector size is 64 or a multiple of 128. Types larger than
7268 // 128 will be split into multiple interleaved accesses.
7269 return VecSize == 64 || VecSize % 128 == 0;
7270}
7271
Hao Liu7ec8ee32015-06-26 02:32:07 +00007272/// \brief Lower an interleaved load into a ldN intrinsic.
7273///
7274/// E.g. Lower an interleaved load (Factor = 2):
7275/// %wide.vec = load <8 x i32>, <8 x i32>* %ptr
7276/// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
7277/// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
7278///
7279/// Into:
7280/// %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
7281/// %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
7282/// %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
7283bool AArch64TargetLowering::lowerInterleavedLoad(
7284 LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
7285 ArrayRef<unsigned> Indices, unsigned Factor) const {
7286 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7287 "Invalid interleave factor");
7288 assert(!Shuffles.empty() && "Empty shufflevector input");
7289 assert(Shuffles.size() == Indices.size() &&
7290 "Unmatched number of shufflevectors and indices");
7291
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007292 const DataLayout &DL = LI->getModule()->getDataLayout();
Hao Liu7ec8ee32015-06-26 02:32:07 +00007293
7294 VectorType *VecTy = Shuffles[0]->getType();
Hao Liu7ec8ee32015-06-26 02:32:07 +00007295
Matthew Simpson1bfa1592017-03-02 15:11:20 +00007296 // Skip if we do not have NEON and skip illegal vector types. We can
7297 // "legalize" wide vector types into multiple interleaved accesses as long as
7298 // the vector types are divisible by 128.
Matthew Simpson1468d3e2017-04-10 18:34:37 +00007299 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL))
Hao Liu7ec8ee32015-06-26 02:32:07 +00007300 return false;
7301
Matthew Simpson1bfa1592017-03-02 15:11:20 +00007302 unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
7303
Hao Liu7ec8ee32015-06-26 02:32:07 +00007304 // A pointer vector can not be the return type of the ldN intrinsics. Need to
7305 // load integer vectors first and then convert to pointer vectors.
7306 Type *EltTy = VecTy->getVectorElementType();
7307 if (EltTy->isPointerTy())
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007308 VecTy =
7309 VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
Hao Liu7ec8ee32015-06-26 02:32:07 +00007310
Matthew Simpson1bfa1592017-03-02 15:11:20 +00007311 IRBuilder<> Builder(LI);
7312
7313 // The base address of the load.
7314 Value *BaseAddr = LI->getPointerOperand();
7315
7316 if (NumLoads > 1) {
7317 // If we're going to generate more than one load, reset the sub-vector type
7318 // to something legal.
7319 VecTy = VectorType::get(VecTy->getVectorElementType(),
7320 VecTy->getVectorNumElements() / NumLoads);
7321
7322 // We will compute the pointer operand of each load from the original base
7323 // address using GEPs. Cast the base address to a pointer to the scalar
7324 // element type.
7325 BaseAddr = Builder.CreateBitCast(
7326 BaseAddr, VecTy->getVectorElementType()->getPointerTo(
7327 LI->getPointerAddressSpace()));
7328 }
7329
Hao Liu7ec8ee32015-06-26 02:32:07 +00007330 Type *PtrTy = VecTy->getPointerTo(LI->getPointerAddressSpace());
7331 Type *Tys[2] = {VecTy, PtrTy};
7332 static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
7333 Intrinsic::aarch64_neon_ld3,
7334 Intrinsic::aarch64_neon_ld4};
7335 Function *LdNFunc =
7336 Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
7337
Matthew Simpson1bfa1592017-03-02 15:11:20 +00007338 // Holds sub-vectors extracted from the load intrinsic return values. The
7339 // sub-vectors are associated with the shufflevector instructions they will
7340 // replace.
7341 DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
Hao Liu7ec8ee32015-06-26 02:32:07 +00007342
Matthew Simpson1bfa1592017-03-02 15:11:20 +00007343 for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
Hao Liu7ec8ee32015-06-26 02:32:07 +00007344
Matthew Simpson1bfa1592017-03-02 15:11:20 +00007345 // If we're generating more than one load, compute the base address of
7346 // subsequent loads as an offset from the previous.
7347 if (LoadCount > 0)
7348 BaseAddr = Builder.CreateConstGEP1_32(
7349 BaseAddr, VecTy->getVectorNumElements() * Factor);
Hao Liu7ec8ee32015-06-26 02:32:07 +00007350
Matthew Simpson1bfa1592017-03-02 15:11:20 +00007351 CallInst *LdN = Builder.CreateCall(
7352 LdNFunc, Builder.CreateBitCast(BaseAddr, PtrTy), "ldN");
Hao Liu7ec8ee32015-06-26 02:32:07 +00007353
Matthew Simpson1bfa1592017-03-02 15:11:20 +00007354 // Extract and store the sub-vectors returned by the load intrinsic.
7355 for (unsigned i = 0; i < Shuffles.size(); i++) {
7356 ShuffleVectorInst *SVI = Shuffles[i];
7357 unsigned Index = Indices[i];
Hao Liu7ec8ee32015-06-26 02:32:07 +00007358
Matthew Simpson1bfa1592017-03-02 15:11:20 +00007359 Value *SubVec = Builder.CreateExtractValue(LdN, Index);
7360
7361 // Convert the integer vector to pointer vector if the element is pointer.
7362 if (EltTy->isPointerTy())
7363 SubVec = Builder.CreateIntToPtr(SubVec, SVI->getType());
7364
7365 SubVecs[SVI].push_back(SubVec);
7366 }
7367 }
7368
7369 // Replace uses of the shufflevector instructions with the sub-vectors
7370 // returned by the load intrinsic. If a shufflevector instruction is
7371 // associated with more than one sub-vector, those sub-vectors will be
7372 // concatenated into a single wide vector.
7373 for (ShuffleVectorInst *SVI : Shuffles) {
7374 auto &SubVec = SubVecs[SVI];
7375 auto *WideVec =
7376 SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
7377 SVI->replaceAllUsesWith(WideVec);
Hao Liu7ec8ee32015-06-26 02:32:07 +00007378 }
7379
7380 return true;
7381}
7382
Hao Liu7ec8ee32015-06-26 02:32:07 +00007383/// \brief Lower an interleaved store into a stN intrinsic.
7384///
7385/// E.g. Lower an interleaved store (Factor = 3):
7386/// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00007387/// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
Hao Liu7ec8ee32015-06-26 02:32:07 +00007388/// store <12 x i32> %i.vec, <12 x i32>* %ptr
7389///
7390/// Into:
7391/// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
7392/// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
7393/// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
7394/// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
7395///
7396/// Note that the new shufflevectors will be removed and we'll only generate one
7397/// st3 instruction in CodeGen.
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00007398///
7399/// Example for a more general valid mask (Factor 3). Lower:
7400/// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
7401/// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
7402/// store <12 x i32> %i.vec, <12 x i32>* %ptr
7403///
7404/// Into:
7405/// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
7406/// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
7407/// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
7408/// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
Hao Liu7ec8ee32015-06-26 02:32:07 +00007409bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
7410 ShuffleVectorInst *SVI,
7411 unsigned Factor) const {
7412 assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
7413 "Invalid interleave factor");
7414
7415 VectorType *VecTy = SVI->getType();
7416 assert(VecTy->getVectorNumElements() % Factor == 0 &&
7417 "Invalid interleaved store");
7418
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00007419 unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
Hao Liu7ec8ee32015-06-26 02:32:07 +00007420 Type *EltTy = VecTy->getVectorElementType();
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00007421 VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
Hao Liu7ec8ee32015-06-26 02:32:07 +00007422
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007423 const DataLayout &DL = SI->getModule()->getDataLayout();
Hao Liu7ec8ee32015-06-26 02:32:07 +00007424
Matthew Simpson1bfa1592017-03-02 15:11:20 +00007425 // Skip if we do not have NEON and skip illegal vector types. We can
7426 // "legalize" wide vector types into multiple interleaved accesses as long as
7427 // the vector types are divisible by 128.
Matthew Simpson1468d3e2017-04-10 18:34:37 +00007428 if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
Hao Liu7ec8ee32015-06-26 02:32:07 +00007429 return false;
7430
Matthew Simpson1bfa1592017-03-02 15:11:20 +00007431 unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
7432
Hao Liu7ec8ee32015-06-26 02:32:07 +00007433 Value *Op0 = SVI->getOperand(0);
7434 Value *Op1 = SVI->getOperand(1);
7435 IRBuilder<> Builder(SI);
7436
7437 // StN intrinsics don't support pointer vectors as arguments. Convert pointer
7438 // vectors to integer vectors.
7439 if (EltTy->isPointerTy()) {
Mehdi Aminia749f2a2015-07-09 02:09:52 +00007440 Type *IntTy = DL.getIntPtrType(EltTy);
Hao Liu7ec8ee32015-06-26 02:32:07 +00007441 unsigned NumOpElts =
7442 dyn_cast<VectorType>(Op0->getType())->getVectorNumElements();
7443
7444 // Convert to the corresponding integer vector.
7445 Type *IntVecTy = VectorType::get(IntTy, NumOpElts);
7446 Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
7447 Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
7448
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00007449 SubVecTy = VectorType::get(IntTy, LaneLen);
Hao Liu7ec8ee32015-06-26 02:32:07 +00007450 }
7451
Matthew Simpson1bfa1592017-03-02 15:11:20 +00007452 // The base address of the store.
7453 Value *BaseAddr = SI->getPointerOperand();
7454
7455 if (NumStores > 1) {
7456 // If we're going to generate more than one store, reset the lane length
7457 // and sub-vector type to something legal.
7458 LaneLen /= NumStores;
7459 SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen);
7460
7461 // We will compute the pointer operand of each store from the original base
7462 // address using GEPs. Cast the base address to a pointer to the scalar
7463 // element type.
7464 BaseAddr = Builder.CreateBitCast(
7465 BaseAddr, SubVecTy->getVectorElementType()->getPointerTo(
7466 SI->getPointerAddressSpace()));
7467 }
7468
7469 auto Mask = SVI->getShuffleMask();
7470
Hao Liu7ec8ee32015-06-26 02:32:07 +00007471 Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
7472 Type *Tys[2] = {SubVecTy, PtrTy};
7473 static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
7474 Intrinsic::aarch64_neon_st3,
7475 Intrinsic::aarch64_neon_st4};
7476 Function *StNFunc =
7477 Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
7478
Matthew Simpson1bfa1592017-03-02 15:11:20 +00007479 for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
Hao Liu7ec8ee32015-06-26 02:32:07 +00007480
Matthew Simpson1bfa1592017-03-02 15:11:20 +00007481 SmallVector<Value *, 5> Ops;
7482
7483 // Split the shufflevector operands into sub vectors for the new stN call.
7484 for (unsigned i = 0; i < Factor; i++) {
7485 unsigned IdxI = StoreCount * LaneLen * Factor + i;
7486 if (Mask[IdxI] >= 0) {
7487 Ops.push_back(Builder.CreateShuffleVector(
7488 Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0)));
7489 } else {
7490 unsigned StartMask = 0;
7491 for (unsigned j = 1; j < LaneLen; j++) {
7492 unsigned IdxJ = StoreCount * LaneLen * Factor + j;
7493 if (Mask[IdxJ * Factor + IdxI] >= 0) {
7494 StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
7495 break;
7496 }
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00007497 }
Matthew Simpson1bfa1592017-03-02 15:11:20 +00007498 // Note: Filling undef gaps with random elements is ok, since
7499 // those elements were being written anyway (with undefs).
7500 // In the case of all undefs we're defaulting to using elems from 0
7501 // Note: StartMask cannot be negative, it's checked in
7502 // isReInterleaveMask
7503 Ops.push_back(Builder.CreateShuffleVector(
7504 Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0)));
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00007505 }
Alina Sbirlea77c5eaa2016-12-13 19:32:36 +00007506 }
Hao Liu7ec8ee32015-06-26 02:32:07 +00007507
Matthew Simpson1bfa1592017-03-02 15:11:20 +00007508 // If we generating more than one store, we compute the base address of
7509 // subsequent stores as an offset from the previous.
7510 if (StoreCount > 0)
7511 BaseAddr = Builder.CreateConstGEP1_32(BaseAddr, LaneLen * Factor);
7512
7513 Ops.push_back(Builder.CreateBitCast(BaseAddr, PtrTy));
7514 Builder.CreateCall(StNFunc, Ops);
7515 }
Hao Liu7ec8ee32015-06-26 02:32:07 +00007516 return true;
7517}
7518
Tim Northover3b0846e2014-05-24 12:50:23 +00007519static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
7520 unsigned AlignCheck) {
7521 return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
7522 (DstAlign == 0 || DstAlign % AlignCheck == 0));
7523}
7524
7525EVT AArch64TargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
7526 unsigned SrcAlign, bool IsMemset,
7527 bool ZeroMemset,
7528 bool MemcpyStrSrc,
7529 MachineFunction &MF) const {
7530 // Don't use AdvSIMD to implement 16-byte memset. It would have taken one
7531 // instruction to materialize the v2i64 zero and one store (with restrictive
7532 // addressing mode). Just do two i64 store of zero-registers.
7533 bool Fast;
7534 const Function *F = MF.getFunction();
7535 if (Subtarget->hasFPARMv8() && !IsMemset && Size >= 16 &&
Duncan P. N. Exon Smith003bb7d2015-02-14 02:09:06 +00007536 !F->hasFnAttribute(Attribute::NoImplicitFloat) &&
Tim Northover3b0846e2014-05-24 12:50:23 +00007537 (memOpAlign(SrcAlign, DstAlign, 16) ||
Matt Arsenault6f2a5262014-07-27 17:46:40 +00007538 (allowsMisalignedMemoryAccesses(MVT::f128, 0, 1, &Fast) && Fast)))
Tim Northover3b0846e2014-05-24 12:50:23 +00007539 return MVT::f128;
7540
Lang Hames90333852015-04-09 03:40:33 +00007541 if (Size >= 8 &&
7542 (memOpAlign(SrcAlign, DstAlign, 8) ||
7543 (allowsMisalignedMemoryAccesses(MVT::i64, 0, 1, &Fast) && Fast)))
7544 return MVT::i64;
7545
7546 if (Size >= 4 &&
7547 (memOpAlign(SrcAlign, DstAlign, 4) ||
7548 (allowsMisalignedMemoryAccesses(MVT::i32, 0, 1, &Fast) && Fast)))
Lang Hames522bf132015-04-09 05:34:57 +00007549 return MVT::i32;
Lang Hames90333852015-04-09 03:40:33 +00007550
7551 return MVT::Other;
Tim Northover3b0846e2014-05-24 12:50:23 +00007552}
7553
7554// 12-bit optionally shifted immediates are legal for adds.
7555bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
Geoff Berry486f49c2016-06-07 16:48:43 +00007556 // Avoid UB for INT64_MIN.
7557 if (Immed == std::numeric_limits<int64_t>::min())
7558 return false;
7559 // Same encoding for add/sub, just flip the sign.
7560 Immed = std::abs(Immed);
Eric Christopher114fa1c2016-02-29 22:50:49 +00007561 return ((Immed >> 12) == 0 || ((Immed & 0xfff) == 0 && Immed >> 24 == 0));
Tim Northover3b0846e2014-05-24 12:50:23 +00007562}
7563
7564// Integer comparisons are implemented with ADDS/SUBS, so the range of valid
7565// immediates is the same as for an add or a sub.
7566bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00007567 return isLegalAddImmediate(Immed);
7568}
7569
7570/// isLegalAddressingMode - Return true if the addressing mode represented
7571/// by AM is legal for this target, for a load/store of the specified type.
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00007572bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
7573 const AddrMode &AM, Type *Ty,
Matt Arsenaultbd7d80a2015-06-01 05:31:59 +00007574 unsigned AS) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00007575 // AArch64 has five basic addressing modes:
7576 // reg
7577 // reg + 9-bit signed offset
7578 // reg + SIZE_IN_BYTES * 12-bit unsigned offset
7579 // reg1 + reg2
7580 // reg + SIZE_IN_BYTES * reg
7581
7582 // No global is ever allowed as a base.
7583 if (AM.BaseGV)
7584 return false;
7585
7586 // No reg+reg+imm addressing.
7587 if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
7588 return false;
7589
7590 // check reg + imm case:
7591 // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
7592 uint64_t NumBytes = 0;
7593 if (Ty->isSized()) {
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00007594 uint64_t NumBits = DL.getTypeSizeInBits(Ty);
Tim Northover3b0846e2014-05-24 12:50:23 +00007595 NumBytes = NumBits / 8;
7596 if (!isPowerOf2_64(NumBits))
7597 NumBytes = 0;
7598 }
7599
7600 if (!AM.Scale) {
7601 int64_t Offset = AM.BaseOffs;
7602
7603 // 9-bit signed offset
Haicheng Wuf8b83402016-12-07 01:45:04 +00007604 if (isInt<9>(Offset))
Tim Northover3b0846e2014-05-24 12:50:23 +00007605 return true;
7606
7607 // 12-bit unsigned offset
7608 unsigned shift = Log2_64(NumBytes);
7609 if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
7610 // Must be a multiple of NumBytes (NumBytes is a power of 2)
7611 (Offset >> shift) << shift == Offset)
7612 return true;
7613 return false;
7614 }
7615
7616 // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
7617
Haicheng Wu6bb0e392016-12-21 21:40:47 +00007618 return AM.Scale == 1 || (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes);
Tim Northover3b0846e2014-05-24 12:50:23 +00007619}
7620
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00007621int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
7622 const AddrMode &AM, Type *Ty,
Matt Arsenaultbd7d80a2015-06-01 05:31:59 +00007623 unsigned AS) const {
Tim Northover3b0846e2014-05-24 12:50:23 +00007624 // Scaling factors are not free at all.
7625 // Operands | Rt Latency
7626 // -------------------------------------------
7627 // Rt, [Xn, Xm] | 4
7628 // -------------------------------------------
7629 // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5
7630 // Rt, [Xn, Wm, <extend> #imm] |
Mehdi Amini0cdec1e2015-07-09 02:09:40 +00007631 if (isLegalAddressingMode(DL, AM, Ty, AS))
Tim Northover3b0846e2014-05-24 12:50:23 +00007632 // Scale represents reg2 * scale, thus account for 1 if
7633 // it is not equal to 0 or 1.
7634 return AM.Scale != 0 && AM.Scale != 1;
7635 return -1;
7636}
7637
7638bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
7639 VT = VT.getScalarType();
7640
7641 if (!VT.isSimple())
7642 return false;
7643
7644 switch (VT.getSimpleVT().SimpleTy) {
7645 case MVT::f32:
7646 case MVT::f64:
7647 return true;
7648 default:
7649 break;
7650 }
7651
7652 return false;
7653}
7654
7655const MCPhysReg *
7656AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
7657 // LR is a callee-save register, but we must treat it as clobbered by any call
7658 // site. Hence we include LR in the scratch registers, which are in turn added
7659 // as implicit-defs for stackmaps and patchpoints.
7660 static const MCPhysReg ScratchRegs[] = {
7661 AArch64::X16, AArch64::X17, AArch64::LR, 0
7662 };
7663 return ScratchRegs;
7664}
7665
7666bool
7667AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N) const {
7668 EVT VT = N->getValueType(0);
7669 // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
7670 // it with shift to let it be lowered to UBFX.
7671 if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
7672 isa<ConstantSDNode>(N->getOperand(1))) {
7673 uint64_t TruncMask = N->getConstantOperandVal(1);
7674 if (isMask_64(TruncMask) &&
7675 N->getOperand(0).getOpcode() == ISD::SRL &&
7676 isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
7677 return false;
7678 }
7679 return true;
7680}
7681
7682bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
7683 Type *Ty) const {
7684 assert(Ty->isIntegerTy());
7685
7686 unsigned BitSize = Ty->getPrimitiveSizeInBits();
7687 if (BitSize == 0)
7688 return false;
7689
7690 int64_t Val = Imm.getSExtValue();
7691 if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
7692 return true;
7693
7694 if ((int64_t)Val < 0)
7695 Val = ~Val;
7696 if (BitSize == 32)
7697 Val &= (1LL << 32) - 1;
7698
7699 unsigned LZ = countLeadingZeros((uint64_t)Val);
7700 unsigned Shift = (63 - LZ) / 16;
7701 // MOVZ is free so return true for one or fewer MOVK.
David Blaikie186d2cb2015-03-24 16:24:01 +00007702 return Shift < 3;
Tim Northover3b0846e2014-05-24 12:50:23 +00007703}
7704
Sanjay Pateld6cb4ec2016-03-03 15:56:08 +00007705/// Turn vector tests of the signbit in the form of:
7706/// xor (sra X, elt_size(X)-1), -1
7707/// into:
7708/// cmge X, X, #0
7709static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
7710 const AArch64Subtarget *Subtarget) {
7711 EVT VT = N->getValueType(0);
7712 if (!Subtarget->hasNEON() || !VT.isVector())
7713 return SDValue();
7714
7715 // There must be a shift right algebraic before the xor, and the xor must be a
7716 // 'not' operation.
7717 SDValue Shift = N->getOperand(0);
7718 SDValue Ones = N->getOperand(1);
7719 if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() ||
7720 !ISD::isBuildVectorAllOnes(Ones.getNode()))
7721 return SDValue();
7722
7723 // The shift should be smearing the sign bit across each vector element.
7724 auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
7725 EVT ShiftEltTy = Shift.getValueType().getVectorElementType();
7726 if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1)
7727 return SDValue();
7728
7729 return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0));
7730}
7731
Tim Northover3b0846e2014-05-24 12:50:23 +00007732// Generate SUBS and CSEL for integer abs.
7733static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
7734 EVT VT = N->getValueType(0);
7735
7736 SDValue N0 = N->getOperand(0);
7737 SDValue N1 = N->getOperand(1);
7738 SDLoc DL(N);
7739
7740 // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
7741 // and change it to SUB and CSEL.
7742 if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
7743 N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1 &&
7744 N1.getOpcode() == ISD::SRA && N1.getOperand(0) == N0.getOperand(0))
7745 if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
7746 if (Y1C->getAPIntValue() == VT.getSizeInBits() - 1) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007747 SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
Tim Northover3b0846e2014-05-24 12:50:23 +00007748 N0.getOperand(0));
7749 // Generate SUBS & CSEL.
7750 SDValue Cmp =
7751 DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007752 N0.getOperand(0), DAG.getConstant(0, DL, VT));
Tim Northover3b0846e2014-05-24 12:50:23 +00007753 return DAG.getNode(AArch64ISD::CSEL, DL, VT, N0.getOperand(0), Neg,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007754 DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
Tim Northover3b0846e2014-05-24 12:50:23 +00007755 SDValue(Cmp.getNode(), 1));
7756 }
7757 return SDValue();
7758}
7759
Tim Northover3b0846e2014-05-24 12:50:23 +00007760static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
7761 TargetLowering::DAGCombinerInfo &DCI,
7762 const AArch64Subtarget *Subtarget) {
7763 if (DCI.isBeforeLegalizeOps())
7764 return SDValue();
7765
Sanjay Pateld6cb4ec2016-03-03 15:56:08 +00007766 if (SDValue Cmp = foldVectorXorShiftIntoCmp(N, DAG, Subtarget))
7767 return Cmp;
7768
Tim Northover3b0846e2014-05-24 12:50:23 +00007769 return performIntegerAbsCombine(N, DAG);
7770}
7771
Chad Rosier17020f92014-07-23 14:57:52 +00007772SDValue
7773AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
7774 SelectionDAG &DAG,
7775 std::vector<SDNode *> *Created) const {
Reid Klecknerb5180542017-03-21 16:57:19 +00007776 AttributeList Attr = DAG.getMachineFunction().getFunction()->getAttributes();
Haicheng Wu6a6bc752016-03-28 18:17:07 +00007777 if (isIntDivCheap(N->getValueType(0), Attr))
7778 return SDValue(N,0); // Lower SDIV as SDIV
7779
Chad Rosier17020f92014-07-23 14:57:52 +00007780 // fold (sdiv X, pow2)
7781 EVT VT = N->getValueType(0);
7782 if ((VT != MVT::i32 && VT != MVT::i64) ||
7783 !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
7784 return SDValue();
7785
7786 SDLoc DL(N);
7787 SDValue N0 = N->getOperand(0);
7788 unsigned Lg2 = Divisor.countTrailingZeros();
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007789 SDValue Zero = DAG.getConstant(0, DL, VT);
7790 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
Chad Rosier17020f92014-07-23 14:57:52 +00007791
7792 // Add (N0 < 0) ? Pow2 - 1 : 0;
7793 SDValue CCVal;
7794 SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
7795 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
7796 SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
7797
7798 if (Created) {
7799 Created->push_back(Cmp.getNode());
7800 Created->push_back(Add.getNode());
7801 Created->push_back(CSel.getNode());
7802 }
7803
7804 // Divide by pow2.
7805 SDValue SRA =
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007806 DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
Chad Rosier17020f92014-07-23 14:57:52 +00007807
7808 // If we're dividing by a positive value, we're done. Otherwise, we must
7809 // negate the result.
7810 if (Divisor.isNonNegative())
7811 return SRA;
7812
7813 if (Created)
7814 Created->push_back(SRA.getNode());
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00007815 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
Chad Rosier17020f92014-07-23 14:57:52 +00007816}
7817
Tim Northover3b0846e2014-05-24 12:50:23 +00007818static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
7819 TargetLowering::DAGCombinerInfo &DCI,
7820 const AArch64Subtarget *Subtarget) {
7821 if (DCI.isBeforeLegalizeOps())
7822 return SDValue();
7823
Chad Rosier31ee8132016-11-11 17:07:37 +00007824 // The below optimizations require a constant RHS.
7825 if (!isa<ConstantSDNode>(N->getOperand(1)))
7826 return SDValue();
7827
7828 ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1));
7829 const APInt &ConstValue = C->getAPIntValue();
7830
Tim Northover3b0846e2014-05-24 12:50:23 +00007831 // Multiplication of a power of two plus/minus one can be done more
7832 // cheaply as as shift+add/sub. For now, this is true unilaterally. If
7833 // future CPUs have a cheaper MADD instruction, this may need to be
7834 // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
7835 // 64-bit is 5 cycles, so this is always a win.
Haicheng Wufaee2b72016-11-15 20:16:48 +00007836 // More aggressively, some multiplications N0 * C can be lowered to
7837 // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M,
7838 // e.g. 6=3*2=(2+1)*2.
7839 // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45
7840 // which equals to (1+2)*16-(1+2).
7841 SDValue N0 = N->getOperand(0);
7842 // TrailingZeroes is used to test if the mul can be lowered to
7843 // shift+add+shift.
7844 unsigned TrailingZeroes = ConstValue.countTrailingZeros();
7845 if (TrailingZeroes) {
7846 // Conservatively do not lower to shift+add+shift if the mul might be
7847 // folded into smul or umul.
7848 if (N0->hasOneUse() && (isSignExtended(N0.getNode(), DAG) ||
7849 isZeroExtended(N0.getNode(), DAG)))
7850 return SDValue();
7851 // Conservatively do not lower to shift+add+shift if the mul might be
7852 // folded into madd or msub.
7853 if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ADD ||
7854 N->use_begin()->getOpcode() == ISD::SUB))
7855 return SDValue();
7856 }
7857 // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub
7858 // and shift+add+shift.
7859 APInt ShiftedConstValue = ConstValue.ashr(TrailingZeroes);
7860
Chad Rosierd6e85ce2016-11-11 17:49:34 +00007861 unsigned ShiftAmt, AddSubOpc;
7862 // Is the shifted value the LHS operand of the add/sub?
7863 bool ShiftValUseIsN0 = true;
7864 // Do we need to negate the result?
7865 bool NegateResult = false;
7866
Chad Rosier31ee8132016-11-11 17:07:37 +00007867 if (ConstValue.isNonNegative()) {
7868 // (mul x, 2^N + 1) => (add (shl x, N), x)
Chad Rosier31ee8132016-11-11 17:07:37 +00007869 // (mul x, 2^N - 1) => (sub (shl x, N), x)
Haicheng Wufaee2b72016-11-15 20:16:48 +00007870 // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M)
7871 APInt SCVMinus1 = ShiftedConstValue - 1;
Chad Rosier31ee8132016-11-11 17:07:37 +00007872 APInt CVPlus1 = ConstValue + 1;
Haicheng Wufaee2b72016-11-15 20:16:48 +00007873 if (SCVMinus1.isPowerOf2()) {
7874 ShiftAmt = SCVMinus1.logBase2();
Chad Rosierd6e85ce2016-11-11 17:49:34 +00007875 AddSubOpc = ISD::ADD;
7876 } else if (CVPlus1.isPowerOf2()) {
7877 ShiftAmt = CVPlus1.logBase2();
7878 AddSubOpc = ISD::SUB;
7879 } else
7880 return SDValue();
Chad Rosier31ee8132016-11-11 17:07:37 +00007881 } else {
7882 // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
Chad Rosier31ee8132016-11-11 17:07:37 +00007883 // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
Chad Rosierd6e85ce2016-11-11 17:49:34 +00007884 APInt CVNegPlus1 = -ConstValue + 1;
Chad Rosier31ee8132016-11-11 17:07:37 +00007885 APInt CVNegMinus1 = -ConstValue - 1;
Chad Rosierd6e85ce2016-11-11 17:49:34 +00007886 if (CVNegPlus1.isPowerOf2()) {
7887 ShiftAmt = CVNegPlus1.logBase2();
7888 AddSubOpc = ISD::SUB;
7889 ShiftValUseIsN0 = false;
7890 } else if (CVNegMinus1.isPowerOf2()) {
7891 ShiftAmt = CVNegMinus1.logBase2();
7892 AddSubOpc = ISD::ADD;
7893 NegateResult = true;
7894 } else
7895 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00007896 }
Chad Rosierd6e85ce2016-11-11 17:49:34 +00007897
7898 SDLoc DL(N);
7899 EVT VT = N->getValueType(0);
Haicheng Wufaee2b72016-11-15 20:16:48 +00007900 SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, VT, N0,
Chad Rosierd6e85ce2016-11-11 17:49:34 +00007901 DAG.getConstant(ShiftAmt, DL, MVT::i64));
7902
7903 SDValue AddSubN0 = ShiftValUseIsN0 ? ShiftedVal : N0;
7904 SDValue AddSubN1 = ShiftValUseIsN0 ? N0 : ShiftedVal;
7905 SDValue Res = DAG.getNode(AddSubOpc, DL, VT, AddSubN0, AddSubN1);
Haicheng Wufaee2b72016-11-15 20:16:48 +00007906 assert(!(NegateResult && TrailingZeroes) &&
7907 "NegateResult and TrailingZeroes cannot both be true for now.");
Chad Rosierd6e85ce2016-11-11 17:49:34 +00007908 // Negate the result.
Haicheng Wufaee2b72016-11-15 20:16:48 +00007909 if (NegateResult)
7910 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
7911 // Shift the result.
7912 if (TrailingZeroes)
7913 return DAG.getNode(ISD::SHL, DL, VT, Res,
7914 DAG.getConstant(TrailingZeroes, DL, MVT::i64));
7915 return Res;
Tim Northover3b0846e2014-05-24 12:50:23 +00007916}
7917
Jim Grosbachf7502c42014-07-18 00:40:52 +00007918static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
7919 SelectionDAG &DAG) {
7920 // Take advantage of vector comparisons producing 0 or -1 in each lane to
7921 // optimize away operation when it's from a constant.
7922 //
7923 // The general transformation is:
7924 // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
7925 // AND(VECTOR_CMP(x,y), constant2)
7926 // constant2 = UNARYOP(constant)
7927
Jim Grosbach8f6f0852014-07-23 20:41:38 +00007928 // Early exit if this isn't a vector operation, the operand of the
7929 // unary operation isn't a bitwise AND, or if the sizes of the operations
7930 // aren't the same.
Jim Grosbachf7502c42014-07-18 00:40:52 +00007931 EVT VT = N->getValueType(0);
7932 if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
Jim Grosbach8f6f0852014-07-23 20:41:38 +00007933 N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
7934 VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
Jim Grosbachf7502c42014-07-18 00:40:52 +00007935 return SDValue();
7936
Jim Grosbach724e4382014-07-23 20:41:43 +00007937 // Now check that the other operand of the AND is a constant. We could
Jim Grosbachf7502c42014-07-18 00:40:52 +00007938 // make the transformation for non-constant splats as well, but it's unclear
7939 // that would be a benefit as it would not eliminate any operations, just
7940 // perform one more step in scalar code before moving to the vector unit.
7941 if (BuildVectorSDNode *BV =
7942 dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
Jim Grosbach724e4382014-07-23 20:41:43 +00007943 // Bail out if the vector isn't a constant.
7944 if (!BV->isConstant())
Jim Grosbachf7502c42014-07-18 00:40:52 +00007945 return SDValue();
7946
7947 // Everything checks out. Build up the new and improved node.
7948 SDLoc DL(N);
7949 EVT IntVT = BV->getValueType(0);
7950 // Create a new constant of the appropriate type for the transformed
7951 // DAG.
7952 SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
7953 // The AND node needs bitcasts to/from an integer vector type around it.
7954 SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
7955 SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
7956 N->getOperand(0)->getOperand(0), MaskConst);
7957 SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
7958 return Res;
7959 }
7960
7961 return SDValue();
7962}
7963
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00007964static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
7965 const AArch64Subtarget *Subtarget) {
Jim Grosbachf7502c42014-07-18 00:40:52 +00007966 // First try to optimize away the conversion when it's conditionally from
7967 // a constant. Vectors only.
Ahmed Bougacha239d6352015-08-04 00:48:02 +00007968 if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
Jim Grosbachf7502c42014-07-18 00:40:52 +00007969 return Res;
7970
Tim Northover3b0846e2014-05-24 12:50:23 +00007971 EVT VT = N->getValueType(0);
7972 if (VT != MVT::f32 && VT != MVT::f64)
7973 return SDValue();
Jim Grosbachf7502c42014-07-18 00:40:52 +00007974
Tim Northover3b0846e2014-05-24 12:50:23 +00007975 // Only optimize when the source and destination types have the same width.
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00007976 if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits())
Tim Northover3b0846e2014-05-24 12:50:23 +00007977 return SDValue();
7978
7979 // If the result of an integer load is only used by an integer-to-float
7980 // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
Chad Rosier1f385612015-10-02 16:42:59 +00007981 // This eliminates an "integer-to-vector-move" UOP and improves throughput.
Tim Northover3b0846e2014-05-24 12:50:23 +00007982 SDValue N0 = N->getOperand(0);
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +00007983 if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
Tim Northover3b0846e2014-05-24 12:50:23 +00007984 // Do not change the width of a volatile load.
7985 !cast<LoadSDNode>(N0)->isVolatile()) {
7986 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7987 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
Justin Lebar9c375812016-07-15 18:27:10 +00007988 LN0->getPointerInfo(), LN0->getAlignment(),
7989 LN0->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +00007990
7991 // Make sure successors of the original load stay after it by updating them
7992 // to use the new Chain.
7993 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
7994
7995 unsigned Opcode =
7996 (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
7997 return DAG.getNode(Opcode, SDLoc(N), VT, Load);
7998 }
7999
8000 return SDValue();
8001}
8002
Chad Rosierfa30c9b2015-10-07 17:39:18 +00008003/// Fold a floating-point multiply by power of two into floating-point to
8004/// fixed-point conversion.
8005static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
Silviu Barangafa00ba32016-08-08 13:13:57 +00008006 TargetLowering::DAGCombinerInfo &DCI,
Chad Rosierfa30c9b2015-10-07 17:39:18 +00008007 const AArch64Subtarget *Subtarget) {
8008 if (!Subtarget->hasNEON())
8009 return SDValue();
8010
8011 SDValue Op = N->getOperand(0);
Tim Northover6092de52016-03-10 23:02:21 +00008012 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
8013 Op.getOpcode() != ISD::FMUL)
Chad Rosierfa30c9b2015-10-07 17:39:18 +00008014 return SDValue();
8015
8016 SDValue ConstVec = Op->getOperand(1);
8017 if (!isa<BuildVectorSDNode>(ConstVec))
8018 return SDValue();
8019
8020 MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
8021 uint32_t FloatBits = FloatTy.getSizeInBits();
8022 if (FloatBits != 32 && FloatBits != 64)
8023 return SDValue();
8024
8025 MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
8026 uint32_t IntBits = IntTy.getSizeInBits();
8027 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
8028 return SDValue();
8029
8030 // Avoid conversions where iN is larger than the float (e.g., float -> i64).
8031 if (IntBits > FloatBits)
8032 return SDValue();
8033
8034 BitVector UndefElements;
8035 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
8036 int32_t Bits = IntBits == 64 ? 64 : 32;
8037 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
8038 if (C == -1 || C == 0 || C > Bits)
8039 return SDValue();
8040
8041 MVT ResTy;
8042 unsigned NumLanes = Op.getValueType().getVectorNumElements();
8043 switch (NumLanes) {
8044 default:
8045 return SDValue();
8046 case 2:
8047 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
8048 break;
8049 case 4:
Silviu Barangafa00ba32016-08-08 13:13:57 +00008050 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
Chad Rosierfa30c9b2015-10-07 17:39:18 +00008051 break;
8052 }
8053
Silviu Barangafa00ba32016-08-08 13:13:57 +00008054 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
8055 return SDValue();
8056
8057 assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) &&
8058 "Illegal vector type after legalization");
8059
Chad Rosierfa30c9b2015-10-07 17:39:18 +00008060 SDLoc DL(N);
8061 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
8062 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
8063 : Intrinsic::aarch64_neon_vcvtfp2fxu;
8064 SDValue FixConv =
8065 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
8066 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
8067 Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
8068 // We can handle smaller integers by generating an extra trunc.
8069 if (IntBits < FloatBits)
8070 FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
8071
8072 return FixConv;
8073}
8074
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00008075/// Fold a floating-point divide by power of two into fixed-point to
8076/// floating-point conversion.
8077static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
Tim Northover85cf5642016-08-26 18:52:31 +00008078 TargetLowering::DAGCombinerInfo &DCI,
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00008079 const AArch64Subtarget *Subtarget) {
8080 if (!Subtarget->hasNEON())
8081 return SDValue();
8082
8083 SDValue Op = N->getOperand(0);
8084 unsigned Opc = Op->getOpcode();
Tim Northover85cf5642016-08-26 18:52:31 +00008085 if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
8086 !Op.getOperand(0).getValueType().isSimple() ||
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00008087 (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
8088 return SDValue();
8089
8090 SDValue ConstVec = N->getOperand(1);
8091 if (!isa<BuildVectorSDNode>(ConstVec))
8092 return SDValue();
8093
8094 MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
8095 int32_t IntBits = IntTy.getSizeInBits();
8096 if (IntBits != 16 && IntBits != 32 && IntBits != 64)
8097 return SDValue();
8098
8099 MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
8100 int32_t FloatBits = FloatTy.getSizeInBits();
8101 if (FloatBits != 32 && FloatBits != 64)
8102 return SDValue();
8103
8104 // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
8105 if (IntBits > FloatBits)
8106 return SDValue();
8107
8108 BitVector UndefElements;
8109 BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
8110 int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
8111 if (C == -1 || C == 0 || C > FloatBits)
8112 return SDValue();
8113
8114 MVT ResTy;
8115 unsigned NumLanes = Op.getValueType().getVectorNumElements();
8116 switch (NumLanes) {
8117 default:
8118 return SDValue();
8119 case 2:
8120 ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
8121 break;
8122 case 4:
Tim Northover85cf5642016-08-26 18:52:31 +00008123 ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00008124 break;
8125 }
8126
Tim Northover85cf5642016-08-26 18:52:31 +00008127 if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
8128 return SDValue();
8129
Chad Rosier7c6ac2b2015-10-07 17:51:37 +00008130 SDLoc DL(N);
8131 SDValue ConvInput = Op.getOperand(0);
8132 bool IsSigned = Opc == ISD::SINT_TO_FP;
8133 if (IntBits < FloatBits)
8134 ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
8135 ResTy, ConvInput);
8136
8137 unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
8138 : Intrinsic::aarch64_neon_vcvtfxu2fp;
8139 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
8140 DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
8141 DAG.getConstant(C, DL, MVT::i32));
8142}
8143
Tim Northover3b0846e2014-05-24 12:50:23 +00008144/// An EXTR instruction is made up of two shifts, ORed together. This helper
8145/// searches for and classifies those shifts.
8146static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
8147 bool &FromHi) {
8148 if (N.getOpcode() == ISD::SHL)
8149 FromHi = false;
8150 else if (N.getOpcode() == ISD::SRL)
8151 FromHi = true;
8152 else
8153 return false;
8154
8155 if (!isa<ConstantSDNode>(N.getOperand(1)))
8156 return false;
8157
8158 ShiftAmount = N->getConstantOperandVal(1);
8159 Src = N->getOperand(0);
8160 return true;
8161}
8162
8163/// EXTR instruction extracts a contiguous chunk of bits from two existing
8164/// registers viewed as a high/low pair. This function looks for the pattern:
8165/// (or (shl VAL1, #N), (srl VAL2, #RegWidth-N)) and replaces it with an
8166/// EXTR. Can't quite be done in TableGen because the two immediates aren't
8167/// independent.
8168static SDValue tryCombineToEXTR(SDNode *N,
8169 TargetLowering::DAGCombinerInfo &DCI) {
8170 SelectionDAG &DAG = DCI.DAG;
8171 SDLoc DL(N);
8172 EVT VT = N->getValueType(0);
8173
8174 assert(N->getOpcode() == ISD::OR && "Unexpected root");
8175
8176 if (VT != MVT::i32 && VT != MVT::i64)
8177 return SDValue();
8178
8179 SDValue LHS;
8180 uint32_t ShiftLHS = 0;
Eugene Zelenko049b0172017-01-06 00:30:53 +00008181 bool LHSFromHi = false;
Tim Northover3b0846e2014-05-24 12:50:23 +00008182 if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
8183 return SDValue();
8184
8185 SDValue RHS;
8186 uint32_t ShiftRHS = 0;
Eugene Zelenko049b0172017-01-06 00:30:53 +00008187 bool RHSFromHi = false;
Tim Northover3b0846e2014-05-24 12:50:23 +00008188 if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
8189 return SDValue();
8190
8191 // If they're both trying to come from the high part of the register, they're
8192 // not really an EXTR.
8193 if (LHSFromHi == RHSFromHi)
8194 return SDValue();
8195
8196 if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
8197 return SDValue();
8198
8199 if (LHSFromHi) {
8200 std::swap(LHS, RHS);
8201 std::swap(ShiftLHS, ShiftRHS);
8202 }
8203
8204 return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008205 DAG.getConstant(ShiftRHS, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008206}
8207
8208static SDValue tryCombineToBSL(SDNode *N,
8209 TargetLowering::DAGCombinerInfo &DCI) {
8210 EVT VT = N->getValueType(0);
8211 SelectionDAG &DAG = DCI.DAG;
8212 SDLoc DL(N);
8213
8214 if (!VT.isVector())
8215 return SDValue();
8216
8217 SDValue N0 = N->getOperand(0);
8218 if (N0.getOpcode() != ISD::AND)
8219 return SDValue();
8220
8221 SDValue N1 = N->getOperand(1);
8222 if (N1.getOpcode() != ISD::AND)
8223 return SDValue();
8224
8225 // We only have to look for constant vectors here since the general, variable
8226 // case can be handled in TableGen.
Sanjay Patel1ed771f2016-09-14 16:37:15 +00008227 unsigned Bits = VT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00008228 uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
8229 for (int i = 1; i >= 0; --i)
8230 for (int j = 1; j >= 0; --j) {
8231 BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
8232 BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
8233 if (!BVN0 || !BVN1)
8234 continue;
8235
8236 bool FoundMatch = true;
8237 for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
8238 ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
8239 ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
8240 if (!CN0 || !CN1 ||
8241 CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
8242 FoundMatch = false;
8243 break;
8244 }
8245 }
8246
8247 if (FoundMatch)
8248 return DAG.getNode(AArch64ISD::BSL, DL, VT, SDValue(BVN0, 0),
8249 N0->getOperand(1 - i), N1->getOperand(1 - j));
8250 }
8251
8252 return SDValue();
8253}
8254
8255static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
8256 const AArch64Subtarget *Subtarget) {
8257 // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
Tim Northover3b0846e2014-05-24 12:50:23 +00008258 SelectionDAG &DAG = DCI.DAG;
8259 EVT VT = N->getValueType(0);
8260
8261 if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
8262 return SDValue();
8263
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00008264 if (SDValue Res = tryCombineToEXTR(N, DCI))
Tim Northover3b0846e2014-05-24 12:50:23 +00008265 return Res;
8266
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +00008267 if (SDValue Res = tryCombineToBSL(N, DCI))
Tim Northover3b0846e2014-05-24 12:50:23 +00008268 return Res;
8269
8270 return SDValue();
8271}
8272
Chad Rosier14aa2ad2016-05-26 19:41:33 +00008273static SDValue performSRLCombine(SDNode *N,
8274 TargetLowering::DAGCombinerInfo &DCI) {
8275 SelectionDAG &DAG = DCI.DAG;
8276 EVT VT = N->getValueType(0);
8277 if (VT != MVT::i32 && VT != MVT::i64)
8278 return SDValue();
8279
8280 // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the
8281 // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32)
8282 // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero.
8283 SDValue N0 = N->getOperand(0);
8284 if (N0.getOpcode() == ISD::BSWAP) {
8285 SDLoc DL(N);
8286 SDValue N1 = N->getOperand(1);
8287 SDValue N00 = N0.getOperand(0);
8288 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
8289 uint64_t ShiftAmt = C->getZExtValue();
8290 if (VT == MVT::i32 && ShiftAmt == 16 &&
8291 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16)))
8292 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
8293 if (VT == MVT::i64 && ShiftAmt == 32 &&
8294 DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32)))
8295 return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
8296 }
8297 }
8298 return SDValue();
8299}
8300
Tim Northover3b0846e2014-05-24 12:50:23 +00008301static SDValue performBitcastCombine(SDNode *N,
8302 TargetLowering::DAGCombinerInfo &DCI,
8303 SelectionDAG &DAG) {
8304 // Wait 'til after everything is legalized to try this. That way we have
8305 // legal vector types and such.
8306 if (DCI.isBeforeLegalizeOps())
8307 return SDValue();
8308
8309 // Remove extraneous bitcasts around an extract_subvector.
8310 // For example,
8311 // (v4i16 (bitconvert
8312 // (extract_subvector (v2i64 (bitconvert (v8i16 ...)), (i64 1)))))
8313 // becomes
8314 // (extract_subvector ((v8i16 ...), (i64 4)))
8315
8316 // Only interested in 64-bit vectors as the ultimate result.
8317 EVT VT = N->getValueType(0);
8318 if (!VT.isVector())
8319 return SDValue();
8320 if (VT.getSimpleVT().getSizeInBits() != 64)
8321 return SDValue();
8322 // Is the operand an extract_subvector starting at the beginning or halfway
8323 // point of the vector? A low half may also come through as an
8324 // EXTRACT_SUBREG, so look for that, too.
8325 SDValue Op0 = N->getOperand(0);
8326 if (Op0->getOpcode() != ISD::EXTRACT_SUBVECTOR &&
8327 !(Op0->isMachineOpcode() &&
8328 Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG))
8329 return SDValue();
8330 uint64_t idx = cast<ConstantSDNode>(Op0->getOperand(1))->getZExtValue();
8331 if (Op0->getOpcode() == ISD::EXTRACT_SUBVECTOR) {
8332 if (Op0->getValueType(0).getVectorNumElements() != idx && idx != 0)
8333 return SDValue();
8334 } else if (Op0->getMachineOpcode() == AArch64::EXTRACT_SUBREG) {
8335 if (idx != AArch64::dsub)
8336 return SDValue();
8337 // The dsub reference is equivalent to a lane zero subvector reference.
8338 idx = 0;
8339 }
8340 // Look through the bitcast of the input to the extract.
8341 if (Op0->getOperand(0)->getOpcode() != ISD::BITCAST)
8342 return SDValue();
8343 SDValue Source = Op0->getOperand(0)->getOperand(0);
8344 // If the source type has twice the number of elements as our destination
8345 // type, we know this is an extract of the high or low half of the vector.
8346 EVT SVT = Source->getValueType(0);
8347 if (SVT.getVectorNumElements() != VT.getVectorNumElements() * 2)
8348 return SDValue();
8349
8350 DEBUG(dbgs() << "aarch64-lower: bitcast extract_subvector simplification\n");
8351
8352 // Create the simplified form to just extract the low or high half of the
8353 // vector directly rather than bothering with the bitcasts.
8354 SDLoc dl(N);
8355 unsigned NumElements = VT.getVectorNumElements();
8356 if (idx) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008357 SDValue HalfIdx = DAG.getConstant(NumElements, dl, MVT::i64);
Tim Northover3b0846e2014-05-24 12:50:23 +00008358 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, Source, HalfIdx);
8359 } else {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008360 SDValue SubReg = DAG.getTargetConstant(AArch64::dsub, dl, MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00008361 return SDValue(DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, VT,
8362 Source, SubReg),
8363 0);
8364 }
8365}
8366
8367static SDValue performConcatVectorsCombine(SDNode *N,
8368 TargetLowering::DAGCombinerInfo &DCI,
8369 SelectionDAG &DAG) {
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00008370 SDLoc dl(N);
8371 EVT VT = N->getValueType(0);
8372 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
8373
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00008374 // Optimize concat_vectors of truncated vectors, where the intermediate
8375 // type is illegal, to avoid said illegality, e.g.,
8376 // (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
8377 // (v2i16 (truncate (v2i64)))))
8378 // ->
Ahmed Bougachae6bb09a2015-03-21 01:08:39 +00008379 // (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
8380 // (v4i32 (bitcast (v2i64))),
8381 // <0, 2, 4, 6>)))
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00008382 // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
8383 // on both input and result type, so we might generate worse code.
8384 // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
8385 if (N->getNumOperands() == 2 &&
8386 N0->getOpcode() == ISD::TRUNCATE &&
8387 N1->getOpcode() == ISD::TRUNCATE) {
8388 SDValue N00 = N0->getOperand(0);
8389 SDValue N10 = N1->getOperand(0);
8390 EVT N00VT = N00.getValueType();
8391
8392 if (N00VT == N10.getValueType() &&
8393 (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
8394 N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
Ahmed Bougachae6bb09a2015-03-21 01:08:39 +00008395 MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
8396 SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
8397 for (size_t i = 0; i < Mask.size(); ++i)
8398 Mask[i] = i * 2;
8399 return DAG.getNode(ISD::TRUNCATE, dl, VT,
8400 DAG.getVectorShuffle(
8401 MidVT, dl,
8402 DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
8403 DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
Ahmed Bougachae0afb1f2015-03-17 03:23:09 +00008404 }
8405 }
8406
Tim Northover3b0846e2014-05-24 12:50:23 +00008407 // Wait 'til after everything is legalized to try this. That way we have
8408 // legal vector types and such.
8409 if (DCI.isBeforeLegalizeOps())
8410 return SDValue();
8411
Tim Northover3b0846e2014-05-24 12:50:23 +00008412 // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
8413 // splat. The indexed instructions are going to be expecting a DUPLANE64, so
8414 // canonicalise to that.
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00008415 if (N0 == N1 && VT.getVectorNumElements() == 2) {
Sanjay Patel1ed771f2016-09-14 16:37:15 +00008416 assert(VT.getScalarSizeInBits() == 64);
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00008417 return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008418 DAG.getConstant(0, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008419 }
8420
8421 // Canonicalise concat_vectors so that the right-hand vector has as few
8422 // bit-casts as possible before its real operation. The primary matching
8423 // destination for these operations will be the narrowing "2" instructions,
8424 // which depend on the operation being performed on this right-hand vector.
8425 // For example,
8426 // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS))))
8427 // becomes
8428 // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
8429
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00008430 if (N1->getOpcode() != ISD::BITCAST)
Tim Northover3b0846e2014-05-24 12:50:23 +00008431 return SDValue();
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00008432 SDValue RHS = N1->getOperand(0);
Tim Northover3b0846e2014-05-24 12:50:23 +00008433 MVT RHSTy = RHS.getValueType().getSimpleVT();
8434 // If the RHS is not a vector, this is not the pattern we're looking for.
8435 if (!RHSTy.isVector())
8436 return SDValue();
8437
8438 DEBUG(dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
8439
8440 MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
8441 RHSTy.getVectorNumElements() * 2);
Ahmed Bougachae33e6c92015-03-17 03:19:18 +00008442 return DAG.getNode(ISD::BITCAST, dl, VT,
8443 DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
8444 DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
8445 RHS));
Tim Northover3b0846e2014-05-24 12:50:23 +00008446}
8447
8448static SDValue tryCombineFixedPointConvert(SDNode *N,
8449 TargetLowering::DAGCombinerInfo &DCI,
8450 SelectionDAG &DAG) {
8451 // Wait 'til after everything is legalized to try this. That way we have
8452 // legal vector types and such.
8453 if (DCI.isBeforeLegalizeOps())
8454 return SDValue();
8455 // Transform a scalar conversion of a value from a lane extract into a
8456 // lane extract of a vector conversion. E.g., from foo1 to foo2:
8457 // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
8458 // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
8459 //
8460 // The second form interacts better with instruction selection and the
8461 // register allocator to avoid cross-class register copies that aren't
8462 // coalescable due to a lane reference.
8463
8464 // Check the operand and see if it originates from a lane extract.
8465 SDValue Op1 = N->getOperand(1);
8466 if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
8467 // Yep, no additional predication needed. Perform the transform.
8468 SDValue IID = N->getOperand(0);
8469 SDValue Shift = N->getOperand(2);
8470 SDValue Vec = Op1.getOperand(0);
8471 SDValue Lane = Op1.getOperand(1);
8472 EVT ResTy = N->getValueType(0);
8473 EVT VecResTy;
8474 SDLoc DL(N);
8475
8476 // The vector width should be 128 bits by the time we get here, even
8477 // if it started as 64 bits (the extract_vector handling will have
8478 // done so).
Sanjay Patelb1f0a0f2016-09-14 16:05:51 +00008479 assert(Vec.getValueSizeInBits() == 128 &&
Tim Northover3b0846e2014-05-24 12:50:23 +00008480 "unexpected vector size on extract_vector_elt!");
8481 if (Vec.getValueType() == MVT::v4i32)
8482 VecResTy = MVT::v4f32;
8483 else if (Vec.getValueType() == MVT::v2i64)
8484 VecResTy = MVT::v2f64;
8485 else
Craig Topper2a30d782014-06-18 05:05:13 +00008486 llvm_unreachable("unexpected vector type!");
Tim Northover3b0846e2014-05-24 12:50:23 +00008487
8488 SDValue Convert =
8489 DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
8490 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
8491 }
8492 return SDValue();
8493}
8494
8495// AArch64 high-vector "long" operations are formed by performing the non-high
8496// version on an extract_subvector of each operand which gets the high half:
8497//
8498// (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
8499//
8500// However, there are cases which don't have an extract_high explicitly, but
8501// have another operation that can be made compatible with one for free. For
8502// example:
8503//
8504// (dupv64 scalar) --> (extract_high (dup128 scalar))
8505//
8506// This routine does the actual conversion of such DUPs, once outer routines
8507// have determined that everything else is in order.
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008508// It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
8509// similarly here.
Tim Northover3b0846e2014-05-24 12:50:23 +00008510static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
Tim Northover3b0846e2014-05-24 12:50:23 +00008511 switch (N.getOpcode()) {
8512 case AArch64ISD::DUP:
Tim Northover3b0846e2014-05-24 12:50:23 +00008513 case AArch64ISD::DUPLANE8:
8514 case AArch64ISD::DUPLANE16:
8515 case AArch64ISD::DUPLANE32:
8516 case AArch64ISD::DUPLANE64:
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008517 case AArch64ISD::MOVI:
8518 case AArch64ISD::MOVIshift:
8519 case AArch64ISD::MOVIedit:
8520 case AArch64ISD::MOVImsl:
8521 case AArch64ISD::MVNIshift:
8522 case AArch64ISD::MVNImsl:
Tim Northover3b0846e2014-05-24 12:50:23 +00008523 break;
8524 default:
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008525 // FMOV could be supported, but isn't very useful, as it would only occur
8526 // if you passed a bitcast' floating point immediate to an eligible long
8527 // integer op (addl, smull, ...).
Tim Northover3b0846e2014-05-24 12:50:23 +00008528 return SDValue();
8529 }
8530
8531 MVT NarrowTy = N.getSimpleValueType();
8532 if (!NarrowTy.is64BitVector())
8533 return SDValue();
8534
8535 MVT ElementTy = NarrowTy.getVectorElementType();
8536 unsigned NumElems = NarrowTy.getVectorNumElements();
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008537 MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
Tim Northover3b0846e2014-05-24 12:50:23 +00008538
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008539 SDLoc dl(N);
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +00008540 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
8541 DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008542 DAG.getConstant(NumElems, dl, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00008543}
8544
8545static bool isEssentiallyExtractSubvector(SDValue N) {
8546 if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
8547 return true;
8548
8549 return N.getOpcode() == ISD::BITCAST &&
8550 N.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR;
8551}
8552
8553/// \brief Helper structure to keep track of ISD::SET_CC operands.
8554struct GenericSetCCInfo {
8555 const SDValue *Opnd0;
8556 const SDValue *Opnd1;
8557 ISD::CondCode CC;
8558};
8559
8560/// \brief Helper structure to keep track of a SET_CC lowered into AArch64 code.
8561struct AArch64SetCCInfo {
8562 const SDValue *Cmp;
8563 AArch64CC::CondCode CC;
8564};
8565
8566/// \brief Helper structure to keep track of SetCC information.
8567union SetCCInfo {
8568 GenericSetCCInfo Generic;
8569 AArch64SetCCInfo AArch64;
8570};
8571
8572/// \brief Helper structure to be able to read SetCC information. If set to
8573/// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
8574/// GenericSetCCInfo.
8575struct SetCCInfoAndKind {
8576 SetCCInfo Info;
8577 bool IsAArch64;
8578};
8579
8580/// \brief Check whether or not \p Op is a SET_CC operation, either a generic or
8581/// an
8582/// AArch64 lowered one.
8583/// \p SetCCInfo is filled accordingly.
8584/// \post SetCCInfo is meanginfull only when this function returns true.
8585/// \return True when Op is a kind of SET_CC operation.
8586static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
8587 // If this is a setcc, this is straight forward.
8588 if (Op.getOpcode() == ISD::SETCC) {
8589 SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
8590 SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
8591 SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
8592 SetCCInfo.IsAArch64 = false;
8593 return true;
8594 }
8595 // Otherwise, check if this is a matching csel instruction.
8596 // In other words:
8597 // - csel 1, 0, cc
8598 // - csel 0, 1, !cc
8599 if (Op.getOpcode() != AArch64ISD::CSEL)
8600 return false;
8601 // Set the information about the operands.
8602 // TODO: we want the operands of the Cmp not the csel
8603 SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
8604 SetCCInfo.IsAArch64 = true;
8605 SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
8606 cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
8607
8608 // Check that the operands matches the constraints:
8609 // (1) Both operands must be constants.
8610 // (2) One must be 1 and the other must be 0.
8611 ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
8612 ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
8613
8614 // Check (1).
8615 if (!TValue || !FValue)
8616 return false;
8617
8618 // Check (2).
8619 if (!TValue->isOne()) {
8620 // Update the comparison when we are interested in !cc.
8621 std::swap(TValue, FValue);
8622 SetCCInfo.Info.AArch64.CC =
8623 AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
8624 }
8625 return TValue->isOne() && FValue->isNullValue();
8626}
8627
8628// Returns true if Op is setcc or zext of setcc.
8629static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
8630 if (isSetCC(Op, Info))
8631 return true;
8632 return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
8633 isSetCC(Op->getOperand(0), Info));
8634}
8635
8636// The folding we want to perform is:
8637// (add x, [zext] (setcc cc ...) )
8638// -->
8639// (csel x, (add x, 1), !cc ...)
8640//
8641// The latter will get matched to a CSINC instruction.
8642static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
8643 assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
8644 SDValue LHS = Op->getOperand(0);
8645 SDValue RHS = Op->getOperand(1);
8646 SetCCInfoAndKind InfoAndKind;
8647
8648 // If neither operand is a SET_CC, give up.
8649 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
8650 std::swap(LHS, RHS);
8651 if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
8652 return SDValue();
8653 }
8654
8655 // FIXME: This could be generatized to work for FP comparisons.
8656 EVT CmpVT = InfoAndKind.IsAArch64
8657 ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
8658 : InfoAndKind.Info.Generic.Opnd0->getValueType();
8659 if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
8660 return SDValue();
8661
8662 SDValue CCVal;
8663 SDValue Cmp;
8664 SDLoc dl(Op);
8665 if (InfoAndKind.IsAArch64) {
8666 CCVal = DAG.getConstant(
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008667 AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
8668 MVT::i32);
Tim Northover3b0846e2014-05-24 12:50:23 +00008669 Cmp = *InfoAndKind.Info.AArch64.Cmp;
8670 } else
8671 Cmp = getAArch64Cmp(*InfoAndKind.Info.Generic.Opnd0,
8672 *InfoAndKind.Info.Generic.Opnd1,
8673 ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, true),
8674 CCVal, DAG, dl);
8675
8676 EVT VT = Op->getValueType(0);
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008677 LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
Tim Northover3b0846e2014-05-24 12:50:23 +00008678 return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
8679}
8680
8681// The basic add/sub long vector instructions have variants with "2" on the end
8682// which act on the high-half of their inputs. They are normally matched by
8683// patterns like:
8684//
8685// (add (zeroext (extract_high LHS)),
8686// (zeroext (extract_high RHS)))
8687// -> uaddl2 vD, vN, vM
8688//
8689// However, if one of the extracts is something like a duplicate, this
8690// instruction can still be used profitably. This function puts the DAG into a
8691// more appropriate form for those patterns to trigger.
8692static SDValue performAddSubLongCombine(SDNode *N,
8693 TargetLowering::DAGCombinerInfo &DCI,
8694 SelectionDAG &DAG) {
8695 if (DCI.isBeforeLegalizeOps())
8696 return SDValue();
8697
8698 MVT VT = N->getSimpleValueType(0);
8699 if (!VT.is128BitVector()) {
8700 if (N->getOpcode() == ISD::ADD)
8701 return performSetccAddFolding(N, DAG);
8702 return SDValue();
8703 }
8704
8705 // Make sure both branches are extended in the same way.
8706 SDValue LHS = N->getOperand(0);
8707 SDValue RHS = N->getOperand(1);
8708 if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
8709 LHS.getOpcode() != ISD::SIGN_EXTEND) ||
8710 LHS.getOpcode() != RHS.getOpcode())
8711 return SDValue();
8712
8713 unsigned ExtType = LHS.getOpcode();
8714
8715 // It's not worth doing if at least one of the inputs isn't already an
8716 // extract, but we don't know which it'll be so we have to try both.
8717 if (isEssentiallyExtractSubvector(LHS.getOperand(0))) {
8718 RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
8719 if (!RHS.getNode())
8720 return SDValue();
8721
8722 RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
8723 } else if (isEssentiallyExtractSubvector(RHS.getOperand(0))) {
8724 LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
8725 if (!LHS.getNode())
8726 return SDValue();
8727
8728 LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
8729 }
8730
8731 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
8732}
8733
8734// Massage DAGs which we can use the high-half "long" operations on into
8735// something isel will recognize better. E.g.
8736//
8737// (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
8738// (aarch64_neon_umull (extract_high (v2i64 vec)))
8739// (extract_high (v2i64 (dup128 scalar)))))
8740//
Hal Finkelcd8664c2015-12-11 23:11:52 +00008741static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
Tim Northover3b0846e2014-05-24 12:50:23 +00008742 TargetLowering::DAGCombinerInfo &DCI,
8743 SelectionDAG &DAG) {
8744 if (DCI.isBeforeLegalizeOps())
8745 return SDValue();
8746
Hal Finkelcd8664c2015-12-11 23:11:52 +00008747 SDValue LHS = N->getOperand(1);
8748 SDValue RHS = N->getOperand(2);
Tim Northover3b0846e2014-05-24 12:50:23 +00008749 assert(LHS.getValueType().is64BitVector() &&
8750 RHS.getValueType().is64BitVector() &&
8751 "unexpected shape for long operation");
8752
8753 // Either node could be a DUP, but it's not worth doing both of them (you'd
8754 // just as well use the non-high version) so look for a corresponding extract
8755 // operation on the other "wing".
8756 if (isEssentiallyExtractSubvector(LHS)) {
8757 RHS = tryExtendDUPToExtractHigh(RHS, DAG);
8758 if (!RHS.getNode())
8759 return SDValue();
8760 } else if (isEssentiallyExtractSubvector(RHS)) {
8761 LHS = tryExtendDUPToExtractHigh(LHS, DAG);
8762 if (!LHS.getNode())
8763 return SDValue();
8764 }
8765
Hal Finkelcd8664c2015-12-11 23:11:52 +00008766 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
8767 N->getOperand(0), LHS, RHS);
Tim Northover3b0846e2014-05-24 12:50:23 +00008768}
8769
8770static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
8771 MVT ElemTy = N->getSimpleValueType(0).getScalarType();
8772 unsigned ElemBits = ElemTy.getSizeInBits();
8773
8774 int64_t ShiftAmount;
8775 if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
8776 APInt SplatValue, SplatUndef;
8777 unsigned SplatBitSize;
8778 bool HasAnyUndefs;
8779 if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
8780 HasAnyUndefs, ElemBits) ||
8781 SplatBitSize != ElemBits)
8782 return SDValue();
8783
8784 ShiftAmount = SplatValue.getSExtValue();
8785 } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
8786 ShiftAmount = CVN->getSExtValue();
8787 } else
8788 return SDValue();
8789
8790 unsigned Opcode;
8791 bool IsRightShift;
8792 switch (IID) {
8793 default:
8794 llvm_unreachable("Unknown shift intrinsic");
8795 case Intrinsic::aarch64_neon_sqshl:
8796 Opcode = AArch64ISD::SQSHL_I;
8797 IsRightShift = false;
8798 break;
8799 case Intrinsic::aarch64_neon_uqshl:
8800 Opcode = AArch64ISD::UQSHL_I;
8801 IsRightShift = false;
8802 break;
8803 case Intrinsic::aarch64_neon_srshl:
8804 Opcode = AArch64ISD::SRSHR_I;
8805 IsRightShift = true;
8806 break;
8807 case Intrinsic::aarch64_neon_urshl:
8808 Opcode = AArch64ISD::URSHR_I;
8809 IsRightShift = true;
8810 break;
8811 case Intrinsic::aarch64_neon_sqshlu:
8812 Opcode = AArch64ISD::SQSHLU_I;
8813 IsRightShift = false;
8814 break;
8815 }
8816
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008817 if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
8818 SDLoc dl(N);
8819 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8820 DAG.getConstant(-ShiftAmount, dl, MVT::i32));
8821 } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
8822 SDLoc dl(N);
8823 return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
8824 DAG.getConstant(ShiftAmount, dl, MVT::i32));
8825 }
Tim Northover3b0846e2014-05-24 12:50:23 +00008826
8827 return SDValue();
8828}
8829
8830// The CRC32[BH] instructions ignore the high bits of their data operand. Since
8831// the intrinsics must be legal and take an i32, this means there's almost
8832// certainly going to be a zext in the DAG which we can eliminate.
8833static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
8834 SDValue AndN = N->getOperand(2);
8835 if (AndN.getOpcode() != ISD::AND)
8836 return SDValue();
8837
8838 ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
8839 if (!CMask || CMask->getZExtValue() != Mask)
8840 return SDValue();
8841
8842 return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
8843 N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
8844}
8845
Ahmed Bougachafab58922015-03-10 20:45:38 +00008846static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
8847 SelectionDAG &DAG) {
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008848 SDLoc dl(N);
8849 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
8850 DAG.getNode(Opc, dl,
Ahmed Bougachafab58922015-03-10 20:45:38 +00008851 N->getOperand(1).getSimpleValueType(),
8852 N->getOperand(1)),
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008853 DAG.getConstant(0, dl, MVT::i64));
Ahmed Bougachafab58922015-03-10 20:45:38 +00008854}
8855
Tim Northover3b0846e2014-05-24 12:50:23 +00008856static SDValue performIntrinsicCombine(SDNode *N,
8857 TargetLowering::DAGCombinerInfo &DCI,
8858 const AArch64Subtarget *Subtarget) {
8859 SelectionDAG &DAG = DCI.DAG;
8860 unsigned IID = getIntrinsicID(N);
8861 switch (IID) {
8862 default:
8863 break;
8864 case Intrinsic::aarch64_neon_vcvtfxs2fp:
8865 case Intrinsic::aarch64_neon_vcvtfxu2fp:
8866 return tryCombineFixedPointConvert(N, DCI, DAG);
Ahmed Bougachafab58922015-03-10 20:45:38 +00008867 case Intrinsic::aarch64_neon_saddv:
8868 return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
8869 case Intrinsic::aarch64_neon_uaddv:
8870 return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
8871 case Intrinsic::aarch64_neon_sminv:
8872 return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
8873 case Intrinsic::aarch64_neon_uminv:
8874 return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
8875 case Intrinsic::aarch64_neon_smaxv:
8876 return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
8877 case Intrinsic::aarch64_neon_umaxv:
8878 return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00008879 case Intrinsic::aarch64_neon_fmax:
James Molloyedf38f02015-08-11 12:06:33 +00008880 return DAG.getNode(ISD::FMAXNAN, SDLoc(N), N->getValueType(0),
Tim Northover3b0846e2014-05-24 12:50:23 +00008881 N->getOperand(1), N->getOperand(2));
8882 case Intrinsic::aarch64_neon_fmin:
James Molloyedf38f02015-08-11 12:06:33 +00008883 return DAG.getNode(ISD::FMINNAN, SDLoc(N), N->getValueType(0),
Tim Northover3b0846e2014-05-24 12:50:23 +00008884 N->getOperand(1), N->getOperand(2));
James Molloyb7b2a1e2015-08-11 12:06:37 +00008885 case Intrinsic::aarch64_neon_fmaxnm:
8886 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
8887 N->getOperand(1), N->getOperand(2));
8888 case Intrinsic::aarch64_neon_fminnm:
8889 return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
8890 N->getOperand(1), N->getOperand(2));
Tim Northover3b0846e2014-05-24 12:50:23 +00008891 case Intrinsic::aarch64_neon_smull:
8892 case Intrinsic::aarch64_neon_umull:
8893 case Intrinsic::aarch64_neon_pmull:
8894 case Intrinsic::aarch64_neon_sqdmull:
Hal Finkelcd8664c2015-12-11 23:11:52 +00008895 return tryCombineLongOpWithDup(IID, N, DCI, DAG);
Tim Northover3b0846e2014-05-24 12:50:23 +00008896 case Intrinsic::aarch64_neon_sqshl:
8897 case Intrinsic::aarch64_neon_uqshl:
8898 case Intrinsic::aarch64_neon_sqshlu:
8899 case Intrinsic::aarch64_neon_srshl:
8900 case Intrinsic::aarch64_neon_urshl:
8901 return tryCombineShiftImm(IID, N, DAG);
8902 case Intrinsic::aarch64_crc32b:
8903 case Intrinsic::aarch64_crc32cb:
8904 return tryCombineCRC32(0xff, N, DAG);
8905 case Intrinsic::aarch64_crc32h:
8906 case Intrinsic::aarch64_crc32ch:
8907 return tryCombineCRC32(0xffff, N, DAG);
8908 }
8909 return SDValue();
8910}
8911
8912static SDValue performExtendCombine(SDNode *N,
8913 TargetLowering::DAGCombinerInfo &DCI,
8914 SelectionDAG &DAG) {
8915 // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
8916 // we can convert that DUP into another extract_high (of a bigger DUP), which
8917 // helps the backend to decide that an sabdl2 would be useful, saving a real
8918 // extract_high operation.
8919 if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
Hal Finkelcd8664c2015-12-11 23:11:52 +00008920 N->getOperand(0).getOpcode() == ISD::INTRINSIC_WO_CHAIN) {
Tim Northover3b0846e2014-05-24 12:50:23 +00008921 SDNode *ABDNode = N->getOperand(0).getNode();
Hal Finkelcd8664c2015-12-11 23:11:52 +00008922 unsigned IID = getIntrinsicID(ABDNode);
8923 if (IID == Intrinsic::aarch64_neon_sabd ||
8924 IID == Intrinsic::aarch64_neon_uabd) {
8925 SDValue NewABD = tryCombineLongOpWithDup(IID, ABDNode, DCI, DAG);
8926 if (!NewABD.getNode())
8927 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00008928
Hal Finkelcd8664c2015-12-11 23:11:52 +00008929 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0),
8930 NewABD);
8931 }
Tim Northover3b0846e2014-05-24 12:50:23 +00008932 }
8933
8934 // This is effectively a custom type legalization for AArch64.
8935 //
8936 // Type legalization will split an extend of a small, legal, type to a larger
8937 // illegal type by first splitting the destination type, often creating
8938 // illegal source types, which then get legalized in isel-confusing ways,
8939 // leading to really terrible codegen. E.g.,
8940 // %result = v8i32 sext v8i8 %value
8941 // becomes
8942 // %losrc = extract_subreg %value, ...
8943 // %hisrc = extract_subreg %value, ...
8944 // %lo = v4i32 sext v4i8 %losrc
8945 // %hi = v4i32 sext v4i8 %hisrc
8946 // Things go rapidly downhill from there.
8947 //
8948 // For AArch64, the [sz]ext vector instructions can only go up one element
8949 // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
8950 // take two instructions.
8951 //
8952 // This implies that the most efficient way to do the extend from v8i8
8953 // to two v4i32 values is to first extend the v8i8 to v8i16, then do
8954 // the normal splitting to happen for the v8i16->v8i32.
8955
8956 // This is pre-legalization to catch some cases where the default
8957 // type legalization will create ill-tempered code.
8958 if (!DCI.isBeforeLegalizeOps())
8959 return SDValue();
8960
8961 // We're only interested in cleaning things up for non-legal vector types
8962 // here. If both the source and destination are legal, things will just
8963 // work naturally without any fiddling.
Matthew Simpson13dddb02015-12-17 21:29:47 +00008964 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +00008965 EVT ResVT = N->getValueType(0);
8966 if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
8967 return SDValue();
8968 // If the vector type isn't a simple VT, it's beyond the scope of what
8969 // we're worried about here. Let legalization do its thing and hope for
8970 // the best.
Jim Grosbachec2b0d02014-08-28 22:08:28 +00008971 SDValue Src = N->getOperand(0);
8972 EVT SrcVT = Src->getValueType(0);
8973 if (!ResVT.isSimple() || !SrcVT.isSimple())
Tim Northover3b0846e2014-05-24 12:50:23 +00008974 return SDValue();
8975
Tim Northover3b0846e2014-05-24 12:50:23 +00008976 // If the source VT is a 64-bit vector, we can play games and get the
8977 // better results we want.
8978 if (SrcVT.getSizeInBits() != 64)
8979 return SDValue();
8980
Sanjay Patel1ed771f2016-09-14 16:37:15 +00008981 unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
Tim Northover3b0846e2014-05-24 12:50:23 +00008982 unsigned ElementCount = SrcVT.getVectorNumElements();
8983 SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), ElementCount);
8984 SDLoc DL(N);
8985 Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
8986
8987 // Now split the rest of the operation into two halves, each with a 64
8988 // bit source.
8989 EVT LoVT, HiVT;
8990 SDValue Lo, Hi;
8991 unsigned NumElements = ResVT.getVectorNumElements();
8992 assert(!(NumElements & 1) && "Splitting vector, but not in half!");
8993 LoVT = HiVT = EVT::getVectorVT(*DAG.getContext(),
8994 ResVT.getVectorElementType(), NumElements / 2);
8995
8996 EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
8997 LoVT.getVectorNumElements());
8998 Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00008999 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00009000 Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009001 DAG.getConstant(InNVT.getVectorNumElements(), DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00009002 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
9003 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
9004
9005 // Now combine the parts back together so we still have a single result
9006 // like the combiner expects.
9007 return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
9008}
9009
Geoff Berry8301c642016-11-16 19:35:19 +00009010static SDValue splitStoreSplat(SelectionDAG &DAG, StoreSDNode &St,
9011 SDValue SplatVal, unsigned NumVecElts) {
Geoff Berrye8de67ab2016-11-14 19:59:11 +00009012 unsigned OrigAlignment = St.getAlignment();
Geoff Berry8301c642016-11-16 19:35:19 +00009013 unsigned EltOffset = SplatVal.getValueType().getSizeInBits() / 8;
Geoff Berrydef4bfa2016-11-14 19:39:00 +00009014
9015 // Create scalar stores. This is at least as good as the code sequence for a
9016 // split unaligned store which is a dup.s, ext.b, and two stores.
9017 // Most of the time the three stores should be replaced by store pair
9018 // instructions (stp).
Geoff Berrye8de67ab2016-11-14 19:59:11 +00009019 SDLoc DL(&St);
9020 SDValue BasePtr = St.getBasePtr();
John Brawn3a9c8422017-02-06 18:07:20 +00009021 const MachinePointerInfo &PtrInfo = St.getPointerInfo();
Geoff Berrydef4bfa2016-11-14 19:39:00 +00009022 SDValue NewST1 =
John Brawn3a9c8422017-02-06 18:07:20 +00009023 DAG.getStore(St.getChain(), DL, SplatVal, BasePtr, PtrInfo,
Geoff Berry8301c642016-11-16 19:35:19 +00009024 OrigAlignment, St.getMemOperand()->getFlags());
Geoff Berrydef4bfa2016-11-14 19:39:00 +00009025
9026 unsigned Offset = EltOffset;
9027 while (--NumVecElts) {
Geoff Berry8301c642016-11-16 19:35:19 +00009028 unsigned Alignment = MinAlign(OrigAlignment, Offset);
Geoff Berrydef4bfa2016-11-14 19:39:00 +00009029 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
9030 DAG.getConstant(Offset, DL, MVT::i64));
9031 NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
John Brawn3a9c8422017-02-06 18:07:20 +00009032 PtrInfo.getWithOffset(Offset), Alignment,
Geoff Berrye8de67ab2016-11-14 19:59:11 +00009033 St.getMemOperand()->getFlags());
Geoff Berrydef4bfa2016-11-14 19:39:00 +00009034 Offset += EltOffset;
9035 }
9036 return NewST1;
9037}
9038
Geoff Berry526c5052016-11-14 19:39:04 +00009039/// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR. The
9040/// load store optimizer pass will merge them to store pair stores. This should
9041/// be better than a movi to create the vector zero followed by a vector store
9042/// if the zero constant is not re-used, since one instructions and one register
9043/// live range will be removed.
9044///
9045/// For example, the final generated code should be:
9046///
9047/// stp xzr, xzr, [x0]
9048///
9049/// instead of:
9050///
9051/// movi v0.2d, #0
9052/// str q0, [x0]
9053///
Geoff Berrye8de67ab2016-11-14 19:59:11 +00009054static SDValue replaceZeroVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
9055 SDValue StVal = St.getValue();
Geoff Berry526c5052016-11-14 19:39:04 +00009056 EVT VT = StVal.getValueType();
9057
Geoff Berry8301c642016-11-16 19:35:19 +00009058 // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or
9059 // 2, 3 or 4 i32 elements.
Geoff Berry526c5052016-11-14 19:39:04 +00009060 int NumVecElts = VT.getVectorNumElements();
Geoff Berry8301c642016-11-16 19:35:19 +00009061 if (!(((NumVecElts == 2 || NumVecElts == 3) &&
9062 VT.getVectorElementType().getSizeInBits() == 64) ||
9063 ((NumVecElts == 2 || NumVecElts == 3 || NumVecElts == 4) &&
9064 VT.getVectorElementType().getSizeInBits() == 32)))
Geoff Berry526c5052016-11-14 19:39:04 +00009065 return SDValue();
9066
9067 if (StVal.getOpcode() != ISD::BUILD_VECTOR)
9068 return SDValue();
9069
9070 // If the zero constant has more than one use then the vector store could be
9071 // better since the constant mov will be amortized and stp q instructions
9072 // should be able to be formed.
9073 if (!StVal.hasOneUse())
9074 return SDValue();
9075
9076 // If the immediate offset of the address operand is too large for the stp
9077 // instruction, then bail out.
Geoff Berrye8de67ab2016-11-14 19:59:11 +00009078 if (DAG.isBaseWithConstantOffset(St.getBasePtr())) {
9079 int64_t Offset = St.getBasePtr()->getConstantOperandVal(1);
Geoff Berry526c5052016-11-14 19:39:04 +00009080 if (Offset < -512 || Offset > 504)
9081 return SDValue();
9082 }
9083
9084 for (int I = 0; I < NumVecElts; ++I) {
9085 SDValue EltVal = StVal.getOperand(I);
Geoff Berry8301c642016-11-16 19:35:19 +00009086 if (!isNullConstant(EltVal) && !isNullFPConstant(EltVal))
Geoff Berry526c5052016-11-14 19:39:04 +00009087 return SDValue();
9088 }
Geoff Berry8301c642016-11-16 19:35:19 +00009089
Geoff Berry526c5052016-11-14 19:39:04 +00009090 // Use WZR/XZR here to prevent DAGCombiner::MergeConsecutiveStores from
9091 // undoing this transformation.
Geoff Berry8301c642016-11-16 19:35:19 +00009092 SDValue SplatVal = VT.getVectorElementType().getSizeInBits() == 32
9093 ? DAG.getRegister(AArch64::WZR, MVT::i32)
9094 : DAG.getRegister(AArch64::XZR, MVT::i64);
9095 return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
Geoff Berry526c5052016-11-14 19:39:04 +00009096}
9097
Tim Northover3b0846e2014-05-24 12:50:23 +00009098/// Replace a splat of a scalar to a vector store by scalar stores of the scalar
9099/// value. The load store optimizer pass will merge them to store pair stores.
9100/// This has better performance than a splat of the scalar followed by a split
9101/// vector store. Even if the stores are not merged it is four stores vs a dup,
9102/// followed by an ext.b and two stores.
Geoff Berrye8de67ab2016-11-14 19:59:11 +00009103static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
9104 SDValue StVal = St.getValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00009105 EVT VT = StVal.getValueType();
9106
9107 // Don't replace floating point stores, they possibly won't be transformed to
9108 // stp because of the store pair suppress pass.
9109 if (VT.isFloatingPoint())
9110 return SDValue();
9111
Tim Northover3b0846e2014-05-24 12:50:23 +00009112 // We can express a splat as store pair(s) for 2 or 4 elements.
9113 unsigned NumVecElts = VT.getVectorNumElements();
9114 if (NumVecElts != 4 && NumVecElts != 2)
9115 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +00009116
9117 // Check that this is a splat.
Geoff Berry25fa4992016-11-11 19:25:20 +00009118 // Make sure that each of the relevant vector element locations are inserted
9119 // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32.
9120 std::bitset<4> IndexNotInserted((1 << NumVecElts) - 1);
9121 SDValue SplatVal;
9122 for (unsigned I = 0; I < NumVecElts; ++I) {
9123 // Check for insert vector elements.
9124 if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
Tim Northover3b0846e2014-05-24 12:50:23 +00009125 return SDValue();
Geoff Berry25fa4992016-11-11 19:25:20 +00009126
9127 // Check that same value is inserted at each vector element.
9128 if (I == 0)
9129 SplatVal = StVal.getOperand(1);
9130 else if (StVal.getOperand(1) != SplatVal)
Tim Northover3b0846e2014-05-24 12:50:23 +00009131 return SDValue();
Geoff Berry25fa4992016-11-11 19:25:20 +00009132
9133 // Check insert element index.
9134 ConstantSDNode *CIndex = dyn_cast<ConstantSDNode>(StVal.getOperand(2));
9135 if (!CIndex)
9136 return SDValue();
9137 uint64_t IndexVal = CIndex->getZExtValue();
9138 if (IndexVal >= NumVecElts)
9139 return SDValue();
9140 IndexNotInserted.reset(IndexVal);
9141
9142 StVal = StVal.getOperand(0);
Tim Northover3b0846e2014-05-24 12:50:23 +00009143 }
Geoff Berry25fa4992016-11-11 19:25:20 +00009144 // Check that all vector element locations were inserted to.
9145 if (IndexNotInserted.any())
9146 return SDValue();
9147
Geoff Berry8301c642016-11-16 19:35:19 +00009148 return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
Tim Northover3b0846e2014-05-24 12:50:23 +00009149}
9150
Geoff Berry8301c642016-11-16 19:35:19 +00009151static SDValue splitStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
9152 SelectionDAG &DAG,
9153 const AArch64Subtarget *Subtarget) {
Tim Northover3b0846e2014-05-24 12:50:23 +00009154 if (!DCI.isBeforeLegalize())
9155 return SDValue();
9156
9157 StoreSDNode *S = cast<StoreSDNode>(N);
9158 if (S->isVolatile())
9159 return SDValue();
9160
Geoff Berry526c5052016-11-14 19:39:04 +00009161 SDValue StVal = S->getValue();
9162 EVT VT = StVal.getValueType();
9163 if (!VT.isVector())
9164 return SDValue();
9165
9166 // If we get a splat of zeros, convert this vector store to a store of
9167 // scalars. They will be merged into store pairs of xzr thereby removing one
9168 // instruction and one register.
Geoff Berrye8de67ab2016-11-14 19:59:11 +00009169 if (SDValue ReplacedZeroSplat = replaceZeroVectorStore(DAG, *S))
Geoff Berry526c5052016-11-14 19:39:04 +00009170 return ReplacedZeroSplat;
9171
Sanjay Patelbbbf9a12015-09-25 21:49:48 +00009172 // FIXME: The logic for deciding if an unaligned store should be split should
9173 // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
9174 // a call to that function here.
9175
Matthias Braun651cff42016-06-02 18:03:53 +00009176 if (!Subtarget->isMisaligned128StoreSlow())
Tim Northover3b0846e2014-05-24 12:50:23 +00009177 return SDValue();
9178
Sanjay Patel924879a2015-08-04 15:49:57 +00009179 // Don't split at -Oz.
9180 if (DAG.getMachineFunction().getFunction()->optForMinSize())
Tim Northover3b0846e2014-05-24 12:50:23 +00009181 return SDValue();
9182
Tim Northover3b0846e2014-05-24 12:50:23 +00009183 // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
9184 // those up regresses performance on micro-benchmarks and olden/bh.
Geoff Berry526c5052016-11-14 19:39:04 +00009185 if (VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
Tim Northover3b0846e2014-05-24 12:50:23 +00009186 return SDValue();
9187
9188 // Split unaligned 16B stores. They are terrible for performance.
9189 // Don't split stores with alignment of 1 or 2. Code that uses clang vector
9190 // extensions can use this to mark that it does not want splitting to happen
9191 // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
9192 // eliminating alignment hazards is only 1 in 8 for alignment of 2.
9193 if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
9194 S->getAlignment() <= 2)
9195 return SDValue();
9196
9197 // If we get a splat of a scalar convert this vector store to a store of
9198 // scalars. They will be merged into store pairs thereby removing two
9199 // instructions.
Geoff Berrye8de67ab2016-11-14 19:59:11 +00009200 if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, *S))
Tim Northover3b0846e2014-05-24 12:50:23 +00009201 return ReplacedSplat;
9202
9203 SDLoc DL(S);
9204 unsigned NumElts = VT.getVectorNumElements() / 2;
9205 // Split VT into two.
9206 EVT HalfVT =
9207 EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), NumElts);
9208 SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009209 DAG.getConstant(0, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00009210 SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009211 DAG.getConstant(NumElts, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00009212 SDValue BasePtr = S->getBasePtr();
9213 SDValue NewST1 =
9214 DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
Justin Lebar9c375812016-07-15 18:27:10 +00009215 S->getAlignment(), S->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +00009216 SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +00009217 DAG.getConstant(8, DL, MVT::i64));
Tim Northover3b0846e2014-05-24 12:50:23 +00009218 return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
Justin Lebar9c375812016-07-15 18:27:10 +00009219 S->getPointerInfo(), S->getAlignment(),
9220 S->getMemOperand()->getFlags());
Tim Northover3b0846e2014-05-24 12:50:23 +00009221}
9222
9223/// Target-specific DAG combine function for post-increment LD1 (lane) and
9224/// post-increment LD1R.
9225static SDValue performPostLD1Combine(SDNode *N,
9226 TargetLowering::DAGCombinerInfo &DCI,
9227 bool IsLaneOp) {
9228 if (DCI.isBeforeLegalizeOps())
9229 return SDValue();
9230
9231 SelectionDAG &DAG = DCI.DAG;
9232 EVT VT = N->getValueType(0);
9233
9234 unsigned LoadIdx = IsLaneOp ? 1 : 0;
9235 SDNode *LD = N->getOperand(LoadIdx).getNode();
9236 // If it is not LOAD, can not do such combine.
9237 if (LD->getOpcode() != ISD::LOAD)
9238 return SDValue();
9239
9240 LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
9241 EVT MemVT = LoadSDN->getMemoryVT();
9242 // Check if memory operand is the same type as the vector element.
9243 if (MemVT != VT.getVectorElementType())
9244 return SDValue();
9245
9246 // Check if there are other uses. If so, do not combine as it will introduce
9247 // an extra load.
9248 for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
9249 ++UI) {
9250 if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
9251 continue;
9252 if (*UI != N)
9253 return SDValue();
9254 }
9255
9256 SDValue Addr = LD->getOperand(1);
9257 SDValue Vector = N->getOperand(0);
9258 // Search for a use of the address operand that is an increment.
9259 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
9260 Addr.getNode()->use_end(); UI != UE; ++UI) {
9261 SDNode *User = *UI;
9262 if (User->getOpcode() != ISD::ADD
9263 || UI.getUse().getResNo() != Addr.getResNo())
9264 continue;
9265
9266 // Check that the add is independent of the load. Otherwise, folding it
9267 // would create a cycle.
9268 if (User->isPredecessorOf(LD) || LD->isPredecessorOf(User))
9269 continue;
9270 // Also check that add is not used in the vector operand. This would also
9271 // create a cycle.
9272 if (User->isPredecessorOf(Vector.getNode()))
9273 continue;
9274
9275 // If the increment is a constant, it must match the memory ref size.
9276 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9277 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9278 uint32_t IncVal = CInc->getZExtValue();
9279 unsigned NumBytes = VT.getScalarSizeInBits() / 8;
9280 if (IncVal != NumBytes)
9281 continue;
9282 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
9283 }
9284
Ahmed Bougacha2448ef52015-04-17 21:02:30 +00009285 // Finally, check that the vector doesn't depend on the load.
9286 // Again, this would create a cycle.
9287 // The load depending on the vector is fine, as that's the case for the
9288 // LD1*post we'll eventually generate anyway.
9289 if (LoadSDN->isPredecessorOf(Vector.getNode()))
9290 continue;
9291
Tim Northover3b0846e2014-05-24 12:50:23 +00009292 SmallVector<SDValue, 8> Ops;
9293 Ops.push_back(LD->getOperand(0)); // Chain
9294 if (IsLaneOp) {
9295 Ops.push_back(Vector); // The vector to be inserted
9296 Ops.push_back(N->getOperand(2)); // The lane to be inserted in the vector
9297 }
9298 Ops.push_back(Addr);
9299 Ops.push_back(Inc);
9300
9301 EVT Tys[3] = { VT, MVT::i64, MVT::Other };
Craig Toppere1d12942014-08-27 05:25:25 +00009302 SDVTList SDTys = DAG.getVTList(Tys);
Tim Northover3b0846e2014-05-24 12:50:23 +00009303 unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
9304 SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
9305 MemVT,
9306 LoadSDN->getMemOperand());
9307
9308 // Update the uses.
Benjamin Kramer3bc1edf2016-07-02 11:41:39 +00009309 SDValue NewResults[] = {
9310 SDValue(LD, 0), // The result of load
9311 SDValue(UpdN.getNode(), 2) // Chain
9312 };
Tim Northover3b0846e2014-05-24 12:50:23 +00009313 DCI.CombineTo(LD, NewResults);
9314 DCI.CombineTo(N, SDValue(UpdN.getNode(), 0)); // Dup/Inserted Result
9315 DCI.CombineTo(User, SDValue(UpdN.getNode(), 1)); // Write back register
9316
9317 break;
9318 }
9319 return SDValue();
9320}
9321
Tim Northover339c83e2015-11-10 00:44:23 +00009322/// Simplify \Addr given that the top byte of it is ignored by HW during
9323/// address translation.
9324static bool performTBISimplification(SDValue Addr,
9325 TargetLowering::DAGCombinerInfo &DCI,
9326 SelectionDAG &DAG) {
9327 APInt DemandedMask = APInt::getLowBitsSet(64, 56);
9328 APInt KnownZero, KnownOne;
9329 TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
9330 DCI.isBeforeLegalizeOps());
9331 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9332 if (TLI.SimplifyDemandedBits(Addr, DemandedMask, KnownZero, KnownOne, TLO)) {
9333 DCI.CommitTargetLoweringOpt(TLO);
9334 return true;
9335 }
9336 return false;
9337}
9338
9339static SDValue performSTORECombine(SDNode *N,
9340 TargetLowering::DAGCombinerInfo &DCI,
9341 SelectionDAG &DAG,
9342 const AArch64Subtarget *Subtarget) {
Geoff Berry8301c642016-11-16 19:35:19 +00009343 if (SDValue Split = splitStores(N, DCI, DAG, Subtarget))
Tim Northover339c83e2015-11-10 00:44:23 +00009344 return Split;
9345
9346 if (Subtarget->supportsAddressTopByteIgnored() &&
9347 performTBISimplification(N->getOperand(2), DCI, DAG))
9348 return SDValue(N, 0);
9349
9350 return SDValue();
9351}
9352
Nirav Dave54e22f32017-03-14 00:34:14 +00009353/// This function handles the log2-shuffle pattern produced by the
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009354/// LoopVectorizer for the across vector reduction. It consists of
9355/// log2(NumVectorElements) steps and, in each step, 2^(s) elements
9356/// are reduced, where s is an induction variable from 0 to
9357/// log2(NumVectorElements).
9358static SDValue tryMatchAcrossLaneShuffleForReduction(SDNode *N, SDValue OpV,
9359 unsigned Op,
9360 SelectionDAG &DAG) {
9361 EVT VTy = OpV->getOperand(0).getValueType();
9362 if (!VTy.isVector())
Chad Rosier6c36eff2015-09-03 18:13:57 +00009363 return SDValue();
9364
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009365 int NumVecElts = VTy.getVectorNumElements();
Jun Bum Lim0aace132015-10-09 14:11:25 +00009366 if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) {
9367 if (NumVecElts != 4)
9368 return SDValue();
9369 } else {
9370 if (NumVecElts != 4 && NumVecElts != 8 && NumVecElts != 16)
9371 return SDValue();
9372 }
Chad Rosier6c36eff2015-09-03 18:13:57 +00009373
9374 int NumExpectedSteps = APInt(8, NumVecElts).logBase2();
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009375 SDValue PreOp = OpV;
Chad Rosier6c36eff2015-09-03 18:13:57 +00009376 // Iterate over each step of the across vector reduction.
9377 for (int CurStep = 0; CurStep != NumExpectedSteps; ++CurStep) {
Chad Rosier6c36eff2015-09-03 18:13:57 +00009378 SDValue CurOp = PreOp.getOperand(0);
9379 SDValue Shuffle = PreOp.getOperand(1);
9380 if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE) {
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009381 // Try to swap the 1st and 2nd operand as add and min/max instructions
9382 // are commutative.
Chad Rosier6c36eff2015-09-03 18:13:57 +00009383 CurOp = PreOp.getOperand(1);
9384 Shuffle = PreOp.getOperand(0);
9385 if (Shuffle.getOpcode() != ISD::VECTOR_SHUFFLE)
9386 return SDValue();
9387 }
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009388
9389 // Check if the input vector is fed by the operator we want to handle,
9390 // except the last step; the very first input vector is not necessarily
9391 // the same operator we are handling.
9392 if (CurOp.getOpcode() != Op && (CurStep != (NumExpectedSteps - 1)))
9393 return SDValue();
9394
Chad Rosier6c36eff2015-09-03 18:13:57 +00009395 // Check if it forms one step of the across vector reduction.
9396 // E.g.,
9397 // %cur = add %1, %0
9398 // %shuffle = vector_shuffle %cur, <2, 3, u, u>
9399 // %pre = add %cur, %shuffle
9400 if (Shuffle.getOperand(0) != CurOp)
9401 return SDValue();
9402
9403 int NumMaskElts = 1 << CurStep;
9404 ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Shuffle)->getMask();
9405 // Check mask values in each step.
9406 // We expect the shuffle mask in each step follows a specific pattern
9407 // denoted here by the <M, U> form, where M is a sequence of integers
9408 // starting from NumMaskElts, increasing by 1, and the number integers
9409 // in M should be NumMaskElts. U is a sequence of UNDEFs and the number
9410 // of undef in U should be NumVecElts - NumMaskElts.
9411 // E.g., for <8 x i16>, mask values in each step should be :
9412 // step 0 : <1,u,u,u,u,u,u,u>
9413 // step 1 : <2,3,u,u,u,u,u,u>
9414 // step 2 : <4,5,6,7,u,u,u,u>
9415 for (int i = 0; i < NumVecElts; ++i)
9416 if ((i < NumMaskElts && Mask[i] != (NumMaskElts + i)) ||
9417 (i >= NumMaskElts && !(Mask[i] < 0)))
9418 return SDValue();
9419
9420 PreOp = CurOp;
9421 }
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009422 unsigned Opcode;
Jun Bum Lim0aace132015-10-09 14:11:25 +00009423 bool IsIntrinsic = false;
9424
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009425 switch (Op) {
9426 default:
9427 llvm_unreachable("Unexpected operator for across vector reduction");
9428 case ISD::ADD:
9429 Opcode = AArch64ISD::UADDV;
9430 break;
9431 case ISD::SMAX:
9432 Opcode = AArch64ISD::SMAXV;
9433 break;
9434 case ISD::UMAX:
9435 Opcode = AArch64ISD::UMAXV;
9436 break;
9437 case ISD::SMIN:
9438 Opcode = AArch64ISD::SMINV;
9439 break;
9440 case ISD::UMIN:
9441 Opcode = AArch64ISD::UMINV;
9442 break;
Jun Bum Lim0aace132015-10-09 14:11:25 +00009443 case ISD::FMAXNUM:
9444 Opcode = Intrinsic::aarch64_neon_fmaxnmv;
9445 IsIntrinsic = true;
9446 break;
9447 case ISD::FMINNUM:
9448 Opcode = Intrinsic::aarch64_neon_fminnmv;
9449 IsIntrinsic = true;
9450 break;
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009451 }
Chad Rosier6c36eff2015-09-03 18:13:57 +00009452 SDLoc DL(N);
Jun Bum Lim0aace132015-10-09 14:11:25 +00009453
9454 return IsIntrinsic
9455 ? DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, N->getValueType(0),
9456 DAG.getConstant(Opcode, DL, MVT::i32), PreOp)
9457 : DAG.getNode(
9458 ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0),
9459 DAG.getNode(Opcode, DL, PreOp.getSimpleValueType(), PreOp),
9460 DAG.getConstant(0, DL, MVT::i64));
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009461}
9462
9463/// Target-specific DAG combine for the across vector min/max reductions.
9464/// This function specifically handles the final clean-up step of the vector
9465/// min/max reductions produced by the LoopVectorizer. It is the log2-shuffle
9466/// pattern, which narrows down and finds the final min/max value from all
9467/// elements of the vector.
9468/// For example, for a <16 x i8> vector :
9469/// svn0 = vector_shuffle %0, undef<8,9,10,11,12,13,14,15,u,u,u,u,u,u,u,u>
9470/// %smax0 = smax %arr, svn0
9471/// %svn1 = vector_shuffle %smax0, undef<4,5,6,7,u,u,u,u,u,u,u,u,u,u,u,u>
9472/// %smax1 = smax %smax0, %svn1
9473/// %svn2 = vector_shuffle %smax1, undef<2,3,u,u,u,u,u,u,u,u,u,u,u,u,u,u>
9474/// %smax2 = smax %smax1, svn2
9475/// %svn3 = vector_shuffle %smax2, undef<1,u,u,u,u,u,u,u,u,u,u,u,u,u,u,u>
9476/// %sc = setcc %smax2, %svn3, gt
9477/// %n0 = extract_vector_elt %sc, #0
9478/// %n1 = extract_vector_elt %smax2, #0
9479/// %n2 = extract_vector_elt $smax2, #1
9480/// %result = select %n0, %n1, n2
9481/// becomes :
9482/// %1 = smaxv %0
9483/// %result = extract_vector_elt %1, 0
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009484static SDValue
9485performAcrossLaneMinMaxReductionCombine(SDNode *N, SelectionDAG &DAG,
9486 const AArch64Subtarget *Subtarget) {
9487 if (!Subtarget->hasNEON())
9488 return SDValue();
9489
9490 SDValue N0 = N->getOperand(0);
9491 SDValue IfTrue = N->getOperand(1);
9492 SDValue IfFalse = N->getOperand(2);
9493
9494 // Check if the SELECT merges up the final result of the min/max
9495 // from a vector.
9496 if (N0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9497 IfTrue.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9498 IfFalse.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9499 return SDValue();
9500
9501 // Expect N0 is fed by SETCC.
9502 SDValue SetCC = N0.getOperand(0);
9503 EVT SetCCVT = SetCC.getValueType();
9504 if (SetCC.getOpcode() != ISD::SETCC || !SetCCVT.isVector() ||
9505 SetCCVT.getVectorElementType() != MVT::i1)
9506 return SDValue();
9507
9508 SDValue VectorOp = SetCC.getOperand(0);
9509 unsigned Op = VectorOp->getOpcode();
9510 // Check if the input vector is fed by the operator we want to handle.
Jun Bum Lim0aace132015-10-09 14:11:25 +00009511 if (Op != ISD::SMAX && Op != ISD::UMAX && Op != ISD::SMIN &&
9512 Op != ISD::UMIN && Op != ISD::FMAXNUM && Op != ISD::FMINNUM)
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009513 return SDValue();
9514
9515 EVT VTy = VectorOp.getValueType();
9516 if (!VTy.isVector())
9517 return SDValue();
9518
Jun Bum Lim0aace132015-10-09 14:11:25 +00009519 if (VTy.getSizeInBits() < 64)
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009520 return SDValue();
9521
Jun Bum Lim0aace132015-10-09 14:11:25 +00009522 EVT EltTy = VTy.getVectorElementType();
9523 if (Op == ISD::FMAXNUM || Op == ISD::FMINNUM) {
9524 if (EltTy != MVT::f32)
9525 return SDValue();
9526 } else {
9527 if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8)
9528 return SDValue();
9529 }
9530
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009531 // Check if extracting from the same vector.
9532 // For example,
9533 // %sc = setcc %vector, %svn1, gt
9534 // %n0 = extract_vector_elt %sc, #0
9535 // %n1 = extract_vector_elt %vector, #0
9536 // %n2 = extract_vector_elt $vector, #1
9537 if (!(VectorOp == IfTrue->getOperand(0) &&
9538 VectorOp == IfFalse->getOperand(0)))
9539 return SDValue();
9540
9541 // Check if the condition code is matched with the operator type.
9542 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get();
9543 if ((Op == ISD::SMAX && CC != ISD::SETGT && CC != ISD::SETGE) ||
9544 (Op == ISD::UMAX && CC != ISD::SETUGT && CC != ISD::SETUGE) ||
9545 (Op == ISD::SMIN && CC != ISD::SETLT && CC != ISD::SETLE) ||
Jun Bum Lim0aace132015-10-09 14:11:25 +00009546 (Op == ISD::UMIN && CC != ISD::SETULT && CC != ISD::SETULE) ||
9547 (Op == ISD::FMAXNUM && CC != ISD::SETOGT && CC != ISD::SETOGE &&
9548 CC != ISD::SETUGT && CC != ISD::SETUGE && CC != ISD::SETGT &&
9549 CC != ISD::SETGE) ||
9550 (Op == ISD::FMINNUM && CC != ISD::SETOLT && CC != ISD::SETOLE &&
9551 CC != ISD::SETULT && CC != ISD::SETULE && CC != ISD::SETLT &&
9552 CC != ISD::SETLE))
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009553 return SDValue();
9554
9555 // Expect to check only lane 0 from the vector SETCC.
Artyom Skrobov314ee042015-11-25 19:41:11 +00009556 if (!isNullConstant(N0.getOperand(1)))
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009557 return SDValue();
9558
9559 // Expect to extract the true value from lane 0.
Artyom Skrobov314ee042015-11-25 19:41:11 +00009560 if (!isNullConstant(IfTrue.getOperand(1)))
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009561 return SDValue();
9562
9563 // Expect to extract the false value from lane 1.
Artyom Skrobov314ee042015-11-25 19:41:11 +00009564 if (!isOneConstant(IfFalse.getOperand(1)))
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009565 return SDValue();
9566
9567 return tryMatchAcrossLaneShuffleForReduction(N, SetCC, Op, DAG);
9568}
9569
9570/// Target-specific DAG combine for the across vector add reduction.
9571/// This function specifically handles the final clean-up step of the vector
9572/// add reduction produced by the LoopVectorizer. It is the log2-shuffle
9573/// pattern, which adds all elements of a vector together.
9574/// For example, for a <4 x i32> vector :
9575/// %1 = vector_shuffle %0, <2,3,u,u>
9576/// %2 = add %0, %1
9577/// %3 = vector_shuffle %2, <1,u,u,u>
9578/// %4 = add %2, %3
9579/// %result = extract_vector_elt %4, 0
9580/// becomes :
9581/// %0 = uaddv %0
9582/// %result = extract_vector_elt %0, 0
9583static SDValue
9584performAcrossLaneAddReductionCombine(SDNode *N, SelectionDAG &DAG,
9585 const AArch64Subtarget *Subtarget) {
9586 if (!Subtarget->hasNEON())
9587 return SDValue();
9588 SDValue N0 = N->getOperand(0);
9589 SDValue N1 = N->getOperand(1);
9590
9591 // Check if the input vector is fed by the ADD.
9592 if (N0->getOpcode() != ISD::ADD)
9593 return SDValue();
9594
9595 // The vector extract idx must constant zero because we only expect the final
9596 // result of the reduction is placed in lane 0.
Artyom Skrobov314ee042015-11-25 19:41:11 +00009597 if (!isNullConstant(N1))
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009598 return SDValue();
9599
9600 EVT VTy = N0.getValueType();
9601 if (!VTy.isVector())
9602 return SDValue();
9603
9604 EVT EltTy = VTy.getVectorElementType();
9605 if (EltTy != MVT::i32 && EltTy != MVT::i16 && EltTy != MVT::i8)
9606 return SDValue();
9607
Jun Bum Lim0aace132015-10-09 14:11:25 +00009608 if (VTy.getSizeInBits() < 64)
9609 return SDValue();
9610
Jun Bum Lim34b9bd02015-09-14 16:19:52 +00009611 return tryMatchAcrossLaneShuffleForReduction(N, N0, ISD::ADD, DAG);
Chad Rosier6c36eff2015-09-03 18:13:57 +00009612}
9613
Tim Northover3b0846e2014-05-24 12:50:23 +00009614/// Target-specific DAG combine function for NEON load/store intrinsics
9615/// to merge base address updates.
9616static SDValue performNEONPostLDSTCombine(SDNode *N,
9617 TargetLowering::DAGCombinerInfo &DCI,
9618 SelectionDAG &DAG) {
9619 if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9620 return SDValue();
9621
9622 unsigned AddrOpIdx = N->getNumOperands() - 1;
9623 SDValue Addr = N->getOperand(AddrOpIdx);
9624
9625 // Search for a use of the address operand that is an increment.
9626 for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
9627 UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
9628 SDNode *User = *UI;
9629 if (User->getOpcode() != ISD::ADD ||
9630 UI.getUse().getResNo() != Addr.getResNo())
9631 continue;
9632
9633 // Check that the add is independent of the load/store. Otherwise, folding
9634 // it would create a cycle.
9635 if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
9636 continue;
9637
9638 // Find the new opcode for the updating load/store.
9639 bool IsStore = false;
9640 bool IsLaneOp = false;
9641 bool IsDupOp = false;
9642 unsigned NewOpc = 0;
9643 unsigned NumVecs = 0;
9644 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9645 switch (IntNo) {
9646 default: llvm_unreachable("unexpected intrinsic for Neon base update");
9647 case Intrinsic::aarch64_neon_ld2: NewOpc = AArch64ISD::LD2post;
9648 NumVecs = 2; break;
9649 case Intrinsic::aarch64_neon_ld3: NewOpc = AArch64ISD::LD3post;
9650 NumVecs = 3; break;
9651 case Intrinsic::aarch64_neon_ld4: NewOpc = AArch64ISD::LD4post;
9652 NumVecs = 4; break;
9653 case Intrinsic::aarch64_neon_st2: NewOpc = AArch64ISD::ST2post;
9654 NumVecs = 2; IsStore = true; break;
9655 case Intrinsic::aarch64_neon_st3: NewOpc = AArch64ISD::ST3post;
9656 NumVecs = 3; IsStore = true; break;
9657 case Intrinsic::aarch64_neon_st4: NewOpc = AArch64ISD::ST4post;
9658 NumVecs = 4; IsStore = true; break;
9659 case Intrinsic::aarch64_neon_ld1x2: NewOpc = AArch64ISD::LD1x2post;
9660 NumVecs = 2; break;
9661 case Intrinsic::aarch64_neon_ld1x3: NewOpc = AArch64ISD::LD1x3post;
9662 NumVecs = 3; break;
9663 case Intrinsic::aarch64_neon_ld1x4: NewOpc = AArch64ISD::LD1x4post;
9664 NumVecs = 4; break;
9665 case Intrinsic::aarch64_neon_st1x2: NewOpc = AArch64ISD::ST1x2post;
9666 NumVecs = 2; IsStore = true; break;
9667 case Intrinsic::aarch64_neon_st1x3: NewOpc = AArch64ISD::ST1x3post;
9668 NumVecs = 3; IsStore = true; break;
9669 case Intrinsic::aarch64_neon_st1x4: NewOpc = AArch64ISD::ST1x4post;
9670 NumVecs = 4; IsStore = true; break;
9671 case Intrinsic::aarch64_neon_ld2r: NewOpc = AArch64ISD::LD2DUPpost;
9672 NumVecs = 2; IsDupOp = true; break;
9673 case Intrinsic::aarch64_neon_ld3r: NewOpc = AArch64ISD::LD3DUPpost;
9674 NumVecs = 3; IsDupOp = true; break;
9675 case Intrinsic::aarch64_neon_ld4r: NewOpc = AArch64ISD::LD4DUPpost;
9676 NumVecs = 4; IsDupOp = true; break;
9677 case Intrinsic::aarch64_neon_ld2lane: NewOpc = AArch64ISD::LD2LANEpost;
9678 NumVecs = 2; IsLaneOp = true; break;
9679 case Intrinsic::aarch64_neon_ld3lane: NewOpc = AArch64ISD::LD3LANEpost;
9680 NumVecs = 3; IsLaneOp = true; break;
9681 case Intrinsic::aarch64_neon_ld4lane: NewOpc = AArch64ISD::LD4LANEpost;
9682 NumVecs = 4; IsLaneOp = true; break;
9683 case Intrinsic::aarch64_neon_st2lane: NewOpc = AArch64ISD::ST2LANEpost;
9684 NumVecs = 2; IsStore = true; IsLaneOp = true; break;
9685 case Intrinsic::aarch64_neon_st3lane: NewOpc = AArch64ISD::ST3LANEpost;
9686 NumVecs = 3; IsStore = true; IsLaneOp = true; break;
9687 case Intrinsic::aarch64_neon_st4lane: NewOpc = AArch64ISD::ST4LANEpost;
9688 NumVecs = 4; IsStore = true; IsLaneOp = true; break;
9689 }
9690
9691 EVT VecTy;
9692 if (IsStore)
9693 VecTy = N->getOperand(2).getValueType();
9694 else
9695 VecTy = N->getValueType(0);
9696
9697 // If the increment is a constant, it must match the memory ref size.
9698 SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
9699 if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
9700 uint32_t IncVal = CInc->getZExtValue();
9701 unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
9702 if (IsLaneOp || IsDupOp)
9703 NumBytes /= VecTy.getVectorNumElements();
9704 if (IncVal != NumBytes)
9705 continue;
9706 Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
9707 }
9708 SmallVector<SDValue, 8> Ops;
9709 Ops.push_back(N->getOperand(0)); // Incoming chain
9710 // Load lane and store have vector list as input.
9711 if (IsLaneOp || IsStore)
9712 for (unsigned i = 2; i < AddrOpIdx; ++i)
9713 Ops.push_back(N->getOperand(i));
9714 Ops.push_back(Addr); // Base register
9715 Ops.push_back(Inc);
9716
9717 // Return Types.
9718 EVT Tys[6];
9719 unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
9720 unsigned n;
9721 for (n = 0; n < NumResultVecs; ++n)
9722 Tys[n] = VecTy;
9723 Tys[n++] = MVT::i64; // Type of write back register
9724 Tys[n] = MVT::Other; // Type of the chain
Craig Toppere1d12942014-08-27 05:25:25 +00009725 SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
Tim Northover3b0846e2014-05-24 12:50:23 +00009726
9727 MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
9728 SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
9729 MemInt->getMemoryVT(),
9730 MemInt->getMemOperand());
9731
9732 // Update the uses.
9733 std::vector<SDValue> NewResults;
9734 for (unsigned i = 0; i < NumResultVecs; ++i) {
9735 NewResults.push_back(SDValue(UpdN.getNode(), i));
9736 }
9737 NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
9738 DCI.CombineTo(N, NewResults);
9739 DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
9740
9741 break;
9742 }
9743 return SDValue();
9744}
9745
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009746// Checks to see if the value is the prescribed width and returns information
9747// about its extension mode.
9748static
9749bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
9750 ExtType = ISD::NON_EXTLOAD;
9751 switch(V.getNode()->getOpcode()) {
9752 default:
9753 return false;
9754 case ISD::LOAD: {
9755 LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
9756 if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
9757 || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
9758 ExtType = LoadNode->getExtensionType();
9759 return true;
9760 }
9761 return false;
9762 }
9763 case ISD::AssertSext: {
9764 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9765 if ((TypeNode->getVT() == MVT::i8 && width == 8)
9766 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9767 ExtType = ISD::SEXTLOAD;
9768 return true;
9769 }
9770 return false;
9771 }
9772 case ISD::AssertZext: {
9773 VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
9774 if ((TypeNode->getVT() == MVT::i8 && width == 8)
9775 || (TypeNode->getVT() == MVT::i16 && width == 16)) {
9776 ExtType = ISD::ZEXTLOAD;
9777 return true;
9778 }
9779 return false;
9780 }
9781 case ISD::Constant:
9782 case ISD::TargetConstant: {
Eric Christopher114fa1c2016-02-29 22:50:49 +00009783 return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
9784 1LL << (width - 1);
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009785 }
9786 }
9787
9788 return true;
9789}
9790
9791// This function does a whole lot of voodoo to determine if the tests are
9792// equivalent without and with a mask. Essentially what happens is that given a
9793// DAG resembling:
9794//
9795// +-------------+ +-------------+ +-------------+ +-------------+
9796// | Input | | AddConstant | | CompConstant| | CC |
9797// +-------------+ +-------------+ +-------------+ +-------------+
9798// | | | |
9799// V V | +----------+
9800// +-------------+ +----+ | |
9801// | ADD | |0xff| | |
9802// +-------------+ +----+ | |
9803// | | | |
9804// V V | |
9805// +-------------+ | |
9806// | AND | | |
9807// +-------------+ | |
9808// | | |
9809// +-----+ | |
9810// | | |
9811// V V V
9812// +-------------+
9813// | CMP |
9814// +-------------+
9815//
9816// The AND node may be safely removed for some combinations of inputs. In
9817// particular we need to take into account the extension type of the Input,
9818// the exact values of AddConstant, CompConstant, and CC, along with the nominal
9819// width of the input (this can work for any width inputs, the above graph is
9820// specific to 8 bits.
9821//
9822// The specific equations were worked out by generating output tables for each
9823// AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
9824// problem was simplified by working with 4 bit inputs, which means we only
9825// needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
9826// extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
9827// patterns present in both extensions (0,7). For every distinct set of
9828// AddConstant and CompConstants bit patterns we can consider the masked and
9829// unmasked versions to be equivalent if the result of this function is true for
9830// all 16 distinct bit patterns of for the current extension type of Input (w0).
9831//
9832// sub w8, w0, w1
9833// and w10, w8, #0x0f
9834// cmp w8, w2
9835// cset w9, AArch64CC
9836// cmp w10, w2
9837// cset w11, AArch64CC
9838// cmp w9, w11
9839// cset w0, eq
9840// ret
9841//
9842// Since the above function shows when the outputs are equivalent it defines
9843// when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
9844// would be expensive to run during compiles. The equations below were written
9845// in a test harness that confirmed they gave equivalent outputs to the above
9846// for all inputs function, so they can be used determine if the removal is
9847// legal instead.
9848//
9849// isEquivalentMaskless() is the code for testing if the AND can be removed
9850// factored out of the DAG recognition as the DAG can take several forms.
9851
David Majnemere61e4bf2016-06-21 05:10:24 +00009852static bool isEquivalentMaskless(unsigned CC, unsigned width,
9853 ISD::LoadExtType ExtType, int AddConstant,
9854 int CompConstant) {
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009855 // By being careful about our equations and only writing the in term
9856 // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
9857 // make them generally applicable to all bit widths.
David Majnemere61e4bf2016-06-21 05:10:24 +00009858 int MaxUInt = (1 << width);
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009859
9860 // For the purposes of these comparisons sign extending the type is
9861 // equivalent to zero extending the add and displacing it by half the integer
9862 // width. Provided we are careful and make sure our equations are valid over
9863 // the whole range we can just adjust the input and avoid writing equations
9864 // for sign extended inputs.
9865 if (ExtType == ISD::SEXTLOAD)
9866 AddConstant -= (1 << (width-1));
9867
9868 switch(CC) {
9869 case AArch64CC::LE:
Eugene Zelenko049b0172017-01-06 00:30:53 +00009870 case AArch64CC::GT:
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009871 if ((AddConstant == 0) ||
9872 (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
9873 (AddConstant >= 0 && CompConstant < 0) ||
9874 (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
9875 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +00009876 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009877 case AArch64CC::LT:
Eugene Zelenko049b0172017-01-06 00:30:53 +00009878 case AArch64CC::GE:
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009879 if ((AddConstant == 0) ||
9880 (AddConstant >= 0 && CompConstant <= 0) ||
9881 (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
9882 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +00009883 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009884 case AArch64CC::HI:
Eugene Zelenko049b0172017-01-06 00:30:53 +00009885 case AArch64CC::LS:
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009886 if ((AddConstant >= 0 && CompConstant < 0) ||
9887 (AddConstant <= 0 && CompConstant >= -1 &&
9888 CompConstant < AddConstant + MaxUInt))
9889 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +00009890 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009891 case AArch64CC::PL:
Eugene Zelenko049b0172017-01-06 00:30:53 +00009892 case AArch64CC::MI:
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009893 if ((AddConstant == 0) ||
9894 (AddConstant > 0 && CompConstant <= 0) ||
9895 (AddConstant < 0 && CompConstant <= AddConstant))
9896 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +00009897 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009898 case AArch64CC::LO:
Eugene Zelenko049b0172017-01-06 00:30:53 +00009899 case AArch64CC::HS:
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009900 if ((AddConstant >= 0 && CompConstant <= 0) ||
9901 (AddConstant <= 0 && CompConstant >= 0 &&
9902 CompConstant <= AddConstant + MaxUInt))
9903 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +00009904 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009905 case AArch64CC::EQ:
Eugene Zelenko049b0172017-01-06 00:30:53 +00009906 case AArch64CC::NE:
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009907 if ((AddConstant > 0 && CompConstant < 0) ||
9908 (AddConstant < 0 && CompConstant >= 0 &&
9909 CompConstant < AddConstant + MaxUInt) ||
9910 (AddConstant >= 0 && CompConstant >= 0 &&
9911 CompConstant >= AddConstant) ||
9912 (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009913 return true;
Eugene Zelenko049b0172017-01-06 00:30:53 +00009914 break;
Louis Gerbarg03c627e2014-08-29 21:00:22 +00009915 case AArch64CC::VS:
9916 case AArch64CC::VC:
9917 case AArch64CC::AL:
9918 case AArch64CC::NV:
9919 return true;
9920 case AArch64CC::Invalid:
9921 break;
9922 }
9923
9924 return false;
9925}
9926
9927static
9928SDValue performCONDCombine(SDNode *N,
9929 TargetLowering::DAGCombinerInfo &DCI,
9930 SelectionDAG &DAG, unsigned CCIndex,
9931 unsigned CmpIndex) {
9932 unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
9933 SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
9934 unsigned CondOpcode = SubsNode->getOpcode();
9935
9936 if (CondOpcode != AArch64ISD::SUBS)
9937 return SDValue();
9938
9939 // There is a SUBS feeding this condition. Is it fed by a mask we can
9940 // use?
9941
9942 SDNode *AndNode = SubsNode->getOperand(0).getNode();
9943 unsigned MaskBits = 0;
9944
9945 if (AndNode->getOpcode() != ISD::AND)
9946 return SDValue();
9947
9948 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
9949 uint32_t CNV = CN->getZExtValue();
9950 if (CNV == 255)
9951 MaskBits = 8;
9952 else if (CNV == 65535)
9953 MaskBits = 16;
9954 }
9955
9956 if (!MaskBits)
9957 return SDValue();
9958
9959 SDValue AddValue = AndNode->getOperand(0);
9960
9961 if (AddValue.getOpcode() != ISD::ADD)
9962 return SDValue();
9963
9964 // The basic dag structure is correct, grab the inputs and validate them.
9965
9966 SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
9967 SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
9968 SDValue SubsInputValue = SubsNode->getOperand(1);
9969
9970 // The mask is present and the provenance of all the values is a smaller type,
9971 // lets see if the mask is superfluous.
9972
9973 if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
9974 !isa<ConstantSDNode>(SubsInputValue.getNode()))
9975 return SDValue();
9976
9977 ISD::LoadExtType ExtType;
9978
9979 if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
9980 !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
9981 !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
9982 return SDValue();
9983
9984 if(!isEquivalentMaskless(CC, MaskBits, ExtType,
9985 cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
9986 cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
9987 return SDValue();
9988
9989 // The AND is not necessary, remove it.
9990
9991 SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
9992 SubsNode->getValueType(1));
9993 SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
9994
9995 SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
9996 DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
9997
9998 return SDValue(N, 0);
9999}
10000
Tim Northover3b0846e2014-05-24 12:50:23 +000010001// Optimize compare with zero and branch.
10002static SDValue performBRCONDCombine(SDNode *N,
10003 TargetLowering::DAGCombinerInfo &DCI,
10004 SelectionDAG &DAG) {
Ahmed Bougachaf8dfb472016-02-09 22:54:12 +000010005 if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3))
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010006 N = NV.getNode();
Tim Northover3b0846e2014-05-24 12:50:23 +000010007 SDValue Chain = N->getOperand(0);
10008 SDValue Dest = N->getOperand(1);
10009 SDValue CCVal = N->getOperand(2);
10010 SDValue Cmp = N->getOperand(3);
10011
10012 assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
10013 unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
10014 if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
10015 return SDValue();
10016
10017 unsigned CmpOpc = Cmp.getOpcode();
10018 if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
10019 return SDValue();
10020
10021 // Only attempt folding if there is only one use of the flag and no use of the
10022 // value.
10023 if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
10024 return SDValue();
10025
10026 SDValue LHS = Cmp.getOperand(0);
10027 SDValue RHS = Cmp.getOperand(1);
10028
10029 assert(LHS.getValueType() == RHS.getValueType() &&
10030 "Expected the value type to be the same for both operands!");
10031 if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
10032 return SDValue();
10033
Artyom Skrobov314ee042015-11-25 19:41:11 +000010034 if (isNullConstant(LHS))
Tim Northover3b0846e2014-05-24 12:50:23 +000010035 std::swap(LHS, RHS);
10036
Artyom Skrobov314ee042015-11-25 19:41:11 +000010037 if (!isNullConstant(RHS))
Tim Northover3b0846e2014-05-24 12:50:23 +000010038 return SDValue();
10039
10040 if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
10041 LHS.getOpcode() == ISD::SRL)
10042 return SDValue();
10043
10044 // Fold the compare into the branch instruction.
10045 SDValue BR;
10046 if (CC == AArch64CC::EQ)
10047 BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
10048 else
10049 BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
10050
10051 // Do not add new nodes to DAG combiner worklist.
10052 DCI.CombineTo(N, BR, false);
10053
10054 return SDValue();
10055}
10056
Geoff Berry9e934b02016-01-04 18:55:47 +000010057// Optimize some simple tbz/tbnz cases. Returns the new operand and bit to test
10058// as well as whether the test should be inverted. This code is required to
10059// catch these cases (as opposed to standard dag combines) because
10060// AArch64ISD::TBZ is matched during legalization.
10061static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert,
10062 SelectionDAG &DAG) {
10063
10064 if (!Op->hasOneUse())
10065 return Op;
10066
10067 // We don't handle undef/constant-fold cases below, as they should have
10068 // already been taken care of (e.g. and of 0, test of undefined shifted bits,
10069 // etc.)
10070
10071 // (tbz (trunc x), b) -> (tbz x, b)
10072 // This case is just here to enable more of the below cases to be caught.
10073 if (Op->getOpcode() == ISD::TRUNCATE &&
10074 Bit < Op->getValueType(0).getSizeInBits()) {
10075 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10076 }
10077
10078 if (Op->getNumOperands() != 2)
10079 return Op;
10080
10081 auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
10082 if (!C)
10083 return Op;
10084
10085 switch (Op->getOpcode()) {
10086 default:
10087 return Op;
10088
10089 // (tbz (and x, m), b) -> (tbz x, b)
10090 case ISD::AND:
10091 if ((C->getZExtValue() >> Bit) & 1)
10092 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10093 return Op;
10094
10095 // (tbz (shl x, c), b) -> (tbz x, b-c)
10096 case ISD::SHL:
10097 if (C->getZExtValue() <= Bit &&
10098 (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
10099 Bit = Bit - C->getZExtValue();
10100 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10101 }
10102 return Op;
10103
10104 // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
10105 case ISD::SRA:
10106 Bit = Bit + C->getZExtValue();
10107 if (Bit >= Op->getValueType(0).getSizeInBits())
10108 Bit = Op->getValueType(0).getSizeInBits() - 1;
10109 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10110
10111 // (tbz (srl x, c), b) -> (tbz x, b+c)
10112 case ISD::SRL:
10113 if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
10114 Bit = Bit + C->getZExtValue();
10115 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10116 }
10117 return Op;
10118
10119 // (tbz (xor x, -1), b) -> (tbnz x, b)
10120 case ISD::XOR:
10121 if ((C->getZExtValue() >> Bit) & 1)
10122 Invert = !Invert;
10123 return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
10124 }
10125}
10126
10127// Optimize test single bit zero/non-zero and branch.
10128static SDValue performTBZCombine(SDNode *N,
10129 TargetLowering::DAGCombinerInfo &DCI,
10130 SelectionDAG &DAG) {
10131 unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
10132 bool Invert = false;
10133 SDValue TestSrc = N->getOperand(1);
10134 SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG);
10135
10136 if (TestSrc == NewTestSrc)
10137 return SDValue();
10138
10139 unsigned NewOpc = N->getOpcode();
10140 if (Invert) {
10141 if (NewOpc == AArch64ISD::TBZ)
10142 NewOpc = AArch64ISD::TBNZ;
10143 else {
10144 assert(NewOpc == AArch64ISD::TBNZ);
10145 NewOpc = AArch64ISD::TBZ;
10146 }
10147 }
10148
10149 SDLoc DL(N);
10150 return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc,
10151 DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3));
10152}
10153
Tim Northover3b0846e2014-05-24 12:50:23 +000010154// vselect (v1i1 setcc) ->
10155// vselect (v1iXX setcc) (XX is the size of the compared operand type)
10156// FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
10157// condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
10158// such VSELECT.
10159static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
10160 SDValue N0 = N->getOperand(0);
10161 EVT CCVT = N0.getValueType();
10162
10163 if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
10164 CCVT.getVectorElementType() != MVT::i1)
10165 return SDValue();
10166
10167 EVT ResVT = N->getValueType(0);
10168 EVT CmpVT = N0.getOperand(0).getValueType();
10169 // Only combine when the result type is of the same size as the compared
10170 // operands.
10171 if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
10172 return SDValue();
10173
10174 SDValue IfTrue = N->getOperand(1);
10175 SDValue IfFalse = N->getOperand(2);
10176 SDValue SetCC =
10177 DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
10178 N0.getOperand(0), N0.getOperand(1),
10179 cast<CondCodeSDNode>(N0.getOperand(2))->get());
10180 return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
10181 IfTrue, IfFalse);
10182}
10183
10184/// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
10185/// the compare-mask instructions rather than going via NZCV, even if LHS and
10186/// RHS are really scalar. This replaces any scalar setcc in the above pattern
10187/// with a vector one followed by a DUP shuffle on the result.
Ahmed Bougachac004c602015-04-27 21:43:12 +000010188static SDValue performSelectCombine(SDNode *N,
10189 TargetLowering::DAGCombinerInfo &DCI) {
10190 SelectionDAG &DAG = DCI.DAG;
Tim Northover3b0846e2014-05-24 12:50:23 +000010191 SDValue N0 = N->getOperand(0);
10192 EVT ResVT = N->getValueType(0);
Tim Northover3c0915e2014-08-29 15:34:58 +000010193
Ahmed Bougachac004c602015-04-27 21:43:12 +000010194 if (N0.getOpcode() != ISD::SETCC)
Tim Northover3c0915e2014-08-29 15:34:58 +000010195 return SDValue();
Tim Northover3b0846e2014-05-24 12:50:23 +000010196
Ahmed Bougachac004c602015-04-27 21:43:12 +000010197 // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
10198 // scalar SetCCResultType. We also don't expect vectors, because we assume
10199 // that selects fed by vector SETCCs are canonicalized to VSELECT.
10200 assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
10201 "Scalar-SETCC feeding SELECT has unexpected result type!");
10202
Tim Northoverc1c05ae2014-08-29 13:05:18 +000010203 // If NumMaskElts == 0, the comparison is larger than select result. The
10204 // largest real NEON comparison is 64-bits per lane, which means the result is
10205 // at most 32-bits and an illegal vector. Just bail out for now.
Tim Northover3c0915e2014-08-29 15:34:58 +000010206 EVT SrcVT = N0.getOperand(0).getValueType();
Ahmed Bougachad0ce0582014-12-01 20:59:00 +000010207
10208 // Don't try to do this optimization when the setcc itself has i1 operands.
10209 // There are no legal vectors of i1, so this would be pointless.
10210 if (SrcVT == MVT::i1)
10211 return SDValue();
10212
Tim Northover3c0915e2014-08-29 15:34:58 +000010213 int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
Tim Northoverc1c05ae2014-08-29 13:05:18 +000010214 if (!ResVT.isVector() || NumMaskElts == 0)
Tim Northover3b0846e2014-05-24 12:50:23 +000010215 return SDValue();
10216
Tim Northoverc1c05ae2014-08-29 13:05:18 +000010217 SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
Tim Northover3b0846e2014-05-24 12:50:23 +000010218 EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
10219
Ahmed Bougacha89bba612015-04-27 21:01:20 +000010220 // Also bail out if the vector CCVT isn't the same size as ResVT.
10221 // This can happen if the SETCC operand size doesn't divide the ResVT size
10222 // (e.g., f64 vs v3f32).
10223 if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
10224 return SDValue();
10225
Ahmed Bougachac004c602015-04-27 21:43:12 +000010226 // Make sure we didn't create illegal types, if we're not supposed to.
10227 assert(DCI.isBeforeLegalize() ||
10228 DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
10229
Tim Northover3b0846e2014-05-24 12:50:23 +000010230 // First perform a vector comparison, where lane 0 is the one we're interested
10231 // in.
Tim Northoverc1c05ae2014-08-29 13:05:18 +000010232 SDLoc DL(N0);
Tim Northover3b0846e2014-05-24 12:50:23 +000010233 SDValue LHS =
10234 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
10235 SDValue RHS =
10236 DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
10237 SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
10238
10239 // Now duplicate the comparison mask we want across all other lanes.
10240 SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
Craig Topper2bd8b4b2016-07-01 06:54:47 +000010241 SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask);
Tim Northoverc1c05ae2014-08-29 13:05:18 +000010242 Mask = DAG.getNode(ISD::BITCAST, DL,
10243 ResVT.changeVectorElementTypeToInteger(), Mask);
Tim Northover3b0846e2014-05-24 12:50:23 +000010244
10245 return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
10246}
10247
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +000010248/// Get rid of unnecessary NVCASTs (that don't change the type).
10249static SDValue performNVCASTCombine(SDNode *N) {
10250 if (N->getValueType(0) == N->getOperand(0).getValueType())
10251 return N->getOperand(0);
10252
10253 return SDValue();
10254}
10255
Tim Northover3b0846e2014-05-24 12:50:23 +000010256SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
10257 DAGCombinerInfo &DCI) const {
10258 SelectionDAG &DAG = DCI.DAG;
10259 switch (N->getOpcode()) {
10260 default:
10261 break;
10262 case ISD::ADD:
10263 case ISD::SUB:
10264 return performAddSubLongCombine(N, DCI, DAG);
10265 case ISD::XOR:
10266 return performXorCombine(N, DAG, DCI, Subtarget);
10267 case ISD::MUL:
10268 return performMulCombine(N, DAG, DCI, Subtarget);
10269 case ISD::SINT_TO_FP:
10270 case ISD::UINT_TO_FP:
Weiming Zhaocc4bf3f2014-12-04 20:25:50 +000010271 return performIntToFpCombine(N, DAG, Subtarget);
Chad Rosierfa30c9b2015-10-07 17:39:18 +000010272 case ISD::FP_TO_SINT:
10273 case ISD::FP_TO_UINT:
Silviu Barangafa00ba32016-08-08 13:13:57 +000010274 return performFpToIntCombine(N, DAG, DCI, Subtarget);
Chad Rosier7c6ac2b2015-10-07 17:51:37 +000010275 case ISD::FDIV:
Tim Northover85cf5642016-08-26 18:52:31 +000010276 return performFDivCombine(N, DAG, DCI, Subtarget);
Tim Northover3b0846e2014-05-24 12:50:23 +000010277 case ISD::OR:
10278 return performORCombine(N, DCI, Subtarget);
Chad Rosier14aa2ad2016-05-26 19:41:33 +000010279 case ISD::SRL:
10280 return performSRLCombine(N, DCI);
Tim Northover3b0846e2014-05-24 12:50:23 +000010281 case ISD::INTRINSIC_WO_CHAIN:
10282 return performIntrinsicCombine(N, DCI, Subtarget);
10283 case ISD::ANY_EXTEND:
10284 case ISD::ZERO_EXTEND:
10285 case ISD::SIGN_EXTEND:
10286 return performExtendCombine(N, DCI, DAG);
10287 case ISD::BITCAST:
10288 return performBitcastCombine(N, DCI, DAG);
10289 case ISD::CONCAT_VECTORS:
10290 return performConcatVectorsCombine(N, DCI, DAG);
Jun Bum Lim34b9bd02015-09-14 16:19:52 +000010291 case ISD::SELECT: {
10292 SDValue RV = performSelectCombine(N, DCI);
10293 if (!RV.getNode())
10294 RV = performAcrossLaneMinMaxReductionCombine(N, DAG, Subtarget);
10295 return RV;
10296 }
Tim Northover3b0846e2014-05-24 12:50:23 +000010297 case ISD::VSELECT:
10298 return performVSelectCombine(N, DCI.DAG);
Tim Northover339c83e2015-11-10 00:44:23 +000010299 case ISD::LOAD:
10300 if (performTBISimplification(N->getOperand(1), DCI, DAG))
10301 return SDValue(N, 0);
10302 break;
Tim Northover3b0846e2014-05-24 12:50:23 +000010303 case ISD::STORE:
10304 return performSTORECombine(N, DCI, DAG, Subtarget);
10305 case AArch64ISD::BRCOND:
10306 return performBRCONDCombine(N, DCI, DAG);
Geoff Berry9e934b02016-01-04 18:55:47 +000010307 case AArch64ISD::TBNZ:
10308 case AArch64ISD::TBZ:
10309 return performTBZCombine(N, DCI, DAG);
Louis Gerbarg03c627e2014-08-29 21:00:22 +000010310 case AArch64ISD::CSEL:
10311 return performCONDCombine(N, DCI, DAG, 2, 3);
Tim Northover3b0846e2014-05-24 12:50:23 +000010312 case AArch64ISD::DUP:
10313 return performPostLD1Combine(N, DCI, false);
Ahmed Bougacha8c7754b2015-06-16 01:18:14 +000010314 case AArch64ISD::NVCAST:
10315 return performNVCASTCombine(N);
Tim Northover3b0846e2014-05-24 12:50:23 +000010316 case ISD::INSERT_VECTOR_ELT:
10317 return performPostLD1Combine(N, DCI, true);
Chad Rosier6c36eff2015-09-03 18:13:57 +000010318 case ISD::EXTRACT_VECTOR_ELT:
Jun Bum Lim34b9bd02015-09-14 16:19:52 +000010319 return performAcrossLaneAddReductionCombine(N, DAG, Subtarget);
Tim Northover3b0846e2014-05-24 12:50:23 +000010320 case ISD::INTRINSIC_VOID:
10321 case ISD::INTRINSIC_W_CHAIN:
10322 switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
10323 case Intrinsic::aarch64_neon_ld2:
10324 case Intrinsic::aarch64_neon_ld3:
10325 case Intrinsic::aarch64_neon_ld4:
10326 case Intrinsic::aarch64_neon_ld1x2:
10327 case Intrinsic::aarch64_neon_ld1x3:
10328 case Intrinsic::aarch64_neon_ld1x4:
10329 case Intrinsic::aarch64_neon_ld2lane:
10330 case Intrinsic::aarch64_neon_ld3lane:
10331 case Intrinsic::aarch64_neon_ld4lane:
10332 case Intrinsic::aarch64_neon_ld2r:
10333 case Intrinsic::aarch64_neon_ld3r:
10334 case Intrinsic::aarch64_neon_ld4r:
10335 case Intrinsic::aarch64_neon_st2:
10336 case Intrinsic::aarch64_neon_st3:
10337 case Intrinsic::aarch64_neon_st4:
10338 case Intrinsic::aarch64_neon_st1x2:
10339 case Intrinsic::aarch64_neon_st1x3:
10340 case Intrinsic::aarch64_neon_st1x4:
10341 case Intrinsic::aarch64_neon_st2lane:
10342 case Intrinsic::aarch64_neon_st3lane:
10343 case Intrinsic::aarch64_neon_st4lane:
10344 return performNEONPostLDSTCombine(N, DCI, DAG);
10345 default:
10346 break;
10347 }
10348 }
10349 return SDValue();
10350}
10351
10352// Check if the return value is used as only a return value, as otherwise
10353// we can't perform a tail-call. In particular, we need to check for
10354// target ISD nodes that are returns and any other "odd" constructs
10355// that the generic analysis code won't necessarily catch.
10356bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
10357 SDValue &Chain) const {
10358 if (N->getNumValues() != 1)
10359 return false;
10360 if (!N->hasNUsesOfValue(1, 0))
10361 return false;
10362
10363 SDValue TCChain = Chain;
10364 SDNode *Copy = *N->use_begin();
10365 if (Copy->getOpcode() == ISD::CopyToReg) {
10366 // If the copy has a glue operand, we conservatively assume it isn't safe to
10367 // perform a tail call.
10368 if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
10369 MVT::Glue)
10370 return false;
10371 TCChain = Copy->getOperand(0);
10372 } else if (Copy->getOpcode() != ISD::FP_EXTEND)
10373 return false;
10374
10375 bool HasRet = false;
10376 for (SDNode *Node : Copy->uses()) {
10377 if (Node->getOpcode() != AArch64ISD::RET_FLAG)
10378 return false;
10379 HasRet = true;
10380 }
10381
10382 if (!HasRet)
10383 return false;
10384
10385 Chain = TCChain;
10386 return true;
10387}
10388
10389// Return whether the an instruction can potentially be optimized to a tail
10390// call. This will cause the optimizers to attempt to move, or duplicate,
10391// return instructions to help enable tail call optimizations for this
10392// instruction.
10393bool AArch64TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
Eric Christopher114fa1c2016-02-29 22:50:49 +000010394 return CI->isTailCall();
Tim Northover3b0846e2014-05-24 12:50:23 +000010395}
10396
10397bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
10398 SDValue &Offset,
10399 ISD::MemIndexedMode &AM,
10400 bool &IsInc,
10401 SelectionDAG &DAG) const {
10402 if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
10403 return false;
10404
10405 Base = Op->getOperand(0);
10406 // All of the indexed addressing mode instructions take a signed
10407 // 9 bit immediate offset.
10408 if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
Haicheng Wu9ac20a12016-12-22 01:39:24 +000010409 int64_t RHSC = RHS->getSExtValue();
10410 if (Op->getOpcode() == ISD::SUB)
10411 RHSC = -(uint64_t)RHSC;
10412 if (!isInt<9>(RHSC))
Tim Northover3b0846e2014-05-24 12:50:23 +000010413 return false;
10414 IsInc = (Op->getOpcode() == ISD::ADD);
10415 Offset = Op->getOperand(1);
10416 return true;
10417 }
10418 return false;
10419}
10420
10421bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
10422 SDValue &Offset,
10423 ISD::MemIndexedMode &AM,
10424 SelectionDAG &DAG) const {
10425 EVT VT;
10426 SDValue Ptr;
10427 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10428 VT = LD->getMemoryVT();
10429 Ptr = LD->getBasePtr();
10430 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10431 VT = ST->getMemoryVT();
10432 Ptr = ST->getBasePtr();
10433 } else
10434 return false;
10435
10436 bool IsInc;
10437 if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
10438 return false;
10439 AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
10440 return true;
10441}
10442
10443bool AArch64TargetLowering::getPostIndexedAddressParts(
10444 SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
10445 ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
10446 EVT VT;
10447 SDValue Ptr;
10448 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
10449 VT = LD->getMemoryVT();
10450 Ptr = LD->getBasePtr();
10451 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
10452 VT = ST->getMemoryVT();
10453 Ptr = ST->getBasePtr();
10454 } else
10455 return false;
10456
10457 bool IsInc;
10458 if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
10459 return false;
10460 // Post-indexing updates the base, so it's not a valid transform
10461 // if that's not the same as the load's pointer.
10462 if (Ptr != Base)
10463 return false;
10464 AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
10465 return true;
10466}
10467
Tim Northoverf8bfe212014-07-18 13:07:05 +000010468static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
10469 SelectionDAG &DAG) {
Tim Northoverf8bfe212014-07-18 13:07:05 +000010470 SDLoc DL(N);
10471 SDValue Op = N->getOperand(0);
Ahmed Bougacha87946322014-12-01 20:52:32 +000010472
10473 if (N->getValueType(0) != MVT::i16 || Op.getValueType() != MVT::f16)
10474 return;
10475
Tim Northoverf8bfe212014-07-18 13:07:05 +000010476 Op = SDValue(
10477 DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
10478 DAG.getUNDEF(MVT::i32), Op,
Sergey Dmitrouk842a51b2015-04-28 14:05:47 +000010479 DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
Tim Northoverf8bfe212014-07-18 13:07:05 +000010480 0);
10481 Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
10482 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
10483}
10484
Charlie Turner434d4592015-10-16 15:38:25 +000010485static void ReplaceReductionResults(SDNode *N,
10486 SmallVectorImpl<SDValue> &Results,
10487 SelectionDAG &DAG, unsigned InterOp,
10488 unsigned AcrossOp) {
10489 EVT LoVT, HiVT;
10490 SDValue Lo, Hi;
10491 SDLoc dl(N);
10492 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
10493 std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
10494 SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
10495 SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
10496 Results.push_back(SplitVal);
10497}
10498
Tim Northover2f32e7f2016-08-04 19:32:28 +000010499static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) {
10500 SDLoc DL(N);
10501 SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N);
10502 SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64,
10503 DAG.getNode(ISD::SRL, DL, MVT::i128, N,
10504 DAG.getConstant(64, DL, MVT::i64)));
10505 return std::make_pair(Lo, Hi);
10506}
10507
Tim Northovercdf15292016-04-14 17:03:29 +000010508static void ReplaceCMP_SWAP_128Results(SDNode *N,
10509 SmallVectorImpl<SDValue> & Results,
10510 SelectionDAG &DAG) {
10511 assert(N->getValueType(0) == MVT::i128 &&
10512 "AtomicCmpSwap on types less than 128 should be legal");
Tim Northover2f32e7f2016-08-04 19:32:28 +000010513 auto Desired = splitInt128(N->getOperand(2), DAG);
10514 auto New = splitInt128(N->getOperand(3), DAG);
10515 SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second,
10516 New.first, New.second, N->getOperand(0)};
Tim Northovercdf15292016-04-14 17:03:29 +000010517 SDNode *CmpSwap = DAG.getMachineNode(
10518 AArch64::CMP_SWAP_128, SDLoc(N),
10519 DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops);
10520
10521 MachineFunction &MF = DAG.getMachineFunction();
10522 MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1);
10523 MemOp[0] = cast<MemSDNode>(N)->getMemOperand();
10524 cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1);
10525
10526 Results.push_back(SDValue(CmpSwap, 0));
10527 Results.push_back(SDValue(CmpSwap, 1));
10528 Results.push_back(SDValue(CmpSwap, 3));
10529}
10530
Tim Northover3b0846e2014-05-24 12:50:23 +000010531void AArch64TargetLowering::ReplaceNodeResults(
10532 SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
10533 switch (N->getOpcode()) {
10534 default:
10535 llvm_unreachable("Don't know how to custom expand this");
Tim Northoverf8bfe212014-07-18 13:07:05 +000010536 case ISD::BITCAST:
10537 ReplaceBITCASTResults(N, Results, DAG);
10538 return;
Charlie Turner434d4592015-10-16 15:38:25 +000010539 case AArch64ISD::SADDV:
10540 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
10541 return;
10542 case AArch64ISD::UADDV:
10543 ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
10544 return;
10545 case AArch64ISD::SMINV:
10546 ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
10547 return;
10548 case AArch64ISD::UMINV:
10549 ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
10550 return;
10551 case AArch64ISD::SMAXV:
10552 ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
10553 return;
10554 case AArch64ISD::UMAXV:
10555 ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
10556 return;
Tim Northover3b0846e2014-05-24 12:50:23 +000010557 case ISD::FP_TO_UINT:
10558 case ISD::FP_TO_SINT:
10559 assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
10560 // Let normal code take care of it by not adding anything to Results.
10561 return;
Tim Northovercdf15292016-04-14 17:03:29 +000010562 case ISD::ATOMIC_CMP_SWAP:
10563 ReplaceCMP_SWAP_128Results(N, Results, DAG);
10564 return;
Tim Northover3b0846e2014-05-24 12:50:23 +000010565 }
10566}
10567
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +000010568bool AArch64TargetLowering::useLoadStackGuardNode() const {
Petr Hoseka7d59162017-02-24 03:10:10 +000010569 if (Subtarget->isTargetAndroid() || Subtarget->isTargetFuchsia())
10570 return TargetLowering::useLoadStackGuardNode();
10571 return true;
Akira Hatanakae5b6e0d2014-07-25 19:31:34 +000010572}
10573
Sanjay Patel1dd15592015-07-28 23:05:48 +000010574unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
Hao Liu44e5d7a2014-11-21 06:39:58 +000010575 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
10576 // reciprocal if there are three or more FDIVs.
Sanjay Patel1dd15592015-07-28 23:05:48 +000010577 return 3;
Hao Liu44e5d7a2014-11-21 06:39:58 +000010578}
10579
Chandler Carruth9d010ff2014-07-03 00:23:43 +000010580TargetLoweringBase::LegalizeTypeAction
10581AArch64TargetLowering::getPreferredVectorAction(EVT VT) const {
10582 MVT SVT = VT.getSimpleVT();
10583 // During type legalization, we prefer to widen v1i8, v1i16, v1i32 to v8i8,
10584 // v4i16, v2i32 instead of to promote.
10585 if (SVT == MVT::v1i8 || SVT == MVT::v1i16 || SVT == MVT::v1i32
10586 || SVT == MVT::v1f32)
10587 return TypeWidenVector;
10588
10589 return TargetLoweringBase::getPreferredVectorAction(VT);
10590}
10591
Robin Morisseted3d48f2014-09-03 21:29:59 +000010592// Loads and stores less than 128-bits are already atomic; ones above that
10593// are doomed anyway, so defer to the default libcall and blame the OS when
10594// things go wrong.
10595bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
10596 unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
10597 return Size == 128;
10598}
10599
10600// Loads and stores less than 128-bits are already atomic; ones above that
10601// are doomed anyway, so defer to the default libcall and blame the OS when
10602// things go wrong.
Ahmed Bougacha52468672015-09-11 17:08:28 +000010603TargetLowering::AtomicExpansionKind
10604AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
Robin Morisseted3d48f2014-09-03 21:29:59 +000010605 unsigned Size = LI->getType()->getPrimitiveSizeInBits();
Ahmed Bougacha52468672015-09-11 17:08:28 +000010606 return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
Robin Morisseted3d48f2014-09-03 21:29:59 +000010607}
10608
10609// For the real atomic operations, we have ldxr/stxr up to 128 bits,
Ahmed Bougacha52468672015-09-11 17:08:28 +000010610TargetLowering::AtomicExpansionKind
JF Bastienf14889e2015-03-04 15:47:57 +000010611AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
Robin Morisseted3d48f2014-09-03 21:29:59 +000010612 unsigned Size = AI->getType()->getPrimitiveSizeInBits();
Ahmed Bougacha9d677132015-09-11 17:08:17 +000010613 return Size <= 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
Robin Morisseted3d48f2014-09-03 21:29:59 +000010614}
10615
Ahmed Bougacha52468672015-09-11 17:08:28 +000010616bool AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
10617 AtomicCmpXchgInst *AI) const {
Tim Northovercdf15292016-04-14 17:03:29 +000010618 // At -O0, fast-regalloc cannot cope with the live vregs necessary to
10619 // implement cmpxchg without spilling. If the address being exchanged is also
10620 // on the stack and close enough to the spill slot, this can lead to a
10621 // situation where the monitor always gets cleared and the atomic operation
10622 // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
10623 return getTargetMachine().getOptLevel() != 0;
Robin Morisset25c8e312014-09-17 00:06:58 +000010624}
10625
Tim Northover3b0846e2014-05-24 12:50:23 +000010626Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
10627 AtomicOrdering Ord) const {
10628 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
10629 Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
JF Bastien800f87a2016-04-06 21:19:33 +000010630 bool IsAcquire = isAcquireOrStronger(Ord);
Tim Northover3b0846e2014-05-24 12:50:23 +000010631
10632 // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
10633 // intrinsic must return {i64, i64} and we have to recombine them into a
10634 // single i128 here.
10635 if (ValTy->getPrimitiveSizeInBits() == 128) {
10636 Intrinsic::ID Int =
10637 IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010638 Function *Ldxr = Intrinsic::getDeclaration(M, Int);
Tim Northover3b0846e2014-05-24 12:50:23 +000010639
10640 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
10641 Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
10642
10643 Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
10644 Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
10645 Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
10646 Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
10647 return Builder.CreateOr(
10648 Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
10649 }
10650
10651 Type *Tys[] = { Addr->getType() };
10652 Intrinsic::ID Int =
10653 IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
Eugene Zelenko049b0172017-01-06 00:30:53 +000010654 Function *Ldxr = Intrinsic::getDeclaration(M, Int, Tys);
Tim Northover3b0846e2014-05-24 12:50:23 +000010655
10656 return Builder.CreateTruncOrBitCast(
10657 Builder.CreateCall(Ldxr, Addr),
10658 cast<PointerType>(Addr->getType())->getElementType());
10659}
10660
Ahmed Bougacha07a844d2015-09-22 17:21:44 +000010661void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
10662 IRBuilder<> &Builder) const {
10663 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
Eugene Zelenko049b0172017-01-06 00:30:53 +000010664 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
Ahmed Bougacha07a844d2015-09-22 17:21:44 +000010665}
10666
Tim Northover3b0846e2014-05-24 12:50:23 +000010667Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
10668 Value *Val, Value *Addr,
10669 AtomicOrdering Ord) const {
10670 Module *M = Builder.GetInsertBlock()->getParent()->getParent();
JF Bastien800f87a2016-04-06 21:19:33 +000010671 bool IsRelease = isReleaseOrStronger(Ord);
Tim Northover3b0846e2014-05-24 12:50:23 +000010672
10673 // Since the intrinsics must have legal type, the i128 intrinsics take two
10674 // parameters: "i64, i64". We must marshal Val into the appropriate form
10675 // before the call.
10676 if (Val->getType()->getPrimitiveSizeInBits() == 128) {
10677 Intrinsic::ID Int =
10678 IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
10679 Function *Stxr = Intrinsic::getDeclaration(M, Int);
10680 Type *Int64Ty = Type::getInt64Ty(M->getContext());
10681
10682 Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
10683 Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
10684 Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
David Blaikieff6409d2015-05-18 22:13:54 +000010685 return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
Tim Northover3b0846e2014-05-24 12:50:23 +000010686 }
10687
10688 Intrinsic::ID Int =
10689 IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
10690 Type *Tys[] = { Addr->getType() };
10691 Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
10692
David Blaikieff6409d2015-05-18 22:13:54 +000010693 return Builder.CreateCall(Stxr,
10694 {Builder.CreateZExtOrBitCast(
10695 Val, Stxr->getFunctionType()->getParamType(0)),
10696 Addr});
Tim Northover3b0846e2014-05-24 12:50:23 +000010697}
Tim Northover3c55cca2014-11-27 21:02:42 +000010698
10699bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
10700 Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
10701 return Ty->isArrayTy();
10702}
Matthias Braunaf7d7702015-07-16 20:02:37 +000010703
10704bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
10705 EVT) const {
10706 return false;
10707}
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000010708
Petr Hoseka7d59162017-02-24 03:10:10 +000010709static Value *UseTlsOffset(IRBuilder<> &IRB, unsigned Offset) {
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +000010710 Module *M = IRB.GetInsertBlock()->getParent()->getParent();
10711 Function *ThreadPointerFunc =
Marcin Koscielnicki3fdc2572016-04-19 20:51:05 +000010712 Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +000010713 return IRB.CreatePointerCast(
Petr Hoseka7d59162017-02-24 03:10:10 +000010714 IRB.CreateConstGEP1_32(IRB.CreateCall(ThreadPointerFunc), Offset),
Evgeniy Stepanovdde29e22016-04-05 22:41:50 +000010715 Type::getInt8PtrTy(IRB.getContext())->getPointerTo(0));
10716}
10717
Petr Hoseka7d59162017-02-24 03:10:10 +000010718Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const {
10719 // Android provides a fixed TLS slot for the stack cookie. See the definition
10720 // of TLS_SLOT_STACK_GUARD in
10721 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
10722 if (Subtarget->isTargetAndroid())
10723 return UseTlsOffset(IRB, 0x28);
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000010724
Petr Hoseka7d59162017-02-24 03:10:10 +000010725 // Fuchsia is similar.
10726 // <magenta/tls.h> defines MX_TLS_STACK_GUARD_OFFSET with this value.
10727 if (Subtarget->isTargetFuchsia())
10728 return UseTlsOffset(IRB, -0x10);
10729
10730 return TargetLowering::getIRStackGuard(IRB);
10731}
10732
10733Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000010734 // Android provides a fixed TLS slot for the SafeStack pointer. See the
10735 // definition of TLS_SLOT_SAFESTACK in
10736 // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
Petr Hoseka7d59162017-02-24 03:10:10 +000010737 if (Subtarget->isTargetAndroid())
10738 return UseTlsOffset(IRB, 0x48);
10739
10740 // Fuchsia is similar.
10741 // <magenta/tls.h> defines MX_TLS_UNSAFE_SP_OFFSET with this value.
10742 if (Subtarget->isTargetFuchsia())
10743 return UseTlsOffset(IRB, -0x8);
10744
10745 return TargetLowering::getSafeStackPointerLocation(IRB);
Evgeniy Stepanovd1aad262015-10-26 18:28:25 +000010746}
Manman Rencbe4f942015-12-16 21:04:19 +000010747
Geoff Berry5d534b62017-02-21 18:53:14 +000010748bool AArch64TargetLowering::isMaskAndCmp0FoldingBeneficial(
10749 const Instruction &AndI) const {
10750 // Only sink 'and' mask to cmp use block if it is masking a single bit, since
10751 // this is likely to be fold the and/cmp/br into a single tbz instruction. It
10752 // may be beneficial to sink in other cases, but we would have to check that
10753 // the cmp would not get folded into the br to form a cbz for these to be
10754 // beneficial.
10755 ConstantInt* Mask = dyn_cast<ConstantInt>(AndI.getOperand(1));
10756 if (!Mask)
10757 return false;
10758 return Mask->getUniqueInteger().isPowerOf2();
10759}
10760
Manman Rencbe4f942015-12-16 21:04:19 +000010761void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
10762 // Update IsSplitCSR in AArch64unctionInfo.
10763 AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>();
10764 AFI->setIsSplitCSR(true);
10765}
10766
10767void AArch64TargetLowering::insertCopiesSplitCSR(
10768 MachineBasicBlock *Entry,
10769 const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
10770 const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
10771 const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
10772 if (!IStart)
10773 return;
10774
10775 const TargetInstrInfo *TII = Subtarget->getInstrInfo();
10776 MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
Manman Ren4632e8e2016-01-15 20:13:28 +000010777 MachineBasicBlock::iterator MBBI = Entry->begin();
Manman Rencbe4f942015-12-16 21:04:19 +000010778 for (const MCPhysReg *I = IStart; *I; ++I) {
10779 const TargetRegisterClass *RC = nullptr;
10780 if (AArch64::GPR64RegClass.contains(*I))
10781 RC = &AArch64::GPR64RegClass;
10782 else if (AArch64::FPR64RegClass.contains(*I))
10783 RC = &AArch64::FPR64RegClass;
10784 else
10785 llvm_unreachable("Unexpected register class in CSRsViaCopy!");
10786
10787 unsigned NewVR = MRI->createVirtualRegister(RC);
10788 // Create copy from CSR to a virtual register.
10789 // FIXME: this currently does not emit CFI pseudo-instructions, it works
10790 // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
10791 // nounwind. If we want to generalize this later, we may need to emit
10792 // CFI pseudo-instructions.
10793 assert(Entry->getParent()->getFunction()->hasFnAttribute(
10794 Attribute::NoUnwind) &&
10795 "Function should be nounwind in insertCopiesSplitCSR!");
10796 Entry->addLiveIn(*I);
Manman Ren4632e8e2016-01-15 20:13:28 +000010797 BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
Manman Rencbe4f942015-12-16 21:04:19 +000010798 .addReg(*I);
10799
Manman Ren4632e8e2016-01-15 20:13:28 +000010800 // Insert the copy-back instructions right before the terminator.
Manman Rencbe4f942015-12-16 21:04:19 +000010801 for (auto *Exit : Exits)
Manman Ren4632e8e2016-01-15 20:13:28 +000010802 BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
10803 TII->get(TargetOpcode::COPY), *I)
Manman Rencbe4f942015-12-16 21:04:19 +000010804 .addReg(NewVR);
10805 }
10806}
Haicheng Wu6a6bc752016-03-28 18:17:07 +000010807
Reid Klecknerb5180542017-03-21 16:57:19 +000010808bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const {
Haicheng Wu6a6bc752016-03-28 18:17:07 +000010809 // Integer division on AArch64 is expensive. However, when aggressively
10810 // optimizing for code size, we prefer to use a div instruction, as it is
10811 // usually smaller than the alternative sequence.
10812 // The exception to this is vector division. Since AArch64 doesn't have vector
10813 // integer division, leaving the division as-is is a loss even in terms of
10814 // size, because it will have to be scalarized, while the alternative code
10815 // sequence can be performed in vector form.
10816 bool OptSize =
Reid Klecknerb5180542017-03-21 16:57:19 +000010817 Attr.hasAttribute(AttributeList::FunctionIndex, Attribute::MinSize);
Haicheng Wu6a6bc752016-03-28 18:17:07 +000010818 return OptSize && !VT.isVector();
10819}
Tim Northoverf19d4672017-02-08 17:57:20 +000010820
10821unsigned
10822AArch64TargetLowering::getVaListSizeInBits(const DataLayout &DL) const {
10823 if (Subtarget->isTargetDarwin())
10824 return getPointerTy(DL).getSizeInBits();
10825
10826 return 3 * getPointerTy(DL).getSizeInBits() + 2 * 32;
10827}